@walletconnect/ethereum-provider 2.16.2 → 2.16.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +4 -4
- package/dist/index.umd.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/constants/values.d.ts +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* @copyright Chen, Yi-Cyuan 2015-2018
|
|
20
20
|
* @license MIT
|
|
21
21
|
*/(function(t){(function(){var e="input is invalid type",r="finalize already called",i=typeof window=="object",n=i?window:{};n.JS_SHA3_NO_WINDOW&&(i=!1);var s=!i&&typeof self=="object",a=!n.JS_SHA3_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;a?n=Z2:s&&(n=self);var u=!n.JS_SHA3_NO_COMMON_JS&&!0&&t.exports,h=!n.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",l="0123456789abcdef".split(""),b=[31,7936,2031616,520093696],w=[4,1024,262144,67108864],I=[1,256,65536,16777216],S=[6,1536,393216,100663296],D=[0,8,16,24],T=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],q=[224,256,384,512],K=[128,256],F=["hex","buffer","arrayBuffer","array","digest"],W={128:168,256:136};(n.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(P){return Object.prototype.toString.call(P)==="[object Array]"}),h&&(n.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(P){return typeof P=="object"&&P.buffer&&P.buffer.constructor===ArrayBuffer});for(var R=function(P,te,z){return function(G){return new N(P,te,P).update(G)[z]()}},k=function(P,te,z){return function(G,J){return new N(P,te,J).update(G)[z]()}},H=function(P,te,z){return function(G,J,A,V){return d["cshake"+P].update(G,J,A,V)[z]()}},_=function(P,te,z){return function(G,J,A,V){return d["kmac"+P].update(G,J,A,V)[z]()}},B=function(P,te,z,G){for(var J=0;J<F.length;++J){var A=F[J];P[A]=te(z,G,A)}return P},ee=function(P,te){var z=R(P,te,"hex");return z.create=function(){return new N(P,te,P)},z.update=function(G){return z.create().update(G)},B(z,R,P,te)},ie=function(P,te){var z=k(P,te,"hex");return z.create=function(G){return new N(P,te,G)},z.update=function(G,J){return z.create(J).update(G)},B(z,k,P,te)},L=function(P,te){var z=W[P],G=H(P,te,"hex");return G.create=function(J,A,V){return!A&&!V?d["shake"+P].create(J):new N(P,te,J).bytepad([A,V],z)},G.update=function(J,A,V,oe){return G.create(A,V,oe).update(J)},B(G,H,P,te)},y=function(P,te){var z=W[P],G=_(P,te,"hex");return G.create=function(J,A,V){return new X(P,te,A).bytepad(["KMAC",V],z).bytepad([J],z)},G.update=function(J,A,V,oe){return G.create(J,V,oe).update(A)},B(G,_,P,te)},f=[{name:"keccak",padding:I,bits:q,createMethod:ee},{name:"sha3",padding:S,bits:q,createMethod:ee},{name:"shake",padding:b,bits:K,createMethod:ie},{name:"cshake",padding:w,bits:K,createMethod:L},{name:"kmac",padding:w,bits:K,createMethod:y}],d={},v=[],E=0;E<f.length;++E)for(var C=f[E],O=C.bits,M=0;M<O.length;++M){var g=C.name+"_"+O[M];if(v.push(g),d[g]=C.createMethod(O[M],C.padding),C.name!=="sha3"){var m=C.name+O[M];v.push(m),d[m]=d[g]}}function N(P,te,z){this.blocks=[],this.s=[],this.padding=te,this.outputBits=z,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(P<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=z>>5,this.extraBytes=(z&31)>>3;for(var G=0;G<50;++G)this.s[G]=0}N.prototype.update=function(P){if(this.finalized)throw new Error(r);var te,z=typeof P;if(z!=="string"){if(z==="object"){if(P===null)throw new Error(e);if(h&&P.constructor===ArrayBuffer)P=new Uint8Array(P);else if(!Array.isArray(P)&&(!h||!ArrayBuffer.isView(P)))throw new Error(e)}else throw new Error(e);te=!0}for(var G=this.blocks,J=this.byteCount,A=P.length,V=this.blockCount,oe=0,ue=this.s,he,ye;oe<A;){if(this.reset)for(this.reset=!1,G[0]=this.block,he=1;he<V+1;++he)G[he]=0;if(te)for(he=this.start;oe<A&&he<J;++oe)G[he>>2]|=P[oe]<<D[he++&3];else for(he=this.start;oe<A&&he<J;++oe)ye=P.charCodeAt(oe),ye<128?G[he>>2]|=ye<<D[he++&3]:ye<2048?(G[he>>2]|=(192|ye>>6)<<D[he++&3],G[he>>2]|=(128|ye&63)<<D[he++&3]):ye<55296||ye>=57344?(G[he>>2]|=(224|ye>>12)<<D[he++&3],G[he>>2]|=(128|ye>>6&63)<<D[he++&3],G[he>>2]|=(128|ye&63)<<D[he++&3]):(ye=65536+((ye&1023)<<10|P.charCodeAt(++oe)&1023),G[he>>2]|=(240|ye>>18)<<D[he++&3],G[he>>2]|=(128|ye>>12&63)<<D[he++&3],G[he>>2]|=(128|ye>>6&63)<<D[he++&3],G[he>>2]|=(128|ye&63)<<D[he++&3]);if(this.lastByteIndex=he,he>=J){for(this.start=he-J,this.block=G[V],he=0;he<V;++he)ue[he]^=G[he];ae(ue),this.reset=!0}else this.start=he}return this},N.prototype.encode=function(P,te){var z=P&255,G=1,J=[z];for(P=P>>8,z=P&255;z>0;)J.unshift(z),P=P>>8,z=P&255,++G;return te?J.push(G):J.unshift(G),this.update(J),J.length},N.prototype.encodeString=function(P){var te,z=typeof P;if(z!=="string"){if(z==="object"){if(P===null)throw new Error(e);if(h&&P.constructor===ArrayBuffer)P=new Uint8Array(P);else if(!Array.isArray(P)&&(!h||!ArrayBuffer.isView(P)))throw new Error(e)}else throw new Error(e);te=!0}var G=0,J=P.length;if(te)G=J;else for(var A=0;A<P.length;++A){var V=P.charCodeAt(A);V<128?G+=1:V<2048?G+=2:V<55296||V>=57344?G+=3:(V=65536+((V&1023)<<10|P.charCodeAt(++A)&1023),G+=4)}return G+=this.encode(G*8),this.update(P),G},N.prototype.bytepad=function(P,te){for(var z=this.encode(te),G=0;G<P.length;++G)z+=this.encodeString(P[G]);var J=te-z%te,A=[];return A.length=J,this.update(A),this},N.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var P=this.blocks,te=this.lastByteIndex,z=this.blockCount,G=this.s;if(P[te>>2]|=this.padding[te&3],this.lastByteIndex===this.byteCount)for(P[0]=P[z],te=1;te<z+1;++te)P[te]=0;for(P[z-1]|=2147483648,te=0;te<z;++te)G[te]^=P[te];ae(G)}},N.prototype.toString=N.prototype.hex=function(){this.finalize();for(var P=this.blockCount,te=this.s,z=this.outputBlocks,G=this.extraBytes,J=0,A=0,V="",oe;A<z;){for(J=0;J<P&&A<z;++J,++A)oe=te[J],V+=l[oe>>4&15]+l[oe&15]+l[oe>>12&15]+l[oe>>8&15]+l[oe>>20&15]+l[oe>>16&15]+l[oe>>28&15]+l[oe>>24&15];A%P===0&&(ae(te),J=0)}return G&&(oe=te[J],V+=l[oe>>4&15]+l[oe&15],G>1&&(V+=l[oe>>12&15]+l[oe>>8&15]),G>2&&(V+=l[oe>>20&15]+l[oe>>16&15])),V},N.prototype.arrayBuffer=function(){this.finalize();var P=this.blockCount,te=this.s,z=this.outputBlocks,G=this.extraBytes,J=0,A=0,V=this.outputBits>>3,oe;G?oe=new ArrayBuffer(z+1<<2):oe=new ArrayBuffer(V);for(var ue=new Uint32Array(oe);A<z;){for(J=0;J<P&&A<z;++J,++A)ue[A]=te[J];A%P===0&&ae(te)}return G&&(ue[J]=te[J],oe=oe.slice(0,V)),oe},N.prototype.buffer=N.prototype.arrayBuffer,N.prototype.digest=N.prototype.array=function(){this.finalize();for(var P=this.blockCount,te=this.s,z=this.outputBlocks,G=this.extraBytes,J=0,A=0,V=[],oe,ue;A<z;){for(J=0;J<P&&A<z;++J,++A)oe=A<<2,ue=te[J],V[oe]=ue&255,V[oe+1]=ue>>8&255,V[oe+2]=ue>>16&255,V[oe+3]=ue>>24&255;A%P===0&&ae(te)}return G&&(oe=A<<2,ue=te[J],V[oe]=ue&255,G>1&&(V[oe+1]=ue>>8&255),G>2&&(V[oe+2]=ue>>16&255)),V};function X(P,te,z){N.call(this,P,te,z)}X.prototype=new N,X.prototype.finalize=function(){return this.encode(this.outputBits,!0),N.prototype.finalize.call(this)};var ae=function(P){var te,z,G,J,A,V,oe,ue,he,ye,we,Re,Xe,Oe,Ne,Me,be,Pe,Te,ve,$e,Se,me,Ue,Ce,_e,Ke,Ve,Ae,We,pt,Ge,It,gt,Ye,Ot,Tt,Le,et,it,Be,rt,tt,qe,ht,nt,je,st,at,Fe,Ze,lt,ze,qt,jt,ct,_t,Zr,Xr,ei,ti,ri,vr;for(G=0;G<48;G+=2)J=P[0]^P[10]^P[20]^P[30]^P[40],A=P[1]^P[11]^P[21]^P[31]^P[41],V=P[2]^P[12]^P[22]^P[32]^P[42],oe=P[3]^P[13]^P[23]^P[33]^P[43],ue=P[4]^P[14]^P[24]^P[34]^P[44],he=P[5]^P[15]^P[25]^P[35]^P[45],ye=P[6]^P[16]^P[26]^P[36]^P[46],we=P[7]^P[17]^P[27]^P[37]^P[47],Re=P[8]^P[18]^P[28]^P[38]^P[48],Xe=P[9]^P[19]^P[29]^P[39]^P[49],te=Re^(V<<1|oe>>>31),z=Xe^(oe<<1|V>>>31),P[0]^=te,P[1]^=z,P[10]^=te,P[11]^=z,P[20]^=te,P[21]^=z,P[30]^=te,P[31]^=z,P[40]^=te,P[41]^=z,te=J^(ue<<1|he>>>31),z=A^(he<<1|ue>>>31),P[2]^=te,P[3]^=z,P[12]^=te,P[13]^=z,P[22]^=te,P[23]^=z,P[32]^=te,P[33]^=z,P[42]^=te,P[43]^=z,te=V^(ye<<1|we>>>31),z=oe^(we<<1|ye>>>31),P[4]^=te,P[5]^=z,P[14]^=te,P[15]^=z,P[24]^=te,P[25]^=z,P[34]^=te,P[35]^=z,P[44]^=te,P[45]^=z,te=ue^(Re<<1|Xe>>>31),z=he^(Xe<<1|Re>>>31),P[6]^=te,P[7]^=z,P[16]^=te,P[17]^=z,P[26]^=te,P[27]^=z,P[36]^=te,P[37]^=z,P[46]^=te,P[47]^=z,te=ye^(J<<1|A>>>31),z=we^(A<<1|J>>>31),P[8]^=te,P[9]^=z,P[18]^=te,P[19]^=z,P[28]^=te,P[29]^=z,P[38]^=te,P[39]^=z,P[48]^=te,P[49]^=z,Oe=P[0],Ne=P[1],nt=P[11]<<4|P[10]>>>28,je=P[10]<<4|P[11]>>>28,Ve=P[20]<<3|P[21]>>>29,Ae=P[21]<<3|P[20]>>>29,ei=P[31]<<9|P[30]>>>23,ti=P[30]<<9|P[31]>>>23,rt=P[40]<<18|P[41]>>>14,tt=P[41]<<18|P[40]>>>14,gt=P[2]<<1|P[3]>>>31,Ye=P[3]<<1|P[2]>>>31,Me=P[13]<<12|P[12]>>>20,be=P[12]<<12|P[13]>>>20,st=P[22]<<10|P[23]>>>22,at=P[23]<<10|P[22]>>>22,We=P[33]<<13|P[32]>>>19,pt=P[32]<<13|P[33]>>>19,ri=P[42]<<2|P[43]>>>30,vr=P[43]<<2|P[42]>>>30,qt=P[5]<<30|P[4]>>>2,jt=P[4]<<30|P[5]>>>2,Ot=P[14]<<6|P[15]>>>26,Tt=P[15]<<6|P[14]>>>26,Pe=P[25]<<11|P[24]>>>21,Te=P[24]<<11|P[25]>>>21,Fe=P[34]<<15|P[35]>>>17,Ze=P[35]<<15|P[34]>>>17,Ge=P[45]<<29|P[44]>>>3,It=P[44]<<29|P[45]>>>3,Ue=P[6]<<28|P[7]>>>4,Ce=P[7]<<28|P[6]>>>4,ct=P[17]<<23|P[16]>>>9,_t=P[16]<<23|P[17]>>>9,Le=P[26]<<25|P[27]>>>7,et=P[27]<<25|P[26]>>>7,ve=P[36]<<21|P[37]>>>11,$e=P[37]<<21|P[36]>>>11,lt=P[47]<<24|P[46]>>>8,ze=P[46]<<24|P[47]>>>8,qe=P[8]<<27|P[9]>>>5,ht=P[9]<<27|P[8]>>>5,_e=P[18]<<20|P[19]>>>12,Ke=P[19]<<20|P[18]>>>12,Zr=P[29]<<7|P[28]>>>25,Xr=P[28]<<7|P[29]>>>25,it=P[38]<<8|P[39]>>>24,Be=P[39]<<8|P[38]>>>24,Se=P[48]<<14|P[49]>>>18,me=P[49]<<14|P[48]>>>18,P[0]=Oe^~Me&Pe,P[1]=Ne^~be&Te,P[10]=Ue^~_e&Ve,P[11]=Ce^~Ke&Ae,P[20]=gt^~Ot&Le,P[21]=Ye^~Tt&et,P[30]=qe^~nt&st,P[31]=ht^~je&at,P[40]=qt^~ct&Zr,P[41]=jt^~_t&Xr,P[2]=Me^~Pe&ve,P[3]=be^~Te&$e,P[12]=_e^~Ve&We,P[13]=Ke^~Ae&pt,P[22]=Ot^~Le&it,P[23]=Tt^~et&Be,P[32]=nt^~st&Fe,P[33]=je^~at&Ze,P[42]=ct^~Zr&ei,P[43]=_t^~Xr&ti,P[4]=Pe^~ve&Se,P[5]=Te^~$e&me,P[14]=Ve^~We&Ge,P[15]=Ae^~pt&It,P[24]=Le^~it&rt,P[25]=et^~Be&tt,P[34]=st^~Fe<,P[35]=at^~Ze&ze,P[44]=Zr^~ei&ri,P[45]=Xr^~ti&vr,P[6]=ve^~Se&Oe,P[7]=$e^~me&Ne,P[16]=We^~Ge&Ue,P[17]=pt^~It&Ce,P[26]=it^~rt>,P[27]=Be^~tt&Ye,P[36]=Fe^~lt&qe,P[37]=Ze^~ze&ht,P[46]=ei^~ri&qt,P[47]=ti^~vr&jt,P[8]=Se^~Oe&Me,P[9]=me^~Ne&be,P[18]=Ge^~Ue&_e,P[19]=It^~Ce&Ke,P[28]=rt^~gt&Ot,P[29]=tt^~Ye&Tt,P[38]=lt^~qe&nt,P[39]=ze^~ht&je,P[48]=ri^~qt&ct,P[49]=vr^~jt&_t,P[0]^=T[G],P[1]^=T[G+1]};if(u)t.exports=d;else for(E=0;E<v.length;++E)n[v[E]]=d[v[E]]})()})(X2);var aA=X2.exports;const cA="logger/5.7.0";let em=!1,tm=!1;const ih={debug:1,default:2,info:2,warning:3,error:4,off:5};let rm=ih.default,cd=null;function uA(){try{const t=[];if(["NFD","NFC","NFKD","NFKC"].forEach(e=>{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{t.push(e)}}),t.length)throw new Error("missing "+t.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(t){return t.message}return null}const im=uA();var ud;(function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR",t.OFF="OFF"})(ud||(ud={}));var wn;(function(t){t.UNKNOWN_ERROR="UNKNOWN_ERROR",t.NOT_IMPLEMENTED="NOT_IMPLEMENTED",t.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.TIMEOUT="TIMEOUT",t.BUFFER_OVERRUN="BUFFER_OVERRUN",t.NUMERIC_FAULT="NUMERIC_FAULT",t.MISSING_NEW="MISSING_NEW",t.INVALID_ARGUMENT="INVALID_ARGUMENT",t.MISSING_ARGUMENT="MISSING_ARGUMENT",t.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",t.CALL_EXCEPTION="CALL_EXCEPTION",t.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",t.NONCE_EXPIRED="NONCE_EXPIRED",t.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",t.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",t.TRANSACTION_REPLACED="TRANSACTION_REPLACED",t.ACTION_REJECTED="ACTION_REJECTED"})(wn||(wn={}));const nm="0123456789abcdef";class Et{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,r){const i=e.toLowerCase();ih[i]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(rm>ih[i])&&console.log.apply(console,r)}debug(...e){this._log(Et.levels.DEBUG,e)}info(...e){this._log(Et.levels.INFO,e)}warn(...e){this._log(Et.levels.WARNING,e)}makeError(e,r,i){if(tm)return this.makeError("censored error",r,{});r||(r=Et.errors.UNKNOWN_ERROR),i||(i={});const n=[];Object.keys(i).forEach(h=>{const l=i[h];try{if(l instanceof Uint8Array){let b="";for(let w=0;w<l.length;w++)b+=nm[l[w]>>4],b+=nm[l[w]&15];n.push(h+"=Uint8Array(0x"+b+")")}else n.push(h+"="+JSON.stringify(l))}catch{n.push(h+"="+JSON.stringify(i[h].toString()))}}),n.push(`code=${r}`),n.push(`version=${this.version}`);const s=e;let a="";switch(r){case wn.NUMERIC_FAULT:{a="NUMERIC_FAULT";const h=e;switch(h){case"overflow":case"underflow":case"division-by-zero":a+="-"+h;break;case"negative-power":case"negative-width":a+="-unsupported";break;case"unbound-bitwise-result":a+="-unbound-result";break}break}case wn.CALL_EXCEPTION:case wn.INSUFFICIENT_FUNDS:case wn.MISSING_NEW:case wn.NONCE_EXPIRED:case wn.REPLACEMENT_UNDERPRICED:case wn.TRANSACTION_REPLACED:case wn.UNPREDICTABLE_GAS_LIMIT:a=r;break}a&&(e+=" [ See: https://links.ethers.org/v5-errors-"+a+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const u=new Error(e);return u.reason=s,u.code=r,Object.keys(i).forEach(function(h){u[h]=i[h]}),u}throwError(e,r,i){throw this.makeError(e,r,i)}throwArgumentError(e,r,i){return this.throwError(e,Et.errors.INVALID_ARGUMENT,{argument:r,value:i})}assert(e,r,i,n){e||this.throwError(r,i,n)}assertArgument(e,r,i,n){e||this.throwArgumentError(r,i,n)}checkNormalize(e){im&&this.throwError("platform missing String.prototype.normalize",Et.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:im})}checkSafeUint53(e,r){typeof e=="number"&&(r==null&&(r="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(r,Et.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(r,Et.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,r,i){i?i=": "+i:i="",e<r&&this.throwError("missing argument"+i,Et.errors.MISSING_ARGUMENT,{count:e,expectedCount:r}),e>r&&this.throwError("too many arguments"+i,Et.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:r})}checkNew(e,r){(e===Object||e==null)&&this.throwError("missing new",Et.errors.MISSING_NEW,{name:r.name})}checkAbstract(e,r){e===r?this.throwError("cannot instantiate abstract class "+JSON.stringify(r.name)+" directly; use a sub-class",Et.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",Et.errors.MISSING_NEW,{name:r.name})}static globalLogger(){return cd||(cd=new Et(cA)),cd}static setCensorship(e,r){if(!e&&r&&this.globalLogger().throwError("cannot permanently disable censorship",Et.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),em){if(!e)return;this.globalLogger().throwError("error censorship permanent",Et.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}tm=!!e,em=!!r}static setLogLevel(e){const r=ih[e.toLowerCase()];if(r==null){Et.globalLogger().warn("invalid log level - "+e);return}rm=r}static from(e){return new Et(e)}}Et.errors=wn,Et.levels=ud;const fA="bytes/5.7.0",br=new Et(fA);function sm(t){return!!t.toHexString}function Ja(t){return t.slice||(t.slice=function(){const e=Array.prototype.slice.call(arguments);return Ja(new Uint8Array(Array.prototype.slice.apply(t,e)))}),t}function hA(t){return Fi(t)&&!(t.length%2)||Ya(t)}function om(t){return typeof t=="number"&&t==t&&t%1===0}function Ya(t){if(t==null)return!1;if(t.constructor===Uint8Array)return!0;if(typeof t=="string"||!om(t.length)||t.length<0)return!1;for(let e=0;e<t.length;e++){const r=t[e];if(!om(r)||r<0||r>=256)return!1}return!0}function dr(t,e){if(e||(e={}),typeof t=="number"){br.checkSafeUint53(t,"invalid arrayify value");const r=[];for(;t;)r.unshift(t&255),t=parseInt(String(t/256));return r.length===0&&r.push(0),Ja(new Uint8Array(r))}if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),sm(t)&&(t=t.toHexString()),Fi(t)){let r=t.substring(2);r.length%2&&(e.hexPad==="left"?r="0"+r:e.hexPad==="right"?r+="0":br.throwArgumentError("hex data is odd-length","value",t));const i=[];for(let n=0;n<r.length;n+=2)i.push(parseInt(r.substring(n,n+2),16));return Ja(new Uint8Array(i))}return Ya(t)?Ja(new Uint8Array(t)):br.throwArgumentError("invalid arrayify value","value",t)}function lA(t){const e=t.map(n=>dr(n)),r=e.reduce((n,s)=>n+s.length,0),i=new Uint8Array(r);return e.reduce((n,s)=>(i.set(s,n),n+s.length),0),Ja(i)}function dA(t,e){t=dr(t),t.length>e&&br.throwArgumentError("value out of range","value",arguments[0]);const r=new Uint8Array(e);return r.set(t,e-t.length),Ja(r)}function Fi(t,e){return!(typeof t!="string"||!t.match(/^0x[0-9A-Fa-f]*$/)||e&&t.length!==2+2*e)}const fd="0123456789abcdef";function si(t,e){if(e||(e={}),typeof t=="number"){br.checkSafeUint53(t,"invalid hexlify value");let r="";for(;t;)r=fd[t&15]+r,t=Math.floor(t/16);return r.length?(r.length%2&&(r="0"+r),"0x"+r):"0x00"}if(typeof t=="bigint")return t=t.toString(16),t.length%2?"0x0"+t:"0x"+t;if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),sm(t))return t.toHexString();if(Fi(t))return t.length%2&&(e.hexPad==="left"?t="0x0"+t.substring(2):e.hexPad==="right"?t+="0":br.throwArgumentError("hex data is odd-length","value",t)),t.toLowerCase();if(Ya(t)){let r="0x";for(let i=0;i<t.length;i++){let n=t[i];r+=fd[(n&240)>>4]+fd[n&15]}return r}return br.throwArgumentError("invalid hexlify value","value",t)}function pA(t){if(typeof t!="string")t=si(t);else if(!Fi(t)||t.length%2)return null;return(t.length-2)/2}function am(t,e,r){return typeof t!="string"?t=si(t):(!Fi(t)||t.length%2)&&br.throwArgumentError("invalid hexData","value",t),e=2+2*e,r!=null?"0x"+t.substring(e,2+2*r):"0x"+t.substring(e)}function Qn(t,e){for(typeof t!="string"?t=si(t):Fi(t)||br.throwArgumentError("invalid hex string","value",t),t.length>2*e+2&&br.throwArgumentError("value out of range","value",arguments[1]);t.length<2*e+2;)t="0x0"+t.substring(2);return t}function cm(t){const e={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(hA(t)){let r=dr(t);r.length===64?(e.v=27+(r[32]>>7),r[32]&=127,e.r=si(r.slice(0,32)),e.s=si(r.slice(32,64))):r.length===65?(e.r=si(r.slice(0,32)),e.s=si(r.slice(32,64)),e.v=r[64]):br.throwArgumentError("invalid signature string","signature",t),e.v<27&&(e.v===0||e.v===1?e.v+=27:br.throwArgumentError("signature invalid v byte","signature",t)),e.recoveryParam=1-e.v%2,e.recoveryParam&&(r[32]|=128),e._vs=si(r.slice(32,64))}else{if(e.r=t.r,e.s=t.s,e.v=t.v,e.recoveryParam=t.recoveryParam,e._vs=t._vs,e._vs!=null){const n=dA(dr(e._vs),32);e._vs=si(n);const s=n[0]>=128?1:0;e.recoveryParam==null?e.recoveryParam=s:e.recoveryParam!==s&&br.throwArgumentError("signature recoveryParam mismatch _vs","signature",t),n[0]&=127;const a=si(n);e.s==null?e.s=a:e.s!==a&&br.throwArgumentError("signature v mismatch _vs","signature",t)}if(e.recoveryParam==null)e.v==null?br.throwArgumentError("signature missing v and recoveryParam","signature",t):e.v===0||e.v===1?e.recoveryParam=e.v:e.recoveryParam=1-e.v%2;else if(e.v==null)e.v=27+e.recoveryParam;else{const n=e.v===0||e.v===1?e.v:1-e.v%2;e.recoveryParam!==n&&br.throwArgumentError("signature recoveryParam mismatch v","signature",t)}e.r==null||!Fi(e.r)?br.throwArgumentError("signature missing or invalid r","signature",t):e.r=Qn(e.r,32),e.s==null||!Fi(e.s)?br.throwArgumentError("signature missing or invalid s","signature",t):e.s=Qn(e.s,32);const r=dr(e.s);r[0]>=128&&br.throwArgumentError("signature s out of range","signature",t),e.recoveryParam&&(r[0]|=128);const i=si(r);e._vs&&(Fi(e._vs)||br.throwArgumentError("signature invalid _vs","signature",t),e._vs=Qn(e._vs,32)),e._vs==null?e._vs=i:e._vs!==i&&br.throwArgumentError("signature _vs mismatch v and s","signature",t)}return e.yParityAndS=e._vs,e.compact=e.r+e.yParityAndS.substring(2),e}function hd(t){return"0x"+aA.keccak_256(dr(t))}var um={exports:{}},gA={},vA=Object.freeze({__proto__:null,default:gA}),mA=oA(vA);(function(t){(function(e,r){function i(f,d){if(!f)throw new Error(d||"Assertion failed")}function n(f,d){f.super_=d;var v=function(){};v.prototype=d.prototype,f.prototype=new v,f.prototype.constructor=f}function s(f,d,v){if(s.isBN(f))return f;this.negative=0,this.words=null,this.length=0,this.red=null,f!==null&&((d==="le"||d==="be")&&(v=d,d=10),this._init(f||0,d||10,v||"be"))}typeof e=="object"?e.exports=s:r.BN=s,s.BN=s,s.wordSize=26;var a;try{typeof window<"u"&&typeof window.Buffer<"u"?a=window.Buffer:a=mA.Buffer}catch{}s.isBN=function(f){return f instanceof s?!0:f!==null&&typeof f=="object"&&f.constructor.wordSize===s.wordSize&&Array.isArray(f.words)},s.max=function(f,d){return f.cmp(d)>0?f:d},s.min=function(f,d){return f.cmp(d)<0?f:d},s.prototype._init=function(f,d,v){if(typeof f=="number")return this._initNumber(f,d,v);if(typeof f=="object")return this._initArray(f,d,v);d==="hex"&&(d=16),i(d===(d|0)&&d>=2&&d<=36),f=f.toString().replace(/\s+/g,"");var E=0;f[0]==="-"&&(E++,this.negative=1),E<f.length&&(d===16?this._parseHex(f,E,v):(this._parseBase(f,d,E),v==="le"&&this._initArray(this.toArray(),d,v)))},s.prototype._initNumber=function(f,d,v){f<0&&(this.negative=1,f=-f),f<67108864?(this.words=[f&67108863],this.length=1):f<4503599627370496?(this.words=[f&67108863,f/67108864&67108863],this.length=2):(i(f<9007199254740992),this.words=[f&67108863,f/67108864&67108863,1],this.length=3),v==="le"&&this._initArray(this.toArray(),d,v)},s.prototype._initArray=function(f,d,v){if(i(typeof f.length=="number"),f.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(f.length/3),this.words=new Array(this.length);for(var E=0;E<this.length;E++)this.words[E]=0;var C,O,M=0;if(v==="be")for(E=f.length-1,C=0;E>=0;E-=3)O=f[E]|f[E-1]<<8|f[E-2]<<16,this.words[C]|=O<<M&67108863,this.words[C+1]=O>>>26-M&67108863,M+=24,M>=26&&(M-=26,C++);else if(v==="le")for(E=0,C=0;E<f.length;E+=3)O=f[E]|f[E+1]<<8|f[E+2]<<16,this.words[C]|=O<<M&67108863,this.words[C+1]=O>>>26-M&67108863,M+=24,M>=26&&(M-=26,C++);return this._strip()};function u(f,d){var v=f.charCodeAt(d);if(v>=48&&v<=57)return v-48;if(v>=65&&v<=70)return v-55;if(v>=97&&v<=102)return v-87;i(!1,"Invalid character in "+f)}function h(f,d,v){var E=u(f,v);return v-1>=d&&(E|=u(f,v-1)<<4),E}s.prototype._parseHex=function(f,d,v){this.length=Math.ceil((f.length-d)/6),this.words=new Array(this.length);for(var E=0;E<this.length;E++)this.words[E]=0;var C=0,O=0,M;if(v==="be")for(E=f.length-1;E>=d;E-=2)M=h(f,d,E)<<C,this.words[O]|=M&67108863,C>=18?(C-=18,O+=1,this.words[O]|=M>>>26):C+=8;else{var g=f.length-d;for(E=g%2===0?d+1:d;E<f.length;E+=2)M=h(f,d,E)<<C,this.words[O]|=M&67108863,C>=18?(C-=18,O+=1,this.words[O]|=M>>>26):C+=8}this._strip()};function l(f,d,v,E){for(var C=0,O=0,M=Math.min(f.length,v),g=d;g<M;g++){var m=f.charCodeAt(g)-48;C*=E,m>=49?O=m-49+10:m>=17?O=m-17+10:O=m,i(m>=0&&O<E,"Invalid character"),C+=O}return C}s.prototype._parseBase=function(f,d,v){this.words=[0],this.length=1;for(var E=0,C=1;C<=67108863;C*=d)E++;E--,C=C/d|0;for(var O=f.length-v,M=O%E,g=Math.min(O,O-M)+v,m=0,N=v;N<g;N+=E)m=l(f,N,N+E,d),this.imuln(C),this.words[0]+m<67108864?this.words[0]+=m:this._iaddn(m);if(M!==0){var X=1;for(m=l(f,N,f.length,d),N=0;N<M;N++)X*=d;this.imuln(X),this.words[0]+m<67108864?this.words[0]+=m:this._iaddn(m)}this._strip()},s.prototype.copy=function(f){f.words=new Array(this.length);for(var d=0;d<this.length;d++)f.words[d]=this.words[d];f.length=this.length,f.negative=this.negative,f.red=this.red};function b(f,d){f.words=d.words,f.length=d.length,f.negative=d.negative,f.red=d.red}if(s.prototype._move=function(f){b(f,this)},s.prototype.clone=function(){var f=new s(null);return this.copy(f),f},s.prototype._expand=function(f){for(;this.length<f;)this.words[this.length++]=0;return this},s.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=w}catch{s.prototype.inspect=w}else s.prototype.inspect=w;function w(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var I=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],S=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],D=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];s.prototype.toString=function(f,d){f=f||10,d=d|0||1;var v;if(f===16||f==="hex"){v="";for(var E=0,C=0,O=0;O<this.length;O++){var M=this.words[O],g=((M<<E|C)&16777215).toString(16);C=M>>>24-E&16777215,E+=2,E>=26&&(E-=26,O--),C!==0||O!==this.length-1?v=I[6-g.length]+g+v:v=g+v}for(C!==0&&(v=C.toString(16)+v);v.length%d!==0;)v="0"+v;return this.negative!==0&&(v="-"+v),v}if(f===(f|0)&&f>=2&&f<=36){var m=S[f],N=D[f];v="";var X=this.clone();for(X.negative=0;!X.isZero();){var ae=X.modrn(N).toString(f);X=X.idivn(N),X.isZero()?v=ae+v:v=I[m-ae.length]+ae+v}for(this.isZero()&&(v="0"+v);v.length%d!==0;)v="0"+v;return this.negative!==0&&(v="-"+v),v}i(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var f=this.words[0];return this.length===2?f+=this.words[1]*67108864:this.length===3&&this.words[2]===1?f+=4503599627370496+this.words[1]*67108864:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-f:f},s.prototype.toJSON=function(){return this.toString(16,2)},a&&(s.prototype.toBuffer=function(f,d){return this.toArrayLike(a,f,d)}),s.prototype.toArray=function(f,d){return this.toArrayLike(Array,f,d)};var T=function(f,d){return f.allocUnsafe?f.allocUnsafe(d):new f(d)};s.prototype.toArrayLike=function(f,d,v){this._strip();var E=this.byteLength(),C=v||Math.max(1,E);i(E<=C,"byte array longer than desired length"),i(C>0,"Requested array length <= 0");var O=T(f,C),M=d==="le"?"LE":"BE";return this["_toArrayLike"+M](O,E),O},s.prototype._toArrayLikeLE=function(f,d){for(var v=0,E=0,C=0,O=0;C<this.length;C++){var M=this.words[C]<<O|E;f[v++]=M&255,v<f.length&&(f[v++]=M>>8&255),v<f.length&&(f[v++]=M>>16&255),O===6?(v<f.length&&(f[v++]=M>>24&255),E=0,O=0):(E=M>>>24,O+=2)}if(v<f.length)for(f[v++]=E;v<f.length;)f[v++]=0},s.prototype._toArrayLikeBE=function(f,d){for(var v=f.length-1,E=0,C=0,O=0;C<this.length;C++){var M=this.words[C]<<O|E;f[v--]=M&255,v>=0&&(f[v--]=M>>8&255),v>=0&&(f[v--]=M>>16&255),O===6?(v>=0&&(f[v--]=M>>24&255),E=0,O=0):(E=M>>>24,O+=2)}if(v>=0)for(f[v--]=E;v>=0;)f[v--]=0},Math.clz32?s.prototype._countBits=function(f){return 32-Math.clz32(f)}:s.prototype._countBits=function(f){var d=f,v=0;return d>=4096&&(v+=13,d>>>=13),d>=64&&(v+=7,d>>>=7),d>=8&&(v+=4,d>>>=4),d>=2&&(v+=2,d>>>=2),v+d},s.prototype._zeroBits=function(f){if(f===0)return 26;var d=f,v=0;return d&8191||(v+=13,d>>>=13),d&127||(v+=7,d>>>=7),d&15||(v+=4,d>>>=4),d&3||(v+=2,d>>>=2),d&1||v++,v},s.prototype.bitLength=function(){var f=this.words[this.length-1],d=this._countBits(f);return(this.length-1)*26+d};function q(f){for(var d=new Array(f.bitLength()),v=0;v<d.length;v++){var E=v/26|0,C=v%26;d[v]=f.words[E]>>>C&1}return d}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var f=0,d=0;d<this.length;d++){var v=this._zeroBits(this.words[d]);if(f+=v,v!==26)break}return f},s.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},s.prototype.toTwos=function(f){return this.negative!==0?this.abs().inotn(f).iaddn(1):this.clone()},s.prototype.fromTwos=function(f){return this.testn(f-1)?this.notn(f).iaddn(1).ineg():this.clone()},s.prototype.isNeg=function(){return this.negative!==0},s.prototype.neg=function(){return this.clone().ineg()},s.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},s.prototype.iuor=function(f){for(;this.length<f.length;)this.words[this.length++]=0;for(var d=0;d<f.length;d++)this.words[d]=this.words[d]|f.words[d];return this._strip()},s.prototype.ior=function(f){return i((this.negative|f.negative)===0),this.iuor(f)},s.prototype.or=function(f){return this.length>f.length?this.clone().ior(f):f.clone().ior(this)},s.prototype.uor=function(f){return this.length>f.length?this.clone().iuor(f):f.clone().iuor(this)},s.prototype.iuand=function(f){var d;this.length>f.length?d=f:d=this;for(var v=0;v<d.length;v++)this.words[v]=this.words[v]&f.words[v];return this.length=d.length,this._strip()},s.prototype.iand=function(f){return i((this.negative|f.negative)===0),this.iuand(f)},s.prototype.and=function(f){return this.length>f.length?this.clone().iand(f):f.clone().iand(this)},s.prototype.uand=function(f){return this.length>f.length?this.clone().iuand(f):f.clone().iuand(this)},s.prototype.iuxor=function(f){var d,v;this.length>f.length?(d=this,v=f):(d=f,v=this);for(var E=0;E<v.length;E++)this.words[E]=d.words[E]^v.words[E];if(this!==d)for(;E<d.length;E++)this.words[E]=d.words[E];return this.length=d.length,this._strip()},s.prototype.ixor=function(f){return i((this.negative|f.negative)===0),this.iuxor(f)},s.prototype.xor=function(f){return this.length>f.length?this.clone().ixor(f):f.clone().ixor(this)},s.prototype.uxor=function(f){return this.length>f.length?this.clone().iuxor(f):f.clone().iuxor(this)},s.prototype.inotn=function(f){i(typeof f=="number"&&f>=0);var d=Math.ceil(f/26)|0,v=f%26;this._expand(d),v>0&&d--;for(var E=0;E<d;E++)this.words[E]=~this.words[E]&67108863;return v>0&&(this.words[E]=~this.words[E]&67108863>>26-v),this._strip()},s.prototype.notn=function(f){return this.clone().inotn(f)},s.prototype.setn=function(f,d){i(typeof f=="number"&&f>=0);var v=f/26|0,E=f%26;return this._expand(v+1),d?this.words[v]=this.words[v]|1<<E:this.words[v]=this.words[v]&~(1<<E),this._strip()},s.prototype.iadd=function(f){var d;if(this.negative!==0&&f.negative===0)return this.negative=0,d=this.isub(f),this.negative^=1,this._normSign();if(this.negative===0&&f.negative!==0)return f.negative=0,d=this.isub(f),f.negative=1,d._normSign();var v,E;this.length>f.length?(v=this,E=f):(v=f,E=this);for(var C=0,O=0;O<E.length;O++)d=(v.words[O]|0)+(E.words[O]|0)+C,this.words[O]=d&67108863,C=d>>>26;for(;C!==0&&O<v.length;O++)d=(v.words[O]|0)+C,this.words[O]=d&67108863,C=d>>>26;if(this.length=v.length,C!==0)this.words[this.length]=C,this.length++;else if(v!==this)for(;O<v.length;O++)this.words[O]=v.words[O];return this},s.prototype.add=function(f){var d;return f.negative!==0&&this.negative===0?(f.negative=0,d=this.sub(f),f.negative^=1,d):f.negative===0&&this.negative!==0?(this.negative=0,d=f.sub(this),this.negative=1,d):this.length>f.length?this.clone().iadd(f):f.clone().iadd(this)},s.prototype.isub=function(f){if(f.negative!==0){f.negative=0;var d=this.iadd(f);return f.negative=1,d._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(f),this.negative=1,this._normSign();var v=this.cmp(f);if(v===0)return this.negative=0,this.length=1,this.words[0]=0,this;var E,C;v>0?(E=this,C=f):(E=f,C=this);for(var O=0,M=0;M<C.length;M++)d=(E.words[M]|0)-(C.words[M]|0)+O,O=d>>26,this.words[M]=d&67108863;for(;O!==0&&M<E.length;M++)d=(E.words[M]|0)+O,O=d>>26,this.words[M]=d&67108863;if(O===0&&M<E.length&&E!==this)for(;M<E.length;M++)this.words[M]=E.words[M];return this.length=Math.max(this.length,M),E!==this&&(this.negative=1),this._strip()},s.prototype.sub=function(f){return this.clone().isub(f)};function K(f,d,v){v.negative=d.negative^f.negative;var E=f.length+d.length|0;v.length=E,E=E-1|0;var C=f.words[0]|0,O=d.words[0]|0,M=C*O,g=M&67108863,m=M/67108864|0;v.words[0]=g;for(var N=1;N<E;N++){for(var X=m>>>26,ae=m&67108863,P=Math.min(N,d.length-1),te=Math.max(0,N-f.length+1);te<=P;te++){var z=N-te|0;C=f.words[z]|0,O=d.words[te]|0,M=C*O+ae,X+=M/67108864|0,ae=M&67108863}v.words[N]=ae|0,m=X|0}return m!==0?v.words[N]=m|0:v.length--,v._strip()}var F=function(f,d,v){var E=f.words,C=d.words,O=v.words,M=0,g,m,N,X=E[0]|0,ae=X&8191,P=X>>>13,te=E[1]|0,z=te&8191,G=te>>>13,J=E[2]|0,A=J&8191,V=J>>>13,oe=E[3]|0,ue=oe&8191,he=oe>>>13,ye=E[4]|0,we=ye&8191,Re=ye>>>13,Xe=E[5]|0,Oe=Xe&8191,Ne=Xe>>>13,Me=E[6]|0,be=Me&8191,Pe=Me>>>13,Te=E[7]|0,ve=Te&8191,$e=Te>>>13,Se=E[8]|0,me=Se&8191,Ue=Se>>>13,Ce=E[9]|0,_e=Ce&8191,Ke=Ce>>>13,Ve=C[0]|0,Ae=Ve&8191,We=Ve>>>13,pt=C[1]|0,Ge=pt&8191,It=pt>>>13,gt=C[2]|0,Ye=gt&8191,Ot=gt>>>13,Tt=C[3]|0,Le=Tt&8191,et=Tt>>>13,it=C[4]|0,Be=it&8191,rt=it>>>13,tt=C[5]|0,qe=tt&8191,ht=tt>>>13,nt=C[6]|0,je=nt&8191,st=nt>>>13,at=C[7]|0,Fe=at&8191,Ze=at>>>13,lt=C[8]|0,ze=lt&8191,qt=lt>>>13,jt=C[9]|0,ct=jt&8191,_t=jt>>>13;v.negative=f.negative^d.negative,v.length=19,g=Math.imul(ae,Ae),m=Math.imul(ae,We),m=m+Math.imul(P,Ae)|0,N=Math.imul(P,We);var Zr=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(Zr>>>26)|0,Zr&=67108863,g=Math.imul(z,Ae),m=Math.imul(z,We),m=m+Math.imul(G,Ae)|0,N=Math.imul(G,We),g=g+Math.imul(ae,Ge)|0,m=m+Math.imul(ae,It)|0,m=m+Math.imul(P,Ge)|0,N=N+Math.imul(P,It)|0;var Xr=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(Xr>>>26)|0,Xr&=67108863,g=Math.imul(A,Ae),m=Math.imul(A,We),m=m+Math.imul(V,Ae)|0,N=Math.imul(V,We),g=g+Math.imul(z,Ge)|0,m=m+Math.imul(z,It)|0,m=m+Math.imul(G,Ge)|0,N=N+Math.imul(G,It)|0,g=g+Math.imul(ae,Ye)|0,m=m+Math.imul(ae,Ot)|0,m=m+Math.imul(P,Ye)|0,N=N+Math.imul(P,Ot)|0;var ei=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(ei>>>26)|0,ei&=67108863,g=Math.imul(ue,Ae),m=Math.imul(ue,We),m=m+Math.imul(he,Ae)|0,N=Math.imul(he,We),g=g+Math.imul(A,Ge)|0,m=m+Math.imul(A,It)|0,m=m+Math.imul(V,Ge)|0,N=N+Math.imul(V,It)|0,g=g+Math.imul(z,Ye)|0,m=m+Math.imul(z,Ot)|0,m=m+Math.imul(G,Ye)|0,N=N+Math.imul(G,Ot)|0,g=g+Math.imul(ae,Le)|0,m=m+Math.imul(ae,et)|0,m=m+Math.imul(P,Le)|0,N=N+Math.imul(P,et)|0;var ti=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(ti>>>26)|0,ti&=67108863,g=Math.imul(we,Ae),m=Math.imul(we,We),m=m+Math.imul(Re,Ae)|0,N=Math.imul(Re,We),g=g+Math.imul(ue,Ge)|0,m=m+Math.imul(ue,It)|0,m=m+Math.imul(he,Ge)|0,N=N+Math.imul(he,It)|0,g=g+Math.imul(A,Ye)|0,m=m+Math.imul(A,Ot)|0,m=m+Math.imul(V,Ye)|0,N=N+Math.imul(V,Ot)|0,g=g+Math.imul(z,Le)|0,m=m+Math.imul(z,et)|0,m=m+Math.imul(G,Le)|0,N=N+Math.imul(G,et)|0,g=g+Math.imul(ae,Be)|0,m=m+Math.imul(ae,rt)|0,m=m+Math.imul(P,Be)|0,N=N+Math.imul(P,rt)|0;var ri=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(ri>>>26)|0,ri&=67108863,g=Math.imul(Oe,Ae),m=Math.imul(Oe,We),m=m+Math.imul(Ne,Ae)|0,N=Math.imul(Ne,We),g=g+Math.imul(we,Ge)|0,m=m+Math.imul(we,It)|0,m=m+Math.imul(Re,Ge)|0,N=N+Math.imul(Re,It)|0,g=g+Math.imul(ue,Ye)|0,m=m+Math.imul(ue,Ot)|0,m=m+Math.imul(he,Ye)|0,N=N+Math.imul(he,Ot)|0,g=g+Math.imul(A,Le)|0,m=m+Math.imul(A,et)|0,m=m+Math.imul(V,Le)|0,N=N+Math.imul(V,et)|0,g=g+Math.imul(z,Be)|0,m=m+Math.imul(z,rt)|0,m=m+Math.imul(G,Be)|0,N=N+Math.imul(G,rt)|0,g=g+Math.imul(ae,qe)|0,m=m+Math.imul(ae,ht)|0,m=m+Math.imul(P,qe)|0,N=N+Math.imul(P,ht)|0;var vr=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(vr>>>26)|0,vr&=67108863,g=Math.imul(be,Ae),m=Math.imul(be,We),m=m+Math.imul(Pe,Ae)|0,N=Math.imul(Pe,We),g=g+Math.imul(Oe,Ge)|0,m=m+Math.imul(Oe,It)|0,m=m+Math.imul(Ne,Ge)|0,N=N+Math.imul(Ne,It)|0,g=g+Math.imul(we,Ye)|0,m=m+Math.imul(we,Ot)|0,m=m+Math.imul(Re,Ye)|0,N=N+Math.imul(Re,Ot)|0,g=g+Math.imul(ue,Le)|0,m=m+Math.imul(ue,et)|0,m=m+Math.imul(he,Le)|0,N=N+Math.imul(he,et)|0,g=g+Math.imul(A,Be)|0,m=m+Math.imul(A,rt)|0,m=m+Math.imul(V,Be)|0,N=N+Math.imul(V,rt)|0,g=g+Math.imul(z,qe)|0,m=m+Math.imul(z,ht)|0,m=m+Math.imul(G,qe)|0,N=N+Math.imul(G,ht)|0,g=g+Math.imul(ae,je)|0,m=m+Math.imul(ae,st)|0,m=m+Math.imul(P,je)|0,N=N+Math.imul(P,st)|0;var Ii=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(Ii>>>26)|0,Ii&=67108863,g=Math.imul(ve,Ae),m=Math.imul(ve,We),m=m+Math.imul($e,Ae)|0,N=Math.imul($e,We),g=g+Math.imul(be,Ge)|0,m=m+Math.imul(be,It)|0,m=m+Math.imul(Pe,Ge)|0,N=N+Math.imul(Pe,It)|0,g=g+Math.imul(Oe,Ye)|0,m=m+Math.imul(Oe,Ot)|0,m=m+Math.imul(Ne,Ye)|0,N=N+Math.imul(Ne,Ot)|0,g=g+Math.imul(we,Le)|0,m=m+Math.imul(we,et)|0,m=m+Math.imul(Re,Le)|0,N=N+Math.imul(Re,et)|0,g=g+Math.imul(ue,Be)|0,m=m+Math.imul(ue,rt)|0,m=m+Math.imul(he,Be)|0,N=N+Math.imul(he,rt)|0,g=g+Math.imul(A,qe)|0,m=m+Math.imul(A,ht)|0,m=m+Math.imul(V,qe)|0,N=N+Math.imul(V,ht)|0,g=g+Math.imul(z,je)|0,m=m+Math.imul(z,st)|0,m=m+Math.imul(G,je)|0,N=N+Math.imul(G,st)|0,g=g+Math.imul(ae,Fe)|0,m=m+Math.imul(ae,Ze)|0,m=m+Math.imul(P,Fe)|0,N=N+Math.imul(P,Ze)|0;var On=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(On>>>26)|0,On&=67108863,g=Math.imul(me,Ae),m=Math.imul(me,We),m=m+Math.imul(Ue,Ae)|0,N=Math.imul(Ue,We),g=g+Math.imul(ve,Ge)|0,m=m+Math.imul(ve,It)|0,m=m+Math.imul($e,Ge)|0,N=N+Math.imul($e,It)|0,g=g+Math.imul(be,Ye)|0,m=m+Math.imul(be,Ot)|0,m=m+Math.imul(Pe,Ye)|0,N=N+Math.imul(Pe,Ot)|0,g=g+Math.imul(Oe,Le)|0,m=m+Math.imul(Oe,et)|0,m=m+Math.imul(Ne,Le)|0,N=N+Math.imul(Ne,et)|0,g=g+Math.imul(we,Be)|0,m=m+Math.imul(we,rt)|0,m=m+Math.imul(Re,Be)|0,N=N+Math.imul(Re,rt)|0,g=g+Math.imul(ue,qe)|0,m=m+Math.imul(ue,ht)|0,m=m+Math.imul(he,qe)|0,N=N+Math.imul(he,ht)|0,g=g+Math.imul(A,je)|0,m=m+Math.imul(A,st)|0,m=m+Math.imul(V,je)|0,N=N+Math.imul(V,st)|0,g=g+Math.imul(z,Fe)|0,m=m+Math.imul(z,Ze)|0,m=m+Math.imul(G,Fe)|0,N=N+Math.imul(G,Ze)|0,g=g+Math.imul(ae,ze)|0,m=m+Math.imul(ae,qt)|0,m=m+Math.imul(P,ze)|0,N=N+Math.imul(P,qt)|0;var Mi=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(Mi>>>26)|0,Mi&=67108863,g=Math.imul(_e,Ae),m=Math.imul(_e,We),m=m+Math.imul(Ke,Ae)|0,N=Math.imul(Ke,We),g=g+Math.imul(me,Ge)|0,m=m+Math.imul(me,It)|0,m=m+Math.imul(Ue,Ge)|0,N=N+Math.imul(Ue,It)|0,g=g+Math.imul(ve,Ye)|0,m=m+Math.imul(ve,Ot)|0,m=m+Math.imul($e,Ye)|0,N=N+Math.imul($e,Ot)|0,g=g+Math.imul(be,Le)|0,m=m+Math.imul(be,et)|0,m=m+Math.imul(Pe,Le)|0,N=N+Math.imul(Pe,et)|0,g=g+Math.imul(Oe,Be)|0,m=m+Math.imul(Oe,rt)|0,m=m+Math.imul(Ne,Be)|0,N=N+Math.imul(Ne,rt)|0,g=g+Math.imul(we,qe)|0,m=m+Math.imul(we,ht)|0,m=m+Math.imul(Re,qe)|0,N=N+Math.imul(Re,ht)|0,g=g+Math.imul(ue,je)|0,m=m+Math.imul(ue,st)|0,m=m+Math.imul(he,je)|0,N=N+Math.imul(he,st)|0,g=g+Math.imul(A,Fe)|0,m=m+Math.imul(A,Ze)|0,m=m+Math.imul(V,Fe)|0,N=N+Math.imul(V,Ze)|0,g=g+Math.imul(z,ze)|0,m=m+Math.imul(z,qt)|0,m=m+Math.imul(G,ze)|0,N=N+Math.imul(G,qt)|0,g=g+Math.imul(ae,ct)|0,m=m+Math.imul(ae,_t)|0,m=m+Math.imul(P,ct)|0,N=N+Math.imul(P,_t)|0;var Pn=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(Pn>>>26)|0,Pn&=67108863,g=Math.imul(_e,Ge),m=Math.imul(_e,It),m=m+Math.imul(Ke,Ge)|0,N=Math.imul(Ke,It),g=g+Math.imul(me,Ye)|0,m=m+Math.imul(me,Ot)|0,m=m+Math.imul(Ue,Ye)|0,N=N+Math.imul(Ue,Ot)|0,g=g+Math.imul(ve,Le)|0,m=m+Math.imul(ve,et)|0,m=m+Math.imul($e,Le)|0,N=N+Math.imul($e,et)|0,g=g+Math.imul(be,Be)|0,m=m+Math.imul(be,rt)|0,m=m+Math.imul(Pe,Be)|0,N=N+Math.imul(Pe,rt)|0,g=g+Math.imul(Oe,qe)|0,m=m+Math.imul(Oe,ht)|0,m=m+Math.imul(Ne,qe)|0,N=N+Math.imul(Ne,ht)|0,g=g+Math.imul(we,je)|0,m=m+Math.imul(we,st)|0,m=m+Math.imul(Re,je)|0,N=N+Math.imul(Re,st)|0,g=g+Math.imul(ue,Fe)|0,m=m+Math.imul(ue,Ze)|0,m=m+Math.imul(he,Fe)|0,N=N+Math.imul(he,Ze)|0,g=g+Math.imul(A,ze)|0,m=m+Math.imul(A,qt)|0,m=m+Math.imul(V,ze)|0,N=N+Math.imul(V,qt)|0,g=g+Math.imul(z,ct)|0,m=m+Math.imul(z,_t)|0,m=m+Math.imul(G,ct)|0,N=N+Math.imul(G,_t)|0;var $n=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+($n>>>26)|0,$n&=67108863,g=Math.imul(_e,Ye),m=Math.imul(_e,Ot),m=m+Math.imul(Ke,Ye)|0,N=Math.imul(Ke,Ot),g=g+Math.imul(me,Le)|0,m=m+Math.imul(me,et)|0,m=m+Math.imul(Ue,Le)|0,N=N+Math.imul(Ue,et)|0,g=g+Math.imul(ve,Be)|0,m=m+Math.imul(ve,rt)|0,m=m+Math.imul($e,Be)|0,N=N+Math.imul($e,rt)|0,g=g+Math.imul(be,qe)|0,m=m+Math.imul(be,ht)|0,m=m+Math.imul(Pe,qe)|0,N=N+Math.imul(Pe,ht)|0,g=g+Math.imul(Oe,je)|0,m=m+Math.imul(Oe,st)|0,m=m+Math.imul(Ne,je)|0,N=N+Math.imul(Ne,st)|0,g=g+Math.imul(we,Fe)|0,m=m+Math.imul(we,Ze)|0,m=m+Math.imul(Re,Fe)|0,N=N+Math.imul(Re,Ze)|0,g=g+Math.imul(ue,ze)|0,m=m+Math.imul(ue,qt)|0,m=m+Math.imul(he,ze)|0,N=N+Math.imul(he,qt)|0,g=g+Math.imul(A,ct)|0,m=m+Math.imul(A,_t)|0,m=m+Math.imul(V,ct)|0,N=N+Math.imul(V,_t)|0;var Ci=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(Ci>>>26)|0,Ci&=67108863,g=Math.imul(_e,Le),m=Math.imul(_e,et),m=m+Math.imul(Ke,Le)|0,N=Math.imul(Ke,et),g=g+Math.imul(me,Be)|0,m=m+Math.imul(me,rt)|0,m=m+Math.imul(Ue,Be)|0,N=N+Math.imul(Ue,rt)|0,g=g+Math.imul(ve,qe)|0,m=m+Math.imul(ve,ht)|0,m=m+Math.imul($e,qe)|0,N=N+Math.imul($e,ht)|0,g=g+Math.imul(be,je)|0,m=m+Math.imul(be,st)|0,m=m+Math.imul(Pe,je)|0,N=N+Math.imul(Pe,st)|0,g=g+Math.imul(Oe,Fe)|0,m=m+Math.imul(Oe,Ze)|0,m=m+Math.imul(Ne,Fe)|0,N=N+Math.imul(Ne,Ze)|0,g=g+Math.imul(we,ze)|0,m=m+Math.imul(we,qt)|0,m=m+Math.imul(Re,ze)|0,N=N+Math.imul(Re,qt)|0,g=g+Math.imul(ue,ct)|0,m=m+Math.imul(ue,_t)|0,m=m+Math.imul(he,ct)|0,N=N+Math.imul(he,_t)|0;var an=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(an>>>26)|0,an&=67108863,g=Math.imul(_e,Be),m=Math.imul(_e,rt),m=m+Math.imul(Ke,Be)|0,N=Math.imul(Ke,rt),g=g+Math.imul(me,qe)|0,m=m+Math.imul(me,ht)|0,m=m+Math.imul(Ue,qe)|0,N=N+Math.imul(Ue,ht)|0,g=g+Math.imul(ve,je)|0,m=m+Math.imul(ve,st)|0,m=m+Math.imul($e,je)|0,N=N+Math.imul($e,st)|0,g=g+Math.imul(be,Fe)|0,m=m+Math.imul(be,Ze)|0,m=m+Math.imul(Pe,Fe)|0,N=N+Math.imul(Pe,Ze)|0,g=g+Math.imul(Oe,ze)|0,m=m+Math.imul(Oe,qt)|0,m=m+Math.imul(Ne,ze)|0,N=N+Math.imul(Ne,qt)|0,g=g+Math.imul(we,ct)|0,m=m+Math.imul(we,_t)|0,m=m+Math.imul(Re,ct)|0,N=N+Math.imul(Re,_t)|0;var cn=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(cn>>>26)|0,cn&=67108863,g=Math.imul(_e,qe),m=Math.imul(_e,ht),m=m+Math.imul(Ke,qe)|0,N=Math.imul(Ke,ht),g=g+Math.imul(me,je)|0,m=m+Math.imul(me,st)|0,m=m+Math.imul(Ue,je)|0,N=N+Math.imul(Ue,st)|0,g=g+Math.imul(ve,Fe)|0,m=m+Math.imul(ve,Ze)|0,m=m+Math.imul($e,Fe)|0,N=N+Math.imul($e,Ze)|0,g=g+Math.imul(be,ze)|0,m=m+Math.imul(be,qt)|0,m=m+Math.imul(Pe,ze)|0,N=N+Math.imul(Pe,qt)|0,g=g+Math.imul(Oe,ct)|0,m=m+Math.imul(Oe,_t)|0,m=m+Math.imul(Ne,ct)|0,N=N+Math.imul(Ne,_t)|0;var Cr=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(Cr>>>26)|0,Cr&=67108863,g=Math.imul(_e,je),m=Math.imul(_e,st),m=m+Math.imul(Ke,je)|0,N=Math.imul(Ke,st),g=g+Math.imul(me,Fe)|0,m=m+Math.imul(me,Ze)|0,m=m+Math.imul(Ue,Fe)|0,N=N+Math.imul(Ue,Ze)|0,g=g+Math.imul(ve,ze)|0,m=m+Math.imul(ve,qt)|0,m=m+Math.imul($e,ze)|0,N=N+Math.imul($e,qt)|0,g=g+Math.imul(be,ct)|0,m=m+Math.imul(be,_t)|0,m=m+Math.imul(Pe,ct)|0,N=N+Math.imul(Pe,_t)|0;var Rn=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(Rn>>>26)|0,Rn&=67108863,g=Math.imul(_e,Fe),m=Math.imul(_e,Ze),m=m+Math.imul(Ke,Fe)|0,N=Math.imul(Ke,Ze),g=g+Math.imul(me,ze)|0,m=m+Math.imul(me,qt)|0,m=m+Math.imul(Ue,ze)|0,N=N+Math.imul(Ue,qt)|0,g=g+Math.imul(ve,ct)|0,m=m+Math.imul(ve,_t)|0,m=m+Math.imul($e,ct)|0,N=N+Math.imul($e,_t)|0;var Nn=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(Nn>>>26)|0,Nn&=67108863,g=Math.imul(_e,ze),m=Math.imul(_e,qt),m=m+Math.imul(Ke,ze)|0,N=Math.imul(Ke,qt),g=g+Math.imul(me,ct)|0,m=m+Math.imul(me,_t)|0,m=m+Math.imul(Ue,ct)|0,N=N+Math.imul(Ue,_t)|0;var Tn=(M+g|0)+((m&8191)<<13)|0;M=(N+(m>>>13)|0)+(Tn>>>26)|0,Tn&=67108863,g=Math.imul(_e,ct),m=Math.imul(_e,_t),m=m+Math.imul(Ke,ct)|0,N=Math.imul(Ke,_t);var va=(M+g|0)+((m&8191)<<13)|0;return M=(N+(m>>>13)|0)+(va>>>26)|0,va&=67108863,O[0]=Zr,O[1]=Xr,O[2]=ei,O[3]=ti,O[4]=ri,O[5]=vr,O[6]=Ii,O[7]=On,O[8]=Mi,O[9]=Pn,O[10]=$n,O[11]=Ci,O[12]=an,O[13]=cn,O[14]=Cr,O[15]=Rn,O[16]=Nn,O[17]=Tn,O[18]=va,M!==0&&(O[19]=M,v.length++),v};Math.imul||(F=K);function W(f,d,v){v.negative=d.negative^f.negative,v.length=f.length+d.length;for(var E=0,C=0,O=0;O<v.length-1;O++){var M=C;C=0;for(var g=E&67108863,m=Math.min(O,d.length-1),N=Math.max(0,O-f.length+1);N<=m;N++){var X=O-N,ae=f.words[X]|0,P=d.words[N]|0,te=ae*P,z=te&67108863;M=M+(te/67108864|0)|0,z=z+g|0,g=z&67108863,M=M+(z>>>26)|0,C+=M>>>26,M&=67108863}v.words[O]=g,E=M,M=C}return E!==0?v.words[O]=E:v.length--,v._strip()}function R(f,d,v){return W(f,d,v)}s.prototype.mulTo=function(f,d){var v,E=this.length+f.length;return this.length===10&&f.length===10?v=F(this,f,d):E<63?v=K(this,f,d):E<1024?v=W(this,f,d):v=R(this,f,d),v},s.prototype.mul=function(f){var d=new s(null);return d.words=new Array(this.length+f.length),this.mulTo(f,d)},s.prototype.mulf=function(f){var d=new s(null);return d.words=new Array(this.length+f.length),R(this,f,d)},s.prototype.imul=function(f){return this.clone().mulTo(f,this)},s.prototype.imuln=function(f){var d=f<0;d&&(f=-f),i(typeof f=="number"),i(f<67108864);for(var v=0,E=0;E<this.length;E++){var C=(this.words[E]|0)*f,O=(C&67108863)+(v&67108863);v>>=26,v+=C/67108864|0,v+=O>>>26,this.words[E]=O&67108863}return v!==0&&(this.words[E]=v,this.length++),d?this.ineg():this},s.prototype.muln=function(f){return this.clone().imuln(f)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(f){var d=q(f);if(d.length===0)return new s(1);for(var v=this,E=0;E<d.length&&d[E]===0;E++,v=v.sqr());if(++E<d.length)for(var C=v.sqr();E<d.length;E++,C=C.sqr())d[E]!==0&&(v=v.mul(C));return v},s.prototype.iushln=function(f){i(typeof f=="number"&&f>=0);var d=f%26,v=(f-d)/26,E=67108863>>>26-d<<26-d,C;if(d!==0){var O=0;for(C=0;C<this.length;C++){var M=this.words[C]&E,g=(this.words[C]|0)-M<<d;this.words[C]=g|O,O=M>>>26-d}O&&(this.words[C]=O,this.length++)}if(v!==0){for(C=this.length-1;C>=0;C--)this.words[C+v]=this.words[C];for(C=0;C<v;C++)this.words[C]=0;this.length+=v}return this._strip()},s.prototype.ishln=function(f){return i(this.negative===0),this.iushln(f)},s.prototype.iushrn=function(f,d,v){i(typeof f=="number"&&f>=0);var E;d?E=(d-d%26)/26:E=0;var C=f%26,O=Math.min((f-C)/26,this.length),M=67108863^67108863>>>C<<C,g=v;if(E-=O,E=Math.max(0,E),g){for(var m=0;m<O;m++)g.words[m]=this.words[m];g.length=O}if(O!==0)if(this.length>O)for(this.length-=O,m=0;m<this.length;m++)this.words[m]=this.words[m+O];else this.words[0]=0,this.length=1;var N=0;for(m=this.length-1;m>=0&&(N!==0||m>=E);m--){var X=this.words[m]|0;this.words[m]=N<<26-C|X>>>C,N=X&M}return g&&N!==0&&(g.words[g.length++]=N),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(f,d,v){return i(this.negative===0),this.iushrn(f,d,v)},s.prototype.shln=function(f){return this.clone().ishln(f)},s.prototype.ushln=function(f){return this.clone().iushln(f)},s.prototype.shrn=function(f){return this.clone().ishrn(f)},s.prototype.ushrn=function(f){return this.clone().iushrn(f)},s.prototype.testn=function(f){i(typeof f=="number"&&f>=0);var d=f%26,v=(f-d)/26,E=1<<d;if(this.length<=v)return!1;var C=this.words[v];return!!(C&E)},s.prototype.imaskn=function(f){i(typeof f=="number"&&f>=0);var d=f%26,v=(f-d)/26;if(i(this.negative===0,"imaskn works only with positive numbers"),this.length<=v)return this;if(d!==0&&v++,this.length=Math.min(v,this.length),d!==0){var E=67108863^67108863>>>d<<d;this.words[this.length-1]&=E}return this._strip()},s.prototype.maskn=function(f){return this.clone().imaskn(f)},s.prototype.iaddn=function(f){return i(typeof f=="number"),i(f<67108864),f<0?this.isubn(-f):this.negative!==0?this.length===1&&(this.words[0]|0)<=f?(this.words[0]=f-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(f),this.negative=1,this):this._iaddn(f)},s.prototype._iaddn=function(f){this.words[0]+=f;for(var d=0;d<this.length&&this.words[d]>=67108864;d++)this.words[d]-=67108864,d===this.length-1?this.words[d+1]=1:this.words[d+1]++;return this.length=Math.max(this.length,d+1),this},s.prototype.isubn=function(f){if(i(typeof f=="number"),i(f<67108864),f<0)return this.iaddn(-f);if(this.negative!==0)return this.negative=0,this.iaddn(f),this.negative=1,this;if(this.words[0]-=f,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var d=0;d<this.length&&this.words[d]<0;d++)this.words[d]+=67108864,this.words[d+1]-=1;return this._strip()},s.prototype.addn=function(f){return this.clone().iaddn(f)},s.prototype.subn=function(f){return this.clone().isubn(f)},s.prototype.iabs=function(){return this.negative=0,this},s.prototype.abs=function(){return this.clone().iabs()},s.prototype._ishlnsubmul=function(f,d,v){var E=f.length+v,C;this._expand(E);var O,M=0;for(C=0;C<f.length;C++){O=(this.words[C+v]|0)+M;var g=(f.words[C]|0)*d;O-=g&67108863,M=(O>>26)-(g/67108864|0),this.words[C+v]=O&67108863}for(;C<this.length-v;C++)O=(this.words[C+v]|0)+M,M=O>>26,this.words[C+v]=O&67108863;if(M===0)return this._strip();for(i(M===-1),M=0,C=0;C<this.length;C++)O=-(this.words[C]|0)+M,M=O>>26,this.words[C]=O&67108863;return this.negative=1,this._strip()},s.prototype._wordDiv=function(f,d){var v=this.length-f.length,E=this.clone(),C=f,O=C.words[C.length-1]|0,M=this._countBits(O);v=26-M,v!==0&&(C=C.ushln(v),E.iushln(v),O=C.words[C.length-1]|0);var g=E.length-C.length,m;if(d!=="mod"){m=new s(null),m.length=g+1,m.words=new Array(m.length);for(var N=0;N<m.length;N++)m.words[N]=0}var X=E.clone()._ishlnsubmul(C,1,g);X.negative===0&&(E=X,m&&(m.words[g]=1));for(var ae=g-1;ae>=0;ae--){var P=(E.words[C.length+ae]|0)*67108864+(E.words[C.length+ae-1]|0);for(P=Math.min(P/O|0,67108863),E._ishlnsubmul(C,P,ae);E.negative!==0;)P--,E.negative=0,E._ishlnsubmul(C,1,ae),E.isZero()||(E.negative^=1);m&&(m.words[ae]=P)}return m&&m._strip(),E._strip(),d!=="div"&&v!==0&&E.iushrn(v),{div:m||null,mod:E}},s.prototype.divmod=function(f,d,v){if(i(!f.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var E,C,O;return this.negative!==0&&f.negative===0?(O=this.neg().divmod(f,d),d!=="mod"&&(E=O.div.neg()),d!=="div"&&(C=O.mod.neg(),v&&C.negative!==0&&C.iadd(f)),{div:E,mod:C}):this.negative===0&&f.negative!==0?(O=this.divmod(f.neg(),d),d!=="mod"&&(E=O.div.neg()),{div:E,mod:O.mod}):this.negative&f.negative?(O=this.neg().divmod(f.neg(),d),d!=="div"&&(C=O.mod.neg(),v&&C.negative!==0&&C.isub(f)),{div:O.div,mod:C}):f.length>this.length||this.cmp(f)<0?{div:new s(0),mod:this}:f.length===1?d==="div"?{div:this.divn(f.words[0]),mod:null}:d==="mod"?{div:null,mod:new s(this.modrn(f.words[0]))}:{div:this.divn(f.words[0]),mod:new s(this.modrn(f.words[0]))}:this._wordDiv(f,d)},s.prototype.div=function(f){return this.divmod(f,"div",!1).div},s.prototype.mod=function(f){return this.divmod(f,"mod",!1).mod},s.prototype.umod=function(f){return this.divmod(f,"mod",!0).mod},s.prototype.divRound=function(f){var d=this.divmod(f);if(d.mod.isZero())return d.div;var v=d.div.negative!==0?d.mod.isub(f):d.mod,E=f.ushrn(1),C=f.andln(1),O=v.cmp(E);return O<0||C===1&&O===0?d.div:d.div.negative!==0?d.div.isubn(1):d.div.iaddn(1)},s.prototype.modrn=function(f){var d=f<0;d&&(f=-f),i(f<=67108863);for(var v=(1<<26)%f,E=0,C=this.length-1;C>=0;C--)E=(v*E+(this.words[C]|0))%f;return d?-E:E},s.prototype.modn=function(f){return this.modrn(f)},s.prototype.idivn=function(f){var d=f<0;d&&(f=-f),i(f<=67108863);for(var v=0,E=this.length-1;E>=0;E--){var C=(this.words[E]|0)+v*67108864;this.words[E]=C/f|0,v=C%f}return this._strip(),d?this.ineg():this},s.prototype.divn=function(f){return this.clone().idivn(f)},s.prototype.egcd=function(f){i(f.negative===0),i(!f.isZero());var d=this,v=f.clone();d.negative!==0?d=d.umod(f):d=d.clone();for(var E=new s(1),C=new s(0),O=new s(0),M=new s(1),g=0;d.isEven()&&v.isEven();)d.iushrn(1),v.iushrn(1),++g;for(var m=v.clone(),N=d.clone();!d.isZero();){for(var X=0,ae=1;!(d.words[0]&ae)&&X<26;++X,ae<<=1);if(X>0)for(d.iushrn(X);X-- >0;)(E.isOdd()||C.isOdd())&&(E.iadd(m),C.isub(N)),E.iushrn(1),C.iushrn(1);for(var P=0,te=1;!(v.words[0]&te)&&P<26;++P,te<<=1);if(P>0)for(v.iushrn(P);P-- >0;)(O.isOdd()||M.isOdd())&&(O.iadd(m),M.isub(N)),O.iushrn(1),M.iushrn(1);d.cmp(v)>=0?(d.isub(v),E.isub(O),C.isub(M)):(v.isub(d),O.isub(E),M.isub(C))}return{a:O,b:M,gcd:v.iushln(g)}},s.prototype._invmp=function(f){i(f.negative===0),i(!f.isZero());var d=this,v=f.clone();d.negative!==0?d=d.umod(f):d=d.clone();for(var E=new s(1),C=new s(0),O=v.clone();d.cmpn(1)>0&&v.cmpn(1)>0;){for(var M=0,g=1;!(d.words[0]&g)&&M<26;++M,g<<=1);if(M>0)for(d.iushrn(M);M-- >0;)E.isOdd()&&E.iadd(O),E.iushrn(1);for(var m=0,N=1;!(v.words[0]&N)&&m<26;++m,N<<=1);if(m>0)for(v.iushrn(m);m-- >0;)C.isOdd()&&C.iadd(O),C.iushrn(1);d.cmp(v)>=0?(d.isub(v),E.isub(C)):(v.isub(d),C.isub(E))}var X;return d.cmpn(1)===0?X=E:X=C,X.cmpn(0)<0&&X.iadd(f),X},s.prototype.gcd=function(f){if(this.isZero())return f.abs();if(f.isZero())return this.abs();var d=this.clone(),v=f.clone();d.negative=0,v.negative=0;for(var E=0;d.isEven()&&v.isEven();E++)d.iushrn(1),v.iushrn(1);do{for(;d.isEven();)d.iushrn(1);for(;v.isEven();)v.iushrn(1);var C=d.cmp(v);if(C<0){var O=d;d=v,v=O}else if(C===0||v.cmpn(1)===0)break;d.isub(v)}while(!0);return v.iushln(E)},s.prototype.invm=function(f){return this.egcd(f).a.umod(f)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(f){return this.words[0]&f},s.prototype.bincn=function(f){i(typeof f=="number");var d=f%26,v=(f-d)/26,E=1<<d;if(this.length<=v)return this._expand(v+1),this.words[v]|=E,this;for(var C=E,O=v;C!==0&&O<this.length;O++){var M=this.words[O]|0;M+=C,C=M>>>26,M&=67108863,this.words[O]=M}return C!==0&&(this.words[O]=C,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(f){var d=f<0;if(this.negative!==0&&!d)return-1;if(this.negative===0&&d)return 1;this._strip();var v;if(this.length>1)v=1;else{d&&(f=-f),i(f<=67108863,"Number is too big");var E=this.words[0]|0;v=E===f?0:E<f?-1:1}return this.negative!==0?-v|0:v},s.prototype.cmp=function(f){if(this.negative!==0&&f.negative===0)return-1;if(this.negative===0&&f.negative!==0)return 1;var d=this.ucmp(f);return this.negative!==0?-d|0:d},s.prototype.ucmp=function(f){if(this.length>f.length)return 1;if(this.length<f.length)return-1;for(var d=0,v=this.length-1;v>=0;v--){var E=this.words[v]|0,C=f.words[v]|0;if(E!==C){E<C?d=-1:E>C&&(d=1);break}}return d},s.prototype.gtn=function(f){return this.cmpn(f)===1},s.prototype.gt=function(f){return this.cmp(f)===1},s.prototype.gten=function(f){return this.cmpn(f)>=0},s.prototype.gte=function(f){return this.cmp(f)>=0},s.prototype.ltn=function(f){return this.cmpn(f)===-1},s.prototype.lt=function(f){return this.cmp(f)===-1},s.prototype.lten=function(f){return this.cmpn(f)<=0},s.prototype.lte=function(f){return this.cmp(f)<=0},s.prototype.eqn=function(f){return this.cmpn(f)===0},s.prototype.eq=function(f){return this.cmp(f)===0},s.red=function(f){return new L(f)},s.prototype.toRed=function(f){return i(!this.red,"Already a number in reduction context"),i(this.negative===0,"red works only with positives"),f.convertTo(this)._forceRed(f)},s.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(f){return this.red=f,this},s.prototype.forceRed=function(f){return i(!this.red,"Already a number in reduction context"),this._forceRed(f)},s.prototype.redAdd=function(f){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,f)},s.prototype.redIAdd=function(f){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,f)},s.prototype.redSub=function(f){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,f)},s.prototype.redISub=function(f){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,f)},s.prototype.redShl=function(f){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,f)},s.prototype.redMul=function(f){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,f),this.red.mul(this,f)},s.prototype.redIMul=function(f){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,f),this.red.imul(this,f)},s.prototype.redSqr=function(){return i(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return i(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return i(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return i(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return i(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(f){return i(this.red&&!f.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,f)};var k={k256:null,p224:null,p192:null,p25519:null};function H(f,d){this.name=f,this.p=new s(d,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}H.prototype._tmp=function(){var f=new s(null);return f.words=new Array(Math.ceil(this.n/13)),f},H.prototype.ireduce=function(f){var d=f,v;do this.split(d,this.tmp),d=this.imulK(d),d=d.iadd(this.tmp),v=d.bitLength();while(v>this.n);var E=v<this.n?-1:d.ucmp(this.p);return E===0?(d.words[0]=0,d.length=1):E>0?d.isub(this.p):d.strip!==void 0?d.strip():d._strip(),d},H.prototype.split=function(f,d){f.iushrn(this.n,0,d)},H.prototype.imulK=function(f){return f.imul(this.k)};function _(){H.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(_,H),_.prototype.split=function(f,d){for(var v=4194303,E=Math.min(f.length,9),C=0;C<E;C++)d.words[C]=f.words[C];if(d.length=E,f.length<=9){f.words[0]=0,f.length=1;return}var O=f.words[9];for(d.words[d.length++]=O&v,C=10;C<f.length;C++){var M=f.words[C]|0;f.words[C-10]=(M&v)<<4|O>>>22,O=M}O>>>=22,f.words[C-10]=O,O===0&&f.length>10?f.length-=10:f.length-=9},_.prototype.imulK=function(f){f.words[f.length]=0,f.words[f.length+1]=0,f.length+=2;for(var d=0,v=0;v<f.length;v++){var E=f.words[v]|0;d+=E*977,f.words[v]=d&67108863,d=E*64+(d/67108864|0)}return f.words[f.length-1]===0&&(f.length--,f.words[f.length-1]===0&&f.length--),f};function B(){H.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(B,H);function ee(){H.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(ee,H);function ie(){H.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(ie,H),ie.prototype.imulK=function(f){for(var d=0,v=0;v<f.length;v++){var E=(f.words[v]|0)*19+d,C=E&67108863;E>>>=26,f.words[v]=C,d=E}return d!==0&&(f.words[f.length++]=d),f},s._prime=function(f){if(k[f])return k[f];var d;if(f==="k256")d=new _;else if(f==="p224")d=new B;else if(f==="p192")d=new ee;else if(f==="p25519")d=new ie;else throw new Error("Unknown prime "+f);return k[f]=d,d};function L(f){if(typeof f=="string"){var d=s._prime(f);this.m=d.p,this.prime=d}else i(f.gtn(1),"modulus must be greater than 1"),this.m=f,this.prime=null}L.prototype._verify1=function(f){i(f.negative===0,"red works only with positives"),i(f.red,"red works only with red numbers")},L.prototype._verify2=function(f,d){i((f.negative|d.negative)===0,"red works only with positives"),i(f.red&&f.red===d.red,"red works only with red numbers")},L.prototype.imod=function(f){return this.prime?this.prime.ireduce(f)._forceRed(this):(b(f,f.umod(this.m)._forceRed(this)),f)},L.prototype.neg=function(f){return f.isZero()?f.clone():this.m.sub(f)._forceRed(this)},L.prototype.add=function(f,d){this._verify2(f,d);var v=f.add(d);return v.cmp(this.m)>=0&&v.isub(this.m),v._forceRed(this)},L.prototype.iadd=function(f,d){this._verify2(f,d);var v=f.iadd(d);return v.cmp(this.m)>=0&&v.isub(this.m),v},L.prototype.sub=function(f,d){this._verify2(f,d);var v=f.sub(d);return v.cmpn(0)<0&&v.iadd(this.m),v._forceRed(this)},L.prototype.isub=function(f,d){this._verify2(f,d);var v=f.isub(d);return v.cmpn(0)<0&&v.iadd(this.m),v},L.prototype.shl=function(f,d){return this._verify1(f),this.imod(f.ushln(d))},L.prototype.imul=function(f,d){return this._verify2(f,d),this.imod(f.imul(d))},L.prototype.mul=function(f,d){return this._verify2(f,d),this.imod(f.mul(d))},L.prototype.isqr=function(f){return this.imul(f,f.clone())},L.prototype.sqr=function(f){return this.mul(f,f)},L.prototype.sqrt=function(f){if(f.isZero())return f.clone();var d=this.m.andln(3);if(i(d%2===1),d===3){var v=this.m.add(new s(1)).iushrn(2);return this.pow(f,v)}for(var E=this.m.subn(1),C=0;!E.isZero()&&E.andln(1)===0;)C++,E.iushrn(1);i(!E.isZero());var O=new s(1).toRed(this),M=O.redNeg(),g=this.m.subn(1).iushrn(1),m=this.m.bitLength();for(m=new s(2*m*m).toRed(this);this.pow(m,g).cmp(M)!==0;)m.redIAdd(M);for(var N=this.pow(m,E),X=this.pow(f,E.addn(1).iushrn(1)),ae=this.pow(f,E),P=C;ae.cmp(O)!==0;){for(var te=ae,z=0;te.cmp(O)!==0;z++)te=te.redSqr();i(z<P);var G=this.pow(N,new s(1).iushln(P-z-1));X=X.redMul(G),N=G.redSqr(),ae=ae.redMul(N),P=z}return X},L.prototype.invm=function(f){var d=f._invmp(this.m);return d.negative!==0?(d.negative=0,this.imod(d).redNeg()):this.imod(d)},L.prototype.pow=function(f,d){if(d.isZero())return new s(1).toRed(this);if(d.cmpn(1)===0)return f.clone();var v=4,E=new Array(1<<v);E[0]=new s(1).toRed(this),E[1]=f;for(var C=2;C<E.length;C++)E[C]=this.mul(E[C-1],f);var O=E[0],M=0,g=0,m=d.bitLength()%26;for(m===0&&(m=26),C=d.length-1;C>=0;C--){for(var N=d.words[C],X=m-1;X>=0;X--){var ae=N>>X&1;if(O!==E[0]&&(O=this.sqr(O)),ae===0&&M===0){g=0;continue}M<<=1,M|=ae,g++,!(g!==v&&(C!==0||X!==0))&&(O=this.mul(O,E[M]),g=0,M=0)}m=26}return O},L.prototype.convertTo=function(f){var d=f.umod(this.m);return d===f?d.clone():d},L.prototype.convertFrom=function(f){var d=f.clone();return d.red=null,d},s.mont=function(f){return new y(f)};function y(f){L.call(this,f),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}n(y,L),y.prototype.convertTo=function(f){return this.imod(f.ushln(this.shift))},y.prototype.convertFrom=function(f){var d=this.imod(f.mul(this.rinv));return d.red=null,d},y.prototype.imul=function(f,d){if(f.isZero()||d.isZero())return f.words[0]=0,f.length=1,f;var v=f.imul(d),E=v.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),C=v.isub(E).iushrn(this.shift),O=C;return C.cmp(this.m)>=0?O=C.isub(this.m):C.cmpn(0)<0&&(O=C.iadd(this.m)),O._forceRed(this)},y.prototype.mul=function(f,d){if(f.isZero()||d.isZero())return new s(0)._forceRed(this);var v=f.mul(d),E=v.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),C=v.isub(E).iushrn(this.shift),O=C;return C.cmp(this.m)>=0?O=C.isub(this.m):C.cmpn(0)<0&&(O=C.iadd(this.m)),O._forceRed(this)},y.prototype.invm=function(f){var d=this.imod(f._invmp(this.m).mul(this.r2));return d._forceRed(this)}})(t,Z2)})(um);var mt=um.exports;const fm="bignumber/5.7.0";var nh=mt.BN;const Ds=new Et(fm),ld={},hm=9007199254740991;function bA(t){return t!=null&&(sr.isBigNumber(t)||typeof t=="number"&&t%1===0||typeof t=="string"&&!!t.match(/^-?[0-9]+$/)||Fi(t)||typeof t=="bigint"||Ya(t))}let lm=!1;class sr{constructor(e,r){e!==ld&&Ds.throwError("cannot call constructor directly; use BigNumber.from",Et.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=r,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return yi(Rt(this).fromTwos(e))}toTwos(e){return yi(Rt(this).toTwos(e))}abs(){return this._hex[0]==="-"?sr.from(this._hex.substring(1)):this}add(e){return yi(Rt(this).add(Rt(e)))}sub(e){return yi(Rt(this).sub(Rt(e)))}div(e){return sr.from(e).isZero()&&Zi("division-by-zero","div"),yi(Rt(this).div(Rt(e)))}mul(e){return yi(Rt(this).mul(Rt(e)))}mod(e){const r=Rt(e);return r.isNeg()&&Zi("division-by-zero","mod"),yi(Rt(this).umod(r))}pow(e){const r=Rt(e);return r.isNeg()&&Zi("negative-power","pow"),yi(Rt(this).pow(r))}and(e){const r=Rt(e);return(this.isNegative()||r.isNeg())&&Zi("unbound-bitwise-result","and"),yi(Rt(this).and(r))}or(e){const r=Rt(e);return(this.isNegative()||r.isNeg())&&Zi("unbound-bitwise-result","or"),yi(Rt(this).or(r))}xor(e){const r=Rt(e);return(this.isNegative()||r.isNeg())&&Zi("unbound-bitwise-result","xor"),yi(Rt(this).xor(r))}mask(e){return(this.isNegative()||e<0)&&Zi("negative-width","mask"),yi(Rt(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Zi("negative-width","shl"),yi(Rt(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Zi("negative-width","shr"),yi(Rt(this).shrn(e))}eq(e){return Rt(this).eq(Rt(e))}lt(e){return Rt(this).lt(Rt(e))}lte(e){return Rt(this).lte(Rt(e))}gt(e){return Rt(this).gt(Rt(e))}gte(e){return Rt(this).gte(Rt(e))}isNegative(){return this._hex[0]==="-"}isZero(){return Rt(this).isZero()}toNumber(){try{return Rt(this).toNumber()}catch{Zi("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch{}return Ds.throwError("this platform does not support BigInt",Et.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(arguments[0]===10?lm||(lm=!0,Ds.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):arguments[0]===16?Ds.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",Et.errors.UNEXPECTED_ARGUMENT,{}):Ds.throwError("BigNumber.toString does not accept parameters",Et.errors.UNEXPECTED_ARGUMENT,{})),Rt(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof sr)return e;if(typeof e=="string")return e.match(/^-?0x[0-9a-f]+$/i)?new sr(ld,uu(e)):e.match(/^-?[0-9]+$/)?new sr(ld,uu(new nh(e))):Ds.throwArgumentError("invalid BigNumber string","value",e);if(typeof e=="number")return e%1&&Zi("underflow","BigNumber.from",e),(e>=hm||e<=-hm)&&Zi("overflow","BigNumber.from",e),sr.from(String(e));const r=e;if(typeof r=="bigint")return sr.from(r.toString());if(Ya(r))return sr.from(si(r));if(r)if(r.toHexString){const i=r.toHexString();if(typeof i=="string")return sr.from(i)}else{let i=r._hex;if(i==null&&r.type==="BigNumber"&&(i=r.hex),typeof i=="string"&&(Fi(i)||i[0]==="-"&&Fi(i.substring(1))))return sr.from(i)}return Ds.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!!(e&&e._isBigNumber)}}function uu(t){if(typeof t!="string")return uu(t.toString(16));if(t[0]==="-")return t=t.substring(1),t[0]==="-"&&Ds.throwArgumentError("invalid hex","value",t),t=uu(t),t==="0x00"?t:"-"+t;if(t.substring(0,2)!=="0x"&&(t="0x"+t),t==="0x")return"0x00";for(t.length%2&&(t="0x0"+t.substring(2));t.length>4&&t.substring(0,4)==="0x00";)t="0x"+t.substring(4);return t}function yi(t){return sr.from(uu(t))}function Rt(t){const e=sr.from(t).toHexString();return e[0]==="-"?new nh("-"+e.substring(3),16):new nh(e.substring(2),16)}function Zi(t,e,r){const i={fault:t,operation:e};return r!=null&&(i.value=r),Ds.throwError(t,Et.errors.NUMERIC_FAULT,i)}function yA(t){return new nh(t,36).toString(16)}const oi=new Et(fm),fu={},dm=sr.from(0),pm=sr.from(-1);function gm(t,e,r,i){const n={fault:e,operation:r};return i!==void 0&&(n.value=i),oi.throwError(t,Et.errors.NUMERIC_FAULT,n)}let hu="0";for(;hu.length<256;)hu+=hu;function dd(t){if(typeof t!="number")try{t=sr.from(t).toNumber()}catch{}return typeof t=="number"&&t>=0&&t<=256&&!(t%1)?"1"+hu.substring(0,t):oi.throwArgumentError("invalid decimal size","decimals",t)}function pd(t,e){e==null&&(e=0);const r=dd(e);t=sr.from(t);const i=t.lt(dm);i&&(t=t.mul(pm));let n=t.mod(r).toString();for(;n.length<r.length-1;)n="0"+n;n=n.match(/^([0-9]*[1-9]|0)(0*)/)[1];const s=t.div(r).toString();return r.length===1?t=s:t=s+"."+n,i&&(t="-"+t),t}function Os(t,e){e==null&&(e=0);const r=dd(e);(typeof t!="string"||!t.match(/^-?[0-9.]+$/))&&oi.throwArgumentError("invalid decimal value","value",t);const i=t.substring(0,1)==="-";i&&(t=t.substring(1)),t==="."&&oi.throwArgumentError("missing value","value",t);const n=t.split(".");n.length>2&&oi.throwArgumentError("too many decimal points","value",t);let s=n[0],a=n[1];for(s||(s="0"),a||(a="0");a[a.length-1]==="0";)a=a.substring(0,a.length-1);for(a.length>r.length-1&&gm("fractional component exceeds decimals","underflow","parseFixed"),a===""&&(a="0");a.length<r.length-1;)a+="0";const u=sr.from(s),h=sr.from(a);let l=u.mul(r).add(h);return i&&(l=l.mul(pm)),l}class Qa{constructor(e,r,i,n){e!==fu&&oi.throwError("cannot use FixedFormat constructor; use FixedFormat.from",Et.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.signed=r,this.width=i,this.decimals=n,this.name=(r?"":"u")+"fixed"+String(i)+"x"+String(n),this._multiplier=dd(n),Object.freeze(this)}static from(e){if(e instanceof Qa)return e;typeof e=="number"&&(e=`fixed128x${e}`);let r=!0,i=128,n=18;if(typeof e=="string"){if(e!=="fixed")if(e==="ufixed")r=!1;else{const s=e.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);s||oi.throwArgumentError("invalid fixed format","format",e),r=s[1]!=="u",i=parseInt(s[2]),n=parseInt(s[3])}}else if(e){const s=(a,u,h)=>e[a]==null?h:(typeof e[a]!==u&&oi.throwArgumentError("invalid fixed format ("+a+" not "+u+")","format."+a,e[a]),e[a]);r=s("signed","boolean",r),i=s("width","number",i),n=s("decimals","number",n)}return i%8&&oi.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",i),n>80&&oi.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",n),new Qa(fu,r,i,n)}}class zr{constructor(e,r,i,n){e!==fu&&oi.throwError("cannot use FixedNumber constructor; use FixedNumber.from",Et.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=n,this._hex=r,this._value=i,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&oi.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);const r=Os(this._value,this.format.decimals),i=Os(e._value,e.format.decimals);return zr.fromValue(r.add(i),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);const r=Os(this._value,this.format.decimals),i=Os(e._value,e.format.decimals);return zr.fromValue(r.sub(i),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);const r=Os(this._value,this.format.decimals),i=Os(e._value,e.format.decimals);return zr.fromValue(r.mul(i).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);const r=Os(this._value,this.format.decimals),i=Os(e._value,e.format.decimals);return zr.fromValue(r.mul(this.format._multiplier).div(i),this.format.decimals,this.format)}floor(){const e=this.toString().split(".");e.length===1&&e.push("0");let r=zr.from(e[0],this.format);const i=!e[1].match(/^(0*)$/);return this.isNegative()&&i&&(r=r.subUnsafe(vm.toFormat(r.format))),r}ceiling(){const e=this.toString().split(".");e.length===1&&e.push("0");let r=zr.from(e[0],this.format);const i=!e[1].match(/^(0*)$/);return!this.isNegative()&&i&&(r=r.addUnsafe(vm.toFormat(r.format))),r}round(e){e==null&&(e=0);const r=this.toString().split(".");if(r.length===1&&r.push("0"),(e<0||e>80||e%1)&&oi.throwArgumentError("invalid decimal count","decimals",e),r[1].length<=e)return this;const i=zr.from("1"+hu.substring(0,e),this.format),n=wA.toFormat(this.format);return this.mulUnsafe(i).addUnsafe(n).floor().divUnsafe(i)}isZero(){return this._value==="0.0"||this._value==="0"}isNegative(){return this._value[0]==="-"}toString(){return this._value}toHexString(e){if(e==null)return this._hex;e%8&&oi.throwArgumentError("invalid byte width","width",e);const r=sr.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return Qn(r,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return zr.fromString(this._value,e)}static fromValue(e,r,i){return i==null&&r!=null&&!bA(r)&&(i=r,r=null),r==null&&(r=0),i==null&&(i="fixed"),zr.fromString(pd(e,r),Qa.from(i))}static fromString(e,r){r==null&&(r="fixed");const i=Qa.from(r),n=Os(e,i.decimals);!i.signed&&n.lt(dm)&&gm("unsigned value cannot be negative","overflow","value",e);let s=null;i.signed?s=n.toTwos(i.width).toHexString():(s=n.toHexString(),s=Qn(s,i.width/8));const a=pd(n,i.decimals);return new zr(fu,s,a,i)}static fromBytes(e,r){r==null&&(r="fixed");const i=Qa.from(r);if(dr(e).length>i.width/8)throw new Error("overflow");let n=sr.from(e);i.signed&&(n=n.fromTwos(i.width));const s=n.toTwos((i.signed?0:1)+i.width).toHexString(),a=pd(n,i.decimals);return new zr(fu,s,a,i)}static from(e,r){if(typeof e=="string")return zr.fromString(e,r);if(Ya(e))return zr.fromBytes(e,r);try{return zr.fromValue(e,0,r)}catch(i){if(i.code!==Et.errors.INVALID_ARGUMENT)throw i}return oi.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!!(e&&e._isFixedNumber)}}const vm=zr.from(1),wA=zr.from("0.5"),_A="strings/5.7.0",mm=new Et(_A);var sh;(function(t){t.current="",t.NFC="NFC",t.NFD="NFD",t.NFKC="NFKC",t.NFKD="NFKD"})(sh||(sh={}));var Za;(function(t){t.UNEXPECTED_CONTINUE="unexpected continuation byte",t.BAD_PREFIX="bad codepoint prefix",t.OVERRUN="string overrun",t.MISSING_CONTINUE="missing continuation byte",t.OUT_OF_RANGE="out of UTF-8 range",t.UTF16_SURROGATE="UTF-16 surrogate",t.OVERLONG="overlong representation"})(Za||(Za={}));function EA(t,e,r,i,n){return mm.throwArgumentError(`invalid codepoint at offset ${e}; ${t}`,"bytes",r)}function bm(t,e,r,i,n){if(t===Za.BAD_PREFIX||t===Za.UNEXPECTED_CONTINUE){let s=0;for(let a=e+1;a<r.length&&r[a]>>6===2;a++)s++;return s}return t===Za.OVERRUN?r.length-e-1:0}function AA(t,e,r,i,n){return t===Za.OVERLONG?(i.push(n),0):(i.push(65533),bm(t,e,r))}Object.freeze({error:EA,ignore:bm,replace:AA});function gd(t,e=sh.current){e!=sh.current&&(mm.checkNormalize(),t=t.normalize(e));let r=[];for(let i=0;i<t.length;i++){const n=t.charCodeAt(i);if(n<128)r.push(n);else if(n<2048)r.push(n>>6|192),r.push(n&63|128);else if((n&64512)==55296){i++;const s=t.charCodeAt(i);if(i>=t.length||(s&64512)!==56320)throw new Error("invalid utf-8 string");const a=65536+((n&1023)<<10)+(s&1023);r.push(a>>18|240),r.push(a>>12&63|128),r.push(a>>6&63|128),r.push(a&63|128)}else r.push(n>>12|224),r.push(n>>6&63|128),r.push(n&63|128)}return dr(r)}function xA(t){if(t.length%4!==0)throw new Error("bad data");let e=[];for(let r=0;r<t.length;r+=4)e.push(parseInt(t.substring(r,r+4),16));return e}function vd(t,e){e||(e=function(n){return[parseInt(n,16)]});let r=0,i={};return t.split(",").forEach(n=>{let s=n.split(":");r+=parseInt(s[0],16),i[r]=e(s[1])}),i}function ym(t){let e=0;return t.split(",").map(r=>{let i=r.split("-");i.length===1?i[1]="0":i[1]===""&&(i[1]="1");let n=e+parseInt(i[0],16);return e=parseInt(i[1],16),{l:n,h:e}})}ym("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(t=>parseInt(t,16)),vd("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),vd("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),vd("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",xA),ym("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");const wm="hash/5.7.0";function SA(t){t=atob(t);const e=[];for(let r=0;r<t.length;r++)e.push(t.charCodeAt(r));return dr(e)}function _m(t,e){e==null&&(e=1);const r=[],i=r.forEach,n=function(s,a){i.call(s,function(u){a>0&&Array.isArray(u)?n(u,a-1):r.push(u)})};return n(t,e),r}function IA(t){const e={};for(let r=0;r<t.length;r++){const i=t[r];e[i[0]]=i[1]}return e}function MA(t){let e=0;function r(){return t[e++]<<8|t[e++]}let i=r(),n=1,s=[0,1];for(let k=1;k<i;k++)s.push(n+=r());let a=r(),u=e;e+=a;let h=0,l=0;function b(){return h==0&&(l=l<<8|t[e++],h=8),l>>--h&1}const w=31,I=Math.pow(2,w),S=I>>>1,D=S>>1,T=I-1;let q=0;for(let k=0;k<w;k++)q=q<<1|b();let K=[],F=0,W=I;for(;;){let k=Math.floor(((q-F+1)*n-1)/W),H=0,_=i;for(;_-H>1;){let ie=H+_>>>1;k<s[ie]?_=ie:H=ie}if(H==0)break;K.push(H);let B=F+Math.floor(W*s[H]/n),ee=F+Math.floor(W*s[H+1]/n)-1;for(;!((B^ee)&S);)q=q<<1&T|b(),B=B<<1&T,ee=ee<<1&T|1;for(;B&~ee&D;)q=q&S|q<<1&T>>>1|b(),B=B<<1^S,ee=(ee^S)<<1|S|1;F=B,W=1+ee-B}let R=i-4;return K.map(k=>{switch(k-R){case 3:return R+65792+(t[u++]<<16|t[u++]<<8|t[u++]);case 2:return R+256+(t[u++]<<8|t[u++]);case 1:return R+t[u++];default:return k-1}})}function CA(t){let e=0;return()=>t[e++]}function DA(t){return CA(MA(t))}function OA(t){return t&1?~t>>1:t>>1}function PA(t,e){let r=Array(t);for(let i=0;i<t;i++)r[i]=1+e();return r}function Em(t,e){let r=Array(t);for(let i=0,n=-1;i<t;i++)r[i]=n+=1+e();return r}function $A(t,e){let r=Array(t);for(let i=0,n=0;i<t;i++)r[i]=n+=OA(e());return r}function oh(t,e){let r=Em(t(),t),i=t(),n=Em(i,t),s=PA(i,t);for(let a=0;a<i;a++)for(let u=0;u<s[a];u++)r.push(n[a]+u);return e?r.map(a=>e[a]):r}function RA(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(TA(r,t))}for(;;){let r=t()-1;if(r<0)break;e.push(LA(r,t))}return IA(_m(e))}function NA(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(r)}return e}function Am(t,e,r){let i=Array(t).fill(void 0).map(()=>[]);for(let n=0;n<e;n++)$A(t,r).forEach((s,a)=>i[a].push(s));return i}function TA(t,e){let r=1+e(),i=e(),n=NA(e),s=Am(n.length,1+t,e);return _m(s.map((a,u)=>{const h=a[0],l=a.slice(1);return Array(n[u]).fill(void 0).map((b,w)=>{let I=w*i;return[h+w*r,l.map(S=>S+I)]})}))}function LA(t,e){let r=1+e();return Am(r,1+t,e).map(i=>[i[0],i.slice(1)])}function BA(t){let e=oh(t).sort((i,n)=>i-n);return r();function r(){let i=[];for(;;){let l=oh(t,e);if(l.length==0)break;i.push({set:new Set(l),node:r()})}i.sort((l,b)=>b.set.size-l.set.size);let n=t(),s=n%3;n=n/3|0;let a=!!(n&1);n>>=1;let u=n==1,h=n==2;return{branches:i,valid:s,fe0f:a,save:u,check:h}}}function FA(){return DA(SA("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}const ah=FA();new Set(oh(ah)),new Set(oh(ah)),RA(ah),BA(ah),new Et(wm),new Uint8Array(32).fill(0);const UA=`Ethereum Signed Message:
|
|
22
|
-
`;function xm(t){return typeof t=="string"&&(t=gd(t)),hd(lA([gd(UA),gd(String(t.length)),t]))}const kA="rlp/5.7.0";new Et(kA);const qA="address/5.7.0",lu=new Et(qA);function Sm(t){Fi(t,20)||lu.throwArgumentError("invalid address","address",t),t=t.toLowerCase();const e=t.substring(2).split(""),r=new Uint8Array(40);for(let n=0;n<40;n++)r[n]=e[n].charCodeAt(0);const i=dr(hd(r));for(let n=0;n<40;n+=2)i[n>>1]>>4>=8&&(e[n]=e[n].toUpperCase()),(i[n>>1]&15)>=8&&(e[n+1]=e[n+1].toUpperCase());return"0x"+e.join("")}const jA=9007199254740991;function zA(t){return Math.log10?Math.log10(t):Math.log(t)/Math.LN10}const md={};for(let t=0;t<10;t++)md[String(t)]=String(t);for(let t=0;t<26;t++)md[String.fromCharCode(65+t)]=String(10+t);const Im=Math.floor(zA(jA));function HA(t){t=t.toUpperCase(),t=t.substring(4)+t.substring(0,2)+"00";let e=t.split("").map(i=>md[i]).join("");for(;e.length>=Im;){let i=e.substring(0,Im);e=parseInt(i,10)%97+e.substring(i.length)}let r=String(98-parseInt(e,10)%97);for(;r.length<2;)r="0"+r;return r}function KA(t){let e=null;if(typeof t!="string"&&lu.throwArgumentError("invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/))t.substring(0,2)!=="0x"&&(t="0x"+t),e=Sm(t),t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==t&&lu.throwArgumentError("bad address checksum","address",t);else if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(t.substring(2,4)!==HA(t)&&lu.throwArgumentError("bad icap checksum","address",t),e=yA(t.substring(4));e.length<40;)e="0"+e;e=Sm("0x"+e)}else lu.throwArgumentError("invalid address","address",t);return e}const WA="properties/5.7.0";new Et(WA);function du(t,e,r){Object.defineProperty(t,e,{enumerable:!0,value:r,writable:!1})}new Et(wm),new Uint8Array(32).fill(0),sr.from(-1);const VA=sr.from(0),GA=sr.from(1);sr.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Qn(GA.toHexString(),32),Qn(VA.toHexString(),32);var Zn={},Nt={},pu=Mm;function Mm(t,e){if(!t)throw new Error(e||"Assertion failed")}Mm.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var bd={exports:{}};typeof Object.create=="function"?bd.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:bd.exports=function(t,e){if(e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}};var JA=pu,YA=bd.exports;Nt.inherits=YA;function QA(t,e){return(t.charCodeAt(e)&64512)!==55296||e<0||e+1>=t.length?!1:(t.charCodeAt(e+1)&64512)===56320}function ZA(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if(typeof t=="string")if(e){if(e==="hex")for(t=t.replace(/[^a-z0-9]+/ig,""),t.length%2!==0&&(t="0"+t),n=0;n<t.length;n+=2)r.push(parseInt(t[n]+t[n+1],16))}else for(var i=0,n=0;n<t.length;n++){var s=t.charCodeAt(n);s<128?r[i++]=s:s<2048?(r[i++]=s>>6|192,r[i++]=s&63|128):QA(t,n)?(s=65536+((s&1023)<<10)+(t.charCodeAt(++n)&1023),r[i++]=s>>18|240,r[i++]=s>>12&63|128,r[i++]=s>>6&63|128,r[i++]=s&63|128):(r[i++]=s>>12|224,r[i++]=s>>6&63|128,r[i++]=s&63|128)}else for(n=0;n<t.length;n++)r[n]=t[n]|0;return r}Nt.toArray=ZA;function XA(t){for(var e="",r=0;r<t.length;r++)e+=Dm(t[r].toString(16));return e}Nt.toHex=XA;function Cm(t){var e=t>>>24|t>>>8&65280|t<<8&16711680|(t&255)<<24;return e>>>0}Nt.htonl=Cm;function ex(t,e){for(var r="",i=0;i<t.length;i++){var n=t[i];e==="little"&&(n=Cm(n)),r+=Om(n.toString(16))}return r}Nt.toHex32=ex;function Dm(t){return t.length===1?"0"+t:t}Nt.zero2=Dm;function Om(t){return t.length===7?"0"+t:t.length===6?"00"+t:t.length===5?"000"+t:t.length===4?"0000"+t:t.length===3?"00000"+t:t.length===2?"000000"+t:t.length===1?"0000000"+t:t}Nt.zero8=Om;function tx(t,e,r,i){var n=r-e;JA(n%4===0);for(var s=new Array(n/4),a=0,u=e;a<s.length;a++,u+=4){var h;i==="big"?h=t[u]<<24|t[u+1]<<16|t[u+2]<<8|t[u+3]:h=t[u+3]<<24|t[u+2]<<16|t[u+1]<<8|t[u],s[a]=h>>>0}return s}Nt.join32=tx;function rx(t,e){for(var r=new Array(t.length*4),i=0,n=0;i<t.length;i++,n+=4){var s=t[i];e==="big"?(r[n]=s>>>24,r[n+1]=s>>>16&255,r[n+2]=s>>>8&255,r[n+3]=s&255):(r[n+3]=s>>>24,r[n+2]=s>>>16&255,r[n+1]=s>>>8&255,r[n]=s&255)}return r}Nt.split32=rx;function ix(t,e){return t>>>e|t<<32-e}Nt.rotr32=ix;function nx(t,e){return t<<e|t>>>32-e}Nt.rotl32=nx;function sx(t,e){return t+e>>>0}Nt.sum32=sx;function ox(t,e,r){return t+e+r>>>0}Nt.sum32_3=ox;function ax(t,e,r,i){return t+e+r+i>>>0}Nt.sum32_4=ax;function cx(t,e,r,i,n){return t+e+r+i+n>>>0}Nt.sum32_5=cx;function ux(t,e,r,i){var n=t[e],s=t[e+1],a=i+s>>>0,u=(a<i?1:0)+r+n;t[e]=u>>>0,t[e+1]=a}Nt.sum64=ux;function fx(t,e,r,i){var n=e+i>>>0,s=(n<e?1:0)+t+r;return s>>>0}Nt.sum64_hi=fx;function hx(t,e,r,i){var n=e+i;return n>>>0}Nt.sum64_lo=hx;function lx(t,e,r,i,n,s,a,u){var h=0,l=e;l=l+i>>>0,h+=l<e?1:0,l=l+s>>>0,h+=l<s?1:0,l=l+u>>>0,h+=l<u?1:0;var b=t+r+n+a+h;return b>>>0}Nt.sum64_4_hi=lx;function dx(t,e,r,i,n,s,a,u){var h=e+i+s+u;return h>>>0}Nt.sum64_4_lo=dx;function px(t,e,r,i,n,s,a,u,h,l){var b=0,w=e;w=w+i>>>0,b+=w<e?1:0,w=w+s>>>0,b+=w<s?1:0,w=w+u>>>0,b+=w<u?1:0,w=w+l>>>0,b+=w<l?1:0;var I=t+r+n+a+h+b;return I>>>0}Nt.sum64_5_hi=px;function gx(t,e,r,i,n,s,a,u,h,l){var b=e+i+s+u+l;return b>>>0}Nt.sum64_5_lo=gx;function vx(t,e,r){var i=e<<32-r|t>>>r;return i>>>0}Nt.rotr64_hi=vx;function mx(t,e,r){var i=t<<32-r|e>>>r;return i>>>0}Nt.rotr64_lo=mx;function bx(t,e,r){return t>>>r}Nt.shr64_hi=bx;function yx(t,e,r){var i=t<<32-r|e>>>r;return i>>>0}Nt.shr64_lo=yx;var Xa={},Pm=Nt,wx=pu;function ch(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}Xa.BlockHash=ch,ch.prototype.update=function(t,e){if(t=Pm.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;var r=t.length%this._delta8;this.pending=t.slice(t.length-r,t.length),this.pending.length===0&&(this.pending=null),t=Pm.join32(t,0,t.length-r,this.endian);for(var i=0;i<t.length;i+=this._delta32)this._update(t,i,i+this._delta32)}return this},ch.prototype.digest=function(t){return this.update(this._pad()),wx(this.pending===null),this._digest(t)},ch.prototype._pad=function(){var t=this.pendingTotal,e=this._delta8,r=e-(t+this.padLength)%e,i=new Array(r+this.padLength);i[0]=128;for(var n=1;n<r;n++)i[n]=0;if(t<<=3,this.endian==="big"){for(var s=8;s<this.padLength;s++)i[n++]=0;i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=t>>>24&255,i[n++]=t>>>16&255,i[n++]=t>>>8&255,i[n++]=t&255}else for(i[n++]=t&255,i[n++]=t>>>8&255,i[n++]=t>>>16&255,i[n++]=t>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,s=8;s<this.padLength;s++)i[n++]=0;return i};var ec={},Xn={},_x=Nt,es=_x.rotr32;function Ex(t,e,r,i){if(t===0)return $m(e,r,i);if(t===1||t===3)return Nm(e,r,i);if(t===2)return Rm(e,r,i)}Xn.ft_1=Ex;function $m(t,e,r){return t&e^~t&r}Xn.ch32=$m;function Rm(t,e,r){return t&e^t&r^e&r}Xn.maj32=Rm;function Nm(t,e,r){return t^e^r}Xn.p32=Nm;function Ax(t){return es(t,2)^es(t,13)^es(t,22)}Xn.s0_256=Ax;function xx(t){return es(t,6)^es(t,11)^es(t,25)}Xn.s1_256=xx;function Sx(t){return es(t,7)^es(t,18)^t>>>3}Xn.g0_256=Sx;function Ix(t){return es(t,17)^es(t,19)^t>>>10}Xn.g1_256=Ix;var tc=Nt,Mx=Xa,Cx=Xn,yd=tc.rotl32,gu=tc.sum32,Dx=tc.sum32_5,Ox=Cx.ft_1,Tm=Mx.BlockHash,Px=[1518500249,1859775393,2400959708,3395469782];function ts(){if(!(this instanceof ts))return new ts;Tm.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}tc.inherits(ts,Tm);var $x=ts;ts.blockSize=512,ts.outSize=160,ts.hmacStrength=80,ts.padLength=64,ts.prototype._update=function(t,e){for(var r=this.W,i=0;i<16;i++)r[i]=t[e+i];for(;i<r.length;i++)r[i]=yd(r[i-3]^r[i-8]^r[i-14]^r[i-16],1);var n=this.h[0],s=this.h[1],a=this.h[2],u=this.h[3],h=this.h[4];for(i=0;i<r.length;i++){var l=~~(i/20),b=Dx(yd(n,5),Ox(l,s,a,u),h,r[i],Px[l]);h=u,u=a,a=yd(s,30),s=n,n=b}this.h[0]=gu(this.h[0],n),this.h[1]=gu(this.h[1],s),this.h[2]=gu(this.h[2],a),this.h[3]=gu(this.h[3],u),this.h[4]=gu(this.h[4],h)},ts.prototype._digest=function(t){return t==="hex"?tc.toHex32(this.h,"big"):tc.split32(this.h,"big")};var rc=Nt,Rx=Xa,ic=Xn,Nx=pu,_n=rc.sum32,Tx=rc.sum32_4,Lx=rc.sum32_5,Bx=ic.ch32,Fx=ic.maj32,Ux=ic.s0_256,kx=ic.s1_256,qx=ic.g0_256,jx=ic.g1_256,Lm=Rx.BlockHash,zx=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function rs(){if(!(this instanceof rs))return new rs;Lm.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=zx,this.W=new Array(64)}rc.inherits(rs,Lm);var Bm=rs;rs.blockSize=512,rs.outSize=256,rs.hmacStrength=192,rs.padLength=64,rs.prototype._update=function(t,e){for(var r=this.W,i=0;i<16;i++)r[i]=t[e+i];for(;i<r.length;i++)r[i]=Tx(jx(r[i-2]),r[i-7],qx(r[i-15]),r[i-16]);var n=this.h[0],s=this.h[1],a=this.h[2],u=this.h[3],h=this.h[4],l=this.h[5],b=this.h[6],w=this.h[7];for(Nx(this.k.length===r.length),i=0;i<r.length;i++){var I=Lx(w,kx(h),Bx(h,l,b),this.k[i],r[i]),S=_n(Ux(n),Fx(n,s,a));w=b,b=l,l=h,h=_n(u,I),u=a,a=s,s=n,n=_n(I,S)}this.h[0]=_n(this.h[0],n),this.h[1]=_n(this.h[1],s),this.h[2]=_n(this.h[2],a),this.h[3]=_n(this.h[3],u),this.h[4]=_n(this.h[4],h),this.h[5]=_n(this.h[5],l),this.h[6]=_n(this.h[6],b),this.h[7]=_n(this.h[7],w)},rs.prototype._digest=function(t){return t==="hex"?rc.toHex32(this.h,"big"):rc.split32(this.h,"big")};var wd=Nt,Fm=Bm;function Ps(){if(!(this instanceof Ps))return new Ps;Fm.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}wd.inherits(Ps,Fm);var Hx=Ps;Ps.blockSize=512,Ps.outSize=224,Ps.hmacStrength=192,Ps.padLength=64,Ps.prototype._digest=function(t){return t==="hex"?wd.toHex32(this.h.slice(0,7),"big"):wd.split32(this.h.slice(0,7),"big")};var wi=Nt,Kx=Xa,Wx=pu,is=wi.rotr64_hi,ns=wi.rotr64_lo,Um=wi.shr64_hi,km=wi.shr64_lo,no=wi.sum64,_d=wi.sum64_hi,Ed=wi.sum64_lo,Vx=wi.sum64_4_hi,Gx=wi.sum64_4_lo,Jx=wi.sum64_5_hi,Yx=wi.sum64_5_lo,qm=Kx.BlockHash,Qx=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function En(){if(!(this instanceof En))return new En;qm.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=Qx,this.W=new Array(160)}wi.inherits(En,qm);var jm=En;En.blockSize=1024,En.outSize=512,En.hmacStrength=192,En.padLength=128,En.prototype._prepareBlock=function(t,e){for(var r=this.W,i=0;i<32;i++)r[i]=t[e+i];for(;i<r.length;i+=2){var n=cS(r[i-4],r[i-3]),s=uS(r[i-4],r[i-3]),a=r[i-14],u=r[i-13],h=oS(r[i-30],r[i-29]),l=aS(r[i-30],r[i-29]),b=r[i-32],w=r[i-31];r[i]=Vx(n,s,a,u,h,l,b,w),r[i+1]=Gx(n,s,a,u,h,l,b,w)}},En.prototype._update=function(t,e){this._prepareBlock(t,e);var r=this.W,i=this.h[0],n=this.h[1],s=this.h[2],a=this.h[3],u=this.h[4],h=this.h[5],l=this.h[6],b=this.h[7],w=this.h[8],I=this.h[9],S=this.h[10],D=this.h[11],T=this.h[12],q=this.h[13],K=this.h[14],F=this.h[15];Wx(this.k.length===r.length);for(var W=0;W<r.length;W+=2){var R=K,k=F,H=nS(w,I),_=sS(w,I),B=Zx(w,I,S,D,T),ee=Xx(w,I,S,D,T,q),ie=this.k[W],L=this.k[W+1],y=r[W],f=r[W+1],d=Jx(R,k,H,_,B,ee,ie,L,y,f),v=Yx(R,k,H,_,B,ee,ie,L,y,f);R=rS(i,n),k=iS(i,n),H=eS(i,n,s,a,u),_=tS(i,n,s,a,u,h);var E=_d(R,k,H,_),C=Ed(R,k,H,_);K=T,F=q,T=S,q=D,S=w,D=I,w=_d(l,b,d,v),I=Ed(b,b,d,v),l=u,b=h,u=s,h=a,s=i,a=n,i=_d(d,v,E,C),n=Ed(d,v,E,C)}no(this.h,0,i,n),no(this.h,2,s,a),no(this.h,4,u,h),no(this.h,6,l,b),no(this.h,8,w,I),no(this.h,10,S,D),no(this.h,12,T,q),no(this.h,14,K,F)},En.prototype._digest=function(t){return t==="hex"?wi.toHex32(this.h,"big"):wi.split32(this.h,"big")};function Zx(t,e,r,i,n){var s=t&r^~t&n;return s<0&&(s+=4294967296),s}function Xx(t,e,r,i,n,s){var a=e&i^~e&s;return a<0&&(a+=4294967296),a}function eS(t,e,r,i,n){var s=t&r^t&n^r&n;return s<0&&(s+=4294967296),s}function tS(t,e,r,i,n,s){var a=e&i^e&s^i&s;return a<0&&(a+=4294967296),a}function rS(t,e){var r=is(t,e,28),i=is(e,t,2),n=is(e,t,7),s=r^i^n;return s<0&&(s+=4294967296),s}function iS(t,e){var r=ns(t,e,28),i=ns(e,t,2),n=ns(e,t,7),s=r^i^n;return s<0&&(s+=4294967296),s}function nS(t,e){var r=is(t,e,14),i=is(t,e,18),n=is(e,t,9),s=r^i^n;return s<0&&(s+=4294967296),s}function sS(t,e){var r=ns(t,e,14),i=ns(t,e,18),n=ns(e,t,9),s=r^i^n;return s<0&&(s+=4294967296),s}function oS(t,e){var r=is(t,e,1),i=is(t,e,8),n=Um(t,e,7),s=r^i^n;return s<0&&(s+=4294967296),s}function aS(t,e){var r=ns(t,e,1),i=ns(t,e,8),n=km(t,e,7),s=r^i^n;return s<0&&(s+=4294967296),s}function cS(t,e){var r=is(t,e,19),i=is(e,t,29),n=Um(t,e,6),s=r^i^n;return s<0&&(s+=4294967296),s}function uS(t,e){var r=ns(t,e,19),i=ns(e,t,29),n=km(t,e,6),s=r^i^n;return s<0&&(s+=4294967296),s}var Ad=Nt,zm=jm;function $s(){if(!(this instanceof $s))return new $s;zm.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}Ad.inherits($s,zm);var fS=$s;$s.blockSize=1024,$s.outSize=384,$s.hmacStrength=192,$s.padLength=128,$s.prototype._digest=function(t){return t==="hex"?Ad.toHex32(this.h.slice(0,12),"big"):Ad.split32(this.h.slice(0,12),"big")},ec.sha1=$x,ec.sha224=Hx,ec.sha256=Bm,ec.sha384=fS,ec.sha512=jm;var Hm={},Ko=Nt,hS=Xa,uh=Ko.rotl32,Km=Ko.sum32,vu=Ko.sum32_3,Wm=Ko.sum32_4,Vm=hS.BlockHash;function ss(){if(!(this instanceof ss))return new ss;Vm.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}Ko.inherits(ss,Vm),Hm.ripemd160=ss,ss.blockSize=512,ss.outSize=160,ss.hmacStrength=192,ss.padLength=64,ss.prototype._update=function(t,e){for(var r=this.h[0],i=this.h[1],n=this.h[2],s=this.h[3],a=this.h[4],u=r,h=i,l=n,b=s,w=a,I=0;I<80;I++){var S=Km(uh(Wm(r,Gm(I,i,n,s),t[pS[I]+e],lS(I)),vS[I]),a);r=a,a=s,s=uh(n,10),n=i,i=S,S=Km(uh(Wm(u,Gm(79-I,h,l,b),t[gS[I]+e],dS(I)),mS[I]),w),u=w,w=b,b=uh(l,10),l=h,h=S}S=vu(this.h[1],n,b),this.h[1]=vu(this.h[2],s,w),this.h[2]=vu(this.h[3],a,u),this.h[3]=vu(this.h[4],r,h),this.h[4]=vu(this.h[0],i,l),this.h[0]=S},ss.prototype._digest=function(t){return t==="hex"?Ko.toHex32(this.h,"little"):Ko.split32(this.h,"little")};function Gm(t,e,r,i){return t<=15?e^r^i:t<=31?e&r|~e&i:t<=47?(e|~r)^i:t<=63?e&i|r&~i:e^(r|~i)}function lS(t){return t<=15?0:t<=31?1518500249:t<=47?1859775393:t<=63?2400959708:2840853838}function dS(t){return t<=15?1352829926:t<=31?1548603684:t<=47?1836072691:t<=63?2053994217:0}var pS=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],gS=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],vS=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],mS=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],bS=Nt,yS=pu;function nc(t,e,r){if(!(this instanceof nc))return new nc(t,e,r);this.Hash=t,this.blockSize=t.blockSize/8,this.outSize=t.outSize/8,this.inner=null,this.outer=null,this._init(bS.toArray(e,r))}var wS=nc;nc.prototype._init=function(t){t.length>this.blockSize&&(t=new this.Hash().update(t).digest()),yS(t.length<=this.blockSize);for(var e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=new this.Hash().update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=new this.Hash().update(t)},nc.prototype.update=function(t,e){return this.inner.update(t,e),this},nc.prototype.digest=function(t){return this.outer.update(this.inner.digest()),this.outer.digest(t)},function(t){var e=t;e.utils=Nt,e.common=Xa,e.sha=ec,e.ripemd=Hm,e.hmac=wS,e.sha1=e.sha.sha1,e.sha256=e.sha.sha256,e.sha224=e.sha.sha224,e.sha384=e.sha.sha384,e.sha512=e.sha.sha512,e.ripemd160=e.ripemd.ripemd160}(Zn);function sc(t,e,r){return r={path:e,exports:{},require:function(i,n){return _S(i,n??r.path)}},t(r,r.exports),r.exports}function _S(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var xd=Jm;function Jm(t,e){if(!t)throw new Error(e||"Assertion failed")}Jm.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var An=sc(function(t,e){var r=e;function i(a,u){if(Array.isArray(a))return a.slice();if(!a)return[];var h=[];if(typeof a!="string"){for(var l=0;l<a.length;l++)h[l]=a[l]|0;return h}if(u==="hex"){a=a.replace(/[^a-z0-9]+/ig,""),a.length%2!==0&&(a="0"+a);for(var l=0;l<a.length;l+=2)h.push(parseInt(a[l]+a[l+1],16))}else for(var l=0;l<a.length;l++){var b=a.charCodeAt(l),w=b>>8,I=b&255;w?h.push(w,I):h.push(I)}return h}r.toArray=i;function n(a){return a.length===1?"0"+a:a}r.zero2=n;function s(a){for(var u="",h=0;h<a.length;h++)u+=n(a[h].toString(16));return u}r.toHex=s,r.encode=function(a,u){return u==="hex"?s(a):a}}),Ui=sc(function(t,e){var r=e;r.assert=xd,r.toArray=An.toArray,r.zero2=An.zero2,r.toHex=An.toHex,r.encode=An.encode;function i(h,l,b){var w=new Array(Math.max(h.bitLength(),b)+1);w.fill(0);for(var I=1<<l+1,S=h.clone(),D=0;D<w.length;D++){var T,q=S.andln(I-1);S.isOdd()?(q>(I>>1)-1?T=(I>>1)-q:T=q,S.isubn(T)):T=0,w[D]=T,S.iushrn(1)}return w}r.getNAF=i;function n(h,l){var b=[[],[]];h=h.clone(),l=l.clone();for(var w=0,I=0,S;h.cmpn(-w)>0||l.cmpn(-I)>0;){var D=h.andln(3)+w&3,T=l.andln(3)+I&3;D===3&&(D=-1),T===3&&(T=-1);var q;D&1?(S=h.andln(7)+w&7,(S===3||S===5)&&T===2?q=-D:q=D):q=0,b[0].push(q);var K;T&1?(S=l.andln(7)+I&7,(S===3||S===5)&&D===2?K=-T:K=T):K=0,b[1].push(K),2*w===q+1&&(w=1-w),2*I===K+1&&(I=1-I),h.iushrn(1),l.iushrn(1)}return b}r.getJSF=n;function s(h,l,b){var w="_"+l;h.prototype[l]=function(){return this[w]!==void 0?this[w]:this[w]=b.call(this)}}r.cachedProperty=s;function a(h){return typeof h=="string"?r.toArray(h,"hex"):h}r.parseBytes=a;function u(h){return new mt(h,"hex","le")}r.intFromLE=u}),fh=Ui.getNAF,ES=Ui.getJSF,hh=Ui.assert;function so(t,e){this.type=t,this.p=new mt(e.p,16),this.red=e.prime?mt.red(e.prime):mt.mont(this.p),this.zero=new mt(0).toRed(this.red),this.one=new mt(1).toRed(this.red),this.two=new mt(2).toRed(this.red),this.n=e.n&&new mt(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.gRed),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;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Wo=so;so.prototype.point=function(){throw new Error("Not implemented")},so.prototype.validate=function(){throw new Error("Not implemented")},so.prototype._fixedNafMul=function(t,e){hh(t.precomputed);var r=t._getDoubles(),i=fh(e,1,this._bitLength),n=(1<<r.step+1)-(r.step%2===0?2:1);n/=3;var s=[],a,u;for(a=0;a<i.length;a+=r.step){u=0;for(var h=a+r.step-1;h>=a;h--)u=(u<<1)+i[h];s.push(u)}for(var l=this.jpoint(null,null,null),b=this.jpoint(null,null,null),w=n;w>0;w--){for(a=0;a<s.length;a++)u=s[a],u===w?b=b.mixedAdd(r.points[a]):u===-w&&(b=b.mixedAdd(r.points[a].neg()));l=l.add(b)}return l.toP()},so.prototype._wnafMul=function(t,e){var r=4,i=t._getNAFPoints(r);r=i.wnd;for(var n=i.points,s=fh(e,r,this._bitLength),a=this.jpoint(null,null,null),u=s.length-1;u>=0;u--){for(var h=0;u>=0&&s[u]===0;u--)h++;if(u>=0&&h++,a=a.dblp(h),u<0)break;var l=s[u];hh(l!==0),t.type==="affine"?l>0?a=a.mixedAdd(n[l-1>>1]):a=a.mixedAdd(n[-l-1>>1].neg()):l>0?a=a.add(n[l-1>>1]):a=a.add(n[-l-1>>1].neg())}return t.type==="affine"?a.toP():a},so.prototype._wnafMulAdd=function(t,e,r,i,n){var s=this._wnafT1,a=this._wnafT2,u=this._wnafT3,h=0,l,b,w;for(l=0;l<i;l++){w=e[l];var I=w._getNAFPoints(t);s[l]=I.wnd,a[l]=I.points}for(l=i-1;l>=1;l-=2){var S=l-1,D=l;if(s[S]!==1||s[D]!==1){u[S]=fh(r[S],s[S],this._bitLength),u[D]=fh(r[D],s[D],this._bitLength),h=Math.max(u[S].length,h),h=Math.max(u[D].length,h);continue}var T=[e[S],null,null,e[D]];e[S].y.cmp(e[D].y)===0?(T[1]=e[S].add(e[D]),T[2]=e[S].toJ().mixedAdd(e[D].neg())):e[S].y.cmp(e[D].y.redNeg())===0?(T[1]=e[S].toJ().mixedAdd(e[D]),T[2]=e[S].add(e[D].neg())):(T[1]=e[S].toJ().mixedAdd(e[D]),T[2]=e[S].toJ().mixedAdd(e[D].neg()));var q=[-3,-1,-5,-7,0,7,5,1,3],K=ES(r[S],r[D]);for(h=Math.max(K[0].length,h),u[S]=new Array(h),u[D]=new Array(h),b=0;b<h;b++){var F=K[0][b]|0,W=K[1][b]|0;u[S][b]=q[(F+1)*3+(W+1)],u[D][b]=0,a[S]=T}}var R=this.jpoint(null,null,null),k=this._wnafT4;for(l=h;l>=0;l--){for(var H=0;l>=0;){var _=!0;for(b=0;b<i;b++)k[b]=u[b][l]|0,k[b]!==0&&(_=!1);if(!_)break;H++,l--}if(l>=0&&H++,R=R.dblp(H),l<0)break;for(b=0;b<i;b++){var B=k[b];B!==0&&(B>0?w=a[b][B-1>>1]:B<0&&(w=a[b][-B-1>>1].neg()),w.type==="affine"?R=R.mixedAdd(w):R=R.add(w))}}for(l=0;l<i;l++)a[l]=null;return n?R:R.toP()};function Xi(t,e){this.curve=t,this.type=e,this.precomputed=null}so.BasePoint=Xi,Xi.prototype.eq=function(){throw new Error("Not implemented")},Xi.prototype.validate=function(){return this.curve.validate(this)},so.prototype.decodePoint=function(t,e){t=Ui.toArray(t,e);var r=this.p.byteLength();if((t[0]===4||t[0]===6||t[0]===7)&&t.length-1===2*r){t[0]===6?hh(t[t.length-1]%2===0):t[0]===7&&hh(t[t.length-1]%2===1);var i=this.point(t.slice(1,1+r),t.slice(1+r,1+2*r));return i}else if((t[0]===2||t[0]===3)&&t.length-1===r)return this.pointFromX(t.slice(1,1+r),t[0]===3);throw new Error("Unknown point format")},Xi.prototype.encodeCompressed=function(t){return this.encode(t,!0)},Xi.prototype._encode=function(t){var e=this.curve.p.byteLength(),r=this.getX().toArray("be",e);return t?[this.getY().isEven()?2:3].concat(r):[4].concat(r,this.getY().toArray("be",e))},Xi.prototype.encode=function(t,e){return Ui.encode(this._encode(e),t)},Xi.prototype.precompute=function(t){if(this.precomputed)return this;var e={doubles:null,naf:null,beta:null};return e.naf=this._getNAFPoints(8),e.doubles=this._getDoubles(4,t),e.beta=this._getBeta(),this.precomputed=e,this},Xi.prototype._hasDoubles=function(t){if(!this.precomputed)return!1;var e=this.precomputed.doubles;return e?e.points.length>=Math.ceil((t.bitLength()+1)/e.step):!1},Xi.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],i=this,n=0;n<e;n+=t){for(var s=0;s<t;s++)i=i.dbl();r.push(i)}return{step:t,points:r}},Xi.prototype._getNAFPoints=function(t){if(this.precomputed&&this.precomputed.naf)return this.precomputed.naf;for(var e=[this],r=(1<<t)-1,i=r===1?null:this.dbl(),n=1;n<r;n++)e[n]=e[n-1].add(i);return{wnd:t,points:e}},Xi.prototype._getBeta=function(){return null},Xi.prototype.dblp=function(t){for(var e=this,r=0;r<t;r++)e=e.dbl();return e};var Sd=sc(function(t){typeof Object.create=="function"?t.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,r){if(r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}}}),AS=Ui.assert;function en(t){Wo.call(this,"short",t),this.a=new mt(t.a,16).toRed(this.red),this.b=new mt(t.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,this.endo=this._getEndomorphism(t),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}Sd(en,Wo);var xS=en;en.prototype._getEndomorphism=function(t){if(!(!this.zeroA||!this.g||!this.n||this.p.modn(3)!==1)){var e,r;if(t.beta)e=new mt(t.beta,16).toRed(this.red);else{var i=this._getEndoRoots(this.p);e=i[0].cmp(i[1])<0?i[0]:i[1],e=e.toRed(this.red)}if(t.lambda)r=new mt(t.lambda,16);else{var n=this._getEndoRoots(this.n);this.g.mul(n[0]).x.cmp(this.g.x.redMul(e))===0?r=n[0]:(r=n[1],AS(this.g.mul(r).x.cmp(this.g.x.redMul(e))===0))}var s;return t.basis?s=t.basis.map(function(a){return{a:new mt(a.a,16),b:new mt(a.b,16)}}):s=this._getEndoBasis(r),{beta:e,lambda:r,basis:s}}},en.prototype._getEndoRoots=function(t){var e=t===this.p?this.red:mt.mont(t),r=new mt(2).toRed(e).redInvm(),i=r.redNeg(),n=new mt(3).toRed(e).redNeg().redSqrt().redMul(r),s=i.redAdd(n).fromRed(),a=i.redSub(n).fromRed();return[s,a]},en.prototype._getEndoBasis=function(t){for(var e=this.n.ushrn(Math.floor(this.n.bitLength()/2)),r=t,i=this.n.clone(),n=new mt(1),s=new mt(0),a=new mt(0),u=new mt(1),h,l,b,w,I,S,D,T=0,q,K;r.cmpn(0)!==0;){var F=i.div(r);q=i.sub(F.mul(r)),K=a.sub(F.mul(n));var W=u.sub(F.mul(s));if(!b&&q.cmp(e)<0)h=D.neg(),l=n,b=q.neg(),w=K;else if(b&&++T===2)break;D=q,i=r,r=q,a=n,n=K,u=s,s=W}I=q.neg(),S=K;var R=b.sqr().add(w.sqr()),k=I.sqr().add(S.sqr());return k.cmp(R)>=0&&(I=h,S=l),b.negative&&(b=b.neg(),w=w.neg()),I.negative&&(I=I.neg(),S=S.neg()),[{a:b,b:w},{a:I,b:S}]},en.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],i=e[1],n=i.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),a=n.mul(r.a),u=s.mul(i.a),h=n.mul(r.b),l=s.mul(i.b),b=t.sub(a).sub(u),w=h.add(l).neg();return{k1:b,k2:w}},en.prototype.pointFromX=function(t,e){t=new mt(t,16),t.red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),i=r.redSqrt();if(i.redSqr().redSub(r).cmp(this.zero)!==0)throw new Error("invalid point");var n=i.fromRed().isOdd();return(e&&!n||!e&&n)&&(i=i.redNeg()),this.point(t,i)},en.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,i=this.a.redMul(e),n=e.redSqr().redMul(e).redIAdd(i).redIAdd(this.b);return r.redSqr().redISub(n).cmpn(0)===0},en.prototype._endoWnafMulAdd=function(t,e,r){for(var i=this._endoWnafT1,n=this._endoWnafT2,s=0;s<t.length;s++){var a=this._endoSplit(e[s]),u=t[s],h=u._getBeta();a.k1.negative&&(a.k1.ineg(),u=u.neg(!0)),a.k2.negative&&(a.k2.ineg(),h=h.neg(!0)),i[s*2]=u,i[s*2+1]=h,n[s*2]=a.k1,n[s*2+1]=a.k2}for(var l=this._wnafMulAdd(1,i,n,s*2,r),b=0;b<s*2;b++)i[b]=null,n[b]=null;return l};function Nr(t,e,r,i){Wo.BasePoint.call(this,t,"affine"),e===null&&r===null?(this.x=null,this.y=null,this.inf=!0):(this.x=new mt(e,16),this.y=new mt(r,16),i&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}Sd(Nr,Wo.BasePoint),en.prototype.point=function(t,e,r){return new Nr(this,t,e,r)},en.prototype.pointFromJSON=function(t,e){return Nr.fromJSON(this,t,e)},Nr.prototype._getBeta=function(){if(this.curve.endo){var t=this.precomputed;if(t&&t.beta)return t.beta;var e=this.curve.point(this.x.redMul(this.curve.endo.beta),this.y);if(t){var r=this.curve,i=function(n){return r.point(n.x.redMul(r.endo.beta),n.y)};t.beta=e,e.precomputed={beta:null,naf:t.naf&&{wnd:t.naf.wnd,points:t.naf.points.map(i)},doubles:t.doubles&&{step:t.doubles.step,points:t.doubles.points.map(i)}}}return e}},Nr.prototype.toJSON=function(){return this.precomputed?[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)}}]:[this.x,this.y]},Nr.fromJSON=function(t,e,r){typeof e=="string"&&(e=JSON.parse(e));var i=t.point(e[0],e[1],r);if(!e[2])return i;function n(a){return t.point(a[0],a[1],r)}var s=e[2];return i.precomputed={beta:null,doubles:s.doubles&&{step:s.doubles.step,points:[i].concat(s.doubles.points.map(n))},naf:s.naf&&{wnd:s.naf.wnd,points:[i].concat(s.naf.points.map(n))}},i},Nr.prototype.inspect=function(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+">"},Nr.prototype.isInfinity=function(){return this.inf},Nr.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(this.x.cmp(t.x)===0)return this.curve.point(null,null);var e=this.y.redSub(t.y);e.cmpn(0)!==0&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),i=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,i)},Nr.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(t.cmpn(0)===0)return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),i=t.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(i),s=n.redSqr().redISub(this.x.redAdd(this.x)),a=n.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,a)},Nr.prototype.getX=function(){return this.x.fromRed()},Nr.prototype.getY=function(){return this.y.fromRed()},Nr.prototype.mul=function(t){return t=new mt(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},Nr.prototype.mulAdd=function(t,e,r){var i=[this,e],n=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n):this.curve._wnafMulAdd(1,i,n,2)},Nr.prototype.jmulAdd=function(t,e,r){var i=[this,e],n=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n,!0):this.curve._wnafMulAdd(1,i,n,2,!0)},Nr.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||this.x.cmp(t.x)===0&&this.y.cmp(t.y)===0)},Nr.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,i=function(n){return n.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(i)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(i)}}}return e},Nr.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var t=this.curve.jpoint(this.x,this.y,this.curve.one);return t};function Hr(t,e,r,i){Wo.BasePoint.call(this,t,"jacobian"),e===null&&r===null&&i===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new mt(0)):(this.x=new mt(e,16),this.y=new mt(r,16),this.z=new mt(i,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}Sd(Hr,Wo.BasePoint),en.prototype.jpoint=function(t,e,r){return new Hr(this,t,e,r)},Hr.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),i=this.y.redMul(e).redMul(t);return this.curve.point(r,i)},Hr.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},Hr.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(e),n=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),a=t.y.redMul(r.redMul(this.z)),u=i.redSub(n),h=s.redSub(a);if(u.cmpn(0)===0)return h.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var l=u.redSqr(),b=l.redMul(u),w=i.redMul(l),I=h.redSqr().redIAdd(b).redISub(w).redISub(w),S=h.redMul(w.redISub(I)).redISub(s.redMul(b)),D=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(I,S,D)},Hr.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,i=t.x.redMul(e),n=this.y,s=t.y.redMul(e).redMul(this.z),a=r.redSub(i),u=n.redSub(s);if(a.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var h=a.redSqr(),l=h.redMul(a),b=r.redMul(h),w=u.redSqr().redIAdd(l).redISub(b).redISub(b),I=u.redMul(b.redISub(w)).redISub(n.redMul(l)),S=this.z.redMul(a);return this.curve.jpoint(w,I,S)},Hr.prototype.dblp=function(t){if(t===0)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e<t;e++)r=r.dbl();return r}var i=this.curve.a,n=this.curve.tinv,s=this.x,a=this.y,u=this.z,h=u.redSqr().redSqr(),l=a.redAdd(a);for(e=0;e<t;e++){var b=s.redSqr(),w=l.redSqr(),I=w.redSqr(),S=b.redAdd(b).redIAdd(b).redIAdd(i.redMul(h)),D=s.redMul(w),T=S.redSqr().redISub(D.redAdd(D)),q=D.redISub(T),K=S.redMul(q);K=K.redIAdd(K).redISub(I);var F=l.redMul(u);e+1<t&&(h=h.redMul(I)),s=T,u=F,l=K}return this.curve.jpoint(s,l.redMul(n),u)},Hr.prototype.dbl=function(){return this.isInfinity()?this:this.curve.zeroA?this._zeroDbl():this.curve.threeA?this._threeDbl():this._dbl()},Hr.prototype._zeroDbl=function(){var t,e,r;if(this.zOne){var i=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr(),a=this.x.redAdd(n).redSqr().redISub(i).redISub(s);a=a.redIAdd(a);var u=i.redAdd(i).redIAdd(i),h=u.redSqr().redISub(a).redISub(a),l=s.redIAdd(s);l=l.redIAdd(l),l=l.redIAdd(l),t=h,e=u.redMul(a.redISub(h)).redISub(l),r=this.y.redAdd(this.y)}else{var b=this.x.redSqr(),w=this.y.redSqr(),I=w.redSqr(),S=this.x.redAdd(w).redSqr().redISub(b).redISub(I);S=S.redIAdd(S);var D=b.redAdd(b).redIAdd(b),T=D.redSqr(),q=I.redIAdd(I);q=q.redIAdd(q),q=q.redIAdd(q),t=T.redISub(S).redISub(S),e=D.redMul(S.redISub(t)).redISub(q),r=this.y.redMul(this.z),r=r.redIAdd(r)}return this.curve.jpoint(t,e,r)},Hr.prototype._threeDbl=function(){var t,e,r;if(this.zOne){var i=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr(),a=this.x.redAdd(n).redSqr().redISub(i).redISub(s);a=a.redIAdd(a);var u=i.redAdd(i).redIAdd(i).redIAdd(this.curve.a),h=u.redSqr().redISub(a).redISub(a);t=h;var l=s.redIAdd(s);l=l.redIAdd(l),l=l.redIAdd(l),e=u.redMul(a.redISub(h)).redISub(l),r=this.y.redAdd(this.y)}else{var b=this.z.redSqr(),w=this.y.redSqr(),I=this.x.redMul(w),S=this.x.redSub(b).redMul(this.x.redAdd(b));S=S.redAdd(S).redIAdd(S);var D=I.redIAdd(I);D=D.redIAdd(D);var T=D.redAdd(D);t=S.redSqr().redISub(T),r=this.y.redAdd(this.z).redSqr().redISub(w).redISub(b);var q=w.redSqr();q=q.redIAdd(q),q=q.redIAdd(q),q=q.redIAdd(q),e=S.redMul(D.redISub(t)).redISub(q)}return this.curve.jpoint(t,e,r)},Hr.prototype._dbl=function(){var t=this.curve.a,e=this.x,r=this.y,i=this.z,n=i.redSqr().redSqr(),s=e.redSqr(),a=r.redSqr(),u=s.redAdd(s).redIAdd(s).redIAdd(t.redMul(n)),h=e.redAdd(e);h=h.redIAdd(h);var l=h.redMul(a),b=u.redSqr().redISub(l.redAdd(l)),w=l.redISub(b),I=a.redSqr();I=I.redIAdd(I),I=I.redIAdd(I),I=I.redIAdd(I);var S=u.redMul(w).redISub(I),D=r.redAdd(r).redMul(i);return this.curve.jpoint(b,S,D)},Hr.prototype.trpl=function(){if(!this.curve.zeroA)return this.dbl().add(this);var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr(),i=e.redSqr(),n=t.redAdd(t).redIAdd(t),s=n.redSqr(),a=this.x.redAdd(e).redSqr().redISub(t).redISub(i);a=a.redIAdd(a),a=a.redAdd(a).redIAdd(a),a=a.redISub(s);var u=a.redSqr(),h=i.redIAdd(i);h=h.redIAdd(h),h=h.redIAdd(h),h=h.redIAdd(h);var l=n.redIAdd(a).redSqr().redISub(s).redISub(u).redISub(h),b=e.redMul(l);b=b.redIAdd(b),b=b.redIAdd(b);var w=this.x.redMul(u).redISub(b);w=w.redIAdd(w),w=w.redIAdd(w);var I=this.y.redMul(l.redMul(h.redISub(l)).redISub(a.redMul(u)));I=I.redIAdd(I),I=I.redIAdd(I),I=I.redIAdd(I);var S=this.z.redAdd(a).redSqr().redISub(r).redISub(u);return this.curve.jpoint(w,I,S)},Hr.prototype.mul=function(t,e){return t=new mt(t,e),this.curve._wnafMul(this,t)},Hr.prototype.eq=function(t){if(t.type==="affine")return this.eq(t.toJ());if(this===t)return!0;var e=this.z.redSqr(),r=t.z.redSqr();if(this.x.redMul(r).redISub(t.x.redMul(e)).cmpn(0)!==0)return!1;var i=e.redMul(this.z),n=r.redMul(t.z);return this.y.redMul(n).redISub(t.y.redMul(i)).cmpn(0)===0},Hr.prototype.eqXToP=function(t){var e=this.z.redSqr(),r=t.toRed(this.curve.red).redMul(e);if(this.x.cmp(r)===0)return!0;for(var i=t.clone(),n=this.curve.redN.redMul(e);;){if(i.iadd(this.curve.n),i.cmp(this.curve.p)>=0)return!1;if(r.redIAdd(n),this.x.cmp(r)===0)return!0}},Hr.prototype.inspect=function(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"},Hr.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var lh=sc(function(t,e){var r=e;r.base=Wo,r.short=xS,r.mont=null,r.edwards=null}),dh=sc(function(t,e){var r=e,i=Ui.assert;function n(u){u.type==="short"?this.curve=new lh.short(u):u.type==="edwards"?this.curve=new lh.edwards(u):this.curve=new lh.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,i(this.g.validate(),"Invalid curve"),i(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}r.PresetCurve=n;function s(u,h){Object.defineProperty(r,u,{configurable:!0,enumerable:!0,get:function(){var l=new n(h);return Object.defineProperty(r,u,{configurable:!0,enumerable:!0,value:l}),l}})}s("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:Zn.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),s("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:Zn.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),s("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:Zn.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),s("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:Zn.sha384,gRed:!1,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"]}),s("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:Zn.sha512,gRed:!1,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"]}),s("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Zn.sha256,gRed:!1,g:["9"]}),s("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Zn.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var a;try{a=null.crash()}catch{a=void 0}s("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:Zn.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",a]})});function oo(t){if(!(this instanceof oo))return new oo(t);this.hash=t.hash,this.predResist=!!t.predResist,this.outLen=this.hash.outSize,this.minEntropy=t.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=An.toArray(t.entropy,t.entropyEnc||"hex"),r=An.toArray(t.nonce,t.nonceEnc||"hex"),i=An.toArray(t.pers,t.persEnc||"hex");xd(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,i)}var Ym=oo;oo.prototype._init=function(t,e,r){var i=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var n=0;n<this.V.length;n++)this.K[n]=0,this.V[n]=1;this._update(i),this._reseed=1,this.reseedInterval=281474976710656},oo.prototype._hmac=function(){return new Zn.hmac(this.hash,this.K)},oo.prototype._update=function(t){var e=this._hmac().update(this.V).update([0]);t&&(e=e.update(t)),this.K=e.digest(),this.V=this._hmac().update(this.V).digest(),t&&(this.K=this._hmac().update(this.V).update([1]).update(t).digest(),this.V=this._hmac().update(this.V).digest())},oo.prototype.reseed=function(t,e,r,i){typeof e!="string"&&(i=r,r=e,e=null),t=An.toArray(t,e),r=An.toArray(r,i),xd(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},oo.prototype.generate=function(t,e,r,i){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof e!="string"&&(i=r,r=e,e=null),r&&(r=An.toArray(r,i||"hex"),this._update(r));for(var n=[];n.length<t;)this.V=this._hmac().update(this.V).digest(),n=n.concat(this.V);var s=n.slice(0,t);return this._update(r),this._reseed++,An.encode(s,e)};var Id=Ui.assert;function Yr(t,e){this.ec=t,this.priv=null,this.pub=null,e.priv&&this._importPrivate(e.priv,e.privEnc),e.pub&&this._importPublic(e.pub,e.pubEnc)}var Md=Yr;Yr.fromPublic=function(t,e,r){return e instanceof Yr?e:new Yr(t,{pub:e,pubEnc:r})},Yr.fromPrivate=function(t,e,r){return e instanceof Yr?e:new Yr(t,{priv:e,privEnc:r})},Yr.prototype.validate=function(){var t=this.getPublic();return t.isInfinity()?{result:!1,reason:"Invalid public key"}:t.validate()?t.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},Yr.prototype.getPublic=function(t,e){return typeof t=="string"&&(e=t,t=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),e?this.pub.encode(e,t):this.pub},Yr.prototype.getPrivate=function(t){return t==="hex"?this.priv.toString(16,2):this.priv},Yr.prototype._importPrivate=function(t,e){this.priv=new mt(t,e||16),this.priv=this.priv.umod(this.ec.curve.n)},Yr.prototype._importPublic=function(t,e){if(t.x||t.y){this.ec.curve.type==="mont"?Id(t.x,"Need x coordinate"):(this.ec.curve.type==="short"||this.ec.curve.type==="edwards")&&Id(t.x&&t.y,"Need both x and y coordinate"),this.pub=this.ec.curve.point(t.x,t.y);return}this.pub=this.ec.curve.decodePoint(t,e)},Yr.prototype.derive=function(t){return t.validate()||Id(t.validate(),"public point not validated"),t.mul(this.priv).getX()},Yr.prototype.sign=function(t,e,r){return this.ec.sign(t,this,e,r)},Yr.prototype.verify=function(t,e){return this.ec.verify(t,e,this)},Yr.prototype.inspect=function(){return"<Key priv: "+(this.priv&&this.priv.toString(16,2))+" pub: "+(this.pub&&this.pub.inspect())+" >"};var SS=Ui.assert;function ph(t,e){if(t instanceof ph)return t;this._importDER(t,e)||(SS(t.r&&t.s,"Signature without r or s"),this.r=new mt(t.r,16),this.s=new mt(t.s,16),t.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var gh=ph;function IS(){this.place=0}function Cd(t,e){var r=t[e.place++];if(!(r&128))return r;var i=r&15;if(i===0||i>4)return!1;for(var n=0,s=0,a=e.place;s<i;s++,a++)n<<=8,n|=t[a],n>>>=0;return n<=127?!1:(e.place=a,n)}function Qm(t){for(var e=0,r=t.length-1;!t[e]&&!(t[e+1]&128)&&e<r;)e++;return e===0?t:t.slice(e)}ph.prototype._importDER=function(t,e){t=Ui.toArray(t,e);var r=new IS;if(t[r.place++]!==48)return!1;var i=Cd(t,r);if(i===!1||i+r.place!==t.length||t[r.place++]!==2)return!1;var n=Cd(t,r);if(n===!1)return!1;var s=t.slice(r.place,n+r.place);if(r.place+=n,t[r.place++]!==2)return!1;var a=Cd(t,r);if(a===!1||t.length!==a+r.place)return!1;var u=t.slice(r.place,a+r.place);if(s[0]===0)if(s[1]&128)s=s.slice(1);else return!1;if(u[0]===0)if(u[1]&128)u=u.slice(1);else return!1;return this.r=new mt(s),this.s=new mt(u),this.recoveryParam=null,!0};function Dd(t,e){if(e<128){t.push(e);return}var r=1+(Math.log(e)/Math.LN2>>>3);for(t.push(r|128);--r;)t.push(e>>>(r<<3)&255);t.push(e)}ph.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(e[0]&128&&(e=[0].concat(e)),r[0]&128&&(r=[0].concat(r)),e=Qm(e),r=Qm(r);!r[0]&&!(r[1]&128);)r=r.slice(1);var i=[2];Dd(i,e.length),i=i.concat(e),i.push(2),Dd(i,r.length);var n=i.concat(r),s=[48];return Dd(s,n.length),s=s.concat(n),Ui.encode(s,t)};var MS=function(){throw new Error("unsupported")},Zm=Ui.assert;function tn(t){if(!(this instanceof tn))return new tn(t);typeof t=="string"&&(Zm(Object.prototype.hasOwnProperty.call(dh,t),"Unknown curve "+t),t=dh[t]),t instanceof dh.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var CS=tn;tn.prototype.keyPair=function(t){return new Md(this,t)},tn.prototype.keyFromPrivate=function(t,e){return Md.fromPrivate(this,t,e)},tn.prototype.keyFromPublic=function(t,e){return Md.fromPublic(this,t,e)},tn.prototype.genKeyPair=function(t){t||(t={});for(var e=new Ym({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||MS(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),i=this.n.sub(new mt(2));;){var n=new mt(e.generate(r));if(!(n.cmp(i)>0))return n.iaddn(1),this.keyFromPrivate(n)}},tn.prototype._truncateToN=function(t,e){var r=t.byteLength()*8-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},tn.prototype.sign=function(t,e,r,i){typeof r=="object"&&(i=r,r=null),i||(i={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new mt(t,16));for(var n=this.n.byteLength(),s=e.getPrivate().toArray("be",n),a=t.toArray("be",n),u=new Ym({hash:this.hash,entropy:s,nonce:a,pers:i.pers,persEnc:i.persEnc||"utf8"}),h=this.n.sub(new mt(1)),l=0;;l++){var b=i.k?i.k(l):new mt(u.generate(this.n.byteLength()));if(b=this._truncateToN(b,!0),!(b.cmpn(1)<=0||b.cmp(h)>=0)){var w=this.g.mul(b);if(!w.isInfinity()){var I=w.getX(),S=I.umod(this.n);if(S.cmpn(0)!==0){var D=b.invm(this.n).mul(S.mul(e.getPrivate()).iadd(t));if(D=D.umod(this.n),D.cmpn(0)!==0){var T=(w.getY().isOdd()?1:0)|(I.cmp(S)!==0?2:0);return i.canonical&&D.cmp(this.nh)>0&&(D=this.n.sub(D),T^=1),new gh({r:S,s:D,recoveryParam:T})}}}}}},tn.prototype.verify=function(t,e,r,i){t=this._truncateToN(new mt(t,16)),r=this.keyFromPublic(r,i),e=new gh(e,"hex");var n=e.r,s=e.s;if(n.cmpn(1)<0||n.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var a=s.invm(this.n),u=a.mul(t).umod(this.n),h=a.mul(n).umod(this.n),l;return this.curve._maxwellTrick?(l=this.g.jmulAdd(u,r.getPublic(),h),l.isInfinity()?!1:l.eqXToP(n)):(l=this.g.mulAdd(u,r.getPublic(),h),l.isInfinity()?!1:l.getX().umod(this.n).cmp(n)===0)},tn.prototype.recoverPubKey=function(t,e,r,i){Zm((3&r)===r,"The recovery param is more than two bits"),e=new gh(e,i);var n=this.n,s=new mt(t),a=e.r,u=e.s,h=r&1,l=r>>1;if(a.cmp(this.curve.p.umod(this.curve.n))>=0&&l)throw new Error("Unable to find sencond key candinate");l?a=this.curve.pointFromX(a.add(this.curve.n),h):a=this.curve.pointFromX(a,h);var b=e.r.invm(n),w=n.sub(s).mul(b).umod(n),I=u.mul(b).umod(n);return this.g.mulAdd(w,a,I)},tn.prototype.getKeyRecoveryParam=function(t,e,r,i){if(e=new gh(e,i),e.recoveryParam!==null)return e.recoveryParam;for(var n=0;n<4;n++){var s;try{s=this.recoverPubKey(t,e,n)}catch{continue}if(s.eq(r))return n}throw new Error("Unable to find valid recovery factor")};var DS=sc(function(t,e){var r=e;r.version="6.5.4",r.utils=Ui,r.rand=function(){throw new Error("unsupported")},r.curve=lh,r.curves=dh,r.ec=CS,r.eddsa=null}),OS=DS.ec;const PS="signing-key/5.7.0",Od=new Et(PS);let Pd=null;function os(){return Pd||(Pd=new OS("secp256k1")),Pd}class $S{constructor(e){du(this,"curve","secp256k1"),du(this,"privateKey",si(e)),pA(this.privateKey)!==32&&Od.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");const r=os().keyFromPrivate(dr(this.privateKey));du(this,"publicKey","0x"+r.getPublic(!1,"hex")),du(this,"compressedPublicKey","0x"+r.getPublic(!0,"hex")),du(this,"_isSigningKey",!0)}_addPoint(e){const r=os().keyFromPublic(dr(this.publicKey)),i=os().keyFromPublic(dr(e));return"0x"+r.pub.add(i.pub).encodeCompressed("hex")}signDigest(e){const r=os().keyFromPrivate(dr(this.privateKey)),i=dr(e);i.length!==32&&Od.throwArgumentError("bad digest length","digest",e);const n=r.sign(i,{canonical:!0});return cm({recoveryParam:n.recoveryParam,r:Qn("0x"+n.r.toString(16),32),s:Qn("0x"+n.s.toString(16),32)})}computeSharedSecret(e){const r=os().keyFromPrivate(dr(this.privateKey)),i=os().keyFromPublic(dr(Xm(e)));return Qn("0x"+r.derive(i.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}}function RS(t,e){const r=cm(e),i={r:dr(r.r),s:dr(r.s)};return"0x"+os().recoverPubKey(dr(t),i,r.recoveryParam).encode("hex",!1)}function Xm(t,e){const r=dr(t);if(r.length===32){const i=new $S(r);return e?"0x"+os().keyFromPrivate(r).getPublic(!0,"hex"):i.publicKey}else{if(r.length===33)return e?si(r):"0x"+os().keyFromPublic(r).getPublic(!1,"hex");if(r.length===65)return e?"0x"+os().keyFromPublic(r).getPublic(!0,"hex"):si(r)}return Od.throwArgumentError("invalid public or private key","key","[REDACTED]")}const NS="transactions/5.7.0";new Et(NS);var eb;(function(t){t[t.legacy=0]="legacy",t[t.eip2930=1]="eip2930",t[t.eip1559=2]="eip1559"})(eb||(eb={}));function TS(t){const e=Xm(t);return KA(am(hd(am(e,1)),12))}function LS(t,e){return TS(RS(dr(t),e))}const BS="https://rpc.walletconnect.com/v1";async function FS(t,e,r,i,n,s){switch(r.t){case"eip191":return US(t,e,r.s);case"eip1271":return await kS(t,e,r.s,i,n,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function US(t,e,r){return LS(xm(e),r).toLowerCase()===t.toLowerCase()}async function kS(t,e,r,i,n,s){try{const a="0x1626ba7e",u="0000000000000000000000000000000000000000000000000000000000000040",h="0000000000000000000000000000000000000000000000000000000000000041",l=r.substring(2),b=xm(e).substring(2),w=a+b+u+h+l,I=await fetch(`${s||BS}/?chainId=${i}&projectId=${n}`,{method:"POST",body:JSON.stringify({id:qS(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:w},"latest"]})}),{result:S}=await I.json();return S?S.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function qS(){return Date.now()+Math.floor(Math.random()*1e3)}var jS=Object.defineProperty,zS=Object.defineProperties,HS=Object.getOwnPropertyDescriptors,tb=Object.getOwnPropertySymbols,KS=Object.prototype.hasOwnProperty,WS=Object.prototype.propertyIsEnumerable,rb=(t,e,r)=>e in t?jS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,VS=(t,e)=>{for(var r in e||(e={}))KS.call(e,r)&&rb(t,r,e[r]);if(tb)for(var r of tb(e))WS.call(e,r)&&rb(t,r,e[r]);return t},GS=(t,e)=>zS(t,HS(e));const JS="did:pkh:",$d=t=>t?.split(":"),ib=t=>{const e=t&&$d(t);if(e)return t.includes(JS)?e[3]:e[1]},nb=t=>{const e=t&&$d(t);if(e)return e[2]+":"+e[3]},vh=t=>{const e=t&&$d(t);if(e)return e.pop()};async function sb(t){const{cacao:e,projectId:r}=t,{s:i,p:n}=e,s=ob(n,n.iss),a=vh(n.iss);return await FS(a,s,i,ib(n.iss),r)}const ob=(t,e)=>{const r=`${t.domain} wants you to sign in with your Ethereum account:`,i=vh(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let n=t.statement||void 0;const s=`URI: ${t.aud||t.uri}`,a=`Version: ${t.version}`,u=`Chain ID: ${ib(e)}`,h=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,b=t.exp?`Expiration Time: ${t.exp}`:void 0,w=t.nbf?`Not Before: ${t.nbf}`:void 0,I=t.requestId?`Request ID: ${t.requestId}`:void 0,S=t.resources?`Resources:${t.resources.map(T=>`
|
|
22
|
+
`;function xm(t){return typeof t=="string"&&(t=gd(t)),hd(lA([gd(UA),gd(String(t.length)),t]))}const kA="rlp/5.7.0";new Et(kA);const qA="address/5.7.0",lu=new Et(qA);function Sm(t){Fi(t,20)||lu.throwArgumentError("invalid address","address",t),t=t.toLowerCase();const e=t.substring(2).split(""),r=new Uint8Array(40);for(let n=0;n<40;n++)r[n]=e[n].charCodeAt(0);const i=dr(hd(r));for(let n=0;n<40;n+=2)i[n>>1]>>4>=8&&(e[n]=e[n].toUpperCase()),(i[n>>1]&15)>=8&&(e[n+1]=e[n+1].toUpperCase());return"0x"+e.join("")}const jA=9007199254740991;function zA(t){return Math.log10?Math.log10(t):Math.log(t)/Math.LN10}const md={};for(let t=0;t<10;t++)md[String(t)]=String(t);for(let t=0;t<26;t++)md[String.fromCharCode(65+t)]=String(10+t);const Im=Math.floor(zA(jA));function HA(t){t=t.toUpperCase(),t=t.substring(4)+t.substring(0,2)+"00";let e=t.split("").map(i=>md[i]).join("");for(;e.length>=Im;){let i=e.substring(0,Im);e=parseInt(i,10)%97+e.substring(i.length)}let r=String(98-parseInt(e,10)%97);for(;r.length<2;)r="0"+r;return r}function KA(t){let e=null;if(typeof t!="string"&&lu.throwArgumentError("invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/))t.substring(0,2)!=="0x"&&(t="0x"+t),e=Sm(t),t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==t&&lu.throwArgumentError("bad address checksum","address",t);else if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(t.substring(2,4)!==HA(t)&&lu.throwArgumentError("bad icap checksum","address",t),e=yA(t.substring(4));e.length<40;)e="0"+e;e=Sm("0x"+e)}else lu.throwArgumentError("invalid address","address",t);return e}const WA="properties/5.7.0";new Et(WA);function du(t,e,r){Object.defineProperty(t,e,{enumerable:!0,value:r,writable:!1})}new Et(wm),new Uint8Array(32).fill(0),sr.from(-1);const VA=sr.from(0),GA=sr.from(1);sr.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Qn(GA.toHexString(),32),Qn(VA.toHexString(),32);var Zn={},Nt={},pu=Mm;function Mm(t,e){if(!t)throw new Error(e||"Assertion failed")}Mm.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var bd={exports:{}};typeof Object.create=="function"?bd.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:bd.exports=function(t,e){if(e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}};var JA=pu,YA=bd.exports;Nt.inherits=YA;function QA(t,e){return(t.charCodeAt(e)&64512)!==55296||e<0||e+1>=t.length?!1:(t.charCodeAt(e+1)&64512)===56320}function ZA(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if(typeof t=="string")if(e){if(e==="hex")for(t=t.replace(/[^a-z0-9]+/ig,""),t.length%2!==0&&(t="0"+t),n=0;n<t.length;n+=2)r.push(parseInt(t[n]+t[n+1],16))}else for(var i=0,n=0;n<t.length;n++){var s=t.charCodeAt(n);s<128?r[i++]=s:s<2048?(r[i++]=s>>6|192,r[i++]=s&63|128):QA(t,n)?(s=65536+((s&1023)<<10)+(t.charCodeAt(++n)&1023),r[i++]=s>>18|240,r[i++]=s>>12&63|128,r[i++]=s>>6&63|128,r[i++]=s&63|128):(r[i++]=s>>12|224,r[i++]=s>>6&63|128,r[i++]=s&63|128)}else for(n=0;n<t.length;n++)r[n]=t[n]|0;return r}Nt.toArray=ZA;function XA(t){for(var e="",r=0;r<t.length;r++)e+=Dm(t[r].toString(16));return e}Nt.toHex=XA;function Cm(t){var e=t>>>24|t>>>8&65280|t<<8&16711680|(t&255)<<24;return e>>>0}Nt.htonl=Cm;function ex(t,e){for(var r="",i=0;i<t.length;i++){var n=t[i];e==="little"&&(n=Cm(n)),r+=Om(n.toString(16))}return r}Nt.toHex32=ex;function Dm(t){return t.length===1?"0"+t:t}Nt.zero2=Dm;function Om(t){return t.length===7?"0"+t:t.length===6?"00"+t:t.length===5?"000"+t:t.length===4?"0000"+t:t.length===3?"00000"+t:t.length===2?"000000"+t:t.length===1?"0000000"+t:t}Nt.zero8=Om;function tx(t,e,r,i){var n=r-e;JA(n%4===0);for(var s=new Array(n/4),a=0,u=e;a<s.length;a++,u+=4){var h;i==="big"?h=t[u]<<24|t[u+1]<<16|t[u+2]<<8|t[u+3]:h=t[u+3]<<24|t[u+2]<<16|t[u+1]<<8|t[u],s[a]=h>>>0}return s}Nt.join32=tx;function rx(t,e){for(var r=new Array(t.length*4),i=0,n=0;i<t.length;i++,n+=4){var s=t[i];e==="big"?(r[n]=s>>>24,r[n+1]=s>>>16&255,r[n+2]=s>>>8&255,r[n+3]=s&255):(r[n+3]=s>>>24,r[n+2]=s>>>16&255,r[n+1]=s>>>8&255,r[n]=s&255)}return r}Nt.split32=rx;function ix(t,e){return t>>>e|t<<32-e}Nt.rotr32=ix;function nx(t,e){return t<<e|t>>>32-e}Nt.rotl32=nx;function sx(t,e){return t+e>>>0}Nt.sum32=sx;function ox(t,e,r){return t+e+r>>>0}Nt.sum32_3=ox;function ax(t,e,r,i){return t+e+r+i>>>0}Nt.sum32_4=ax;function cx(t,e,r,i,n){return t+e+r+i+n>>>0}Nt.sum32_5=cx;function ux(t,e,r,i){var n=t[e],s=t[e+1],a=i+s>>>0,u=(a<i?1:0)+r+n;t[e]=u>>>0,t[e+1]=a}Nt.sum64=ux;function fx(t,e,r,i){var n=e+i>>>0,s=(n<e?1:0)+t+r;return s>>>0}Nt.sum64_hi=fx;function hx(t,e,r,i){var n=e+i;return n>>>0}Nt.sum64_lo=hx;function lx(t,e,r,i,n,s,a,u){var h=0,l=e;l=l+i>>>0,h+=l<e?1:0,l=l+s>>>0,h+=l<s?1:0,l=l+u>>>0,h+=l<u?1:0;var b=t+r+n+a+h;return b>>>0}Nt.sum64_4_hi=lx;function dx(t,e,r,i,n,s,a,u){var h=e+i+s+u;return h>>>0}Nt.sum64_4_lo=dx;function px(t,e,r,i,n,s,a,u,h,l){var b=0,w=e;w=w+i>>>0,b+=w<e?1:0,w=w+s>>>0,b+=w<s?1:0,w=w+u>>>0,b+=w<u?1:0,w=w+l>>>0,b+=w<l?1:0;var I=t+r+n+a+h+b;return I>>>0}Nt.sum64_5_hi=px;function gx(t,e,r,i,n,s,a,u,h,l){var b=e+i+s+u+l;return b>>>0}Nt.sum64_5_lo=gx;function vx(t,e,r){var i=e<<32-r|t>>>r;return i>>>0}Nt.rotr64_hi=vx;function mx(t,e,r){var i=t<<32-r|e>>>r;return i>>>0}Nt.rotr64_lo=mx;function bx(t,e,r){return t>>>r}Nt.shr64_hi=bx;function yx(t,e,r){var i=t<<32-r|e>>>r;return i>>>0}Nt.shr64_lo=yx;var Xa={},Pm=Nt,wx=pu;function ch(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}Xa.BlockHash=ch,ch.prototype.update=function(t,e){if(t=Pm.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;var r=t.length%this._delta8;this.pending=t.slice(t.length-r,t.length),this.pending.length===0&&(this.pending=null),t=Pm.join32(t,0,t.length-r,this.endian);for(var i=0;i<t.length;i+=this._delta32)this._update(t,i,i+this._delta32)}return this},ch.prototype.digest=function(t){return this.update(this._pad()),wx(this.pending===null),this._digest(t)},ch.prototype._pad=function(){var t=this.pendingTotal,e=this._delta8,r=e-(t+this.padLength)%e,i=new Array(r+this.padLength);i[0]=128;for(var n=1;n<r;n++)i[n]=0;if(t<<=3,this.endian==="big"){for(var s=8;s<this.padLength;s++)i[n++]=0;i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=t>>>24&255,i[n++]=t>>>16&255,i[n++]=t>>>8&255,i[n++]=t&255}else for(i[n++]=t&255,i[n++]=t>>>8&255,i[n++]=t>>>16&255,i[n++]=t>>>24&255,i[n++]=0,i[n++]=0,i[n++]=0,i[n++]=0,s=8;s<this.padLength;s++)i[n++]=0;return i};var ec={},Xn={},_x=Nt,es=_x.rotr32;function Ex(t,e,r,i){if(t===0)return $m(e,r,i);if(t===1||t===3)return Nm(e,r,i);if(t===2)return Rm(e,r,i)}Xn.ft_1=Ex;function $m(t,e,r){return t&e^~t&r}Xn.ch32=$m;function Rm(t,e,r){return t&e^t&r^e&r}Xn.maj32=Rm;function Nm(t,e,r){return t^e^r}Xn.p32=Nm;function Ax(t){return es(t,2)^es(t,13)^es(t,22)}Xn.s0_256=Ax;function xx(t){return es(t,6)^es(t,11)^es(t,25)}Xn.s1_256=xx;function Sx(t){return es(t,7)^es(t,18)^t>>>3}Xn.g0_256=Sx;function Ix(t){return es(t,17)^es(t,19)^t>>>10}Xn.g1_256=Ix;var tc=Nt,Mx=Xa,Cx=Xn,yd=tc.rotl32,gu=tc.sum32,Dx=tc.sum32_5,Ox=Cx.ft_1,Tm=Mx.BlockHash,Px=[1518500249,1859775393,2400959708,3395469782];function ts(){if(!(this instanceof ts))return new ts;Tm.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}tc.inherits(ts,Tm);var $x=ts;ts.blockSize=512,ts.outSize=160,ts.hmacStrength=80,ts.padLength=64,ts.prototype._update=function(t,e){for(var r=this.W,i=0;i<16;i++)r[i]=t[e+i];for(;i<r.length;i++)r[i]=yd(r[i-3]^r[i-8]^r[i-14]^r[i-16],1);var n=this.h[0],s=this.h[1],a=this.h[2],u=this.h[3],h=this.h[4];for(i=0;i<r.length;i++){var l=~~(i/20),b=Dx(yd(n,5),Ox(l,s,a,u),h,r[i],Px[l]);h=u,u=a,a=yd(s,30),s=n,n=b}this.h[0]=gu(this.h[0],n),this.h[1]=gu(this.h[1],s),this.h[2]=gu(this.h[2],a),this.h[3]=gu(this.h[3],u),this.h[4]=gu(this.h[4],h)},ts.prototype._digest=function(t){return t==="hex"?tc.toHex32(this.h,"big"):tc.split32(this.h,"big")};var rc=Nt,Rx=Xa,ic=Xn,Nx=pu,_n=rc.sum32,Tx=rc.sum32_4,Lx=rc.sum32_5,Bx=ic.ch32,Fx=ic.maj32,Ux=ic.s0_256,kx=ic.s1_256,qx=ic.g0_256,jx=ic.g1_256,Lm=Rx.BlockHash,zx=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function rs(){if(!(this instanceof rs))return new rs;Lm.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=zx,this.W=new Array(64)}rc.inherits(rs,Lm);var Bm=rs;rs.blockSize=512,rs.outSize=256,rs.hmacStrength=192,rs.padLength=64,rs.prototype._update=function(t,e){for(var r=this.W,i=0;i<16;i++)r[i]=t[e+i];for(;i<r.length;i++)r[i]=Tx(jx(r[i-2]),r[i-7],qx(r[i-15]),r[i-16]);var n=this.h[0],s=this.h[1],a=this.h[2],u=this.h[3],h=this.h[4],l=this.h[5],b=this.h[6],w=this.h[7];for(Nx(this.k.length===r.length),i=0;i<r.length;i++){var I=Lx(w,kx(h),Bx(h,l,b),this.k[i],r[i]),S=_n(Ux(n),Fx(n,s,a));w=b,b=l,l=h,h=_n(u,I),u=a,a=s,s=n,n=_n(I,S)}this.h[0]=_n(this.h[0],n),this.h[1]=_n(this.h[1],s),this.h[2]=_n(this.h[2],a),this.h[3]=_n(this.h[3],u),this.h[4]=_n(this.h[4],h),this.h[5]=_n(this.h[5],l),this.h[6]=_n(this.h[6],b),this.h[7]=_n(this.h[7],w)},rs.prototype._digest=function(t){return t==="hex"?rc.toHex32(this.h,"big"):rc.split32(this.h,"big")};var wd=Nt,Fm=Bm;function Ps(){if(!(this instanceof Ps))return new Ps;Fm.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}wd.inherits(Ps,Fm);var Hx=Ps;Ps.blockSize=512,Ps.outSize=224,Ps.hmacStrength=192,Ps.padLength=64,Ps.prototype._digest=function(t){return t==="hex"?wd.toHex32(this.h.slice(0,7),"big"):wd.split32(this.h.slice(0,7),"big")};var wi=Nt,Kx=Xa,Wx=pu,is=wi.rotr64_hi,ns=wi.rotr64_lo,Um=wi.shr64_hi,km=wi.shr64_lo,no=wi.sum64,_d=wi.sum64_hi,Ed=wi.sum64_lo,Vx=wi.sum64_4_hi,Gx=wi.sum64_4_lo,Jx=wi.sum64_5_hi,Yx=wi.sum64_5_lo,qm=Kx.BlockHash,Qx=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function En(){if(!(this instanceof En))return new En;qm.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=Qx,this.W=new Array(160)}wi.inherits(En,qm);var jm=En;En.blockSize=1024,En.outSize=512,En.hmacStrength=192,En.padLength=128,En.prototype._prepareBlock=function(t,e){for(var r=this.W,i=0;i<32;i++)r[i]=t[e+i];for(;i<r.length;i+=2){var n=cS(r[i-4],r[i-3]),s=uS(r[i-4],r[i-3]),a=r[i-14],u=r[i-13],h=oS(r[i-30],r[i-29]),l=aS(r[i-30],r[i-29]),b=r[i-32],w=r[i-31];r[i]=Vx(n,s,a,u,h,l,b,w),r[i+1]=Gx(n,s,a,u,h,l,b,w)}},En.prototype._update=function(t,e){this._prepareBlock(t,e);var r=this.W,i=this.h[0],n=this.h[1],s=this.h[2],a=this.h[3],u=this.h[4],h=this.h[5],l=this.h[6],b=this.h[7],w=this.h[8],I=this.h[9],S=this.h[10],D=this.h[11],T=this.h[12],q=this.h[13],K=this.h[14],F=this.h[15];Wx(this.k.length===r.length);for(var W=0;W<r.length;W+=2){var R=K,k=F,H=nS(w,I),_=sS(w,I),B=Zx(w,I,S,D,T),ee=Xx(w,I,S,D,T,q),ie=this.k[W],L=this.k[W+1],y=r[W],f=r[W+1],d=Jx(R,k,H,_,B,ee,ie,L,y,f),v=Yx(R,k,H,_,B,ee,ie,L,y,f);R=rS(i,n),k=iS(i,n),H=eS(i,n,s,a,u),_=tS(i,n,s,a,u,h);var E=_d(R,k,H,_),C=Ed(R,k,H,_);K=T,F=q,T=S,q=D,S=w,D=I,w=_d(l,b,d,v),I=Ed(b,b,d,v),l=u,b=h,u=s,h=a,s=i,a=n,i=_d(d,v,E,C),n=Ed(d,v,E,C)}no(this.h,0,i,n),no(this.h,2,s,a),no(this.h,4,u,h),no(this.h,6,l,b),no(this.h,8,w,I),no(this.h,10,S,D),no(this.h,12,T,q),no(this.h,14,K,F)},En.prototype._digest=function(t){return t==="hex"?wi.toHex32(this.h,"big"):wi.split32(this.h,"big")};function Zx(t,e,r,i,n){var s=t&r^~t&n;return s<0&&(s+=4294967296),s}function Xx(t,e,r,i,n,s){var a=e&i^~e&s;return a<0&&(a+=4294967296),a}function eS(t,e,r,i,n){var s=t&r^t&n^r&n;return s<0&&(s+=4294967296),s}function tS(t,e,r,i,n,s){var a=e&i^e&s^i&s;return a<0&&(a+=4294967296),a}function rS(t,e){var r=is(t,e,28),i=is(e,t,2),n=is(e,t,7),s=r^i^n;return s<0&&(s+=4294967296),s}function iS(t,e){var r=ns(t,e,28),i=ns(e,t,2),n=ns(e,t,7),s=r^i^n;return s<0&&(s+=4294967296),s}function nS(t,e){var r=is(t,e,14),i=is(t,e,18),n=is(e,t,9),s=r^i^n;return s<0&&(s+=4294967296),s}function sS(t,e){var r=ns(t,e,14),i=ns(t,e,18),n=ns(e,t,9),s=r^i^n;return s<0&&(s+=4294967296),s}function oS(t,e){var r=is(t,e,1),i=is(t,e,8),n=Um(t,e,7),s=r^i^n;return s<0&&(s+=4294967296),s}function aS(t,e){var r=ns(t,e,1),i=ns(t,e,8),n=km(t,e,7),s=r^i^n;return s<0&&(s+=4294967296),s}function cS(t,e){var r=is(t,e,19),i=is(e,t,29),n=Um(t,e,6),s=r^i^n;return s<0&&(s+=4294967296),s}function uS(t,e){var r=ns(t,e,19),i=ns(e,t,29),n=km(t,e,6),s=r^i^n;return s<0&&(s+=4294967296),s}var Ad=Nt,zm=jm;function $s(){if(!(this instanceof $s))return new $s;zm.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}Ad.inherits($s,zm);var fS=$s;$s.blockSize=1024,$s.outSize=384,$s.hmacStrength=192,$s.padLength=128,$s.prototype._digest=function(t){return t==="hex"?Ad.toHex32(this.h.slice(0,12),"big"):Ad.split32(this.h.slice(0,12),"big")},ec.sha1=$x,ec.sha224=Hx,ec.sha256=Bm,ec.sha384=fS,ec.sha512=jm;var Hm={},Ko=Nt,hS=Xa,uh=Ko.rotl32,Km=Ko.sum32,vu=Ko.sum32_3,Wm=Ko.sum32_4,Vm=hS.BlockHash;function ss(){if(!(this instanceof ss))return new ss;Vm.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}Ko.inherits(ss,Vm),Hm.ripemd160=ss,ss.blockSize=512,ss.outSize=160,ss.hmacStrength=192,ss.padLength=64,ss.prototype._update=function(t,e){for(var r=this.h[0],i=this.h[1],n=this.h[2],s=this.h[3],a=this.h[4],u=r,h=i,l=n,b=s,w=a,I=0;I<80;I++){var S=Km(uh(Wm(r,Gm(I,i,n,s),t[pS[I]+e],lS(I)),vS[I]),a);r=a,a=s,s=uh(n,10),n=i,i=S,S=Km(uh(Wm(u,Gm(79-I,h,l,b),t[gS[I]+e],dS(I)),mS[I]),w),u=w,w=b,b=uh(l,10),l=h,h=S}S=vu(this.h[1],n,b),this.h[1]=vu(this.h[2],s,w),this.h[2]=vu(this.h[3],a,u),this.h[3]=vu(this.h[4],r,h),this.h[4]=vu(this.h[0],i,l),this.h[0]=S},ss.prototype._digest=function(t){return t==="hex"?Ko.toHex32(this.h,"little"):Ko.split32(this.h,"little")};function Gm(t,e,r,i){return t<=15?e^r^i:t<=31?e&r|~e&i:t<=47?(e|~r)^i:t<=63?e&i|r&~i:e^(r|~i)}function lS(t){return t<=15?0:t<=31?1518500249:t<=47?1859775393:t<=63?2400959708:2840853838}function dS(t){return t<=15?1352829926:t<=31?1548603684:t<=47?1836072691:t<=63?2053994217:0}var pS=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],gS=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],vS=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],mS=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],bS=Nt,yS=pu;function nc(t,e,r){if(!(this instanceof nc))return new nc(t,e,r);this.Hash=t,this.blockSize=t.blockSize/8,this.outSize=t.outSize/8,this.inner=null,this.outer=null,this._init(bS.toArray(e,r))}var wS=nc;nc.prototype._init=function(t){t.length>this.blockSize&&(t=new this.Hash().update(t).digest()),yS(t.length<=this.blockSize);for(var e=t.length;e<this.blockSize;e++)t.push(0);for(e=0;e<t.length;e++)t[e]^=54;for(this.inner=new this.Hash().update(t),e=0;e<t.length;e++)t[e]^=106;this.outer=new this.Hash().update(t)},nc.prototype.update=function(t,e){return this.inner.update(t,e),this},nc.prototype.digest=function(t){return this.outer.update(this.inner.digest()),this.outer.digest(t)},function(t){var e=t;e.utils=Nt,e.common=Xa,e.sha=ec,e.ripemd=Hm,e.hmac=wS,e.sha1=e.sha.sha1,e.sha256=e.sha.sha256,e.sha224=e.sha.sha224,e.sha384=e.sha.sha384,e.sha512=e.sha.sha512,e.ripemd160=e.ripemd.ripemd160}(Zn);function sc(t,e,r){return r={path:e,exports:{},require:function(i,n){return _S(i,n??r.path)}},t(r,r.exports),r.exports}function _S(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var xd=Jm;function Jm(t,e){if(!t)throw new Error(e||"Assertion failed")}Jm.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var An=sc(function(t,e){var r=e;function i(a,u){if(Array.isArray(a))return a.slice();if(!a)return[];var h=[];if(typeof a!="string"){for(var l=0;l<a.length;l++)h[l]=a[l]|0;return h}if(u==="hex"){a=a.replace(/[^a-z0-9]+/ig,""),a.length%2!==0&&(a="0"+a);for(var l=0;l<a.length;l+=2)h.push(parseInt(a[l]+a[l+1],16))}else for(var l=0;l<a.length;l++){var b=a.charCodeAt(l),w=b>>8,I=b&255;w?h.push(w,I):h.push(I)}return h}r.toArray=i;function n(a){return a.length===1?"0"+a:a}r.zero2=n;function s(a){for(var u="",h=0;h<a.length;h++)u+=n(a[h].toString(16));return u}r.toHex=s,r.encode=function(a,u){return u==="hex"?s(a):a}}),Ui=sc(function(t,e){var r=e;r.assert=xd,r.toArray=An.toArray,r.zero2=An.zero2,r.toHex=An.toHex,r.encode=An.encode;function i(h,l,b){var w=new Array(Math.max(h.bitLength(),b)+1);w.fill(0);for(var I=1<<l+1,S=h.clone(),D=0;D<w.length;D++){var T,q=S.andln(I-1);S.isOdd()?(q>(I>>1)-1?T=(I>>1)-q:T=q,S.isubn(T)):T=0,w[D]=T,S.iushrn(1)}return w}r.getNAF=i;function n(h,l){var b=[[],[]];h=h.clone(),l=l.clone();for(var w=0,I=0,S;h.cmpn(-w)>0||l.cmpn(-I)>0;){var D=h.andln(3)+w&3,T=l.andln(3)+I&3;D===3&&(D=-1),T===3&&(T=-1);var q;D&1?(S=h.andln(7)+w&7,(S===3||S===5)&&T===2?q=-D:q=D):q=0,b[0].push(q);var K;T&1?(S=l.andln(7)+I&7,(S===3||S===5)&&D===2?K=-T:K=T):K=0,b[1].push(K),2*w===q+1&&(w=1-w),2*I===K+1&&(I=1-I),h.iushrn(1),l.iushrn(1)}return b}r.getJSF=n;function s(h,l,b){var w="_"+l;h.prototype[l]=function(){return this[w]!==void 0?this[w]:this[w]=b.call(this)}}r.cachedProperty=s;function a(h){return typeof h=="string"?r.toArray(h,"hex"):h}r.parseBytes=a;function u(h){return new mt(h,"hex","le")}r.intFromLE=u}),fh=Ui.getNAF,ES=Ui.getJSF,hh=Ui.assert;function so(t,e){this.type=t,this.p=new mt(e.p,16),this.red=e.prime?mt.red(e.prime):mt.mont(this.p),this.zero=new mt(0).toRed(this.red),this.one=new mt(1).toRed(this.red),this.two=new mt(2).toRed(this.red),this.n=e.n&&new mt(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.gRed),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;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Wo=so;so.prototype.point=function(){throw new Error("Not implemented")},so.prototype.validate=function(){throw new Error("Not implemented")},so.prototype._fixedNafMul=function(t,e){hh(t.precomputed);var r=t._getDoubles(),i=fh(e,1,this._bitLength),n=(1<<r.step+1)-(r.step%2===0?2:1);n/=3;var s=[],a,u;for(a=0;a<i.length;a+=r.step){u=0;for(var h=a+r.step-1;h>=a;h--)u=(u<<1)+i[h];s.push(u)}for(var l=this.jpoint(null,null,null),b=this.jpoint(null,null,null),w=n;w>0;w--){for(a=0;a<s.length;a++)u=s[a],u===w?b=b.mixedAdd(r.points[a]):u===-w&&(b=b.mixedAdd(r.points[a].neg()));l=l.add(b)}return l.toP()},so.prototype._wnafMul=function(t,e){var r=4,i=t._getNAFPoints(r);r=i.wnd;for(var n=i.points,s=fh(e,r,this._bitLength),a=this.jpoint(null,null,null),u=s.length-1;u>=0;u--){for(var h=0;u>=0&&s[u]===0;u--)h++;if(u>=0&&h++,a=a.dblp(h),u<0)break;var l=s[u];hh(l!==0),t.type==="affine"?l>0?a=a.mixedAdd(n[l-1>>1]):a=a.mixedAdd(n[-l-1>>1].neg()):l>0?a=a.add(n[l-1>>1]):a=a.add(n[-l-1>>1].neg())}return t.type==="affine"?a.toP():a},so.prototype._wnafMulAdd=function(t,e,r,i,n){var s=this._wnafT1,a=this._wnafT2,u=this._wnafT3,h=0,l,b,w;for(l=0;l<i;l++){w=e[l];var I=w._getNAFPoints(t);s[l]=I.wnd,a[l]=I.points}for(l=i-1;l>=1;l-=2){var S=l-1,D=l;if(s[S]!==1||s[D]!==1){u[S]=fh(r[S],s[S],this._bitLength),u[D]=fh(r[D],s[D],this._bitLength),h=Math.max(u[S].length,h),h=Math.max(u[D].length,h);continue}var T=[e[S],null,null,e[D]];e[S].y.cmp(e[D].y)===0?(T[1]=e[S].add(e[D]),T[2]=e[S].toJ().mixedAdd(e[D].neg())):e[S].y.cmp(e[D].y.redNeg())===0?(T[1]=e[S].toJ().mixedAdd(e[D]),T[2]=e[S].add(e[D].neg())):(T[1]=e[S].toJ().mixedAdd(e[D]),T[2]=e[S].toJ().mixedAdd(e[D].neg()));var q=[-3,-1,-5,-7,0,7,5,1,3],K=ES(r[S],r[D]);for(h=Math.max(K[0].length,h),u[S]=new Array(h),u[D]=new Array(h),b=0;b<h;b++){var F=K[0][b]|0,W=K[1][b]|0;u[S][b]=q[(F+1)*3+(W+1)],u[D][b]=0,a[S]=T}}var R=this.jpoint(null,null,null),k=this._wnafT4;for(l=h;l>=0;l--){for(var H=0;l>=0;){var _=!0;for(b=0;b<i;b++)k[b]=u[b][l]|0,k[b]!==0&&(_=!1);if(!_)break;H++,l--}if(l>=0&&H++,R=R.dblp(H),l<0)break;for(b=0;b<i;b++){var B=k[b];B!==0&&(B>0?w=a[b][B-1>>1]:B<0&&(w=a[b][-B-1>>1].neg()),w.type==="affine"?R=R.mixedAdd(w):R=R.add(w))}}for(l=0;l<i;l++)a[l]=null;return n?R:R.toP()};function Xi(t,e){this.curve=t,this.type=e,this.precomputed=null}so.BasePoint=Xi,Xi.prototype.eq=function(){throw new Error("Not implemented")},Xi.prototype.validate=function(){return this.curve.validate(this)},so.prototype.decodePoint=function(t,e){t=Ui.toArray(t,e);var r=this.p.byteLength();if((t[0]===4||t[0]===6||t[0]===7)&&t.length-1===2*r){t[0]===6?hh(t[t.length-1]%2===0):t[0]===7&&hh(t[t.length-1]%2===1);var i=this.point(t.slice(1,1+r),t.slice(1+r,1+2*r));return i}else if((t[0]===2||t[0]===3)&&t.length-1===r)return this.pointFromX(t.slice(1,1+r),t[0]===3);throw new Error("Unknown point format")},Xi.prototype.encodeCompressed=function(t){return this.encode(t,!0)},Xi.prototype._encode=function(t){var e=this.curve.p.byteLength(),r=this.getX().toArray("be",e);return t?[this.getY().isEven()?2:3].concat(r):[4].concat(r,this.getY().toArray("be",e))},Xi.prototype.encode=function(t,e){return Ui.encode(this._encode(e),t)},Xi.prototype.precompute=function(t){if(this.precomputed)return this;var e={doubles:null,naf:null,beta:null};return e.naf=this._getNAFPoints(8),e.doubles=this._getDoubles(4,t),e.beta=this._getBeta(),this.precomputed=e,this},Xi.prototype._hasDoubles=function(t){if(!this.precomputed)return!1;var e=this.precomputed.doubles;return e?e.points.length>=Math.ceil((t.bitLength()+1)/e.step):!1},Xi.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],i=this,n=0;n<e;n+=t){for(var s=0;s<t;s++)i=i.dbl();r.push(i)}return{step:t,points:r}},Xi.prototype._getNAFPoints=function(t){if(this.precomputed&&this.precomputed.naf)return this.precomputed.naf;for(var e=[this],r=(1<<t)-1,i=r===1?null:this.dbl(),n=1;n<r;n++)e[n]=e[n-1].add(i);return{wnd:t,points:e}},Xi.prototype._getBeta=function(){return null},Xi.prototype.dblp=function(t){for(var e=this,r=0;r<t;r++)e=e.dbl();return e};var Sd=sc(function(t){typeof Object.create=="function"?t.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,r){if(r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}}}),AS=Ui.assert;function en(t){Wo.call(this,"short",t),this.a=new mt(t.a,16).toRed(this.red),this.b=new mt(t.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,this.endo=this._getEndomorphism(t),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}Sd(en,Wo);var xS=en;en.prototype._getEndomorphism=function(t){if(!(!this.zeroA||!this.g||!this.n||this.p.modn(3)!==1)){var e,r;if(t.beta)e=new mt(t.beta,16).toRed(this.red);else{var i=this._getEndoRoots(this.p);e=i[0].cmp(i[1])<0?i[0]:i[1],e=e.toRed(this.red)}if(t.lambda)r=new mt(t.lambda,16);else{var n=this._getEndoRoots(this.n);this.g.mul(n[0]).x.cmp(this.g.x.redMul(e))===0?r=n[0]:(r=n[1],AS(this.g.mul(r).x.cmp(this.g.x.redMul(e))===0))}var s;return t.basis?s=t.basis.map(function(a){return{a:new mt(a.a,16),b:new mt(a.b,16)}}):s=this._getEndoBasis(r),{beta:e,lambda:r,basis:s}}},en.prototype._getEndoRoots=function(t){var e=t===this.p?this.red:mt.mont(t),r=new mt(2).toRed(e).redInvm(),i=r.redNeg(),n=new mt(3).toRed(e).redNeg().redSqrt().redMul(r),s=i.redAdd(n).fromRed(),a=i.redSub(n).fromRed();return[s,a]},en.prototype._getEndoBasis=function(t){for(var e=this.n.ushrn(Math.floor(this.n.bitLength()/2)),r=t,i=this.n.clone(),n=new mt(1),s=new mt(0),a=new mt(0),u=new mt(1),h,l,b,w,I,S,D,T=0,q,K;r.cmpn(0)!==0;){var F=i.div(r);q=i.sub(F.mul(r)),K=a.sub(F.mul(n));var W=u.sub(F.mul(s));if(!b&&q.cmp(e)<0)h=D.neg(),l=n,b=q.neg(),w=K;else if(b&&++T===2)break;D=q,i=r,r=q,a=n,n=K,u=s,s=W}I=q.neg(),S=K;var R=b.sqr().add(w.sqr()),k=I.sqr().add(S.sqr());return k.cmp(R)>=0&&(I=h,S=l),b.negative&&(b=b.neg(),w=w.neg()),I.negative&&(I=I.neg(),S=S.neg()),[{a:b,b:w},{a:I,b:S}]},en.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],i=e[1],n=i.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),a=n.mul(r.a),u=s.mul(i.a),h=n.mul(r.b),l=s.mul(i.b),b=t.sub(a).sub(u),w=h.add(l).neg();return{k1:b,k2:w}},en.prototype.pointFromX=function(t,e){t=new mt(t,16),t.red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),i=r.redSqrt();if(i.redSqr().redSub(r).cmp(this.zero)!==0)throw new Error("invalid point");var n=i.fromRed().isOdd();return(e&&!n||!e&&n)&&(i=i.redNeg()),this.point(t,i)},en.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,i=this.a.redMul(e),n=e.redSqr().redMul(e).redIAdd(i).redIAdd(this.b);return r.redSqr().redISub(n).cmpn(0)===0},en.prototype._endoWnafMulAdd=function(t,e,r){for(var i=this._endoWnafT1,n=this._endoWnafT2,s=0;s<t.length;s++){var a=this._endoSplit(e[s]),u=t[s],h=u._getBeta();a.k1.negative&&(a.k1.ineg(),u=u.neg(!0)),a.k2.negative&&(a.k2.ineg(),h=h.neg(!0)),i[s*2]=u,i[s*2+1]=h,n[s*2]=a.k1,n[s*2+1]=a.k2}for(var l=this._wnafMulAdd(1,i,n,s*2,r),b=0;b<s*2;b++)i[b]=null,n[b]=null;return l};function Nr(t,e,r,i){Wo.BasePoint.call(this,t,"affine"),e===null&&r===null?(this.x=null,this.y=null,this.inf=!0):(this.x=new mt(e,16),this.y=new mt(r,16),i&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}Sd(Nr,Wo.BasePoint),en.prototype.point=function(t,e,r){return new Nr(this,t,e,r)},en.prototype.pointFromJSON=function(t,e){return Nr.fromJSON(this,t,e)},Nr.prototype._getBeta=function(){if(this.curve.endo){var t=this.precomputed;if(t&&t.beta)return t.beta;var e=this.curve.point(this.x.redMul(this.curve.endo.beta),this.y);if(t){var r=this.curve,i=function(n){return r.point(n.x.redMul(r.endo.beta),n.y)};t.beta=e,e.precomputed={beta:null,naf:t.naf&&{wnd:t.naf.wnd,points:t.naf.points.map(i)},doubles:t.doubles&&{step:t.doubles.step,points:t.doubles.points.map(i)}}}return e}},Nr.prototype.toJSON=function(){return this.precomputed?[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)}}]:[this.x,this.y]},Nr.fromJSON=function(t,e,r){typeof e=="string"&&(e=JSON.parse(e));var i=t.point(e[0],e[1],r);if(!e[2])return i;function n(a){return t.point(a[0],a[1],r)}var s=e[2];return i.precomputed={beta:null,doubles:s.doubles&&{step:s.doubles.step,points:[i].concat(s.doubles.points.map(n))},naf:s.naf&&{wnd:s.naf.wnd,points:[i].concat(s.naf.points.map(n))}},i},Nr.prototype.inspect=function(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+">"},Nr.prototype.isInfinity=function(){return this.inf},Nr.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(this.x.cmp(t.x)===0)return this.curve.point(null,null);var e=this.y.redSub(t.y);e.cmpn(0)!==0&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),i=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,i)},Nr.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(t.cmpn(0)===0)return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),i=t.redInvm(),n=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(i),s=n.redSqr().redISub(this.x.redAdd(this.x)),a=n.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,a)},Nr.prototype.getX=function(){return this.x.fromRed()},Nr.prototype.getY=function(){return this.y.fromRed()},Nr.prototype.mul=function(t){return t=new mt(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},Nr.prototype.mulAdd=function(t,e,r){var i=[this,e],n=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n):this.curve._wnafMulAdd(1,i,n,2)},Nr.prototype.jmulAdd=function(t,e,r){var i=[this,e],n=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(i,n,!0):this.curve._wnafMulAdd(1,i,n,2,!0)},Nr.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||this.x.cmp(t.x)===0&&this.y.cmp(t.y)===0)},Nr.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,i=function(n){return n.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(i)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(i)}}}return e},Nr.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var t=this.curve.jpoint(this.x,this.y,this.curve.one);return t};function Hr(t,e,r,i){Wo.BasePoint.call(this,t,"jacobian"),e===null&&r===null&&i===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new mt(0)):(this.x=new mt(e,16),this.y=new mt(r,16),this.z=new mt(i,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}Sd(Hr,Wo.BasePoint),en.prototype.jpoint=function(t,e,r){return new Hr(this,t,e,r)},Hr.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),i=this.y.redMul(e).redMul(t);return this.curve.point(r,i)},Hr.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},Hr.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),i=this.x.redMul(e),n=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),a=t.y.redMul(r.redMul(this.z)),u=i.redSub(n),h=s.redSub(a);if(u.cmpn(0)===0)return h.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var l=u.redSqr(),b=l.redMul(u),w=i.redMul(l),I=h.redSqr().redIAdd(b).redISub(w).redISub(w),S=h.redMul(w.redISub(I)).redISub(s.redMul(b)),D=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(I,S,D)},Hr.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,i=t.x.redMul(e),n=this.y,s=t.y.redMul(e).redMul(this.z),a=r.redSub(i),u=n.redSub(s);if(a.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var h=a.redSqr(),l=h.redMul(a),b=r.redMul(h),w=u.redSqr().redIAdd(l).redISub(b).redISub(b),I=u.redMul(b.redISub(w)).redISub(n.redMul(l)),S=this.z.redMul(a);return this.curve.jpoint(w,I,S)},Hr.prototype.dblp=function(t){if(t===0)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e<t;e++)r=r.dbl();return r}var i=this.curve.a,n=this.curve.tinv,s=this.x,a=this.y,u=this.z,h=u.redSqr().redSqr(),l=a.redAdd(a);for(e=0;e<t;e++){var b=s.redSqr(),w=l.redSqr(),I=w.redSqr(),S=b.redAdd(b).redIAdd(b).redIAdd(i.redMul(h)),D=s.redMul(w),T=S.redSqr().redISub(D.redAdd(D)),q=D.redISub(T),K=S.redMul(q);K=K.redIAdd(K).redISub(I);var F=l.redMul(u);e+1<t&&(h=h.redMul(I)),s=T,u=F,l=K}return this.curve.jpoint(s,l.redMul(n),u)},Hr.prototype.dbl=function(){return this.isInfinity()?this:this.curve.zeroA?this._zeroDbl():this.curve.threeA?this._threeDbl():this._dbl()},Hr.prototype._zeroDbl=function(){var t,e,r;if(this.zOne){var i=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr(),a=this.x.redAdd(n).redSqr().redISub(i).redISub(s);a=a.redIAdd(a);var u=i.redAdd(i).redIAdd(i),h=u.redSqr().redISub(a).redISub(a),l=s.redIAdd(s);l=l.redIAdd(l),l=l.redIAdd(l),t=h,e=u.redMul(a.redISub(h)).redISub(l),r=this.y.redAdd(this.y)}else{var b=this.x.redSqr(),w=this.y.redSqr(),I=w.redSqr(),S=this.x.redAdd(w).redSqr().redISub(b).redISub(I);S=S.redIAdd(S);var D=b.redAdd(b).redIAdd(b),T=D.redSqr(),q=I.redIAdd(I);q=q.redIAdd(q),q=q.redIAdd(q),t=T.redISub(S).redISub(S),e=D.redMul(S.redISub(t)).redISub(q),r=this.y.redMul(this.z),r=r.redIAdd(r)}return this.curve.jpoint(t,e,r)},Hr.prototype._threeDbl=function(){var t,e,r;if(this.zOne){var i=this.x.redSqr(),n=this.y.redSqr(),s=n.redSqr(),a=this.x.redAdd(n).redSqr().redISub(i).redISub(s);a=a.redIAdd(a);var u=i.redAdd(i).redIAdd(i).redIAdd(this.curve.a),h=u.redSqr().redISub(a).redISub(a);t=h;var l=s.redIAdd(s);l=l.redIAdd(l),l=l.redIAdd(l),e=u.redMul(a.redISub(h)).redISub(l),r=this.y.redAdd(this.y)}else{var b=this.z.redSqr(),w=this.y.redSqr(),I=this.x.redMul(w),S=this.x.redSub(b).redMul(this.x.redAdd(b));S=S.redAdd(S).redIAdd(S);var D=I.redIAdd(I);D=D.redIAdd(D);var T=D.redAdd(D);t=S.redSqr().redISub(T),r=this.y.redAdd(this.z).redSqr().redISub(w).redISub(b);var q=w.redSqr();q=q.redIAdd(q),q=q.redIAdd(q),q=q.redIAdd(q),e=S.redMul(D.redISub(t)).redISub(q)}return this.curve.jpoint(t,e,r)},Hr.prototype._dbl=function(){var t=this.curve.a,e=this.x,r=this.y,i=this.z,n=i.redSqr().redSqr(),s=e.redSqr(),a=r.redSqr(),u=s.redAdd(s).redIAdd(s).redIAdd(t.redMul(n)),h=e.redAdd(e);h=h.redIAdd(h);var l=h.redMul(a),b=u.redSqr().redISub(l.redAdd(l)),w=l.redISub(b),I=a.redSqr();I=I.redIAdd(I),I=I.redIAdd(I),I=I.redIAdd(I);var S=u.redMul(w).redISub(I),D=r.redAdd(r).redMul(i);return this.curve.jpoint(b,S,D)},Hr.prototype.trpl=function(){if(!this.curve.zeroA)return this.dbl().add(this);var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr(),i=e.redSqr(),n=t.redAdd(t).redIAdd(t),s=n.redSqr(),a=this.x.redAdd(e).redSqr().redISub(t).redISub(i);a=a.redIAdd(a),a=a.redAdd(a).redIAdd(a),a=a.redISub(s);var u=a.redSqr(),h=i.redIAdd(i);h=h.redIAdd(h),h=h.redIAdd(h),h=h.redIAdd(h);var l=n.redIAdd(a).redSqr().redISub(s).redISub(u).redISub(h),b=e.redMul(l);b=b.redIAdd(b),b=b.redIAdd(b);var w=this.x.redMul(u).redISub(b);w=w.redIAdd(w),w=w.redIAdd(w);var I=this.y.redMul(l.redMul(h.redISub(l)).redISub(a.redMul(u)));I=I.redIAdd(I),I=I.redIAdd(I),I=I.redIAdd(I);var S=this.z.redAdd(a).redSqr().redISub(r).redISub(u);return this.curve.jpoint(w,I,S)},Hr.prototype.mul=function(t,e){return t=new mt(t,e),this.curve._wnafMul(this,t)},Hr.prototype.eq=function(t){if(t.type==="affine")return this.eq(t.toJ());if(this===t)return!0;var e=this.z.redSqr(),r=t.z.redSqr();if(this.x.redMul(r).redISub(t.x.redMul(e)).cmpn(0)!==0)return!1;var i=e.redMul(this.z),n=r.redMul(t.z);return this.y.redMul(n).redISub(t.y.redMul(i)).cmpn(0)===0},Hr.prototype.eqXToP=function(t){var e=this.z.redSqr(),r=t.toRed(this.curve.red).redMul(e);if(this.x.cmp(r)===0)return!0;for(var i=t.clone(),n=this.curve.redN.redMul(e);;){if(i.iadd(this.curve.n),i.cmp(this.curve.p)>=0)return!1;if(r.redIAdd(n),this.x.cmp(r)===0)return!0}},Hr.prototype.inspect=function(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"},Hr.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var lh=sc(function(t,e){var r=e;r.base=Wo,r.short=xS,r.mont=null,r.edwards=null}),dh=sc(function(t,e){var r=e,i=Ui.assert;function n(u){u.type==="short"?this.curve=new lh.short(u):u.type==="edwards"?this.curve=new lh.edwards(u):this.curve=new lh.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,i(this.g.validate(),"Invalid curve"),i(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}r.PresetCurve=n;function s(u,h){Object.defineProperty(r,u,{configurable:!0,enumerable:!0,get:function(){var l=new n(h);return Object.defineProperty(r,u,{configurable:!0,enumerable:!0,value:l}),l}})}s("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:Zn.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),s("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:Zn.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),s("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:Zn.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),s("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:Zn.sha384,gRed:!1,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"]}),s("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:Zn.sha512,gRed:!1,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"]}),s("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Zn.sha256,gRed:!1,g:["9"]}),s("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Zn.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var a;try{a=null.crash()}catch{a=void 0}s("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:Zn.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",a]})});function oo(t){if(!(this instanceof oo))return new oo(t);this.hash=t.hash,this.predResist=!!t.predResist,this.outLen=this.hash.outSize,this.minEntropy=t.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=An.toArray(t.entropy,t.entropyEnc||"hex"),r=An.toArray(t.nonce,t.nonceEnc||"hex"),i=An.toArray(t.pers,t.persEnc||"hex");xd(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,i)}var Ym=oo;oo.prototype._init=function(t,e,r){var i=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var n=0;n<this.V.length;n++)this.K[n]=0,this.V[n]=1;this._update(i),this._reseed=1,this.reseedInterval=281474976710656},oo.prototype._hmac=function(){return new Zn.hmac(this.hash,this.K)},oo.prototype._update=function(t){var e=this._hmac().update(this.V).update([0]);t&&(e=e.update(t)),this.K=e.digest(),this.V=this._hmac().update(this.V).digest(),t&&(this.K=this._hmac().update(this.V).update([1]).update(t).digest(),this.V=this._hmac().update(this.V).digest())},oo.prototype.reseed=function(t,e,r,i){typeof e!="string"&&(i=r,r=e,e=null),t=An.toArray(t,e),r=An.toArray(r,i),xd(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},oo.prototype.generate=function(t,e,r,i){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof e!="string"&&(i=r,r=e,e=null),r&&(r=An.toArray(r,i||"hex"),this._update(r));for(var n=[];n.length<t;)this.V=this._hmac().update(this.V).digest(),n=n.concat(this.V);var s=n.slice(0,t);return this._update(r),this._reseed++,An.encode(s,e)};var Id=Ui.assert;function Yr(t,e){this.ec=t,this.priv=null,this.pub=null,e.priv&&this._importPrivate(e.priv,e.privEnc),e.pub&&this._importPublic(e.pub,e.pubEnc)}var Md=Yr;Yr.fromPublic=function(t,e,r){return e instanceof Yr?e:new Yr(t,{pub:e,pubEnc:r})},Yr.fromPrivate=function(t,e,r){return e instanceof Yr?e:new Yr(t,{priv:e,privEnc:r})},Yr.prototype.validate=function(){var t=this.getPublic();return t.isInfinity()?{result:!1,reason:"Invalid public key"}:t.validate()?t.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},Yr.prototype.getPublic=function(t,e){return typeof t=="string"&&(e=t,t=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),e?this.pub.encode(e,t):this.pub},Yr.prototype.getPrivate=function(t){return t==="hex"?this.priv.toString(16,2):this.priv},Yr.prototype._importPrivate=function(t,e){this.priv=new mt(t,e||16),this.priv=this.priv.umod(this.ec.curve.n)},Yr.prototype._importPublic=function(t,e){if(t.x||t.y){this.ec.curve.type==="mont"?Id(t.x,"Need x coordinate"):(this.ec.curve.type==="short"||this.ec.curve.type==="edwards")&&Id(t.x&&t.y,"Need both x and y coordinate"),this.pub=this.ec.curve.point(t.x,t.y);return}this.pub=this.ec.curve.decodePoint(t,e)},Yr.prototype.derive=function(t){return t.validate()||Id(t.validate(),"public point not validated"),t.mul(this.priv).getX()},Yr.prototype.sign=function(t,e,r){return this.ec.sign(t,this,e,r)},Yr.prototype.verify=function(t,e){return this.ec.verify(t,e,this)},Yr.prototype.inspect=function(){return"<Key priv: "+(this.priv&&this.priv.toString(16,2))+" pub: "+(this.pub&&this.pub.inspect())+" >"};var SS=Ui.assert;function ph(t,e){if(t instanceof ph)return t;this._importDER(t,e)||(SS(t.r&&t.s,"Signature without r or s"),this.r=new mt(t.r,16),this.s=new mt(t.s,16),t.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var gh=ph;function IS(){this.place=0}function Cd(t,e){var r=t[e.place++];if(!(r&128))return r;var i=r&15;if(i===0||i>4)return!1;for(var n=0,s=0,a=e.place;s<i;s++,a++)n<<=8,n|=t[a],n>>>=0;return n<=127?!1:(e.place=a,n)}function Qm(t){for(var e=0,r=t.length-1;!t[e]&&!(t[e+1]&128)&&e<r;)e++;return e===0?t:t.slice(e)}ph.prototype._importDER=function(t,e){t=Ui.toArray(t,e);var r=new IS;if(t[r.place++]!==48)return!1;var i=Cd(t,r);if(i===!1||i+r.place!==t.length||t[r.place++]!==2)return!1;var n=Cd(t,r);if(n===!1)return!1;var s=t.slice(r.place,n+r.place);if(r.place+=n,t[r.place++]!==2)return!1;var a=Cd(t,r);if(a===!1||t.length!==a+r.place)return!1;var u=t.slice(r.place,a+r.place);if(s[0]===0)if(s[1]&128)s=s.slice(1);else return!1;if(u[0]===0)if(u[1]&128)u=u.slice(1);else return!1;return this.r=new mt(s),this.s=new mt(u),this.recoveryParam=null,!0};function Dd(t,e){if(e<128){t.push(e);return}var r=1+(Math.log(e)/Math.LN2>>>3);for(t.push(r|128);--r;)t.push(e>>>(r<<3)&255);t.push(e)}ph.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(e[0]&128&&(e=[0].concat(e)),r[0]&128&&(r=[0].concat(r)),e=Qm(e),r=Qm(r);!r[0]&&!(r[1]&128);)r=r.slice(1);var i=[2];Dd(i,e.length),i=i.concat(e),i.push(2),Dd(i,r.length);var n=i.concat(r),s=[48];return Dd(s,n.length),s=s.concat(n),Ui.encode(s,t)};var MS=function(){throw new Error("unsupported")},Zm=Ui.assert;function tn(t){if(!(this instanceof tn))return new tn(t);typeof t=="string"&&(Zm(Object.prototype.hasOwnProperty.call(dh,t),"Unknown curve "+t),t=dh[t]),t instanceof dh.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var CS=tn;tn.prototype.keyPair=function(t){return new Md(this,t)},tn.prototype.keyFromPrivate=function(t,e){return Md.fromPrivate(this,t,e)},tn.prototype.keyFromPublic=function(t,e){return Md.fromPublic(this,t,e)},tn.prototype.genKeyPair=function(t){t||(t={});for(var e=new Ym({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||MS(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),i=this.n.sub(new mt(2));;){var n=new mt(e.generate(r));if(!(n.cmp(i)>0))return n.iaddn(1),this.keyFromPrivate(n)}},tn.prototype._truncateToN=function(t,e){var r=t.byteLength()*8-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},tn.prototype.sign=function(t,e,r,i){typeof r=="object"&&(i=r,r=null),i||(i={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new mt(t,16));for(var n=this.n.byteLength(),s=e.getPrivate().toArray("be",n),a=t.toArray("be",n),u=new Ym({hash:this.hash,entropy:s,nonce:a,pers:i.pers,persEnc:i.persEnc||"utf8"}),h=this.n.sub(new mt(1)),l=0;;l++){var b=i.k?i.k(l):new mt(u.generate(this.n.byteLength()));if(b=this._truncateToN(b,!0),!(b.cmpn(1)<=0||b.cmp(h)>=0)){var w=this.g.mul(b);if(!w.isInfinity()){var I=w.getX(),S=I.umod(this.n);if(S.cmpn(0)!==0){var D=b.invm(this.n).mul(S.mul(e.getPrivate()).iadd(t));if(D=D.umod(this.n),D.cmpn(0)!==0){var T=(w.getY().isOdd()?1:0)|(I.cmp(S)!==0?2:0);return i.canonical&&D.cmp(this.nh)>0&&(D=this.n.sub(D),T^=1),new gh({r:S,s:D,recoveryParam:T})}}}}}},tn.prototype.verify=function(t,e,r,i){t=this._truncateToN(new mt(t,16)),r=this.keyFromPublic(r,i),e=new gh(e,"hex");var n=e.r,s=e.s;if(n.cmpn(1)<0||n.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var a=s.invm(this.n),u=a.mul(t).umod(this.n),h=a.mul(n).umod(this.n),l;return this.curve._maxwellTrick?(l=this.g.jmulAdd(u,r.getPublic(),h),l.isInfinity()?!1:l.eqXToP(n)):(l=this.g.mulAdd(u,r.getPublic(),h),l.isInfinity()?!1:l.getX().umod(this.n).cmp(n)===0)},tn.prototype.recoverPubKey=function(t,e,r,i){Zm((3&r)===r,"The recovery param is more than two bits"),e=new gh(e,i);var n=this.n,s=new mt(t),a=e.r,u=e.s,h=r&1,l=r>>1;if(a.cmp(this.curve.p.umod(this.curve.n))>=0&&l)throw new Error("Unable to find sencond key candinate");l?a=this.curve.pointFromX(a.add(this.curve.n),h):a=this.curve.pointFromX(a,h);var b=e.r.invm(n),w=n.sub(s).mul(b).umod(n),I=u.mul(b).umod(n);return this.g.mulAdd(w,a,I)},tn.prototype.getKeyRecoveryParam=function(t,e,r,i){if(e=new gh(e,i),e.recoveryParam!==null)return e.recoveryParam;for(var n=0;n<4;n++){var s;try{s=this.recoverPubKey(t,e,n)}catch{continue}if(s.eq(r))return n}throw new Error("Unable to find valid recovery factor")};var DS=sc(function(t,e){var r=e;r.version="6.5.4",r.utils=Ui,r.rand=function(){throw new Error("unsupported")},r.curve=lh,r.curves=dh,r.ec=CS,r.eddsa=null}),OS=DS.ec;const PS="signing-key/5.7.0",Od=new Et(PS);let Pd=null;function os(){return Pd||(Pd=new OS("secp256k1")),Pd}class $S{constructor(e){du(this,"curve","secp256k1"),du(this,"privateKey",si(e)),pA(this.privateKey)!==32&&Od.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");const r=os().keyFromPrivate(dr(this.privateKey));du(this,"publicKey","0x"+r.getPublic(!1,"hex")),du(this,"compressedPublicKey","0x"+r.getPublic(!0,"hex")),du(this,"_isSigningKey",!0)}_addPoint(e){const r=os().keyFromPublic(dr(this.publicKey)),i=os().keyFromPublic(dr(e));return"0x"+r.pub.add(i.pub).encodeCompressed("hex")}signDigest(e){const r=os().keyFromPrivate(dr(this.privateKey)),i=dr(e);i.length!==32&&Od.throwArgumentError("bad digest length","digest",e);const n=r.sign(i,{canonical:!0});return cm({recoveryParam:n.recoveryParam,r:Qn("0x"+n.r.toString(16),32),s:Qn("0x"+n.s.toString(16),32)})}computeSharedSecret(e){const r=os().keyFromPrivate(dr(this.privateKey)),i=os().keyFromPublic(dr(Xm(e)));return Qn("0x"+r.derive(i.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}}function RS(t,e){const r=cm(e),i={r:dr(r.r),s:dr(r.s)};return"0x"+os().recoverPubKey(dr(t),i,r.recoveryParam).encode("hex",!1)}function Xm(t,e){const r=dr(t);if(r.length===32){const i=new $S(r);return e?"0x"+os().keyFromPrivate(r).getPublic(!0,"hex"):i.publicKey}else{if(r.length===33)return e?si(r):"0x"+os().keyFromPublic(r).getPublic(!1,"hex");if(r.length===65)return e?"0x"+os().keyFromPublic(r).getPublic(!0,"hex"):si(r)}return Od.throwArgumentError("invalid public or private key","key","[REDACTED]")}const NS="transactions/5.7.0";new Et(NS);var eb;(function(t){t[t.legacy=0]="legacy",t[t.eip2930=1]="eip2930",t[t.eip1559=2]="eip1559"})(eb||(eb={}));function TS(t){const e=Xm(t);return KA(am(hd(am(e,1)),12))}function LS(t,e){return TS(RS(dr(t),e))}const BS="https://rpc.walletconnect.org/v1";async function FS(t,e,r,i,n,s){switch(r.t){case"eip191":return US(t,e,r.s);case"eip1271":return await kS(t,e,r.s,i,n,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function US(t,e,r){return LS(xm(e),r).toLowerCase()===t.toLowerCase()}async function kS(t,e,r,i,n,s){try{const a="0x1626ba7e",u="0000000000000000000000000000000000000000000000000000000000000040",h="0000000000000000000000000000000000000000000000000000000000000041",l=r.substring(2),b=xm(e).substring(2),w=a+b+u+h+l,I=await fetch(`${s||BS}/?chainId=${i}&projectId=${n}`,{method:"POST",body:JSON.stringify({id:qS(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:w},"latest"]})}),{result:S}=await I.json();return S?S.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function qS(){return Date.now()+Math.floor(Math.random()*1e3)}var jS=Object.defineProperty,zS=Object.defineProperties,HS=Object.getOwnPropertyDescriptors,tb=Object.getOwnPropertySymbols,KS=Object.prototype.hasOwnProperty,WS=Object.prototype.propertyIsEnumerable,rb=(t,e,r)=>e in t?jS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,VS=(t,e)=>{for(var r in e||(e={}))KS.call(e,r)&&rb(t,r,e[r]);if(tb)for(var r of tb(e))WS.call(e,r)&&rb(t,r,e[r]);return t},GS=(t,e)=>zS(t,HS(e));const JS="did:pkh:",$d=t=>t?.split(":"),ib=t=>{const e=t&&$d(t);if(e)return t.includes(JS)?e[3]:e[1]},nb=t=>{const e=t&&$d(t);if(e)return e[2]+":"+e[3]},vh=t=>{const e=t&&$d(t);if(e)return e.pop()};async function sb(t){const{cacao:e,projectId:r}=t,{s:i,p:n}=e,s=ob(n,n.iss),a=vh(n.iss);return await FS(a,s,i,ib(n.iss),r)}const ob=(t,e)=>{const r=`${t.domain} wants you to sign in with your Ethereum account:`,i=vh(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let n=t.statement||void 0;const s=`URI: ${t.aud||t.uri}`,a=`Version: ${t.version}`,u=`Chain ID: ${ib(e)}`,h=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,b=t.exp?`Expiration Time: ${t.exp}`:void 0,w=t.nbf?`Not Before: ${t.nbf}`:void 0,I=t.requestId?`Request ID: ${t.requestId}`:void 0,S=t.resources?`Resources:${t.resources.map(T=>`
|
|
23
23
|
- ${T}`).join("")}`:void 0,D=mh(t.resources);if(D){const T=mu(D);n=nI(n,T)}return[r,i,"",n,"",s,a,u,h,l,b,w,I,S].filter(T=>T!=null).join(`
|
|
24
24
|
`)};function YS(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function QS(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function Vo(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{const i=t.att[r];if(Array.isArray(i))throw new Error(`Resource must be an object: ${r}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(i).forEach(n=>{const s=i[n];if(!Array.isArray(s))throw new Error(`Ability limits ${n} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${n} is empty array, must be an array with objects`);s.forEach(a=>{if(typeof a!="object")throw new Error(`Ability limits (${n}) must be an array of objects, found: ${a}`)})})})}function ZS(t,e,r,i={}){return r?.sort((n,s)=>n.localeCompare(s)),{att:{[t]:XS(e,r,i)}}}function XS(t,e,r={}){e=e?.sort((n,s)=>n.localeCompare(s));const i=e.map(n=>({[`${t}/${n}`]:[r]}));return Object.assign({},...i)}function ab(t){return Vo(t),`urn:recap:${YS(t).replace(/=/g,"")}`}function mu(t){const e=QS(t.replace("urn:recap:",""));return Vo(e),e}function eI(t,e,r){const i=ZS(t,e,r);return ab(i)}function tI(t){return t&&t.includes("urn:recap:")}function rI(t,e){const r=mu(t),i=mu(e),n=iI(r,i);return ab(n)}function iI(t,e){Vo(t),Vo(e);const r=Object.keys(t.att).concat(Object.keys(e.att)).sort((n,s)=>n.localeCompare(s)),i={att:{}};return r.forEach(n=>{var s,a;Object.keys(((s=t.att)==null?void 0:s[n])||{}).concat(Object.keys(((a=e.att)==null?void 0:a[n])||{})).sort((u,h)=>u.localeCompare(h)).forEach(u=>{var h,l;i.att[n]=GS(VS({},i.att[n]),{[u]:((h=t.att[n])==null?void 0:h[u])||((l=e.att[n])==null?void 0:l[u])})})}),i}function nI(t="",e){Vo(e);const r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;const i=[];let n=0;Object.keys(e.att).forEach(u=>{const h=Object.keys(e.att[u]).map(w=>({ability:w.split("/")[0],action:w.split("/")[1]}));h.sort((w,I)=>w.action.localeCompare(I.action));const l={};h.forEach(w=>{l[w.ability]||(l[w.ability]=[]),l[w.ability].push(w.action)});const b=Object.keys(l).map(w=>(n++,`(${n}) '${w}': '${l[w].join("', '")}' for '${u}'.`));i.push(b.join(", ").replace(".,","."))});const s=i.join(" "),a=`${r}${s}`;return`${t?t+" ":""}${a}`}function cb(t){var e;const r=mu(t);Vo(r);const i=(e=r.att)==null?void 0:e.eip155;return i?Object.keys(i).map(n=>n.split("/")[1]):[]}function ub(t){const e=mu(t);Vo(e);const r=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(n=>{var s;(s=n?.[0])!=null&&s.chains&&r.push(n[0].chains)})}),[...new Set(r.flat())]}function mh(t){if(!t)return;const e=t?.[t.length-1];return tI(e)?e:void 0}const fb="base10",ai="base16",ao="base64pad",bu="base64url",yu="utf8",hb=0,Rs=1,wu=2,sI=0,lb=1,_u=12,Rd=32;function oI(){const t=L0.generateKeyPair();return{privateKey:Ti(t.secretKey,ai),publicKey:Ti(t.publicKey,ai)}}function Nd(){const t=Zs.randomBytes(Rd);return Ti(t,ai)}function aI(t,e){const r=L0.sharedKey(Gi(t,ai),Gi(e,ai),!0),i=new B8(eu.SHA256,r).expand(Rd);return Ti(i,ai)}function bh(t){const e=eu.hash(Gi(t,ai));return Ti(e,ai)}function Ns(t){const e=eu.hash(Gi(t,yu));return Ti(e,ai)}function db(t){return Gi(`${t}`,fb)}function Go(t){return Number(Ti(t,fb))}function cI(t){const e=db(typeof t.type<"u"?t.type:hb);if(Go(e)===Rs&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?Gi(t.senderPublicKey,ai):void 0,i=typeof t.iv<"u"?Gi(t.iv,ai):Zs.randomBytes(_u),n=new C0.ChaCha20Poly1305(Gi(t.symKey,ai)).seal(i,Gi(t.message,yu));return pb({type:e,sealed:n,iv:i,senderPublicKey:r,encoding:t.encoding})}function uI(t,e){const r=db(wu),i=Zs.randomBytes(_u),n=Gi(t,yu);return pb({type:r,sealed:n,iv:i,encoding:e})}function fI(t){const e=new C0.ChaCha20Poly1305(Gi(t.symKey,ai)),{sealed:r,iv:i}=Eu({encoded:t.encoded,encoding:t?.encoding}),n=e.open(i,r);if(n===null)throw new Error("Failed to decrypt");return Ti(n,yu)}function hI(t,e){const{sealed:r}=Eu({encoded:t,encoding:e});return Ti(r,yu)}function pb(t){const{encoding:e=ao}=t;if(Go(t.type)===wu)return Ti(B0([t.type,t.sealed]),e);if(Go(t.type)===Rs){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ti(B0([t.type,t.senderPublicKey,t.iv,t.sealed]),e)}return Ti(B0([t.type,t.iv,t.sealed]),e)}function Eu(t){const{encoded:e,encoding:r=ao}=t,i=Gi(e,r),n=i.slice(sI,lb),s=lb;if(Go(n)===Rs){const l=s+Rd,b=l+_u,w=i.slice(s,l),I=i.slice(l,b),S=i.slice(b);return{type:n,sealed:S,iv:I,senderPublicKey:w}}if(Go(n)===wu){const l=i.slice(s),b=Zs.randomBytes(_u);return{type:n,sealed:l,iv:b}}const a=s+_u,u=i.slice(s,a),h=i.slice(a);return{type:n,sealed:h,iv:u}}function lI(t,e){const r=Eu({encoded:t,encoding:e?.encoding});return gb({type:Go(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ti(r.senderPublicKey,ai):void 0,receiverPublicKey:e?.receiverPublicKey})}function gb(t){const e=t?.type||hb;if(e===Rs){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function vb(t){return t.type===Rs&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function mb(t){return t.type===wu}function dI(t){return new Kv.ec("p256").keyFromPublic({x:Buffer.from(t.x,"base64").toString("hex"),y:Buffer.from(t.y,"base64").toString("hex")},"hex")}function pI(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");const r=e.length%4;return r>0&&(e+="=".repeat(4-r)),e}function gI(t){return Buffer.from(pI(t),"base64")}function vI(t,e){const[r,i,n]=t.split("."),s=gI(n);if(s.length!==64)throw new Error("Invalid signature length");const a=s.slice(0,32).toString("hex"),u=s.slice(32,64).toString("hex"),h=`${r}.${i}`,l=new eu.SHA256().update(Buffer.from(h)).digest(),b=dI(e),w=Buffer.from(l).toString("hex");if(!b.verify(w,{r:a,s:u}))throw new Error("Invalid signature");return od(t).payload}const mI="irn";function Td(t){return t?.relay||{protocol:mI}}function Au(t){const e=HE[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var bI=Object.defineProperty,yI=Object.defineProperties,wI=Object.getOwnPropertyDescriptors,bb=Object.getOwnPropertySymbols,_I=Object.prototype.hasOwnProperty,EI=Object.prototype.propertyIsEnumerable,yb=(t,e,r)=>e in t?bI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wb=(t,e)=>{for(var r in e||(e={}))_I.call(e,r)&&yb(t,r,e[r]);if(bb)for(var r of bb(e))EI.call(e,r)&&yb(t,r,e[r]);return t},AI=(t,e)=>yI(t,wI(e));function xI(t,e="-"){const r={},i="relay"+e;return Object.keys(t).forEach(n=>{if(n.startsWith(i)){const s=n.replace(i,""),a=t[n];r[s]=a}}),r}function _b(t){t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,i=t.substring(0,e),n=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",a=Zc.parse(s),u=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:SI(n[0]),version:parseInt(n[1],10),symKey:a.symKey,relay:xI(a),methods:u,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function SI(t){return t.startsWith("//")?t.substring(2):t}function II(t,e="-"){const r="relay",i={};return Object.keys(t).forEach(n=>{const s=r+e+n;t[n]&&(i[s]=t[n])}),i}function MI(t){return`${t.protocol}:${t.topic}@${t.version}?`+Zc.stringify(wb(AI(wb({symKey:t.symKey},II(t.relay)),{expiryTimestamp:t.expiryTimestamp}),t.methods?{methods:t.methods.join(",")}:{}))}function yh(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}function oc(t){const e=[];return t.forEach(r=>{const[i,n]=r.split(":");e.push(`${i}:${n}`)}),e}function CI(t){const e=[];return Object.values(t).forEach(r=>{e.push(...oc(r.accounts))}),e}function DI(t,e){const r=[];return Object.values(t).forEach(i=>{oc(i.accounts).includes(e)&&r.push(...i.methods)}),r}function OI(t,e){const r=[];return Object.values(t).forEach(i=>{oc(i.accounts).includes(e)&&r.push(...i.events)}),r}function Ld(t){return t.includes(":")}function xu(t){return Ld(t)?t.split(":")[0]:t}function PI(t){const e={};return t?.forEach(r=>{const[i,n]=r.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[]}),e[i].accounts.push(r),e[i].chains.push(`${i}:${n}`)}),e}function Eb(t,e){e=e.map(i=>i.replace("did:pkh:",""));const r=PI(e);for(const[i,n]of Object.entries(r))n.methods?n.methods=rh(n.methods,t):n.methods=t,n.events=["chainChanged","accountsChanged"];return r}const $I={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},RI={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Ee(t,e){const{message:r,code:i}=RI[t];return{message:e?`${r} ${e}`:r,code:i}}function Gt(t,e){const{message:r,code:i}=$I[t];return{message:e?`${r} ${e}`:r,code:i}}function as(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Su(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function ci(t){return typeof t>"u"}function yr(t,e){return e&&ci(t)?!0:typeof t=="string"&&!!t.trim().length}function Bd(t,e){return e&&ci(t)?!0:typeof t=="number"&&!isNaN(t)}function NI(t,e){const{requiredNamespaces:r}=e,i=Object.keys(t.namespaces),n=Object.keys(r);let s=!0;return zo(n,i)?(i.forEach(a=>{const{accounts:u,methods:h,events:l}=t.namespaces[a],b=oc(u),w=r[a];(!zo(k2(a,w),b)||!zo(w.methods,h)||!zo(w.events,l))&&(s=!1)}),s):!1}function wh(t){return yr(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function TI(t){if(yr(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&wh(r)}}return!1}function LI(t){if(yr(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function BI(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function FI(t){return t?.topic}function UI(t,e){let r=null;return yr(t?.publicKey,!1)||(r=Ee("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function Ab(t){let e=!0;return as(t)?t.length&&(e=t.every(r=>yr(r,!1))):e=!1,e}function kI(t,e,r){let i=null;return as(e)&&e.length?e.forEach(n=>{i||wh(n)||(i=Gt("UNSUPPORTED_CHAINS",`${r}, chain ${n} should be a string and conform to "namespace:chainId" format`))}):wh(t)||(i=Gt("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function qI(t,e,r){let i=null;return Object.entries(t).forEach(([n,s])=>{if(i)return;const a=kI(n,k2(n,s),`${e} ${r}`);a&&(i=a)}),i}function jI(t,e){let r=null;return as(t)?t.forEach(i=>{r||TI(i)||(r=Gt("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):r=Gt("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function zI(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const n=jI(i?.accounts,`${e} namespace`);n&&(r=n)}),r}function HI(t,e){let r=null;return Ab(t?.methods)?Ab(t?.events)||(r=Gt("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=Gt("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function xb(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const n=HI(i,`${e}, namespace`);n&&(r=n)}),r}function KI(t,e,r){let i=null;if(t&&Su(t)){const n=xb(t,e);n&&(i=n);const s=qI(t,e,r);s&&(i=s)}else i=Ee("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return i}function Fd(t,e){let r=null;if(t&&Su(t)){const i=xb(t,e);i&&(r=i);const n=zI(t,e);n&&(r=n)}else r=Ee("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function Sb(t){return yr(t.protocol,!0)}function WI(t,e){let r=!1;return e&&!t?r=!0:t&&as(t)&&t.length&&t.forEach(i=>{r=Sb(i)}),r}function VI(t){return typeof t=="number"}function _i(t){return typeof t<"u"&&typeof t!==null}function GI(t){return!(!t||typeof t!="object"||!t.code||!Bd(t.code,!1)||!t.message||!yr(t.message,!1))}function JI(t){return!(ci(t)||!yr(t.method,!1))}function YI(t){return!(ci(t)||ci(t.result)&&ci(t.error)||!Bd(t.id,!1)||!yr(t.jsonrpc,!1))}function QI(t){return!(ci(t)||!yr(t.name,!1))}function Ib(t,e){return!(!wh(e)||!CI(t).includes(e))}function ZI(t,e,r){return yr(r,!1)?DI(t,e).includes(r):!1}function XI(t,e,r){return yr(r,!1)?OI(t,e).includes(r):!1}function Mb(t,e,r){let i=null;const n=eM(t),s=tM(e),a=Object.keys(n),u=Object.keys(s),h=Cb(Object.keys(t)),l=Cb(Object.keys(e)),b=h.filter(w=>!l.includes(w));return b.length&&(i=Ee("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
|
|
25
25
|
Required: ${b.toString()}
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
Required: ${a.toString()}
|
|
28
28
|
Approved: ${u.toString()}`)),Object.keys(e).forEach(w=>{if(!w.includes(":")||i)return;const I=oc(e[w].accounts);I.includes(w)||(i=Ee("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${w}
|
|
29
29
|
Required: ${w}
|
|
30
|
-
Approved: ${I.toString()}`))}),a.forEach(w=>{i||(zo(n[w].methods,s[w].methods)?zo(n[w].events,s[w].events)||(i=Ee("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${w}`)):i=Ee("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${w}`))}),i}function eM(t){const e={};return Object.keys(t).forEach(r=>{var i;r.includes(":")?e[r]=t[r]:(i=t[r].chains)==null||i.forEach(n=>{e[n]={methods:t[r].methods,events:t[r].events}})}),e}function Cb(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function tM(t){const e={};return Object.keys(t).forEach(r=>{if(r.includes(":"))e[r]=t[r];else{const i=oc(t[r].accounts);i?.forEach(n=>{e[n]={accounts:t[r].accounts.filter(s=>s.includes(`${n}:`)),methods:t[r].methods,events:t[r].events}})}}),e}function rM(t,e){return Bd(t,!1)&&t<=e.max&&t>=e.min}function Db(){const t=cu();return new Promise(e=>{switch(t){case Bi.browser:e(iM());break;case Bi.reactNative:e(nM());break;case Bi.node:e(sM());break;default:e(!0)}})}function iM(){return au()&&navigator?.onLine}async function nM(){if(Va()&&typeof global<"u"&&global!=null&&global.NetInfo){const t=await(global==null?void 0:global.NetInfo.fetch());return t?.isConnected}return!0}function sM(){return!0}function oM(t){switch(cu()){case Bi.browser:aM(t);break;case Bi.reactNative:cM(t);break}}function aM(t){!Va()&&au()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function cM(t){Va()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}const Ud={};class Iu{static get(e){return Ud[e]}static set(e,r){Ud[e]=r}static delete(e){delete Ud[e]}}const uM=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,fM=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,hM=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function lM(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){dM(t);return}return e}function dM(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function _h(t,e={}){if(typeof t!="string")return t;const r=t.trim();if(t[0]==='"'&&t.at(-1)==='"'&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){const i=r.toLowerCase();if(i==="true")return!0;if(i==="false")return!1;if(i==="undefined")return;if(i==="null")return null;if(i==="nan")return Number.NaN;if(i==="infinity")return Number.POSITIVE_INFINITY;if(i==="-infinity")return Number.NEGATIVE_INFINITY}if(!hM.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(uM.test(t)||fM.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,lM)}return JSON.parse(t)}catch(i){if(e.strict)throw i;return t}}function pM(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Tr(t,...e){try{return pM(t(...e))}catch(r){return Promise.reject(r)}}function gM(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function vM(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Eh(t){if(gM(t))return String(t);if(vM(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Eh(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function Ob(){if(typeof Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}const kd="base64:";function mM(t){if(typeof t=="string")return t;Ob();const e=Buffer.from(t).toString("base64");return kd+e}function bM(t){return typeof t!="string"||!t.startsWith(kd)?t:(Ob(),Buffer.from(t.slice(kd.length),"base64"))}function Ei(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function yM(...t){return Ei(t.join(":"))}function Ah(t){return t=Ei(t),t?t+":":""}function HH(t){return t}const wM="memory",_M=()=>{const t=new Map;return{name:wM,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)||null},getItemRaw(e){return t.get(e)||null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}};function EM(t={}){const e={mounts:{"":t.driver||_M()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=l=>{for(const b of e.mountpoints)if(l.startsWith(b))return{base:b,relativeKey:l.slice(b.length),driver:e.mounts[b]};return{base:"",relativeKey:l,driver:e.mounts[""]}},i=(l,b)=>e.mountpoints.filter(w=>w.startsWith(l)||b&&l.startsWith(w)).map(w=>({relativeBase:l.length>w.length?l.slice(w.length):void 0,mountpoint:w,driver:e.mounts[w]})),n=(l,b)=>{if(e.watching){b=Ei(b);for(const w of e.watchListeners)w(l,b)}},s=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await Pb(e.mounts[l],n,l)}},a=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},u=(l,b,w)=>{const I=new Map,S=D=>{let T=I.get(D.base);return T||(T={driver:D.driver,base:D.base,items:[]},I.set(D.base,T)),T};for(const D of l){const T=typeof D=="string",q=Ei(T?D:D.key),K=T?void 0:D.value,F=T||!D.options?b:{...b,...D.options},W=r(q);S(W).items.push({key:q,value:K,relativeKey:W.relativeKey,options:F})}return Promise.all([...I.values()].map(D=>w(D))).then(D=>D.flat())},h={hasItem(l,b={}){l=Ei(l);const{relativeKey:w,driver:I}=r(l);return Tr(I.hasItem,w,b)},getItem(l,b={}){l=Ei(l);const{relativeKey:w,driver:I}=r(l);return Tr(I.getItem,w,b).then(S=>_h(S))},getItems(l,b){return u(l,b,w=>w.driver.getItems?Tr(w.driver.getItems,w.items.map(I=>({key:I.relativeKey,options:I.options})),b).then(I=>I.map(S=>({key:yM(w.base,S.key),value:_h(S.value)}))):Promise.all(w.items.map(I=>Tr(w.driver.getItem,I.relativeKey,I.options).then(S=>({key:I.key,value:_h(S)})))))},getItemRaw(l,b={}){l=Ei(l);const{relativeKey:w,driver:I}=r(l);return I.getItemRaw?Tr(I.getItemRaw,w,b):Tr(I.getItem,w,b).then(S=>bM(S))},async setItem(l,b,w={}){if(b===void 0)return h.removeItem(l);l=Ei(l);const{relativeKey:I,driver:S}=r(l);S.setItem&&(await Tr(S.setItem,I,Eh(b),w),S.watch||n("update",l))},async setItems(l,b){await u(l,b,async w=>{w.driver.setItems&&await Tr(w.driver.setItems,w.items.map(I=>({key:I.relativeKey,value:Eh(I.value),options:I.options})),b),w.driver.setItem&&await Promise.all(w.items.map(I=>Tr(w.driver.setItem,I.relativeKey,Eh(I.value),I.options)))})},async setItemRaw(l,b,w={}){if(b===void 0)return h.removeItem(l,w);l=Ei(l);const{relativeKey:I,driver:S}=r(l);if(S.setItemRaw)await Tr(S.setItemRaw,I,b,w);else if(S.setItem)await Tr(S.setItem,I,mM(b),w);else return;S.watch||n("update",l)},async removeItem(l,b={}){typeof b=="boolean"&&(b={removeMeta:b}),l=Ei(l);const{relativeKey:w,driver:I}=r(l);I.removeItem&&(await Tr(I.removeItem,w,b),(b.removeMeta||b.removeMata)&&await Tr(I.removeItem,w+"$",b),I.watch||n("remove",l))},async getMeta(l,b={}){typeof b=="boolean"&&(b={nativeOnly:b}),l=Ei(l);const{relativeKey:w,driver:I}=r(l),S=Object.create(null);if(I.getMeta&&Object.assign(S,await Tr(I.getMeta,w,b)),!b.nativeOnly){const D=await Tr(I.getItem,w+"$",b).then(T=>_h(T));D&&typeof D=="object"&&(typeof D.atime=="string"&&(D.atime=new Date(D.atime)),typeof D.mtime=="string"&&(D.mtime=new Date(D.mtime)),Object.assign(S,D))}return S},setMeta(l,b,w={}){return this.setItem(l+"$",b,w)},removeMeta(l,b={}){return this.removeItem(l+"$",b)},async getKeys(l,b={}){l=Ah(l);const w=i(l,!0);let I=[];const S=[];for(const D of w){const q=(await Tr(D.driver.getKeys,D.relativeBase,b)).map(K=>D.mountpoint+Ei(K)).filter(K=>!I.some(F=>K.startsWith(F)));S.push(...q),I=[D.mountpoint,...I.filter(K=>!K.startsWith(D.mountpoint))]}return l?S.filter(D=>D.startsWith(l)&&!D.endsWith("$")):S.filter(D=>!D.endsWith("$"))},async clear(l,b={}){l=Ah(l),await Promise.all(i(l,!1).map(async w=>{if(w.driver.clear)return Tr(w.driver.clear,w.relativeBase,b);if(w.driver.removeItem){const I=await w.driver.getKeys(w.relativeBase||"",b);return Promise.all(I.map(S=>w.driver.removeItem(S,b)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>$b(l)))},async watch(l){return await s(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(b=>b!==l),e.watchListeners.length===0&&await a()}},async unwatch(){e.watchListeners=[],await a()},mount(l,b){if(l=Ah(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((w,I)=>I.length-w.length)),e.mounts[l]=b,e.watching&&Promise.resolve(Pb(b,n,l)).then(w=>{e.unwatch[l]=w}).catch(console.error),h},async unmount(l,b=!0){l=Ah(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&(e.unwatch[l](),delete e.unwatch[l]),b&&await $b(e.mounts[l]),e.mountpoints=e.mountpoints.filter(w=>w!==l),delete e.mounts[l])},getMount(l=""){l=Ei(l)+":";const b=r(l);return{driver:b.driver,base:b.base}},getMounts(l="",b={}){return l=Ei(l),i(l,b.parents).map(I=>({driver:I.driver,base:I.mountpoint}))}};return h}function Pb(t,e,r){return t.watch?t.watch((i,n)=>e(i,r+n)):()=>{}}async function $b(t){typeof t.dispose=="function"&&await Tr(t.dispose)}function Jo(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Rb(t,e){const r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);const i=Jo(r);return(n,s)=>i.then(a=>s(a.transaction(e,n).objectStore(e)))}let qd;function Mu(){return qd||(qd=Rb("keyval-store","keyval")),qd}function Nb(t,e=Mu()){return e("readonly",r=>Jo(r.get(t)))}function AM(t,e,r=Mu()){return r("readwrite",i=>(i.put(e,t),Jo(i.transaction)))}function xM(t,e=Mu()){return e("readwrite",r=>(r.delete(t),Jo(r.transaction)))}function SM(t=Mu()){return t("readwrite",e=>(e.clear(),Jo(e.transaction)))}function IM(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Jo(t.transaction)}function MM(t=Mu()){return t("readonly",e=>{if(e.getAllKeys)return Jo(e.getAllKeys());const r=[];return IM(e,i=>r.push(i.key)).then(()=>r)})}const CM="idb-keyval";var DM=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=n=>e+n;let i;return t.dbName&&t.storeName&&(i=Rb(t.dbName,t.storeName)),{name:CM,options:t,async hasItem(n){return!(typeof await Nb(r(n),i)>"u")},async getItem(n){return await Nb(r(n),i)??null},setItem(n,s){return AM(r(n),s,i)},removeItem(n){return xM(r(n),i)},getKeys(){return MM(i)},clear(){return SM(i)}}};const OM="WALLET_CONNECT_V2_INDEXED_DB",PM="keyvaluestorage";class $M{constructor(){this.indexedDb=EM({driver:DM({dbName:OM,storeName:PM})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Cs(r))}async removeItem(e){await this.indexedDb.removeItem(e)}}var jd=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},xh={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,i){this[r]=String(i)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(i){r[i]=void 0,delete r[i]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof jd<"u"&&jd.localStorage?xh.exports=jd.localStorage:typeof window<"u"&&window.localStorage?xh.exports=window.localStorage:xh.exports=new e})();function RM(t){var e;return[t[0],jo((e=t[1])!=null?e:"")]}class NM{constructor(){this.localStorage=xh.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(RM)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return jo(r)}async setItem(e,r){this.localStorage.setItem(e,Cs(r))}async removeItem(e){this.localStorage.removeItem(e)}}const TM="wc_storage_version",Tb=1,LM=async(t,e,r)=>{const i=TM,n=await e.getItem(i);if(n&&n>=Tb){r(e);return}const s=await t.getKeys();if(!s.length){r(e);return}const a=[];for(;s.length;){const u=s.shift();if(!u)continue;const h=u.toLowerCase();if(h.includes("wc@")||h.includes("walletconnect")||h.includes("wc_")||h.includes("wallet_connect")){const l=await t.getItem(u);await e.setItem(u,l),a.push(u)}}await e.setItem(i,Tb),r(e),BM(t,a)},BM=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};class FM{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new NM;this.storage=e;try{const r=new $M;LM(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}class Yo{}class UM extends Yo{constructor(e){super()}}const Lb=xe.FIVE_SECONDS,ac={pulse:"heartbeat_pulse"};class zd extends UM{constructor(e){super(e),this.events=new kr.exports.EventEmitter,this.interval=Lb,this.interval=e?.interval||Lb}static async init(e){const r=new zd(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),xe.toMiliseconds(this.interval))}pulse(){this.events.emit(ac.pulse)}}function kM(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var qM=jM;function jM(t,e,r){var i=r&&r.stringify||kM,n=1;if(typeof t=="object"&&t!==null){var s=e.length+n;if(s===1)return t;var a=new Array(s);a[0]=i(t);for(var u=1;u<s;u++)a[u]=i(e[u]);return a.join(" ")}if(typeof t!="string")return t;var h=e.length;if(h===0)return t;for(var l="",b=1-n,w=-1,I=t&&t.length||0,S=0;S<I;){if(t.charCodeAt(S)===37&&S+1<I){switch(w=w>-1?w:0,t.charCodeAt(S+1)){case 100:case 102:if(b>=h||e[b]==null)break;w<S&&(l+=t.slice(w,S)),l+=Number(e[b]),w=S+2,S++;break;case 105:if(b>=h||e[b]==null)break;w<S&&(l+=t.slice(w,S)),l+=Math.floor(Number(e[b])),w=S+2,S++;break;case 79:case 111:case 106:if(b>=h||e[b]===void 0)break;w<S&&(l+=t.slice(w,S));var D=typeof e[b];if(D==="string"){l+="'"+e[b]+"'",w=S+2,S++;break}if(D==="function"){l+=e[b].name||"<anonymous>",w=S+2,S++;break}l+=i(e[b]),w=S+2,S++;break;case 115:if(b>=h)break;w<S&&(l+=t.slice(w,S)),l+=String(e[b]),w=S+2,S++;break;case 37:w<S&&(l+=t.slice(w,S)),l+="%",w=S+2,S++,b--;break}++b}++S}return w===-1?t:(w<I&&(l+=t.slice(w)),l)}const Bb=qM;var cs=us;const Cu=ZM().console||{},zM={mapHttpRequest:Ih,mapHttpResponse:Ih,wrapRequestSerializer:Kd,wrapResponseSerializer:Kd,wrapErrorSerializer:Kd,req:Ih,res:Ih,err:GM};function HM(t,e){return Array.isArray(t)?t.filter(function(i){return i!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function us(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const r=t.browser.write||Cu;t.browser.write&&(t.browser.asObject=!0);const i=t.serializers||{},n=HM(t.browser.serialize,i);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const a=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");const u=t.level||"info",h=Object.create(r);h.log||(h.log=Du),Object.defineProperty(h,"levelVal",{get:b}),Object.defineProperty(h,"level",{get:w,set:I});const l={transmit:e,serialize:n,asObject:t.browser.asObject,levels:a,timestamp:JM(t)};h.levels=us.levels,h.level=u,h.setMaxListeners=h.getMaxListeners=h.emit=h.addListener=h.on=h.prependListener=h.once=h.prependOnceListener=h.removeListener=h.removeAllListeners=h.listeners=h.listenerCount=h.eventNames=h.write=h.flush=Du,h.serializers=i,h._serialize=n,h._stdErrSerialize=s,h.child=S,e&&(h._logEvent=Hd());function b(){return this.level==="silent"?1/0:this.levels.values[this.level]}function w(){return this._level}function I(D){if(D!=="silent"&&!this.levels.values[D])throw Error("unknown level "+D);this._level=D,cc(l,h,"error","log"),cc(l,h,"fatal","error"),cc(l,h,"warn","error"),cc(l,h,"info","log"),cc(l,h,"debug","log"),cc(l,h,"trace","log")}function S(D,T){if(!D)throw new Error("missing bindings for child Pino");T=T||{},n&&D.serializers&&(T.serializers=D.serializers);const q=T.serializers;if(n&&q){var K=Object.assign({},i,q),F=t.browser.serialize===!0?Object.keys(K):n;delete D.serializers,Sh([D],F,K,this._stdErrSerialize)}function W(R){this._childLevel=(R._childLevel|0)+1,this.error=uc(R,D,"error"),this.fatal=uc(R,D,"fatal"),this.warn=uc(R,D,"warn"),this.info=uc(R,D,"info"),this.debug=uc(R,D,"debug"),this.trace=uc(R,D,"trace"),K&&(this.serializers=K,this._serialize=F),e&&(this._logEvent=Hd([].concat(R._logEvent.bindings,D)))}return W.prototype=this,new W(this)}return h}us.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},us.stdSerializers=zM,us.stdTimeFunctions=Object.assign({},{nullTime:Fb,epochTime:Ub,unixTime:YM,isoTime:QM});function cc(t,e,r,i){const n=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?Du:n[r]?n[r]:Cu[r]||Cu[i]||Du,KM(t,e,r)}function KM(t,e,r){!t.transmit&&e[r]===Du||(e[r]=function(i){return function(){const s=t.timestamp(),a=new Array(arguments.length),u=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Cu?Cu:this;for(var h=0;h<a.length;h++)a[h]=arguments[h];if(t.serialize&&!t.asObject&&Sh(a,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?i.call(u,WM(this,r,a,s)):i.apply(u,a),t.transmit){const l=t.transmit.level||e.level,b=us.levels.values[l],w=us.levels.values[r];if(w<b)return;VM(this,{ts:s,methodLevel:r,methodValue:w,transmitLevel:l,transmitValue:us.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},a)}}}(e[r]))}function WM(t,e,r,i){t._serialize&&Sh(r,t._serialize,t.serializers,t._stdErrSerialize);const n=r.slice();let s=n[0];const a={};i&&(a.time=i),a.level=us.levels.values[e];let u=(t._childLevel|0)+1;if(u<1&&(u=1),s!==null&&typeof s=="object"){for(;u--&&typeof n[0]=="object";)Object.assign(a,n.shift());s=n.length?Bb(n.shift(),n):void 0}else typeof s=="string"&&(s=Bb(n.shift(),n));return s!==void 0&&(a.msg=s),a}function Sh(t,e,r,i){for(const n in t)if(i&&t[n]instanceof Error)t[n]=us.stdSerializers.err(t[n]);else if(typeof t[n]=="object"&&!Array.isArray(t[n]))for(const s in t[n])e&&e.indexOf(s)>-1&&s in r&&(t[n][s]=r[s](t[n][s]))}function uc(t,e,r){return function(){const i=new Array(1+arguments.length);i[0]=e;for(var n=1;n<i.length;n++)i[n]=arguments[n-1];return t[r].apply(this,i)}}function VM(t,e,r){const i=e.send,n=e.ts,s=e.methodLevel,a=e.methodValue,u=e.val,h=t._logEvent.bindings;Sh(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=n,t._logEvent.messages=r.filter(function(l){return h.indexOf(l)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=a,i(s,t._logEvent,u),t._logEvent=Hd(h)}function Hd(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function GM(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function JM(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Fb:Ub}function Ih(){return{}}function Kd(t){return t}function Du(){}function Fb(){return!1}function Ub(){return Date.now()}function YM(){return Math.round(Date.now()/1e3)}function QM(){return new Date(Date.now()).toISOString()}function ZM(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}const XM={level:"info"},Ou="custom_context",Wd=1e3*1024;class eC{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class kb{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new eC(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const r=e.value;return e=e.next,{done:!1,value:r}}}}}class qb{constructor(e,r=Wd){this.level=e??"error",this.levelValue=cs.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new kb(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===cs.levels.values.error?console.error(e):r===cs.levels.values.warn?console.warn(e):r===cs.levels.values.debug?console.debug(e):r===cs.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Cs({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new kb(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(Cs({extraMetadata:e})),new Blob(r,{type:"application/json"})}}class tC{constructor(e,r=Wd){this.baseChunkLogger=new qb(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const r=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=r,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}}class rC{constructor(e,r=Wd){this.baseChunkLogger=new qb(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var iC=Object.defineProperty,nC=Object.defineProperties,sC=Object.getOwnPropertyDescriptors,jb=Object.getOwnPropertySymbols,oC=Object.prototype.hasOwnProperty,aC=Object.prototype.propertyIsEnumerable,zb=(t,e,r)=>e in t?iC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mh=(t,e)=>{for(var r in e||(e={}))oC.call(e,r)&&zb(t,r,e[r]);if(jb)for(var r of jb(e))aC.call(e,r)&&zb(t,r,e[r]);return t},Ch=(t,e)=>nC(t,sC(e));function Dh(t){return Ch(Mh({},t),{level:t?.level||XM.level})}function cC(t,e=Ou){return t[e]||""}function uC(t,e,r=Ou){return t[r]=e,t}function Ai(t,e=Ou){let r="";return typeof t.bindings>"u"?r=cC(t,e):r=t.bindings().context||"",r}function fC(t,e,r=Ou){const i=Ai(t,r);return i.trim()?`${i}/${e}`:e}function ui(t,e,r=Ou){const i=fC(t,e,r),n=t.child({context:i});return uC(n,i,r)}function hC(t){var e,r;const i=new tC((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:cs(Ch(Mh({},t.opts),{level:"trace",browser:Ch(Mh({},(r=t.opts)==null?void 0:r.browser),{write:n=>i.write(n)})})),chunkLoggerController:i}}function lC(t){var e;const r=new rC((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:cs(Ch(Mh({},t.opts),{level:"trace"})),chunkLoggerController:r}}function dC(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?hC(t):lC(t)}class pC extends Yo{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class gC extends Yo{constructor(e,r){super(),this.core=e,this.logger=r,this.records=new Map}}class vC{constructor(e,r){this.logger=e,this.core=r}}class mC extends Yo{constructor(e,r){super(),this.relayer=e,this.logger=r}}class bC extends Yo{constructor(e){super()}}class yC{constructor(e,r,i,n){this.core=e,this.logger=r,this.name=i}}class wC extends Yo{constructor(e,r){super(),this.relayer=e,this.logger=r}}class _C extends Yo{constructor(e,r){super(),this.core=e,this.logger=r}}class EC{constructor(e,r,i){this.core=e,this.logger=r,this.store=i}}class AC{constructor(e,r){this.projectId=e,this.logger=r}}class xC{constructor(e,r,i){this.core=e,this.logger=r,this.telemetryEnabled=i}}class SC{constructor(e){this.opts=e,this.protocol="wc",this.version=2}}class IC{constructor(e){this.client=e}}function MC(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Hb(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Kb=Hb("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Vd=Hb("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=MC(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),CC={utf8:Kb,"utf-8":Kb,hex:Ra.base16,latin1:Vd,ascii:Vd,binary:Vd,...Ra};function DC(t,e="utf8"){const r=CC[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}const OC="PARSE_ERROR",PC="INVALID_REQUEST",$C="METHOD_NOT_FOUND",RC="INVALID_PARAMS",Wb="INTERNAL_ERROR",Gd="SERVER_ERROR",NC=[-32700,-32600,-32601,-32602,-32603],Pu={[OC]:{code:-32700,message:"Parse error"},[PC]:{code:-32600,message:"Invalid Request"},[$C]:{code:-32601,message:"Method not found"},[RC]:{code:-32602,message:"Invalid params"},[Wb]:{code:-32603,message:"Internal error"},[Gd]:{code:-32e3,message:"Server error"}},Vb=Gd;function TC(t){return NC.includes(t)}function Gb(t){return Object.keys(Pu).includes(t)?Pu[t]:Pu[Vb]}function LC(t){const e=Object.values(Pu).find(r=>r.code===t);return e||Pu[Vb]}function Jb(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Yb={};/*! *****************************************************************************
|
|
30
|
+
Approved: ${I.toString()}`))}),a.forEach(w=>{i||(zo(n[w].methods,s[w].methods)?zo(n[w].events,s[w].events)||(i=Ee("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${w}`)):i=Ee("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${w}`))}),i}function eM(t){const e={};return Object.keys(t).forEach(r=>{var i;r.includes(":")?e[r]=t[r]:(i=t[r].chains)==null||i.forEach(n=>{e[n]={methods:t[r].methods,events:t[r].events}})}),e}function Cb(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function tM(t){const e={};return Object.keys(t).forEach(r=>{if(r.includes(":"))e[r]=t[r];else{const i=oc(t[r].accounts);i?.forEach(n=>{e[n]={accounts:t[r].accounts.filter(s=>s.includes(`${n}:`)),methods:t[r].methods,events:t[r].events}})}}),e}function rM(t,e){return Bd(t,!1)&&t<=e.max&&t>=e.min}function Db(){const t=cu();return new Promise(e=>{switch(t){case Bi.browser:e(iM());break;case Bi.reactNative:e(nM());break;case Bi.node:e(sM());break;default:e(!0)}})}function iM(){return au()&&navigator?.onLine}async function nM(){if(Va()&&typeof global<"u"&&global!=null&&global.NetInfo){const t=await(global==null?void 0:global.NetInfo.fetch());return t?.isConnected}return!0}function sM(){return!0}function oM(t){switch(cu()){case Bi.browser:aM(t);break;case Bi.reactNative:cM(t);break}}function aM(t){!Va()&&au()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function cM(t){Va()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}const Ud={};class Iu{static get(e){return Ud[e]}static set(e,r){Ud[e]=r}static delete(e){delete Ud[e]}}class Jo{}class uM extends Jo{constructor(e){super()}}const Ob=xe.FIVE_SECONDS,ac={pulse:"heartbeat_pulse"};class kd extends uM{constructor(e){super(e),this.events=new kr.exports.EventEmitter,this.interval=Ob,this.interval=e?.interval||Ob}static async init(e){const r=new kd(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),xe.toMiliseconds(this.interval))}pulse(){this.events.emit(ac.pulse)}}const fM=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,hM=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,lM=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function dM(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){pM(t);return}return e}function pM(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function _h(t,e={}){if(typeof t!="string")return t;const r=t.trim();if(t[0]==='"'&&t.at(-1)==='"'&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){const i=r.toLowerCase();if(i==="true")return!0;if(i==="false")return!1;if(i==="undefined")return;if(i==="null")return null;if(i==="nan")return Number.NaN;if(i==="infinity")return Number.POSITIVE_INFINITY;if(i==="-infinity")return Number.NEGATIVE_INFINITY}if(!lM.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(fM.test(t)||hM.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,dM)}return JSON.parse(t)}catch(i){if(e.strict)throw i;return t}}function gM(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Tr(t,...e){try{return gM(t(...e))}catch(r){return Promise.reject(r)}}function vM(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function mM(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Eh(t){if(vM(t))return String(t);if(mM(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Eh(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function Pb(){if(typeof Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}const qd="base64:";function bM(t){if(typeof t=="string")return t;Pb();const e=Buffer.from(t).toString("base64");return qd+e}function yM(t){return typeof t!="string"||!t.startsWith(qd)?t:(Pb(),Buffer.from(t.slice(qd.length),"base64"))}function Ei(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function wM(...t){return Ei(t.join(":"))}function Ah(t){return t=Ei(t),t?t+":":""}function HH(t){return t}const _M="memory",EM=()=>{const t=new Map;return{name:_M,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)||null},getItemRaw(e){return t.get(e)||null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}};function AM(t={}){const e={mounts:{"":t.driver||EM()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=l=>{for(const b of e.mountpoints)if(l.startsWith(b))return{base:b,relativeKey:l.slice(b.length),driver:e.mounts[b]};return{base:"",relativeKey:l,driver:e.mounts[""]}},i=(l,b)=>e.mountpoints.filter(w=>w.startsWith(l)||b&&l.startsWith(w)).map(w=>({relativeBase:l.length>w.length?l.slice(w.length):void 0,mountpoint:w,driver:e.mounts[w]})),n=(l,b)=>{if(e.watching){b=Ei(b);for(const w of e.watchListeners)w(l,b)}},s=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await $b(e.mounts[l],n,l)}},a=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},u=(l,b,w)=>{const I=new Map,S=D=>{let T=I.get(D.base);return T||(T={driver:D.driver,base:D.base,items:[]},I.set(D.base,T)),T};for(const D of l){const T=typeof D=="string",q=Ei(T?D:D.key),K=T?void 0:D.value,F=T||!D.options?b:{...b,...D.options},W=r(q);S(W).items.push({key:q,value:K,relativeKey:W.relativeKey,options:F})}return Promise.all([...I.values()].map(D=>w(D))).then(D=>D.flat())},h={hasItem(l,b={}){l=Ei(l);const{relativeKey:w,driver:I}=r(l);return Tr(I.hasItem,w,b)},getItem(l,b={}){l=Ei(l);const{relativeKey:w,driver:I}=r(l);return Tr(I.getItem,w,b).then(S=>_h(S))},getItems(l,b){return u(l,b,w=>w.driver.getItems?Tr(w.driver.getItems,w.items.map(I=>({key:I.relativeKey,options:I.options})),b).then(I=>I.map(S=>({key:wM(w.base,S.key),value:_h(S.value)}))):Promise.all(w.items.map(I=>Tr(w.driver.getItem,I.relativeKey,I.options).then(S=>({key:I.key,value:_h(S)})))))},getItemRaw(l,b={}){l=Ei(l);const{relativeKey:w,driver:I}=r(l);return I.getItemRaw?Tr(I.getItemRaw,w,b):Tr(I.getItem,w,b).then(S=>yM(S))},async setItem(l,b,w={}){if(b===void 0)return h.removeItem(l);l=Ei(l);const{relativeKey:I,driver:S}=r(l);S.setItem&&(await Tr(S.setItem,I,Eh(b),w),S.watch||n("update",l))},async setItems(l,b){await u(l,b,async w=>{w.driver.setItems&&await Tr(w.driver.setItems,w.items.map(I=>({key:I.relativeKey,value:Eh(I.value),options:I.options})),b),w.driver.setItem&&await Promise.all(w.items.map(I=>Tr(w.driver.setItem,I.relativeKey,Eh(I.value),I.options)))})},async setItemRaw(l,b,w={}){if(b===void 0)return h.removeItem(l,w);l=Ei(l);const{relativeKey:I,driver:S}=r(l);if(S.setItemRaw)await Tr(S.setItemRaw,I,b,w);else if(S.setItem)await Tr(S.setItem,I,bM(b),w);else return;S.watch||n("update",l)},async removeItem(l,b={}){typeof b=="boolean"&&(b={removeMeta:b}),l=Ei(l);const{relativeKey:w,driver:I}=r(l);I.removeItem&&(await Tr(I.removeItem,w,b),(b.removeMeta||b.removeMata)&&await Tr(I.removeItem,w+"$",b),I.watch||n("remove",l))},async getMeta(l,b={}){typeof b=="boolean"&&(b={nativeOnly:b}),l=Ei(l);const{relativeKey:w,driver:I}=r(l),S=Object.create(null);if(I.getMeta&&Object.assign(S,await Tr(I.getMeta,w,b)),!b.nativeOnly){const D=await Tr(I.getItem,w+"$",b).then(T=>_h(T));D&&typeof D=="object"&&(typeof D.atime=="string"&&(D.atime=new Date(D.atime)),typeof D.mtime=="string"&&(D.mtime=new Date(D.mtime)),Object.assign(S,D))}return S},setMeta(l,b,w={}){return this.setItem(l+"$",b,w)},removeMeta(l,b={}){return this.removeItem(l+"$",b)},async getKeys(l,b={}){l=Ah(l);const w=i(l,!0);let I=[];const S=[];for(const D of w){const q=(await Tr(D.driver.getKeys,D.relativeBase,b)).map(K=>D.mountpoint+Ei(K)).filter(K=>!I.some(F=>K.startsWith(F)));S.push(...q),I=[D.mountpoint,...I.filter(K=>!K.startsWith(D.mountpoint))]}return l?S.filter(D=>D.startsWith(l)&&!D.endsWith("$")):S.filter(D=>!D.endsWith("$"))},async clear(l,b={}){l=Ah(l),await Promise.all(i(l,!1).map(async w=>{if(w.driver.clear)return Tr(w.driver.clear,w.relativeBase,b);if(w.driver.removeItem){const I=await w.driver.getKeys(w.relativeBase||"",b);return Promise.all(I.map(S=>w.driver.removeItem(S,b)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>Rb(l)))},async watch(l){return await s(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(b=>b!==l),e.watchListeners.length===0&&await a()}},async unwatch(){e.watchListeners=[],await a()},mount(l,b){if(l=Ah(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((w,I)=>I.length-w.length)),e.mounts[l]=b,e.watching&&Promise.resolve($b(b,n,l)).then(w=>{e.unwatch[l]=w}).catch(console.error),h},async unmount(l,b=!0){l=Ah(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&(e.unwatch[l](),delete e.unwatch[l]),b&&await Rb(e.mounts[l]),e.mountpoints=e.mountpoints.filter(w=>w!==l),delete e.mounts[l])},getMount(l=""){l=Ei(l)+":";const b=r(l);return{driver:b.driver,base:b.base}},getMounts(l="",b={}){return l=Ei(l),i(l,b.parents).map(I=>({driver:I.driver,base:I.mountpoint}))}};return h}function $b(t,e,r){return t.watch?t.watch((i,n)=>e(i,r+n)):()=>{}}async function Rb(t){typeof t.dispose=="function"&&await Tr(t.dispose)}function Yo(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Nb(t,e){const r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);const i=Yo(r);return(n,s)=>i.then(a=>s(a.transaction(e,n).objectStore(e)))}let jd;function Mu(){return jd||(jd=Nb("keyval-store","keyval")),jd}function Tb(t,e=Mu()){return e("readonly",r=>Yo(r.get(t)))}function xM(t,e,r=Mu()){return r("readwrite",i=>(i.put(e,t),Yo(i.transaction)))}function SM(t,e=Mu()){return e("readwrite",r=>(r.delete(t),Yo(r.transaction)))}function IM(t=Mu()){return t("readwrite",e=>(e.clear(),Yo(e.transaction)))}function MM(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Yo(t.transaction)}function CM(t=Mu()){return t("readonly",e=>{if(e.getAllKeys)return Yo(e.getAllKeys());const r=[];return MM(e,i=>r.push(i.key)).then(()=>r)})}const DM="idb-keyval";var OM=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=n=>e+n;let i;return t.dbName&&t.storeName&&(i=Nb(t.dbName,t.storeName)),{name:DM,options:t,async hasItem(n){return!(typeof await Tb(r(n),i)>"u")},async getItem(n){return await Tb(r(n),i)??null},setItem(n,s){return xM(r(n),s,i)},removeItem(n){return SM(r(n),i)},getKeys(){return CM(i)},clear(){return IM(i)}}};const PM="WALLET_CONNECT_V2_INDEXED_DB",$M="keyvaluestorage";class RM{constructor(){this.indexedDb=AM({driver:OM({dbName:PM,storeName:$M})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Cs(r))}async removeItem(e){await this.indexedDb.removeItem(e)}}var zd=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},xh={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,i){this[r]=String(i)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(i){r[i]=void 0,delete r[i]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof zd<"u"&&zd.localStorage?xh.exports=zd.localStorage:typeof window<"u"&&window.localStorage?xh.exports=window.localStorage:xh.exports=new e})();function NM(t){var e;return[t[0],jo((e=t[1])!=null?e:"")]}class TM{constructor(){this.localStorage=xh.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(NM)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return jo(r)}async setItem(e,r){this.localStorage.setItem(e,Cs(r))}async removeItem(e){this.localStorage.removeItem(e)}}const LM="wc_storage_version",Lb=1,BM=async(t,e,r)=>{const i=LM,n=await e.getItem(i);if(n&&n>=Lb){r(e);return}const s=await t.getKeys();if(!s.length){r(e);return}const a=[];for(;s.length;){const u=s.shift();if(!u)continue;const h=u.toLowerCase();if(h.includes("wc@")||h.includes("walletconnect")||h.includes("wc_")||h.includes("wallet_connect")){const l=await t.getItem(u);await e.setItem(u,l),a.push(u)}}await e.setItem(i,Lb),r(e),FM(t,a)},FM=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};class UM{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new TM;this.storage=e;try{const r=new RM;BM(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}function kM(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var qM=jM;function jM(t,e,r){var i=r&&r.stringify||kM,n=1;if(typeof t=="object"&&t!==null){var s=e.length+n;if(s===1)return t;var a=new Array(s);a[0]=i(t);for(var u=1;u<s;u++)a[u]=i(e[u]);return a.join(" ")}if(typeof t!="string")return t;var h=e.length;if(h===0)return t;for(var l="",b=1-n,w=-1,I=t&&t.length||0,S=0;S<I;){if(t.charCodeAt(S)===37&&S+1<I){switch(w=w>-1?w:0,t.charCodeAt(S+1)){case 100:case 102:if(b>=h||e[b]==null)break;w<S&&(l+=t.slice(w,S)),l+=Number(e[b]),w=S+2,S++;break;case 105:if(b>=h||e[b]==null)break;w<S&&(l+=t.slice(w,S)),l+=Math.floor(Number(e[b])),w=S+2,S++;break;case 79:case 111:case 106:if(b>=h||e[b]===void 0)break;w<S&&(l+=t.slice(w,S));var D=typeof e[b];if(D==="string"){l+="'"+e[b]+"'",w=S+2,S++;break}if(D==="function"){l+=e[b].name||"<anonymous>",w=S+2,S++;break}l+=i(e[b]),w=S+2,S++;break;case 115:if(b>=h)break;w<S&&(l+=t.slice(w,S)),l+=String(e[b]),w=S+2,S++;break;case 37:w<S&&(l+=t.slice(w,S)),l+="%",w=S+2,S++,b--;break}++b}++S}return w===-1?t:(w<I&&(l+=t.slice(w)),l)}const Bb=qM;var cs=us;const Cu=ZM().console||{},zM={mapHttpRequest:Ih,mapHttpResponse:Ih,wrapRequestSerializer:Kd,wrapResponseSerializer:Kd,wrapErrorSerializer:Kd,req:Ih,res:Ih,err:GM};function HM(t,e){return Array.isArray(t)?t.filter(function(i){return i!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function us(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const r=t.browser.write||Cu;t.browser.write&&(t.browser.asObject=!0);const i=t.serializers||{},n=HM(t.browser.serialize,i);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const a=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");const u=t.level||"info",h=Object.create(r);h.log||(h.log=Du),Object.defineProperty(h,"levelVal",{get:b}),Object.defineProperty(h,"level",{get:w,set:I});const l={transmit:e,serialize:n,asObject:t.browser.asObject,levels:a,timestamp:JM(t)};h.levels=us.levels,h.level=u,h.setMaxListeners=h.getMaxListeners=h.emit=h.addListener=h.on=h.prependListener=h.once=h.prependOnceListener=h.removeListener=h.removeAllListeners=h.listeners=h.listenerCount=h.eventNames=h.write=h.flush=Du,h.serializers=i,h._serialize=n,h._stdErrSerialize=s,h.child=S,e&&(h._logEvent=Hd());function b(){return this.level==="silent"?1/0:this.levels.values[this.level]}function w(){return this._level}function I(D){if(D!=="silent"&&!this.levels.values[D])throw Error("unknown level "+D);this._level=D,cc(l,h,"error","log"),cc(l,h,"fatal","error"),cc(l,h,"warn","error"),cc(l,h,"info","log"),cc(l,h,"debug","log"),cc(l,h,"trace","log")}function S(D,T){if(!D)throw new Error("missing bindings for child Pino");T=T||{},n&&D.serializers&&(T.serializers=D.serializers);const q=T.serializers;if(n&&q){var K=Object.assign({},i,q),F=t.browser.serialize===!0?Object.keys(K):n;delete D.serializers,Sh([D],F,K,this._stdErrSerialize)}function W(R){this._childLevel=(R._childLevel|0)+1,this.error=uc(R,D,"error"),this.fatal=uc(R,D,"fatal"),this.warn=uc(R,D,"warn"),this.info=uc(R,D,"info"),this.debug=uc(R,D,"debug"),this.trace=uc(R,D,"trace"),K&&(this.serializers=K,this._serialize=F),e&&(this._logEvent=Hd([].concat(R._logEvent.bindings,D)))}return W.prototype=this,new W(this)}return h}us.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},us.stdSerializers=zM,us.stdTimeFunctions=Object.assign({},{nullTime:Fb,epochTime:Ub,unixTime:YM,isoTime:QM});function cc(t,e,r,i){const n=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?Du:n[r]?n[r]:Cu[r]||Cu[i]||Du,KM(t,e,r)}function KM(t,e,r){!t.transmit&&e[r]===Du||(e[r]=function(i){return function(){const s=t.timestamp(),a=new Array(arguments.length),u=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Cu?Cu:this;for(var h=0;h<a.length;h++)a[h]=arguments[h];if(t.serialize&&!t.asObject&&Sh(a,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?i.call(u,WM(this,r,a,s)):i.apply(u,a),t.transmit){const l=t.transmit.level||e.level,b=us.levels.values[l],w=us.levels.values[r];if(w<b)return;VM(this,{ts:s,methodLevel:r,methodValue:w,transmitLevel:l,transmitValue:us.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},a)}}}(e[r]))}function WM(t,e,r,i){t._serialize&&Sh(r,t._serialize,t.serializers,t._stdErrSerialize);const n=r.slice();let s=n[0];const a={};i&&(a.time=i),a.level=us.levels.values[e];let u=(t._childLevel|0)+1;if(u<1&&(u=1),s!==null&&typeof s=="object"){for(;u--&&typeof n[0]=="object";)Object.assign(a,n.shift());s=n.length?Bb(n.shift(),n):void 0}else typeof s=="string"&&(s=Bb(n.shift(),n));return s!==void 0&&(a.msg=s),a}function Sh(t,e,r,i){for(const n in t)if(i&&t[n]instanceof Error)t[n]=us.stdSerializers.err(t[n]);else if(typeof t[n]=="object"&&!Array.isArray(t[n]))for(const s in t[n])e&&e.indexOf(s)>-1&&s in r&&(t[n][s]=r[s](t[n][s]))}function uc(t,e,r){return function(){const i=new Array(1+arguments.length);i[0]=e;for(var n=1;n<i.length;n++)i[n]=arguments[n-1];return t[r].apply(this,i)}}function VM(t,e,r){const i=e.send,n=e.ts,s=e.methodLevel,a=e.methodValue,u=e.val,h=t._logEvent.bindings;Sh(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=n,t._logEvent.messages=r.filter(function(l){return h.indexOf(l)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=a,i(s,t._logEvent,u),t._logEvent=Hd(h)}function Hd(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function GM(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function JM(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Fb:Ub}function Ih(){return{}}function Kd(t){return t}function Du(){}function Fb(){return!1}function Ub(){return Date.now()}function YM(){return Math.round(Date.now()/1e3)}function QM(){return new Date(Date.now()).toISOString()}function ZM(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}const XM={level:"info"},Ou="custom_context",Wd=1e3*1024;class eC{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class kb{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new eC(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const r=e.value;return e=e.next,{done:!1,value:r}}}}}class qb{constructor(e,r=Wd){this.level=e??"error",this.levelValue=cs.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new kb(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===cs.levels.values.error?console.error(e):r===cs.levels.values.warn?console.warn(e):r===cs.levels.values.debug?console.debug(e):r===cs.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Cs({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new kb(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(Cs({extraMetadata:e})),new Blob(r,{type:"application/json"})}}class tC{constructor(e,r=Wd){this.baseChunkLogger=new qb(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const r=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=r,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}}class rC{constructor(e,r=Wd){this.baseChunkLogger=new qb(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var iC=Object.defineProperty,nC=Object.defineProperties,sC=Object.getOwnPropertyDescriptors,jb=Object.getOwnPropertySymbols,oC=Object.prototype.hasOwnProperty,aC=Object.prototype.propertyIsEnumerable,zb=(t,e,r)=>e in t?iC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mh=(t,e)=>{for(var r in e||(e={}))oC.call(e,r)&&zb(t,r,e[r]);if(jb)for(var r of jb(e))aC.call(e,r)&&zb(t,r,e[r]);return t},Ch=(t,e)=>nC(t,sC(e));function Dh(t){return Ch(Mh({},t),{level:t?.level||XM.level})}function cC(t,e=Ou){return t[e]||""}function uC(t,e,r=Ou){return t[r]=e,t}function Ai(t,e=Ou){let r="";return typeof t.bindings>"u"?r=cC(t,e):r=t.bindings().context||"",r}function fC(t,e,r=Ou){const i=Ai(t,r);return i.trim()?`${i}/${e}`:e}function ui(t,e,r=Ou){const i=fC(t,e,r),n=t.child({context:i});return uC(n,i,r)}function hC(t){var e,r;const i=new tC((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:cs(Ch(Mh({},t.opts),{level:"trace",browser:Ch(Mh({},(r=t.opts)==null?void 0:r.browser),{write:n=>i.write(n)})})),chunkLoggerController:i}}function lC(t){var e;const r=new rC((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:cs(Ch(Mh({},t.opts),{level:"trace"})),chunkLoggerController:r}}function dC(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?hC(t):lC(t)}class pC extends Jo{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class gC extends Jo{constructor(e,r){super(),this.core=e,this.logger=r,this.records=new Map}}class vC{constructor(e,r){this.logger=e,this.core=r}}class mC extends Jo{constructor(e,r){super(),this.relayer=e,this.logger=r}}class bC extends Jo{constructor(e){super()}}class yC{constructor(e,r,i,n){this.core=e,this.logger=r,this.name=i}}class wC extends Jo{constructor(e,r){super(),this.relayer=e,this.logger=r}}class _C extends Jo{constructor(e,r){super(),this.core=e,this.logger=r}}class EC{constructor(e,r,i){this.core=e,this.logger=r,this.store=i}}class AC{constructor(e,r){this.projectId=e,this.logger=r}}class xC{constructor(e,r,i){this.core=e,this.logger=r,this.telemetryEnabled=i}}class SC{constructor(e){this.opts=e,this.protocol="wc",this.version=2}}class IC{constructor(e){this.client=e}}function MC(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Hb(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Kb=Hb("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Vd=Hb("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=MC(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),CC={utf8:Kb,"utf-8":Kb,hex:Ra.base16,latin1:Vd,ascii:Vd,binary:Vd,...Ra};function DC(t,e="utf8"){const r=CC[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}const OC="PARSE_ERROR",PC="INVALID_REQUEST",$C="METHOD_NOT_FOUND",RC="INVALID_PARAMS",Wb="INTERNAL_ERROR",Gd="SERVER_ERROR",NC=[-32700,-32600,-32601,-32602,-32603],Pu={[OC]:{code:-32700,message:"Parse error"},[PC]:{code:-32600,message:"Invalid Request"},[$C]:{code:-32601,message:"Method not found"},[RC]:{code:-32602,message:"Invalid params"},[Wb]:{code:-32603,message:"Internal error"},[Gd]:{code:-32e3,message:"Server error"}},Vb=Gd;function TC(t){return NC.includes(t)}function Gb(t){return Object.keys(Pu).includes(t)?Pu[t]:Pu[Vb]}function LC(t){const e=Object.values(Pu).find(r=>r.code===t);return e||Pu[Vb]}function Jb(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Yb={};/*! *****************************************************************************
|
|
31
31
|
Copyright (c) Microsoft Corporation.
|
|
32
32
|
|
|
33
33
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
41
41
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
42
42
|
PERFORMANCE OF THIS SOFTWARE.
|
|
43
|
-
***************************************************************************** */var Jd=function(t,e){return Jd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},Jd(t,e)};function BC(t,e){Jd(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Yd=function(){return Yd=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Yd.apply(this,arguments)};function FC(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function UC(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var u=t.length-1;u>=0;u--)(a=t[u])&&(s=(n<3?a(s):n>3?a(e,r,s):a(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function kC(t,e){return function(r,i){e(r,i,t)}}function qC(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function jC(t,e,r,i){function n(s){return s instanceof r?s:new r(function(a){a(s)})}return new(r||(r=Promise))(function(s,a){function u(b){try{l(i.next(b))}catch(w){a(w)}}function h(b){try{l(i.throw(b))}catch(w){a(w)}}function l(b){b.done?s(b.value):n(b.value).then(u,h)}l((i=i.apply(t,e||[])).next())})}function zC(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,a;return a={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function u(l){return function(b){return h([l,b])}}function h(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=l[0]&2?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,n=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(b){l=[6,b],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function HC(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function KC(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Qd(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Qb(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],a;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(u){a={error:u}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(a)throw a.error}}return s}function WC(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Qb(arguments[e]));return t}function VC(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],a=0,u=s.length;a<u;a++,n++)i[n]=s[a];return i}function $u(t){return this instanceof $u?(this.v=t,this):new $u(t)}function GC(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},a("next"),a("throw"),a("return"),n[Symbol.asyncIterator]=function(){return this},n;function a(I){i[I]&&(n[I]=function(S){return new Promise(function(D,T){s.push([I,S,D,T])>1||u(I,S)})})}function u(I,S){try{h(i[I](S))}catch(D){w(s[0][3],D)}}function h(I){I.value instanceof $u?Promise.resolve(I.value.v).then(l,b):w(s[0][2],I)}function l(I){u("next",I)}function b(I){u("throw",I)}function w(I,S){I(S),s.shift(),s.length&&u(s[0][0],s[0][1])}}function JC(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(a){return(r=!r)?{value:$u(t[n](a)),done:n==="return"}:s?s(a):a}:s}}function YC(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Qd=="function"?Qd(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[s]=t[s]&&function(a){return new Promise(function(u,h){a=t[s](a),n(u,h,a.done,a.value)})}}function n(s,a,u,h){Promise.resolve(h).then(function(l){s({value:l,done:u})},a)}}function QC(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ZC(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function XC(t){return t&&t.__esModule?t:{default:t}}function eD(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function tD(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var rD=Object.freeze({__proto__:null,__extends:BC,get __assign(){return Yd},__rest:FC,__decorate:UC,__param:kC,__metadata:qC,__awaiter:jC,__generator:zC,__createBinding:HC,__exportStar:KC,__values:Qd,__read:Qb,__spread:WC,__spreadArrays:VC,__await:$u,__asyncGenerator:GC,__asyncDelegator:JC,__asyncValues:YC,__makeTemplateObject:QC,__importStar:ZC,__importDefault:XC,__classPrivateFieldGet:eD,__classPrivateFieldSet:tD}),iD=m0(rD),Ts={},Zb;function nD(){if(Zb)return Ts;Zb=1,Object.defineProperty(Ts,"__esModule",{value:!0}),Ts.isBrowserCryptoAvailable=Ts.getSubtleCrypto=Ts.getBrowerCrypto=void 0;function t(){return Vr?.crypto||Vr?.msCrypto||{}}Ts.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Ts.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Ts.isBrowserCryptoAvailable=r,Ts}var Ls={},Xb;function sD(){if(Xb)return Ls;Xb=1,Object.defineProperty(Ls,"__esModule",{value:!0}),Ls.isBrowser=Ls.isNode=Ls.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ls.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Ls.isNode=e;function r(){return!t()&&!e()}return Ls.isBrowser=r,Ls}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=iD;e.__exportStar(nD(),t),e.__exportStar(sD(),t)})(Yb);function co(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Qo(t=6){return BigInt(co(t))}function uo(t,e,r){return{id:r||co(),jsonrpc:"2.0",method:t,params:e}}function Oh(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Ph(t,e,r){return{id:t,jsonrpc:"2.0",error:oD(e,r)}}function oD(t,e){return typeof t>"u"?Gb(Wb):(typeof t=="string"&&(t=Object.assign(Object.assign({},Gb(Gd)),{message:t})),typeof e<"u"&&(t.data=e),TC(t.code)&&(t=LC(t.code)),t)}class aD{}class cD extends aD{constructor(){super()}}class uD extends cD{constructor(e){super()}}const fD="^https?:",hD="^wss?:";function lD(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function e3(t,e){const r=lD(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function t3(t){return e3(t,fD)}function r3(t){return e3(t,hD)}function dD(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function i3(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Zd(t){return i3(t)&&"method"in t}function $h(t){return i3(t)&&(fs(t)||rn(t))}function fs(t){return"result"in t}function rn(t){return"error"in t}class xn extends uD{constructor(e){super(e),this.events=new kr.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(uo(e.method,e.params||[],e.id||Qo().toString()),r)}async requestStrict(e,r){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{rn(s)?n(s.error):i(s.result)});try{await this.connection.send(e,r)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),$h(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const pD=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),gD=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",n3=t=>t.split("?")[0],s3=10,vD=pD();class mD{constructor(e){if(this.url=e,this.events=new kr.exports.EventEmitter,this.registering=!1,!r3(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Cs(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!r3(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const n=new URLSearchParams(e).get("origin"),s=Yb.isReactNative()?{headers:{origin:n}}:{rejectUnauthorized:!dD(e)},a=new vD(e,[],s);gD()?a.onerror=u=>{const h=u;i(this.emitError(h.error))}:a.on("error",u=>{i(this.emitError(u))}),a.onopen=()=>{this.onOpen(a),r(a)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?jo(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Ph(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Jb(e,n3(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>s3&&this.events.setMaxListeners(s3)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${n3(this.url)}`));return this.events.emit("register_error",r),r}}var Xd={exports:{}};(function(t,e){var r=200,i="__lodash_hash_undefined__",n=1,s=2,a=9007199254740991,u="[object Arguments]",h="[object Array]",l="[object AsyncFunction]",b="[object Boolean]",w="[object Date]",I="[object Error]",S="[object Function]",D="[object GeneratorFunction]",T="[object Map]",q="[object Number]",K="[object Null]",F="[object Object]",W="[object Promise]",R="[object Proxy]",k="[object RegExp]",H="[object Set]",_="[object String]",B="[object Symbol]",ee="[object Undefined]",ie="[object WeakMap]",L="[object ArrayBuffer]",y="[object DataView]",f="[object Float32Array]",d="[object Float64Array]",v="[object Int8Array]",E="[object Int16Array]",C="[object Int32Array]",O="[object Uint8Array]",M="[object Uint8ClampedArray]",g="[object Uint16Array]",m="[object Uint32Array]",N=/[\\^$.*+?()[\]{}|]/g,X=/^\[object .+?Constructor\]$/,ae=/^(?:0|[1-9]\d*)$/,P={};P[f]=P[d]=P[v]=P[E]=P[C]=P[O]=P[M]=P[g]=P[m]=!0,P[u]=P[h]=P[L]=P[b]=P[y]=P[w]=P[I]=P[S]=P[T]=P[q]=P[F]=P[k]=P[H]=P[_]=P[ie]=!1;var te=typeof Vr=="object"&&Vr&&Vr.Object===Object&&Vr,z=typeof self=="object"&&self&&self.Object===Object&&self,G=te||z||Function("return this")(),J=e&&!e.nodeType&&e,A=J&&!0&&t&&!t.nodeType&&t,V=A&&A.exports===J,oe=V&&te.process,ue=function(){try{return oe&&oe.binding&&oe.binding("util")}catch{}}(),he=ue&&ue.isTypedArray;function ye(Y,re){for(var pe=-1,ke=Y==null?0:Y.length,er=0,bt=[];++pe<ke;){var ar=Y[pe];re(ar,pe,Y)&&(bt[er++]=ar)}return bt}function we(Y,re){for(var pe=-1,ke=re.length,er=Y.length;++pe<ke;)Y[er+pe]=re[pe];return Y}function Re(Y,re){for(var pe=-1,ke=Y==null?0:Y.length;++pe<ke;)if(re(Y[pe],pe,Y))return!0;return!1}function Xe(Y,re){for(var pe=-1,ke=Array(Y);++pe<Y;)ke[pe]=re(pe);return ke}function Oe(Y){return function(re){return Y(re)}}function Ne(Y,re){return Y.has(re)}function Me(Y,re){return Y?.[re]}function be(Y){var re=-1,pe=Array(Y.size);return Y.forEach(function(ke,er){pe[++re]=[er,ke]}),pe}function Pe(Y,re){return function(pe){return Y(re(pe))}}function Te(Y){var re=-1,pe=Array(Y.size);return Y.forEach(function(ke){pe[++re]=ke}),pe}var ve=Array.prototype,$e=Function.prototype,Se=Object.prototype,me=G["__core-js_shared__"],Ue=$e.toString,Ce=Se.hasOwnProperty,_e=function(){var Y=/[^.]+$/.exec(me&&me.keys&&me.keys.IE_PROTO||"");return Y?"Symbol(src)_1."+Y:""}(),Ke=Se.toString,Ve=RegExp("^"+Ue.call(Ce).replace(N,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ae=V?G.Buffer:void 0,We=G.Symbol,pt=G.Uint8Array,Ge=Se.propertyIsEnumerable,It=ve.splice,gt=We?We.toStringTag:void 0,Ye=Object.getOwnPropertySymbols,Ot=Ae?Ae.isBuffer:void 0,Tt=Pe(Object.keys,Object),Le=ji(G,"DataView"),et=ji(G,"Map"),it=ji(G,"Promise"),Be=ji(G,"Set"),rt=ji(G,"WeakMap"),tt=ji(Object,"create"),qe=qs(Le),ht=qs(et),nt=qs(it),je=qs(Be),st=qs(rt),at=We?We.prototype:void 0,Fe=at?at.valueOf:void 0;function Ze(Y){var re=-1,pe=Y==null?0:Y.length;for(this.clear();++re<pe;){var ke=Y[re];this.set(ke[0],ke[1])}}function lt(){this.__data__=tt?tt(null):{},this.size=0}function ze(Y){var re=this.has(Y)&&delete this.__data__[Y];return this.size-=re?1:0,re}function qt(Y){var re=this.__data__;if(tt){var pe=re[Y];return pe===i?void 0:pe}return Ce.call(re,Y)?re[Y]:void 0}function jt(Y){var re=this.__data__;return tt?re[Y]!==void 0:Ce.call(re,Y)}function ct(Y,re){var pe=this.__data__;return this.size+=this.has(Y)?0:1,pe[Y]=tt&&re===void 0?i:re,this}Ze.prototype.clear=lt,Ze.prototype.delete=ze,Ze.prototype.get=qt,Ze.prototype.has=jt,Ze.prototype.set=ct;function _t(Y){var re=-1,pe=Y==null?0:Y.length;for(this.clear();++re<pe;){var ke=Y[re];this.set(ke[0],ke[1])}}function Zr(){this.__data__=[],this.size=0}function Xr(Y){var re=this.__data__,pe=ma(re,Y);if(pe<0)return!1;var ke=re.length-1;return pe==ke?re.pop():It.call(re,pe,1),--this.size,!0}function ei(Y){var re=this.__data__,pe=ma(re,Y);return pe<0?void 0:re[pe][1]}function ti(Y){return ma(this.__data__,Y)>-1}function ri(Y,re){var pe=this.__data__,ke=ma(pe,Y);return ke<0?(++this.size,pe.push([Y,re])):pe[ke][1]=re,this}_t.prototype.clear=Zr,_t.prototype.delete=Xr,_t.prototype.get=ei,_t.prototype.has=ti,_t.prototype.set=ri;function vr(Y){var re=-1,pe=Y==null?0:Y.length;for(this.clear();++re<pe;){var ke=Y[re];this.set(ke[0],ke[1])}}function Ii(){this.size=0,this.__data__={hash:new Ze,map:new(et||_t),string:new Ze}}function On(Y){var re=Ao(this,Y).delete(Y);return this.size-=re?1:0,re}function Mi(Y){return Ao(this,Y).get(Y)}function Pn(Y){return Ao(this,Y).has(Y)}function $n(Y,re){var pe=Ao(this,Y),ke=pe.size;return pe.set(Y,re),this.size+=pe.size==ke?0:1,this}vr.prototype.clear=Ii,vr.prototype.delete=On,vr.prototype.get=Mi,vr.prototype.has=Pn,vr.prototype.set=$n;function Ci(Y){var re=-1,pe=Y==null?0:Y.length;for(this.__data__=new vr;++re<pe;)this.add(Y[re])}function an(Y){return this.__data__.set(Y,i),this}function cn(Y){return this.__data__.has(Y)}Ci.prototype.add=Ci.prototype.push=an,Ci.prototype.has=cn;function Cr(Y){var re=this.__data__=new _t(Y);this.size=re.size}function Rn(){this.__data__=new _t,this.size=0}function Nn(Y){var re=this.__data__,pe=re.delete(Y);return this.size=re.size,pe}function Tn(Y){return this.__data__.get(Y)}function va(Y){return this.__data__.has(Y)}function gl(Y,re){var pe=this.__data__;if(pe instanceof _t){var ke=pe.__data__;if(!et||ke.length<r-1)return ke.push([Y,re]),this.size=++pe.size,this;pe=this.__data__=new vr(ke)}return pe.set(Y,re),this.size=pe.size,this}Cr.prototype.clear=Rn,Cr.prototype.delete=Nn,Cr.prototype.get=Tn,Cr.prototype.has=va,Cr.prototype.set=gl;function vl(Y,re){var pe=Nc(Y),ke=!pe&&Cl(Y),er=!pe&&!ke&&cf(Y),bt=!pe&&!ke&&!er&&Pl(Y),ar=pe||ke||er||bt,xr=ar?Xe(Y.length,String):[],Ft=xr.length;for(var tr in Y)(re||Ce.call(Y,tr))&&!(ar&&(tr=="length"||er&&(tr=="offset"||tr=="parent")||bt&&(tr=="buffer"||tr=="byteLength"||tr=="byteOffset")||Al(tr,Ft)))&&xr.push(tr);return xr}function ma(Y,re){for(var pe=Y.length;pe--;)if(Ml(Y[pe][0],re))return pe;return-1}function of(Y,re,pe){var ke=re(Y);return Nc(Y)?ke:we(ke,pe(Y))}function ba(Y){return Y==null?Y===void 0?ee:K:gt&> in Object(Y)?_l(Y):Op(Y)}function af(Y){return wa(Y)&&ba(Y)==u}function ya(Y,re,pe,ke,er){return Y===re?!0:Y==null||re==null||!wa(Y)&&!wa(re)?Y!==Y&&re!==re:ml(Y,re,pe,ke,ya,er)}function ml(Y,re,pe,ke,er,bt){var ar=Nc(Y),xr=Nc(re),Ft=ar?h:ws(Y),tr=xr?h:ws(re);Ft=Ft==u?F:Ft,tr=tr==u?F:tr;var _r=Ft==F,Di=tr==F,Sr=Ft==tr;if(Sr&&cf(Y)){if(!cf(re))return!1;ar=!0,_r=!1}if(Sr&&!_r)return bt||(bt=new Cr),ar||Pl(Y)?$c(Y,re,pe,ke,er,bt):Dp(Y,re,Ft,pe,ke,er,bt);if(!(pe&n)){var cr=_r&&Ce.call(Y,"__wrapped__"),di=Di&&Ce.call(re,"__wrapped__");if(cr||di){var Ln=cr?Y.value():Y,un=di?re.value():re;return bt||(bt=new Cr),er(Ln,un,pe,ke,bt)}}return Sr?(bt||(bt=new Cr),wl(Y,re,pe,ke,er,bt)):!1}function Cp(Y){if(!Ol(Y)||Sl(Y))return!1;var re=Tc(Y)?Ve:X;return re.test(qs(Y))}function bl(Y){return wa(Y)&&Dl(Y.length)&&!!P[ba(Y)]}function yl(Y){if(!Il(Y))return Tt(Y);var re=[];for(var pe in Object(Y))Ce.call(Y,pe)&&pe!="constructor"&&re.push(pe);return re}function $c(Y,re,pe,ke,er,bt){var ar=pe&n,xr=Y.length,Ft=re.length;if(xr!=Ft&&!(ar&&Ft>xr))return!1;var tr=bt.get(Y);if(tr&&bt.get(re))return tr==re;var _r=-1,Di=!0,Sr=pe&s?new Ci:void 0;for(bt.set(Y,re),bt.set(re,Y);++_r<xr;){var cr=Y[_r],di=re[_r];if(ke)var Ln=ar?ke(di,cr,_r,re,Y,bt):ke(cr,di,_r,Y,re,bt);if(Ln!==void 0){if(Ln)continue;Di=!1;break}if(Sr){if(!Re(re,function(un,_s){if(!Ne(Sr,_s)&&(cr===un||er(cr,un,pe,ke,bt)))return Sr.push(_s)})){Di=!1;break}}else if(!(cr===di||er(cr,di,pe,ke,bt))){Di=!1;break}}return bt.delete(Y),bt.delete(re),Di}function Dp(Y,re,pe,ke,er,bt,ar){switch(pe){case y:if(Y.byteLength!=re.byteLength||Y.byteOffset!=re.byteOffset)return!1;Y=Y.buffer,re=re.buffer;case L:return!(Y.byteLength!=re.byteLength||!bt(new pt(Y),new pt(re)));case b:case w:case q:return Ml(+Y,+re);case I:return Y.name==re.name&&Y.message==re.message;case k:case _:return Y==re+"";case T:var xr=be;case H:var Ft=ke&n;if(xr||(xr=Te),Y.size!=re.size&&!Ft)return!1;var tr=ar.get(Y);if(tr)return tr==re;ke|=s,ar.set(Y,re);var _r=$c(xr(Y),xr(re),ke,er,bt,ar);return ar.delete(Y),_r;case B:if(Fe)return Fe.call(Y)==Fe.call(re)}return!1}function wl(Y,re,pe,ke,er,bt){var ar=pe&n,xr=Rc(Y),Ft=xr.length,tr=Rc(re),_r=tr.length;if(Ft!=_r&&!ar)return!1;for(var Di=Ft;Di--;){var Sr=xr[Di];if(!(ar?Sr in re:Ce.call(re,Sr)))return!1}var cr=bt.get(Y);if(cr&&bt.get(re))return cr==re;var di=!0;bt.set(Y,re),bt.set(re,Y);for(var Ln=ar;++Di<Ft;){Sr=xr[Di];var un=Y[Sr],_s=re[Sr];if(ke)var uf=ar?ke(_s,un,Sr,re,Y,bt):ke(un,_s,Sr,Y,re,bt);if(!(uf===void 0?un===_s||er(un,_s,pe,ke,bt):uf)){di=!1;break}Ln||(Ln=Sr=="constructor")}if(di&&!Ln){var _a=Y.constructor,Fr=re.constructor;_a!=Fr&&"constructor"in Y&&"constructor"in re&&!(typeof _a=="function"&&_a instanceof _a&&typeof Fr=="function"&&Fr instanceof Fr)&&(di=!1)}return bt.delete(Y),bt.delete(re),di}function Rc(Y){return of(Y,Rp,El)}function Ao(Y,re){var pe=Y.__data__;return xl(re)?pe[typeof re=="string"?"string":"hash"]:pe.map}function ji(Y,re){var pe=Me(Y,re);return Cp(pe)?pe:void 0}function _l(Y){var re=Ce.call(Y,gt),pe=Y[gt];try{Y[gt]=void 0;var ke=!0}catch{}var er=Ke.call(Y);return ke&&(re?Y[gt]=pe:delete Y[gt]),er}var El=Ye?function(Y){return Y==null?[]:(Y=Object(Y),ye(Ye(Y),function(re){return Ge.call(Y,re)}))}:Xt,ws=ba;(Le&&ws(new Le(new ArrayBuffer(1)))!=y||et&&ws(new et)!=T||it&&ws(it.resolve())!=W||Be&&ws(new Be)!=H||rt&&ws(new rt)!=ie)&&(ws=function(Y){var re=ba(Y),pe=re==F?Y.constructor:void 0,ke=pe?qs(pe):"";if(ke)switch(ke){case qe:return y;case ht:return T;case nt:return W;case je:return H;case st:return ie}return re});function Al(Y,re){return re=re??a,!!re&&(typeof Y=="number"||ae.test(Y))&&Y>-1&&Y%1==0&&Y<re}function xl(Y){var re=typeof Y;return re=="string"||re=="number"||re=="symbol"||re=="boolean"?Y!=="__proto__":Y===null}function Sl(Y){return!!_e&&_e in Y}function Il(Y){var re=Y&&Y.constructor,pe=typeof re=="function"&&re.prototype||Se;return Y===pe}function Op(Y){return Ke.call(Y)}function qs(Y){if(Y!=null){try{return Ue.call(Y)}catch{}try{return Y+""}catch{}}return""}function Ml(Y,re){return Y===re||Y!==Y&&re!==re}var Cl=af(function(){return arguments}())?af:function(Y){return wa(Y)&&Ce.call(Y,"callee")&&!Ge.call(Y,"callee")},Nc=Array.isArray;function Pp(Y){return Y!=null&&Dl(Y.length)&&!Tc(Y)}var cf=Ot||Qt;function $p(Y,re){return ya(Y,re)}function Tc(Y){if(!Ol(Y))return!1;var re=ba(Y);return re==S||re==D||re==l||re==R}function Dl(Y){return typeof Y=="number"&&Y>-1&&Y%1==0&&Y<=a}function Ol(Y){var re=typeof Y;return Y!=null&&(re=="object"||re=="function")}function wa(Y){return Y!=null&&typeof Y=="object"}var Pl=he?Oe(he):bl;function Rp(Y){return Pp(Y)?vl(Y):yl(Y)}function Xt(){return[]}function Qt(){return!1}t.exports=$p})(Xd,Xd.exports);var bD=Xd.exports,yD=Object.defineProperty,o3=Object.getOwnPropertySymbols,wD=Object.prototype.hasOwnProperty,_D=Object.prototype.propertyIsEnumerable,a3=(t,e,r)=>e in t?yD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fi=(t,e)=>{for(var r in e||(e={}))wD.call(e,r)&&a3(t,r,e[r]);if(o3)for(var r of o3(e))_D.call(e,r)&&a3(t,r,e[r]);return t};function ED(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),a=s.charCodeAt(0);if(r[a]!==255)throw new TypeError(s+" is ambiguous");r[a]=n}var u=t.length,h=t.charAt(0),l=Math.log(u)/Math.log(256),b=Math.log(256)/Math.log(u);function w(D){if(D instanceof Uint8Array||(ArrayBuffer.isView(D)?D=new Uint8Array(D.buffer,D.byteOffset,D.byteLength):Array.isArray(D)&&(D=Uint8Array.from(D))),!(D instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(D.length===0)return"";for(var T=0,q=0,K=0,F=D.length;K!==F&&D[K]===0;)K++,T++;for(var W=(F-K)*b+1>>>0,R=new Uint8Array(W);K!==F;){for(var k=D[K],H=0,_=W-1;(k!==0||H<q)&&_!==-1;_--,H++)k+=256*R[_]>>>0,R[_]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");q=H,K++}for(var B=W-q;B!==W&&R[B]===0;)B++;for(var ee=h.repeat(T);B<W;++B)ee+=t.charAt(R[B]);return ee}function I(D){if(typeof D!="string")throw new TypeError("Expected String");if(D.length===0)return new Uint8Array;var T=0;if(D[T]!==" "){for(var q=0,K=0;D[T]===h;)q++,T++;for(var F=(D.length-T)*l+1>>>0,W=new Uint8Array(F);D[T];){var R=r[D.charCodeAt(T)];if(R===255)return;for(var k=0,H=F-1;(R!==0||k<K)&&H!==-1;H--,k++)R+=u*W[H]>>>0,W[H]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");K=k,T++}if(D[T]!==" "){for(var _=F-K;_!==F&&W[_]===0;)_++;for(var B=new Uint8Array(q+(F-_)),ee=q;_!==F;)B[ee++]=W[_++];return B}}}function S(D){var T=I(D);if(T)return T;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:I,decode:S}}var AD=ED,xD=AD;const c3=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},SD=t=>new TextEncoder().encode(t),ID=t=>new TextDecoder().decode(t);class MD{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class CD{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return u3(this,e)}}class DD{constructor(e){this.decoders=e}or(e){return u3(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const u3=(t,e)=>new DD(fi(fi({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class OD{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new MD(e,r,i),this.decoder=new CD(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Rh=({name:t,prefix:e,encode:r,decode:i})=>new OD(t,e,r,i),Ru=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=xD(r,e);return Rh({prefix:t,name:e,encode:i,decode:s=>c3(n(s))})},PD=(t,e,r,i)=>{const n={};for(let b=0;b<e.length;++b)n[e[b]]=b;let s=t.length;for(;t[s-1]==="=";)--s;const a=new Uint8Array(s*r/8|0);let u=0,h=0,l=0;for(let b=0;b<s;++b){const w=n[t[b]];if(w===void 0)throw new SyntaxError(`Non-${i} character`);h=h<<r|w,u+=r,u>=8&&(u-=8,a[l++]=255&h>>u)}if(u>=r||255&h<<8-u)throw new SyntaxError("Unexpected end of data");return a},$D=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",a=0,u=0;for(let h=0;h<t.length;++h)for(u=u<<8|t[h],a+=8;a>r;)a-=r,s+=e[n&u>>a];if(a&&(s+=e[n&u<<r-a]),i)for(;s.length*r&7;)s+="=";return s},Kr=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Rh({prefix:e,name:t,encode(n){return $D(n,i,r)},decode(n){return PD(n,i,r,t)}}),RD=Rh({prefix:"\0",name:"identity",encode:t=>ID(t),decode:t=>SD(t)});var ND=Object.freeze({__proto__:null,identity:RD});const TD=Kr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var LD=Object.freeze({__proto__:null,base2:TD});const BD=Kr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var FD=Object.freeze({__proto__:null,base8:BD});const UD=Ru({prefix:"9",name:"base10",alphabet:"0123456789"});var kD=Object.freeze({__proto__:null,base10:UD});const qD=Kr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),jD=Kr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var zD=Object.freeze({__proto__:null,base16:qD,base16upper:jD});const HD=Kr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),KD=Kr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),WD=Kr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),VD=Kr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),GD=Kr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),JD=Kr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),YD=Kr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),QD=Kr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ZD=Kr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var XD=Object.freeze({__proto__:null,base32:HD,base32upper:KD,base32pad:WD,base32padupper:VD,base32hex:GD,base32hexupper:JD,base32hexpad:YD,base32hexpadupper:QD,base32z:ZD});const eO=Ru({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),tO=Ru({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var rO=Object.freeze({__proto__:null,base36:eO,base36upper:tO});const iO=Ru({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nO=Ru({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var sO=Object.freeze({__proto__:null,base58btc:iO,base58flickr:nO});const oO=Kr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),aO=Kr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cO=Kr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),uO=Kr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var fO=Object.freeze({__proto__:null,base64:oO,base64pad:aO,base64url:cO,base64urlpad:uO});const f3=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}"),hO=f3.reduce((t,e,r)=>(t[r]=e,t),[]),lO=f3.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function dO(t){return t.reduce((e,r)=>(e+=hO[r],e),"")}function pO(t){const e=[];for(const r of t){const i=lO[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const gO=Rh({prefix:"\u{1F680}",name:"base256emoji",encode:dO,decode:pO});var vO=Object.freeze({__proto__:null,base256emoji:gO}),mO=l3,h3=128,bO=127,yO=~bO,wO=Math.pow(2,31);function l3(t,e,r){e=e||[],r=r||0;for(var i=r;t>=wO;)e[r++]=t&255|h3,t/=128;for(;t&yO;)e[r++]=t&255|h3,t>>>=7;return e[r]=t|0,l3.bytes=r-i+1,e}var _O=e1,EO=128,d3=127;function e1(t,i){var r=0,i=i||0,n=0,s=i,a,u=t.length;do{if(s>=u)throw e1.bytes=0,new RangeError("Could not decode varint");a=t[s++],r+=n<28?(a&d3)<<n:(a&d3)*Math.pow(2,n),n+=7}while(a>=EO);return e1.bytes=s-i,r}var AO=Math.pow(2,7),xO=Math.pow(2,14),SO=Math.pow(2,21),IO=Math.pow(2,28),MO=Math.pow(2,35),CO=Math.pow(2,42),DO=Math.pow(2,49),OO=Math.pow(2,56),PO=Math.pow(2,63),$O=function(t){return t<AO?1:t<xO?2:t<SO?3:t<IO?4:t<MO?5:t<CO?6:t<DO?7:t<OO?8:t<PO?9:10},RO={encode:mO,decode:_O,encodingLength:$O},p3=RO;const g3=(t,e,r=0)=>(p3.encode(t,e,r),e),v3=t=>p3.encodingLength(t),t1=(t,e)=>{const r=e.byteLength,i=v3(t),n=i+v3(r),s=new Uint8Array(n+r);return g3(t,s,0),g3(r,s,i),s.set(e,n),new NO(t,r,e,s)};class NO{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const m3=({name:t,code:e,encode:r})=>new TO(t,e,r);class TO{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?t1(this.code,r):r.then(i=>t1(this.code,i))}else throw Error("Unknown type, must be binary type")}}const b3=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),LO=m3({name:"sha2-256",code:18,encode:b3("SHA-256")}),BO=m3({name:"sha2-512",code:19,encode:b3("SHA-512")});var FO=Object.freeze({__proto__:null,sha256:LO,sha512:BO});const y3=0,UO="identity",w3=c3;var kO=Object.freeze({__proto__:null,identity:{code:y3,name:UO,encode:w3,digest:t=>t1(y3,w3(t))}});new TextEncoder,new TextDecoder;const _3=fi(fi(fi(fi(fi(fi(fi(fi(fi(fi({},ND),LD),FD),kD),zD),XD),rO),sO),fO),vO);fi(fi({},FO),kO);function qO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function E3(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const A3=E3("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),r1=E3("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=qO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),jO=fi({utf8:A3,"utf-8":A3,hex:_3.base16,latin1:r1,ascii:r1,binary:r1},_3);function zO(t,e="utf8"){const r=jO[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}const x3="wc",S3=2,i1="core",hs=`${x3}@2:${i1}:`,HO={name:i1,logger:"error"},KO={database:":memory:"},WO="crypto",I3="client_ed25519_seed",VO=xe.ONE_DAY,GO="keychain",JO="0.3",YO="messages",QO="0.3",ZO=xe.SIX_HOURS,XO="publisher",M3="irn",eP="error",C3="wss://relay.walletconnect.org",tP="relayer",hi={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},rP="_subscription",nn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},iP=.1,n1="2.16.2",Zt={link_mode:"link_mode",relay:"relay"},nP="0.3",sP="WALLETCONNECT_CLIENT_ID",D3="WALLETCONNECT_LINK_MODE_APPS",ls={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},oP="subscription",aP="0.3",cP=xe.FIVE_SECONDS*1e3,uP="pairing",fP="0.3",Nu={wc_pairingDelete:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:xe.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:xe.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:0},res:{ttl:xe.ONE_DAY,prompt:!1,tag:0}}},fc={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Sn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},hP="history",lP="0.3",dP="expirer",sn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},pP="0.3",gP="verify-api",vP="https://verify.walletconnect.com",O3="https://verify.walletconnect.org",Tu=O3,mP=`${Tu}/v3`,bP=[vP,O3],yP="echo",wP="https://echo.walletconnect.com",ds={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Bs={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},In={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Zo={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Xo={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Lu={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},_P=.1,EP="event-client",AP=86400,xP="https://pulse.walletconnect.com/batch";class SP{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=GO,this.version=JO,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}},this.has=i=>(this.isInitialized(),this.keychain.has(i)),this.set=async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()},this.get=i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=Ee("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=ui(r,this.name)}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,W2(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?V2(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class IP{constructor(e,r,i){this.core=e,this.logger=r,this.name=WO,this.randomSessionIdentifier=Nd(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=n=>(this.isInitialized(),this.keychain.has(n)),this.getClientId=async()=>{this.isInitialized();const n=await this.getClientSeed(),s=F2(n);return B2(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const n=oI();return this.setPrivateKey(n.publicKey,n.privateKey)},this.signJWT=async n=>{this.isInitialized();const s=await this.getClientSeed(),a=F2(s),u=this.randomSessionIdentifier;return await zE(u,n,VO,a)},this.generateSharedKey=(n,s,a)=>{this.isInitialized();const u=this.getPrivateKey(n),h=aI(u,s);return this.setSymKey(h,a)},this.setSymKey=async(n,s)=>{this.isInitialized();const a=s||bh(n);return await this.keychain.set(a,n),a},this.deleteKeyPair=async n=>{this.isInitialized(),await this.keychain.del(n)},this.deleteSymKey=async n=>{this.isInitialized(),await this.keychain.del(n)},this.encode=async(n,s,a)=>{this.isInitialized();const u=gb(a),h=Cs(s);if(mb(u))return uI(h,a?.encoding);if(vb(u)){const I=u.senderPublicKey,S=u.receiverPublicKey;n=await this.generateSharedKey(I,S)}const l=this.getSymKey(n),{type:b,senderPublicKey:w}=u;return cI({type:b,symKey:l,message:h,senderPublicKey:w,encoding:a?.encoding})},this.decode=async(n,s,a)=>{this.isInitialized();const u=lI(s,a);if(mb(u)){const h=hI(s,a?.encoding);return jo(h)}if(vb(u)){const h=u.receiverPublicKey,l=u.senderPublicKey;n=await this.generateSharedKey(h,l)}try{const h=this.getSymKey(n),l=fI({symKey:h,encoded:s,encoding:a?.encoding});return jo(l)}catch(h){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=(n,s=ao)=>{const a=Eu({encoded:n,encoding:s});return Go(a.type)},this.getPayloadSenderPublicKey=(n,s=ao)=>{const a=Eu({encoded:n,encoding:s});return a.senderPublicKey?DC(a.senderPublicKey,ai):void 0},this.core=e,this.logger=ui(r,this.name),this.keychain=i||new SP(this.core,this.logger)}get context(){return Ai(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(I3)}catch{e=Nd(),await this.keychain.set(I3,e)}return zO(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class MP extends vC{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=YO,this.version=QO,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}},this.set=async(i,n)=>{this.isInitialized();const s=Ns(n);let a=this.messages.get(i);return typeof a>"u"&&(a={}),typeof a[s]<"u"||(a[s]=n,this.messages.set(i,a),await this.persist()),s},this.get=i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n},this.has=(i,n)=>{this.isInitialized();const s=this.get(i),a=Ns(n);return typeof s[a]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=ui(e,this.name),this.core=r}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,W2(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?V2(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class CP extends mC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new kr.exports.EventEmitter,this.name=XO,this.queue=new Map,this.publishTimeout=xe.toMiliseconds(xe.ONE_MINUTE),this.failedPublishTimeout=xe.toMiliseconds(xe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(i,n,s)=>{var a;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const u=s?.ttl||ZO,h=Td(s),l=s?.prompt||!1,b=s?.tag||0,w=s?.id||Qo().toString(),I={topic:i,message:n,opts:{ttl:u,relay:h,prompt:l,tag:b,id:w,attestation:s?.attestation}},S=`Failed to publish payload, please try again. id:${w} tag:${b}`,D=Date.now();let T,q=1;try{for(;T===void 0;){if(Date.now()-D>this.publishTimeout)throw new Error(S);this.logger.trace({id:w,attempts:q},`publisher.publish - attempt ${q}`),T=await await Ga(this.rpcPublish(i,n,u,h,l,b,w,s?.attestation).catch(K=>this.logger.warn(K)),this.publishTimeout,S),q++,T||await new Promise(K=>setTimeout(K,this.failedPublishTimeout))}this.relayer.events.emit(hi.publish,I),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:w,topic:i,message:n,opts:s}})}catch(K){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(K),(a=s?.internal)!=null&&a.throwOnFailedPublish)throw K;this.queue.set(w,I)}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.relayer=e,this.logger=ui(r,this.name),this.registerEventListeners()}get context(){return Ai(this.logger)}rpcPublish(e,r,i,n,s,a,u,h){var l,b,w,I;const S={method:Au(n.protocol).publish,params:{topic:e,message:r,ttl:i,prompt:s,tag:a,attestation:h},id:u};return ci((l=S.params)==null?void 0:l.prompt)&&((b=S.params)==null||delete b.prompt),ci((w=S.params)==null?void 0:w.tag)&&((I=S.params)==null||delete I.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:S}),this.relayer.request(S)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:i,opts:n}=e;await this.publish(r,i,n)})}registerEventListeners(){this.relayer.core.heartbeat.on(ac.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(hi.connection_stalled);return}this.checkQueue()}),this.relayer.on(hi.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class DP{constructor(){this.map=new Map,this.set=(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var OP=Object.defineProperty,PP=Object.defineProperties,$P=Object.getOwnPropertyDescriptors,P3=Object.getOwnPropertySymbols,RP=Object.prototype.hasOwnProperty,NP=Object.prototype.propertyIsEnumerable,$3=(t,e,r)=>e in t?OP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bu=(t,e)=>{for(var r in e||(e={}))RP.call(e,r)&&$3(t,r,e[r]);if(P3)for(var r of P3(e))NP.call(e,r)&&$3(t,r,e[r]);return t},s1=(t,e)=>PP(t,$P(e));class TP extends wC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new DP,this.events=new kr.exports.EventEmitter,this.name=oP,this.version=aP,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=hs,this.subscribeTimeout=xe.toMiliseconds(xe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.pendingBatchMessages=[],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(i,n)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const s=Td(n),a={topic:i,relay:s,transportType:n?.transportType};this.pending.set(i,a);const u=await this.rpcSubscribe(i,s,n?.transportType);return typeof u=="string"&&(this.onSubscribe(u,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),u}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(i,n)=>{await this.restartToComplete(),this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)},this.isSubscribed=async i=>{if(this.topics.includes(i))return!0;const n=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((s,a)=>{const u=new xe.Watch;u.start(n);const h=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(h),u.stop(n),s(!0)),u.elapsed(n)>=cP&&(clearInterval(h),u.stop(n),a(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=ui(r,this.name),this.clientId=""}get context(){return Ai(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,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=Td(i);await this.rpcUnsubscribe(e,r,n);const s=Gt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i=Zt.relay){i===Zt.relay&&await this.restartToComplete();const n={method:Au(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{const s=Ns(e+this.clientId);return i===Zt.link_mode?(setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(a=>this.logger.warn(a))},xe.toMiliseconds(xe.ONE_SECOND)),s):await await Ga(this.relayer.request(n).catch(a=>this.logger.warn(a)),this.subscribeTimeout)?s:null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(hi.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:Au(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await await Ga(this.relayer.request(i).catch(n=>this.logger.warn(n)),this.subscribeTimeout)}catch{this.relayer.events.emit(hi.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:Au(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Ga(this.relayer.request(i).catch(s=>this.logger.warn(s)),this.subscribeTimeout)}catch{this.relayer.events.emit(hi.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:Au(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,s1(Bu({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Bu({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,Bu({},r)),this.topicMap.set(r.topic,e),this.events.emit(ls.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(ls.deleted,s1(Bu({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ls.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const i=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchFetchMessages(i),await this.batchSubscribe(i)}}this.events.emit(ls.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}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){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);as(r)&&this.onBatchSubscribe(r.map((i,n)=>s1(Bu({},e[n]),{id:i})))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(this.pendingBatchMessages=this.pendingBatchMessages.concat(r.messages))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e),this.pendingBatchMessages.length&&(await this.relayer.handleBatchMessageEvents(this.pendingBatchMessages),this.pendingBatchMessages=[])}registerEventListeners(){this.relayer.core.heartbeat.on(ac.pulse,async()=>{await this.checkPending()}),this.events.on(ls.created,async e=>{const r=ls.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(ls.deleted,async e=>{const r=ls.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen(),this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var LP=Object.defineProperty,R3=Object.getOwnPropertySymbols,BP=Object.prototype.hasOwnProperty,FP=Object.prototype.propertyIsEnumerable,N3=(t,e,r)=>e in t?LP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,UP=(t,e)=>{for(var r in e||(e={}))BP.call(e,r)&&N3(t,r,e[r]);if(R3)for(var r of R3(e))FP.call(e,r)&&N3(t,r,e[r]);return t};class kP extends bC{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new kr.exports.EventEmitter,this.name=tP,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=xe.toMiliseconds(xe.THIRTY_SECONDS+xe.ONE_SECOND),this.request=async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||Qo().toString();await this.toEstablishConnection();try{const a=this.provider.request(r);this.requestsInFlight.set(s,{promise:a,request:r}),this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - attempt to publish...");const u=await new Promise(async(h,l)=>{const b=()=>{l(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(nn.disconnect,b);const w=await a;this.provider.off(nn.disconnect,b),h(w)});return this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - published"),u}catch(a){throw this.logger.debug(`Failed to Publish Request: ${s}`),a}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(th())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,n;(n=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||n.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.trace("relayer connected"),this.startPingTimeout(),this.events.emit(hi.connect)},this.onDisconnectHandler=()=>{this.logger.trace("relayer disconnected"),this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(hi.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(nn.payload,this.onPayloadHandler),this.provider.on(nn.connect,this.onConnectHandler),this.provider.on(nn.disconnect,this.onDisconnectHandler),this.provider.on(nn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ui(e.logger,this.name):cs(Dh({level:e.logger||eP})),this.messages=new MP(this.logger,e.core),this.subscriber=new TP(this,this.logger),this.publisher=new CP(this,this.logger),this.relayUrl=e?.relayUrl||C3,this.projectId=e.projectId,this.bundleId=QE(),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)}}get context(){return Ai(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:Zt.relay})}async subscribe(e,r){var i;this.isInitialized(),r?.transportType==="relay"&&await this.toEstablishConnection();let n=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",s;const a=u=>{u.topic===e&&(this.subscriber.off(ls.created,a),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(ls.created,a)}),new Promise(async u=>{n=await this.subscriber.subscribe(e,r)||n,u()})]),n}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await Ga(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),await this.createProvider(),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,i)=>{const n=()=>{this.provider.off(nn.disconnect,n),i(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(nn.disconnect,n),await Ga(this.provider.connect(),xe.toMiliseconds(xe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{i(s)}).finally(()=>{clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),this.subscriber.start().catch(s=>{this.logger.error(s),this.onDisconnectHandler()}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);const i=r;if(this.hasExperiencedNetworkDisruption=!0,!this.isConnectionStalled(i.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Db())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 r=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.trace(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=Ir(xe.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(hi.message,e),await this.recordMessageEvent(e)}startPingTimeout(){var e,r,i,n,s;if(th())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null||s.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(a){this.logger.warn(a)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new xn(new mD(tA({sdkVersion:n1,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:r,message:i}=e;await this.messages.set(r,i)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.debug(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Zd(e)){if(!e.method.endsWith(rP))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:a}=r.data,u={topic:i,message:n,publishedAt:s,transportType:Zt.relay,attestation:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(UP({type:"event",event:r.id},u)),this.events.emit(r.id,u),await this.acknowledgePayload(e),await this.onMessageEvent(u)}else $h(e)&&this.events.emit(hi.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(hi.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Oh(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(nn.payload,this.onPayloadHandler),this.provider.off(nn.connect,this.onConnectHandler),this.provider.off(nn.disconnect,this.onDisconnectHandler),this.provider.off(nn.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Db();oM(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(i=>this.logger.error(i)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.requestsInFlight.clear(),clearTimeout(this.pingTimeout),this.events.emit(hi.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},xe.toMiliseconds(iP))))}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}}var qP=Object.defineProperty,T3=Object.getOwnPropertySymbols,jP=Object.prototype.hasOwnProperty,zP=Object.prototype.propertyIsEnumerable,L3=(t,e,r)=>e in t?qP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,B3=(t,e)=>{for(var r in e||(e={}))jP.call(e,r)&&L3(t,r,e[r]);if(T3)for(var r of T3(e))zP.call(e,r)&&L3(t,r,e[r]);return t};class ea extends yC{constructor(e,r,i,n=hs,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,this.map=new Map,this.version=nP,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(a=>{this.getKey&&a!==null&&!ci(a)?this.map.set(this.getKey(a),a):BI(a)?this.map.set(a.id,a):FI(a)&&this.map.set(a.topic,a)}),this.cached=[],this.initialized=!0)},this.set=async(a,u)=>{this.isInitialized(),this.map.has(a)?await this.update(a,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:a,value:u}),this.map.set(a,u),await this.persist())},this.get=a=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:a}),this.getData(a)),this.getAll=a=>(this.isInitialized(),a?this.values.filter(u=>Object.keys(a).every(h=>bD(u[h],a[h]))):this.values),this.update=async(a,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:a,update:u});const h=B3(B3({},this.getData(a)),u);this.map.set(a,h),await this.persist()},this.delete=async(a,u)=>{this.isInitialized(),this.map.has(a)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:a,reason:u}),this.map.delete(a),this.addToRecentlyDeleted(a),await this.persist())},this.logger=ui(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return Ai(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 r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:n}=Ee("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}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:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class HP{constructor(e,r){this.core=e,this.logger=r,this.name=uP,this.version=fP,this.events=new kr.exports,this.initialized=!1,this.storagePrefix=hs,this.ignoredPayloadTypes=[Rs],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:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async i=>{this.isInitialized();const n=Nd(),s=await this.core.crypto.setSymKey(n),a=Ir(xe.FIVE_MINUTES),u={protocol:M3},h={topic:s,expiry:a,relay:u,active:!1},l=MI({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:u,expiryTimestamp:a,methods:i?.methods});return this.core.expirer.set(s,a),await this.pairings.set(s,h),await this.core.relayer.subscribe(s,{transportType:i?.transportType}),{topic:s,uri:l}},this.pair=async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[ds.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:a,relay:u,expiryTimestamp:h,methods:l}=_b(i.uri);n.props.properties.topic=s,n.addTrace(ds.pairing_uri_validation_success),n.addTrace(ds.pairing_uri_not_expired);let b;if(this.pairings.keys.includes(s)){if(b=this.pairings.get(s),n.addTrace(ds.existing_pairing),b.active)throw n.setError(Bs.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(ds.pairing_not_expired)}const w=h||Ir(xe.FIVE_MINUTES),I={topic:s,relay:u,expiry:w,active:!1,methods:l};this.core.expirer.set(s,w),await this.pairings.set(s,I),n.addTrace(ds.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(fc.create,I),n.addTrace(ds.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(a,s),n.addTrace(ds.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(Bs.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:u})}catch(S){throw n.setError(Bs.subscribe_pairing_topic_failure),S}return n.addTrace(ds.subscribe_pairing_topic_success),I},this.activate=async({topic:i})=>{this.isInitialized();const n=Ir(xe.THIRTY_DAYS);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i);const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:a,resolve:u,reject:h}=Ho();this.events.once(Dt("pairing_ping",s),({error:l})=>{l?h(l):u()}),await a()}},this.updateExpiry=async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})},this.updateMetadata=async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",Gt("USER_DISCONNECTED")),await this.deletePairing(n))},this.sendRequest=async(i,n,s)=>{const a=uo(n,s),u=await this.core.crypto.encode(i,a),h=Nu[n].req;return this.core.history.set(i,a),this.core.relayer.publish(i,u,h),a.id},this.sendResult=async(i,n,s)=>{const a=Oh(i,s),u=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),l=Nu[h.request.method].res;await this.core.relayer.publish(n,u,l),await this.core.history.resolve(a)},this.sendError=async(i,n,s)=>{const a=Ph(i,s),u=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),l=Nu[h.request.method]?Nu[h.request.method].res:Nu.unregistered_method.res;await this.core.relayer.publish(n,u,l),await this.core.history.resolve(a)},this.deletePairing=async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Gt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(n=>io(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))},this.onRelayEventRequest=i=>{const{topic:n,payload:s}=i;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(n,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(n,s);default:return this.onUnknownRpcMethodRequest(n,s)}},this.onRelayEventResponse=async i=>{const{topic:n,payload:s}=i,a=(await this.core.history.get(n,s.id)).request.method;switch(a){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(a)}},this.onPairingPingRequest=async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(fc.ping,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onPairingPingResponse=(i,n)=>{const{id:s}=n;setTimeout(()=>{fs(n)?this.events.emit(Dt("pairing_ping",s),{}):rn(n)&&this.events.emit(Dt("pairing_ping",s),{error:n.error})},500)},this.onPairingDeleteRequest=async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(fc.delete,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onUnknownRpcMethodRequest=async(i,n)=>{const{id:s,method:a}=n;try{if(this.registeredMethods.includes(a))return;const u=Gt("WC_METHOD_UNSUPPORTED",a);await this.sendError(s,i,u),this.logger.error(u)}catch(u){await this.sendError(s,i,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(Gt("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=(i,n)=>{var s;if(!_i(i)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(!LI(i.uri)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(Bs.malformed_pairing_uri),new Error(u)}const a=_b(i?.uri);if(!((s=a?.relay)!=null&&s.protocol)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(!(a!=null&&a.symKey)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(a!=null&&a.expiryTimestamp&&xe.toMiliseconds(a?.expiryTimestamp)<Date.now()){n.setError(Bs.pairing_expired);const{message:u}=Ee("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(u)}},this.isValidPing=async i=>{if(!_i(i)){const{message:s}=Ee("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidDisconnect=async i=>{if(!_i(i)){const{message:s}=Ee("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidPairingTopic=async i=>{if(!yr(i,!1)){const{message:n}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(io(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=Ee("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}},this.core=e,this.logger=ui(r,this.name),this.pairings=new ea(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ai(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(hi.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(!this.pairings.keys.includes(r)||n===Zt.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(r,i);try{Zd(s)?(this.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):$h(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id))}catch(a){this.logger.error(a)}})}registerExpirerEvents(){this.core.expirer.on(sn.expired,async e=>{const{topic:r}=J2(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(fc.expire,{topic:r}))})}}class KP extends gC{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new kr.exports.EventEmitter,this.name=hP,this.version=lP,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const a={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:Ir(xe.THIRTY_DAYS)};this.records.set(a.id,a),this.persist(),this.events.emit(Sn.created,a)},this.resolve=async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=rn(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Sn.updated,n))},this.get=async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n)),this.delete=(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Sn.deleted,s)}}),this.persist()},this.exists=async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1),this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ui(r,this.name)}get context(){return Ai(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(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:uo(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),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 r=this.records.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Sn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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(Sn.created,e=>{const r=Sn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Sn.updated,e=>{const r=Sn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Sn.deleted,e=>{const r=Sn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(ac.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{xe.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Sn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class WP extends _C{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new kr.exports.EventEmitter,this.name=dP,this.version=pP,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}},this.set=(i,n)=>{this.isInitialized();const s=this.formatTarget(i),a={target:s,expiry:n};this.expirations.set(s,a),this.checkExpiry(s,a),this.events.emit(sn.created,{target:s,expiration:a})},this.get=i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)},this.del=i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(sn.deleted,{target:n,expiration:s})}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ui(r,this.name)}get context(){return Ai(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 rA(e);if(typeof e=="number")return iA(e);const{message:r}=Ee("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}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(sn.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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 r=this.expirations.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;xe.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(sn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ac.pulse,()=>this.checkExpirations()),this.events.on(sn.created,e=>{const r=sn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(sn.expired,e=>{const r=sn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(sn.deleted,e=>{const r=sn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var or={};Object.defineProperty(or,"__esModule",{value:!0}),or.getLocalStorage=or.getLocalStorageOrThrow=or.getCrypto=or.getCryptoOrThrow=or.getLocation=or.getLocationOrThrow=or.getNavigator=or.getNavigatorOrThrow=F3=or.getDocument=or.getDocumentOrThrow=or.getFromWindowOrThrow=or.getFromWindow=void 0;function ta(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}or.getFromWindow=ta;function hc(t){const e=ta(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}or.getFromWindowOrThrow=hc;function VP(){return hc("document")}or.getDocumentOrThrow=VP;function GP(){return ta("document")}var F3=or.getDocument=GP;function JP(){return hc("navigator")}or.getNavigatorOrThrow=JP;function YP(){return ta("navigator")}or.getNavigator=YP;function QP(){return hc("location")}or.getLocationOrThrow=QP;function ZP(){return ta("location")}or.getLocation=ZP;function XP(){return hc("crypto")}or.getCryptoOrThrow=XP;function e$(){return ta("crypto")}or.getCrypto=e$;function t$(){return hc("localStorage")}or.getLocalStorageOrThrow=t$;function r$(){return ta("localStorage")}or.getLocalStorage=r$;class i$ extends EC{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,this.name=gP,this.verifyUrlV3=mP,this.storagePrefix=hs,this.version=S3,this.init=async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&xe.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async n=>{if(!au()||this.isDevEnv)return;const s=window.location.origin,{id:a,decryptedId:u}=n,h=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${a}&decryptedId=${u}`;try{const l=F3(),b=this.startAbortTimer(xe.ONE_SECOND*5),w=await new Promise((I,S)=>{const D=()=>{window.removeEventListener("message",q),l.body.removeChild(T),S("attestation aborted")};this.abortController.signal.addEventListener("abort",D);const T=l.createElement("iframe");T.src=h,T.style.display="none",T.addEventListener("error",D,{signal:this.abortController.signal});const q=K=>{if(!K.data)return;const F=JSON.parse(K.data);if(F.type==="verify_attestation"){if(od(F.attestation).payload.id!==a)return;clearInterval(b),l.body.removeChild(T),this.abortController.signal.removeEventListener("abort",D),window.removeEventListener("message",q),I(F.attestation===null?"":F.attestation)}};l.body.appendChild(T),window.addEventListener("message",q,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",w),w}catch(l){this.logger.warn(l)}return""},this.resolve=async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:a,encryptedId:u}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(od(s).payload.id!==u)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!a)return;const h=this.getVerifyUrl(n?.verifyUrl);return this.fetchAttestation(a,h)},this.fetchAttestation=async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const a=this.startAbortTimer(xe.ONE_SECOND*5),u=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(a),u.status===200?await u.json():void 0},this.getVerifyUrl=n=>{let s=n||Tu;return bP.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Tu}`),s=Tu),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(xe.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}},this.persistPublicKey=async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n},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 n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(u){this.logger.error(u),this.logger.warn("error validating attestation")}const a=await this.fetchAndPersistPublicKey();try{if(a)return this.validateAttestation(n,a)}catch(u){this.logger.error(u),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 s=>{const a=await this.fetchPublicKey();a&&(await this.persistPublicKey(a),s(a))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n},this.validateAttestation=(n,s)=>{const a=vI(n,s.publicKey),u={hasExpired:xe.toMiliseconds(a.exp)<Date.now(),payload:a};if(u.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:u.payload.origin,isScam:u.payload.isScam,isVerified:u.payload.isVerified}},this.logger=ui(r,this.name),this.abortController=new AbortController,this.isDevEnv=ad(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ai(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),xe.toMiliseconds(e))}}class n$ extends AC{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=yP,this.registerDeviceToken=async i=>{const{clientId:n,token:s,notificationType:a,enableEncrypted:u=!1}=i,h=`${wP}/${this.projectId}/clients`;await fetch(h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:a,token:s,always_raw:u})})},this.logger=ui(r,this.context)}}var s$=Object.defineProperty,U3=Object.getOwnPropertySymbols,o$=Object.prototype.hasOwnProperty,a$=Object.prototype.propertyIsEnumerable,k3=(t,e,r)=>e in t?s$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fu=(t,e)=>{for(var r in e||(e={}))o$.call(e,r)&&k3(t,r,e[r]);if(U3)for(var r of U3(e))a$.call(e,r)&&k3(t,r,e[r]);return t};class c$ extends xC{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,this.context=EP,this.storagePrefix=hs,this.storageVersion=_P,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!ad())try{const n={eventId:Q2(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:K2(this.core.relayer.protocol,this.core.relayer.version,n1)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}},this.createEvent=n=>{const{event:s="ERROR",type:a="",properties:{topic:u,trace:h}}=n,l=Q2(),b=this.core.projectId||"",w=Date.now(),I=Fu({eventId:l,timestamp:w,props:{event:s,type:a,properties:{topic:u,trace:h}},bundleId:b,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,I),this.shouldPersist=!0),I},this.getEvent=n=>{const{eventId:s,topic:a}=n;if(s)return this.events.get(s);const u=Array.from(this.events.values()).find(h=>h.props.properties.topic===a);if(u)return Fu(Fu({},u),this.setMethods(u.eventId))},this.deleteEvent=n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(ac.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{xe.fromMiliseconds(Date.now())-xe.fromMiliseconds(n.timestamp)>AP&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})},this.setMethods=n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)}),this.addTrace=(n,s)=>{const a=this.events.get(n);a&&(a.props.properties.trace.push(s),this.events.set(n,a),this.shouldPersist=!0)},this.setError=(n,s)=>{const a=this.events.get(n);a&&(a.props.type=s,a.timestamp=Date.now(),this.events.set(n,a),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 n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,Fu(Fu({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,a]of this.events)a.props.type&&n.push(a);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}},this.sendEvent=async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${xP}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${n1}${s}`,{method:"POST",body:JSON.stringify(n)})},this.getAppDomain=()=>H2().url,this.logger=ui(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var u$=Object.defineProperty,q3=Object.getOwnPropertySymbols,f$=Object.prototype.hasOwnProperty,h$=Object.prototype.propertyIsEnumerable,j3=(t,e,r)=>e in t?u$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,z3=(t,e)=>{for(var r in e||(e={}))f$.call(e,r)&&j3(t,r,e[r]);if(q3)for(var r of q3(e))h$.call(e,r)&&j3(t,r,e[r]);return t};class o1 extends pC{constructor(e){var r;super(e),this.protocol=x3,this.version=S3,this.name=i1,this.events=new kr.exports.EventEmitter,this.initialized=!1,this.on=(a,u)=>this.events.on(a,u),this.once=(a,u)=>this.events.once(a,u),this.off=(a,u)=>this.events.off(a,u),this.removeListener=(a,u)=>this.events.removeListener(a,u),this.dispatchEnvelope=({topic:a,message:u,sessionExists:h})=>{if(!a||!u)return;const l={topic:a,message:u,publishedAt:Date.now(),transportType:Zt.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})},this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||C3,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Dh({level:typeof e?.logger=="string"&&e.logger?e.logger:HO.logger}),{logger:n,chunkLoggerController:s}=dC({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,u;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=ui(n,this.name),this.heartbeat=new zd,this.crypto=new IP(this,this.logger,e?.keychain),this.history=new KP(this,this.logger),this.expirer=new WP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new FM(z3(z3({},KO),e?.storageOptions)),this.relayer=new kP({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new HP(this,this.logger),this.verify=new i$(this,this.logger,this.storage),this.echoClient=new n$(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new c$(this,this.logger,e?.telemetryEnabled)}static async init(e){const r=new o1(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(sP,i),r}get context(){return Ai(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(D3,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(D3)||[],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 l$=o1,H3="wc",K3=2,W3="client",a1=`${H3}@${K3}:${W3}:`,c1={name:W3,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},V3="WALLETCONNECT_DEEPLINK_CHOICE",d$="proposal",G3="Proposal expired",p$="session",lc=xe.SEVEN_DAYS,g$="engine",Lr={wc_sessionPropose:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1104},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1106},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1112},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1114},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:xe.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:xe.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1119}}},u1={min:xe.FIVE_MINUTES,max:xe.SEVEN_DAYS},ps={idle:"IDLE",active:"ACTIVE"},v$="request",m$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],b$="wc",y$="auth",w$="authKeys",_$="pairingTopics",E$="requests",Nh=`${b$}@${1.5}:${y$}:`,Th=`${Nh}:PUB_KEY`;var A$=Object.defineProperty,x$=Object.defineProperties,S$=Object.getOwnPropertyDescriptors,J3=Object.getOwnPropertySymbols,I$=Object.prototype.hasOwnProperty,M$=Object.prototype.propertyIsEnumerable,Y3=(t,e,r)=>e in t?A$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pr=(t,e)=>{for(var r in e||(e={}))I$.call(e,r)&&Y3(t,r,e[r]);if(J3)for(var r of J3(e))M$.call(e,r)&&Y3(t,r,e[r]);return t},Mn=(t,e)=>x$(t,S$(e));class C$ extends IC{constructor(e){super(e),this.name=g$,this.events=new kr.exports,this.initialized=!1,this.requestQueue={state:ps.idle,queue:[]},this.sessionRequestQueue={state:ps.idle,queue:[]},this.requestQueueDelay=xe.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(Lr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},xe.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Mn(pr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:a,sessionProperties:u,relays:h}=i;let l=n,b,w=!1;try{l&&(w=this.client.core.pairing.pairings.get(l).active)}catch(R){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),R}if(!l||!w){const{topic:R,uri:k}=await this.client.core.pairing.create();l=R,b=k}if(!l){const{message:R}=Ee("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(R)}const I=await this.client.core.crypto.generateKeyPair(),S=Lr.wc_sessionPropose.req.ttl||xe.FIVE_MINUTES,D=Ir(S),T=pr({requiredNamespaces:s,optionalNamespaces:a,relays:h??[{protocol:M3}],proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:D,pairingTopic:l},u&&{sessionProperties:u}),{reject:q,resolve:K,done:F}=Ho(S,G3);this.events.once(Dt("session_connect"),async({error:R,session:k})=>{if(R)q(R);else if(k){k.self.publicKey=I;const H=Mn(pr({},k),{pairingTopic:T.pairingTopic,requiredNamespaces:T.requiredNamespaces,optionalNamespaces:T.optionalNamespaces,transportType:Zt.relay});await this.client.session.set(k.topic,H),await this.setExpiry(k.topic,k.expiry),l&&await this.client.core.pairing.updateMetadata({topic:l,metadata:k.peer.metadata}),this.cleanupDuplicatePairings(H),K(H)}});const W=await this.sendRequest({topic:l,method:"wc_sessionPropose",params:T,throwOnFailedPublish:!0});return await this.setProposal(W,pr({id:W},T)),{uri:b,approval:F}},this.pair=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}},this.approve=async r=>{var i,n,s;const a=this.client.core.eventClient.createEvent({properties:{topic:(i=r?.id)==null?void 0:i.toString(),trace:[In.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(B){throw a.setError(Zo.no_internet_connection),B}try{await this.isValidProposalId(r?.id)}catch(B){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),a.setError(Zo.proposal_not_found),B}try{await this.isValidApprove(r)}catch(B){throw this.client.logger.error("approve() -> isValidApprove() failed"),a.setError(Zo.session_approve_namespace_validation_failure),B}const{id:u,relayProtocol:h,namespaces:l,sessionProperties:b,sessionConfig:w}=r,I=this.client.proposal.get(u);this.client.core.eventClient.deleteEvent({eventId:a.eventId});const{pairingTopic:S,proposer:D,requiredNamespaces:T,optionalNamespaces:q}=I;let K=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:S});K||(K=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:In.session_approve_started,properties:{topic:S,trace:[In.session_approve_started,In.session_namespaces_validation_success]}}));const F=await this.client.core.crypto.generateKeyPair(),W=D.publicKey,R=await this.client.core.crypto.generateSharedKey(F,W),k=pr(pr({relay:{protocol:h??"irn"},namespaces:l,controller:{publicKey:F,metadata:this.client.metadata},expiry:Ir(lc)},b&&{sessionProperties:b}),w&&{sessionConfig:w}),H=Zt.relay;K.addTrace(In.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:H})}catch(B){throw K.setError(Zo.subscribe_session_topic_failure),B}K.addTrace(In.subscribe_session_topic_success);const _=Mn(pr({},k),{topic:R,requiredNamespaces:T,optionalNamespaces:q,pairingTopic:S,acknowledged:!1,self:k.controller,peer:{publicKey:D.publicKey,metadata:D.metadata},controller:F,transportType:Zt.relay});await this.client.session.set(R,_),K.addTrace(In.store_session);try{K.addTrace(In.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:k,throwOnFailedPublish:!0}).catch(B=>{throw K?.setError(Zo.session_settle_publish_failure),B}),K.addTrace(In.session_settle_publish_success),K.addTrace(In.publishing_session_approve),await this.sendResult({id:u,topic:S,result:{relay:{protocol:h??"irn"},responderPublicKey:F},throwOnFailedPublish:!0}).catch(B=>{throw K?.setError(Zo.session_approve_publish_failure),B}),K.addTrace(In.session_approve_publish_success)}catch(B){throw this.client.logger.error(B),this.client.session.delete(R,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),B}return this.client.core.eventClient.deleteEvent({eventId:K.eventId}),await this.client.core.pairing.updateMetadata({topic:S,metadata:D.metadata}),await this.client.proposal.delete(u,Gt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:S}),await this.setExpiry(R,Ir(lc)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}},this.reject=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(a){throw this.client.logger.error("reject() -> isValidReject() failed"),a}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(a){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),a}s&&(await this.sendError({id:i,topic:s,error:n,rpcOpts:Lr.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(w){throw this.client.logger.error("update() -> isValidUpdate() failed"),w}const{topic:i,namespaces:n}=r,{done:s,resolve:a,reject:u}=Ho(),h=co(),l=Qo().toString(),b=this.client.session.get(i).namespaces;return this.events.once(Dt("session_update",h),({error:w})=>{w?u(w):a()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:h,relayRpcId:l}).catch(w=>{this.client.logger.error(w),this.client.session.update(i,{namespaces:b}),u(w)}),{acknowledged:s}},this.extend=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(h){throw this.client.logger.error("extend() -> isValidExtend() failed"),h}const{topic:i}=r,n=co(),{done:s,resolve:a,reject:u}=Ho();return this.events.once(Dt("session_extend",n),({error:h})=>{h?u(h):a()}),await this.setExpiry(i,Ir(lc)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(h=>{u(h)}),{acknowledged:s}},this.request=async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(D){throw this.client.logger.error("request() -> isValidRequest() failed"),D}const{chainId:i,request:n,topic:s,expiry:a=Lr.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s);u?.transportType===Zt.relay&&await this.confirmOnlineStateOrThrow();const h=co(),l=Qo().toString(),{done:b,resolve:w,reject:I}=Ho(a,"Request expired. Please try again.");this.events.once(Dt("session_request",h),({error:D,result:T})=>{D?I(D):w(T)});const S=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);return S?(await this.sendRequest({clientRpcId:h,relayRpcId:l,topic:s,method:"wc_sessionRequest",params:{request:Mn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0,appLink:S}).catch(D=>I(D)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),await b()):await Promise.all([new Promise(async D=>{await this.sendRequest({clientRpcId:h,relayRpcId:l,topic:s,method:"wc_sessionRequest",params:{request:Mn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0}).catch(T=>I(T)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),D()}),new Promise(async D=>{var T;if(!((T=u.sessionConfig)!=null&&T.disableDeepLink)){const q=await sA(this.client.core.storage,V3);nA({id:h,topic:s,wcDeepLink:q})}D()}),b()]).then(D=>D[2])},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:n}=r,{id:s}=n,a=this.client.session.get(i);a.transportType===Zt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);fs(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:u}):rn(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:u}),this.cleanupAfterResponse(r)},this.ping=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=co(),s=Qo().toString(),{done:a,resolve:u,reject:h}=Ho();this.events.once(Dt("session_ping",n),({error:l})=>{l?h(l):u()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),a()])}else this.client.core.pairing.pairings.keys.includes(i)&&await this.client.core.pairing.ping({topic:i})},this.emit=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,a=Qo().toString();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:a})},this.disconnect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Gt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=Ee("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(i=>NI(i,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),a=s?Zt.link_mode:Zt.relay;a===Zt.relay&&await this.confirmOnlineStateOrThrow();const{chains:u,statement:h="",uri:l,domain:b,nonce:w,type:I,exp:S,nbf:D,methods:T=[],expiry:q}=r,K=[...r.resources||[]],{topic:F,uri:W}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:a});this.client.logger.info({message:"Generated new pairing",pairing:{topic:F,uri:W}});const R=await this.client.core.crypto.generateKeyPair(),k=bh(R);if(await Promise.all([this.client.auth.authKeys.set(Th,{responseTopic:k,publicKey:R}),this.client.auth.pairingTopics.set(k,{topic:k,pairingTopic:F})]),await this.client.core.relayer.subscribe(k,{transportType:a}),this.client.logger.info(`sending request to new pairing topic: ${F}`),T.length>0){const{namespace:O}=ou(u[0]);let M=eI(O,"request",T);mh(K)&&(M=rI(M,K.pop())),K.push(M)}const H=q&&q>Lr.wc_sessionAuthenticate.req.ttl?q:Lr.wc_sessionAuthenticate.req.ttl,_={authPayload:{type:I??"caip122",chains:u,statement:h,aud:l,domain:b,version:"1",nonce:w,iat:new Date().toISOString(),exp:S,nbf:D,resources:K},requester:{publicKey:R,metadata:this.client.metadata},expiryTimestamp:Ir(H)},B={eip155:{chains:u,methods:[...new Set(["personal_sign",...T])],events:["chainChanged","accountsChanged"]}},ee={requiredNamespaces:{},optionalNamespaces:B,relays:[{protocol:"irn"}],pairingTopic:F,proposer:{publicKey:R,metadata:this.client.metadata},expiryTimestamp:Ir(Lr.wc_sessionPropose.req.ttl)},{done:ie,resolve:L,reject:y}=Ho(H,"Request expired"),f=async({error:O,session:M})=>{if(this.events.off(Dt("session_request",v),d),O)y(O);else if(M){M.self.publicKey=R,await this.client.session.set(M.topic,M),await this.setExpiry(M.topic,M.expiry),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:M.peer.metadata});const g=this.client.session.get(M.topic);await this.deleteProposal(E),L({session:g})}},d=async O=>{var M,g,m;if(await this.deletePendingAuthRequest(v,{message:"fulfilled",code:0}),O.error){const G=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===G.code?void 0:(this.events.off(Dt("session_connect"),f),y(O.error.message))}await this.deleteProposal(E),this.events.off(Dt("session_connect"),f);const{cacaos:N,responder:X}=O.result,ae=[],P=[];for(const G of N){await sb({cacao:G,projectId:this.client.core.projectId})||(this.client.logger.error(G,"Signature verification failed"),y(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:J}=G,A=mh(J.resources),V=[nb(J.iss)],oe=vh(J.iss);if(A){const ue=cb(A),he=ub(A);ae.push(...ue),V.push(...he)}for(const ue of V)P.push(`${ue}:${oe}`)}const te=await this.client.core.crypto.generateSharedKey(R,X.publicKey);let z;ae.length>0&&(z={topic:te,acknowledged:!0,self:{publicKey:R,metadata:this.client.metadata},peer:X,controller:X.publicKey,expiry:Ir(lc),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:F,namespaces:Eb([...new Set(ae)],[...new Set(P)]),transportType:a},await this.client.core.relayer.subscribe(te,{transportType:a}),await this.client.session.set(te,z),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:X.metadata}),z=this.client.session.get(te)),(M=this.client.metadata.redirect)!=null&&M.linkMode&&(g=X.metadata.redirect)!=null&&g.linkMode&&(m=X.metadata.redirect)!=null&&m.universal&&i&&(this.client.core.addLinkModeSupportedApp(X.metadata.redirect.universal),this.client.session.update(te,{transportType:Zt.link_mode})),L({auths:N,session:z})},v=co(),E=co();this.events.once(Dt("session_connect"),f),this.events.once(Dt("session_request",v),d);let C;try{if(s){const O=uo("wc_sessionAuthenticate",_,v);this.client.core.history.set(F,O);const M=await this.client.core.crypto.encode("",O,{type:wu,encoding:bu});C=yh(i,F,M)}else await Promise.all([this.sendRequest({topic:F,method:"wc_sessionAuthenticate",params:_,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:v}),this.sendRequest({topic:F,method:"wc_sessionPropose",params:ee,expiry:Lr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E})])}catch(O){throw this.events.off(Dt("session_connect"),f),this.events.off(Dt("session_request",v),d),O}return await this.setProposal(E,pr({id:E},ee)),await this.setAuthRequest(v,{request:Mn(pr({},_),{verifyContext:{}}),pairingTopic:F,transportType:a}),{uri:C??W,response:ie}},this.approveSessionAuthenticate=async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Xo.authenticated_session_approve_started]}});try{this.isInitialized()}catch(q){throw s.setError(Lu.no_internet_connection),q}const a=this.getPendingAuthRequest(i);if(!a)throw s.setError(Lu.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const u=a.transportType||Zt.relay;u===Zt.relay&&await this.confirmOnlineStateOrThrow();const h=a.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),b=bh(h),w={type:Rs,receiverPublicKey:h,senderPublicKey:l},I=[],S=[];for(const q of n){if(!await sb({cacao:q,projectId:this.client.core.projectId})){s.setError(Lu.invalid_cacao);const k=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:b,error:k,encodeOpts:w}),new Error(k.message)}s.addTrace(Xo.cacaos_verified);const{p:K}=q,F=mh(K.resources),W=[nb(K.iss)],R=vh(K.iss);if(F){const k=cb(F),H=ub(F);I.push(...k),W.push(...H)}for(const k of W)S.push(`${k}:${R}`)}const D=await this.client.core.crypto.generateSharedKey(l,h);s.addTrace(Xo.create_authenticated_session_topic);let T;if(I?.length>0){T={topic:D,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:h,metadata:a.requester.metadata},controller:h,expiry:Ir(lc),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:a.pairingTopic,namespaces:Eb([...new Set(I)],[...new Set(S)]),transportType:u},s.addTrace(Xo.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(D,{transportType:u})}catch(q){throw s.setError(Lu.subscribe_authenticated_session_topic_failure),q}s.addTrace(Xo.subscribe_authenticated_session_topic_success),await this.client.session.set(D,T),s.addTrace(Xo.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:a.pairingTopic,metadata:a.requester.metadata})}s.addTrace(Xo.publishing_authenticated_session_approve);try{await this.sendResult({topic:b,id:i,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:w,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(a.requester.metadata,u)})}catch(q){throw s.setError(Lu.authenticated_session_approve_publish_failure),q}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:a.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:T}},this.rejectSessionAuthenticate=async r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===Zt.relay&&await this.confirmOnlineStateOrThrow();const a=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=bh(a),l={type:Rs,receiverPublicKey:a,senderPublicKey:u};await this.sendError({id:i,topic:h,error:n,encodeOpts:l,rpcOpts:Lr.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();const{request:i,iss:n}=r;return ob(i,n)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var a,u;return((a=s.peerMetadata)==null?void 0:a.url)&&((u=s.peerMetadata)==null?void 0:u.url)===r.peer.metadata.url&&s.topic&&s.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}},this.deleteSession=async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:a=!0,id:u=0}=r,{self:h}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,Gt("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(h.publicKey)&&await this.client.core.crypto.deleteKeyPair(h.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(V3).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===n&&this.deletePendingSessionRequest(l.id,Gt("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=ps.idle),a&&this.client.events.emit("session_delete",{id:u,topic:n})},this.deleteProposal=async(r,i)=>{if(i)try{const n=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s?.setError(Zo.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Gt("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=ps.idle,this.client.events.emit("session_request_expire",{id:r}))},this.deletePendingAuthRequest=async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))},this.setProposal=async(r,i)=>{this.client.core.expirer.set(r,Ir(Lr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)},this.setAuthRequest=async(r,i)=>{const{request:n,pairingTopic:s,transportType:a=Zt.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:a})},this.setPendingSessionRequest=async r=>{const{id:i,topic:n,params:s,verifyContext:a}=r,u=s.request.expiryTimestamp||Ir(Lr.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,u),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:a})},this.sendRequest=async r=>{const{topic:i,method:n,params:s,expiry:a,relayRpcId:u,clientRpcId:h,throwOnFailedPublish:l,appLink:b}=r,w=uo(n,s,h);let I;const S=!!b;try{const q=S?bu:ao;I=await this.client.core.crypto.encode(i,w,{encoding:q})}catch(q){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),q}let D;if(m$.includes(n)){const q=Ns(JSON.stringify(w)),K=Ns(I);D=await this.client.core.verify.register({id:K,decryptedId:q})}const T=Lr[n].req;if(T.attestation=D,a&&(T.ttl=a),u&&(T.id=u),this.client.core.history.set(i,w),S){const q=yh(b,i,I);await global.Linking.openURL(q,this.client.name)}else{const q=Lr[n].req;a&&(q.ttl=a),u&&(q.id=u),l?(q.internal=Mn(pr({},q.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,I,q)):this.client.core.relayer.publish(i,I,q).catch(K=>this.client.logger.error(K))}return w.id},this.sendResult=async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:a,encodeOpts:u,appLink:h}=r,l=Oh(i,s);let b;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const S=w?bu:ao;b=await this.client.core.crypto.encode(n,l,Mn(pr({},u||{}),{encoding:S}))}catch(S){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),S}let I;try{I=await this.client.core.history.get(n,i)}catch(S){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),S}if(w){const S=yh(h,n,b);await global.Linking.openURL(S,this.client.name)}else{const S=Lr[I.request.method].res;a?(S.internal=Mn(pr({},S.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,b,S)):this.client.core.relayer.publish(n,b,S).catch(D=>this.client.logger.error(D))}await this.client.core.history.resolve(l)},this.sendError=async r=>{const{id:i,topic:n,error:s,encodeOpts:a,rpcOpts:u,appLink:h}=r,l=Ph(i,s);let b;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const S=w?bu:ao;b=await this.client.core.crypto.encode(n,l,Mn(pr({},a||{}),{encoding:S}))}catch(S){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),S}let I;try{I=await this.client.core.history.get(n,i)}catch(S){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),S}if(w){const S=yh(h,n,b);await global.Linking.openURL(S,this.client.name)}else{const S=u||Lr[I.request.method].res;this.client.core.relayer.publish(n,b,S)}await this.client.core.history.resolve(l)},this.cleanup=async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;io(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{io(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===ps.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=ps.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=ps.idle},this.processRequest=async r=>{const{topic:i,payload:n,attestation:s,transportType:a,encryptedId:u}=r,h=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:h}))switch(h){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:u});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:u,transportType:a});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:u,transportType:a});default:return this.client.logger.info(`Unsupported request method ${h}`)}},this.onRelayEventResponse=async r=>{const{topic:i,payload:n,transportType:s}=r,a=(await this.client.core.history.get(i,n.id)).request.method;switch(a){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${a}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:i}=r,{message:n}=Ee("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)},this.shouldIgnorePairingRequest=r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async r=>{const{topic:i,payload:n,attestation:s,encryptedId:a}=r,{params:u,id:h}=n;try{const l=this.client.core.eventClient.getEvent({topic:i});this.isValidConnect(pr({},n.params));const b=u.expiryTimestamp||Ir(Lr.wc_sessionPropose.req.ttl),w=pr({id:h,pairingTopic:i,expiryTimestamp:b},u);await this.setProposal(h,w);const I=await this.getVerifyContext({attestationId:s,hash:Ns(JSON.stringify(n)),encryptedId:a,metadata:w.proposer.metadata});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(Bs.proposal_listener_not_found)),l?.addTrace(ds.emit_session_proposal),this.client.events.emit("session_proposal",{id:h,params:w,verifyContext:I})}catch(l){await this.sendError({id:h,topic:i,error:l,rpcOpts:Lr.wc_sessionPropose.autoReject}),this.client.logger.error(l)}},this.onSessionProposeResponse=async(r,i,n)=>{const{id:s}=i;if(fs(i)){const{result:a}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:a});const u=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:u});const h=u.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:h});const l=a.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const b=await this.client.core.crypto.generateSharedKey(h,l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:b});const w=await this.client.core.relayer.subscribe(b,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:r})}else if(rn(i)){await this.client.proposal.delete(s,Gt("USER_DISCONNECTED"));const a=Dt("session_connect");if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners, 954`);this.events.emit(Dt("session_connect"),{error:i.error})}},this.onSessionSettleRequest=async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:a,controller:u,expiry:h,namespaces:l,sessionProperties:b,sessionConfig:w}=i.params,I=Mn(pr(pr({topic:r,relay:a,expiry:h,namespaces:l,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},b&&{sessionProperties:b}),w&&{sessionConfig:w}),{transportType:Zt.relay}),S=Dt("session_connect");if(this.events.listenerCount(S)===0)throw new Error(`emitting ${S} without any listeners 997`);this.events.emit(Dt("session_connect"),{session:I}),await this.sendResult({id:i.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(a){await this.sendError({id:n,topic:r,error:a}),this.client.logger.error(a)}},this.onSessionSettleResponse=async(r,i)=>{const{id:n}=i;fs(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Dt("session_approve",n),{})):rn(i)&&(await this.client.session.delete(r,Gt("USER_DISCONNECTED")),this.events.emit(Dt("session_approve",n),{error:i.error}))},this.onSessionUpdateRequest=async(r,i)=>{const{params:n,id:s}=i;try{const a=`${r}_session_update`,u=Iu.get(a);if(u&&this.isRequestOutOfSync(u,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Gt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(pr({topic:r},n));try{Iu.set(a,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(h){throw Iu.delete(a),h}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(a){await this.sendError({id:s,topic:r,error:a}),this.client.logger.error(a)}},this.isRequestOutOfSync=(r,i)=>parseInt(i.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,i)=>{const{id:n}=i,s=Dt("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_update",n),{}):rn(i)&&this.events.emit(Dt("session_update",n),{error:i.error})},this.onSessionExtendRequest=async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Ir(lc)),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,i)=>{const{id:n}=i,s=Dt("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_extend",n),{}):rn(i)&&this.events.emit(Dt("session_extend",n),{error:i.error})},this.onSessionPingRequest=async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,i)=>{const{id:n}=i,s=Dt("session_ping",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{fs(i)?this.events.emit(Dt("session_ping",n),{}):rn(i)&&this.events.emit(Dt("session_ping",n),{error:i.error})},500)},this.onSessionDeleteRequest=async(r,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:r,reason:i.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(hi.publish,async()=>{s(await this.deleteSession({topic:r,id:n}))})}),this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Gt("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async r=>{var i,n,s;const{topic:a,payload:u,attestation:h,encryptedId:l,transportType:b}=r,{id:w,params:I}=u;try{await this.isValidRequest(pr({topic:a},I));const S=this.client.session.get(a),D=await this.getVerifyContext({attestationId:h,hash:Ns(JSON.stringify(uo("wc_sessionRequest",I,w))),encryptedId:l,metadata:S.peer.metadata,transportType:b}),T={id:w,topic:a,params:I,verifyContext:D};await this.setPendingSessionRequest(T),b===Zt.link_mode&&(i=S.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=S.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(T):(this.addSessionRequestToSessionRequestQueue(T),this.processSessionRequestQueue())}catch(S){await this.sendError({id:w,topic:a,error:S}),this.client.logger.error(S)}},this.onSessionRequestResponse=(r,i)=>{const{id:n}=i,s=Dt("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):rn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionEventRequest=async(r,i)=>{const{id:n,params:s}=i;try{const a=`${r}_session_event_${s.event.name}`,u=Iu.get(a);if(u&&this.isRequestOutOfSync(u,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(pr({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Iu.set(a,n)}catch(a){await this.sendError({id:n,topic:r,error:a}),this.client.logger.error(a)}},this.onSessionAuthenticateResponse=(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),fs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):rn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionAuthenticateRequest=async r=>{var i;const{topic:n,payload:s,attestation:a,encryptedId:u,transportType:h}=r;try{const{requester:l,authPayload:b,expiryTimestamp:w}=s.params,I=await this.getVerifyContext({attestationId:a,hash:Ns(JSON.stringify(s)),encryptedId:u,metadata:l.metadata,transportType:h}),S={requester:l,pairingTopic:n,id:s.id,authPayload:b,verifyContext:I,expiryTimestamp:w};await this.setAuthRequest(s.id,{request:S,pairingTopic:n,transportType:h}),h===Zt.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:I})}catch(l){this.client.logger.error(l);const b=s.params.requester.publicKey,w=await this.client.core.crypto.generateKeyPair(),I=this.getAppLinkIfEnabled(s.params.requester.metadata,h),S={type:Rs,receiverPublicKey:b,senderPublicKey:w};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:S,rpcOpts:Lr.wc_sessionAuthenticate.autoReject,appLink:I})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ps.idle,this.processSessionRequestQueue()},xe.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const a=s.request.id,u=Dt("session_request",a);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(Dt("session_request",s.request.id),{error:i})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===ps.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=ps.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}},this.emitSessionRequest=r=>{this.client.events.emit("session_request",r)},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:uo("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})},this.isValidConnect=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(h)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:a,relays:u}=r;if(ci(i)||await this.isValidPairingTopic(i),!WI(u,!0)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(h)}!ci(n)&&Su(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!ci(s)&&Su(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ci(a)||this.validateSessionProps(a,"sessionProperties")},this.validateNamespaces=(r,i)=>{const n=KI(r,"connect()",i);if(n)throw new Error(n.message)},this.isValidApprove=async r=>{if(!_i(r))throw new Error(Ee("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const u=this.client.proposal.get(i),h=Fd(n,"approve()");if(h)throw new Error(h.message);const l=Mb(u.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!yr(s,!0)){const{message:b}=Ee("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(b)}ci(a)||this.validateSessionProps(a,"sessionProperties")},this.isValidReject=async r=>{if(!_i(r)){const{message:s}=Ee("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!GI(n)){const{message:s}=Ee("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!_i(r)){const{message:l}=Ee("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:a}=r;if(!Sb(i)){const{message:l}=Ee("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const u=UI(n,"onSessionSettleRequest()");if(u)throw new Error(u.message);const h=Fd(s,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(io(a)){const{message:l}=Ee("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(h)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),a=Fd(n,"update()");if(a)throw new Error(a.message);const u=Mb(s.requiredNamespaces,n,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)},this.isValidRequest=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(h)}const{topic:i,request:n,chainId:s,expiry:a}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:u}=this.client.session.get(i);if(!Ib(u,s)){const{message:h}=Ee("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(h)}if(!JI(n)){const{message:h}=Ee("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(h)}if(!ZI(u,s,n.method)){const{message:h}=Ee("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(h)}if(a&&!rM(a,u1)){const{message:h}=Ee("MISSING_OR_INVALID",`request() expiry: ${a}. Expiry must be a number (in seconds) between ${u1.min} and ${u1.max}`);throw new Error(h)}},this.isValidRespond=async r=>{var i;if(!_i(r)){const{message:a}=Ee("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(a){throw(i=r?.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!YI(s)){const{message:a}=Ee("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidPing=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)},this.isValidEmit=async r=>{if(!_i(r)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(u)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!Ib(a,s)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!QI(n)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(u)}if(!XI(a,s,n.name)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(u)}},this.isValidDisconnect=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)},this.isValidAuthenticate=r=>{const{chains:i,uri:n,domain:s,nonce:a}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!yr(n,!1))throw new Error("uri is required parameter");if(!yr(s,!1))throw new Error("domain is required parameter");if(!yr(a,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(h=>ou(h).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:u}=ou(i[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:a,transportType:u}=r,h={verified:{verifyUrl:a.verifyUrl||Tu,validation:"UNKNOWN",origin:a.url||""}};try{if(u===Zt.link_mode){const b=this.getAppLinkIfEnabled(a,u);return h.verified.validation=b&&new URL(b).origin===new URL(a.url).origin?"VALID":"INVALID",h}const l=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:a.verifyUrl});l&&(h.verified.origin=l.origin,h.verified.isScam=l.isScam,h.verified.validation=l.origin===new URL(a.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(h)}`),h},this.validateSessionProps=(r,i)=>{Object.values(r).forEach(n=>{if(!yr(n,!1)){const{message:s}=Ee("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(n)}`);throw new Error(s)}})},this.getPendingAuthRequest=r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0},this.addToRecentlyDeleted=(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const a of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(a)}}},this.checkRecentlyDeleted=r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=Ee("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}},this.isLinkModeEnabled=(r,i)=>{var n,s,a,u,h,l,b,w,I;return!r||i!==Zt.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((u=(a=this.client.metadata)==null?void 0:a.redirect)==null?void 0:u.universal)!==void 0&&((l=(h=this.client.metadata)==null?void 0:h.redirect)==null?void 0:l.universal)!==""&&((b=r?.redirect)==null?void 0:b.universal)!==void 0&&((w=r?.redirect)==null?void 0:w.universal)!==""&&((I=r?.redirect)==null?void 0:I.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"},this.getAppLinkIfEnabled=(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r?.redirect)==null?void 0:n.universal:void 0},this.handleLinkModeMessage=({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Y2(r,"topic")||"",n=decodeURIComponent(Y2(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:Zt.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})},this.registerLinkModeListeners=async()=>{var r;if(ad()||Va()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(hi.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:n,transportType:s}=e,{publicKey:a}=this.client.auth.authKeys.keys.includes(Th)?this.client.auth.authKeys.get(Th):{responseTopic:void 0,publicKey:void 0},u=await this.client.core.crypto.decode(r,i,{receiverPublicKey:a,encoding:s===Zt.link_mode?bu:ao});try{Zd(u)?(this.client.core.history.set(r,u),this.onRelayEventRequest({topic:r,payload:u,attestation:n,transportType:s,encryptedId:Ns(i)})):$h(u)?(await this.client.core.history.resolve(u),await this.onRelayEventResponse({topic:r,payload:u,transportType:s}),this.client.core.history.delete(r,u.id)):this.onRelayEventUnknownPayload({topic:r,payload:u,transportType:s})}catch(h){this.client.logger.error(h)}}registerExpirerEvents(){this.client.core.expirer.on(sn.expired,async e=>{const{topic:r,id:i}=J2(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,Ee("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,Ee("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(fc.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(fc.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!yr(e,!1)){const{message:r}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=Ee("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!yr(e,!1)){const{message:r}=Ee("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=Ee("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=Ee("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(yr(e,!1)){const{message:r}=Ee("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=Ee("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!VI(e)){const{message:r}=Ee("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=Ee("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class D$ extends ea{constructor(e,r){super(e,r,d$,a1),this.core=e,this.logger=r}}class O$ extends ea{constructor(e,r){super(e,r,p$,a1),this.core=e,this.logger=r}}class P$ extends ea{constructor(e,r){super(e,r,v$,a1,i=>i.id),this.core=e,this.logger=r}}class $$ extends ea{constructor(e,r){super(e,r,w$,Nh,()=>Th),this.core=e,this.logger=r}}class R$ extends ea{constructor(e,r){super(e,r,_$,Nh),this.core=e,this.logger=r}}class N$ extends ea{constructor(e,r){super(e,r,E$,Nh,i=>i.id),this.core=e,this.logger=r}}class T${constructor(e,r){this.core=e,this.logger=r,this.authKeys=new $$(this.core,this.logger),this.pairingTopics=new R$(this.core,this.logger),this.requests=new N$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class f1 extends SC{constructor(e){super(e),this.protocol=H3,this.version=K3,this.name=c1.name,this.events=new kr.exports.EventEmitter,this.on=(i,n)=>this.events.on(i,n),this.once=(i,n)=>this.events.once(i,n),this.off=(i,n)=>this.events.off(i,n),this.removeListener=(i,n)=>this.events.removeListener(i,n),this.removeAllListeners=i=>this.events.removeAllListeners(i),this.connect=async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}},this.pair=async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}},this.approve=async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}},this.reject=async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}},this.update=async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}},this.extend=async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}},this.request=async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}},this.respond=async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}},this.ping=async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}},this.emit=async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}},this.disconnect=async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}},this.find=i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}},this.authenticate=async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}},this.formatAuthMessage=i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}},this.approveSessionAuthenticate=async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.rejectSessionAuthenticate=async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||c1.name,this.metadata=e?.metadata||H2(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:cs(Dh({level:e?.logger||c1.logger}));this.core=e?.core||new l$(e),this.logger=ui(r,this.name),this.session=new O$(this.core,this.logger),this.proposal=new D$(this.core,this.logger),this.pendingRequest=new P$(this.core,this.logger),this.engine=new C$(this),this.auth=new T$(this.core,this.logger)}static async init(e){const r=new f1(e);return await r.initialize(),r}get context(){return Ai(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(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var h1={exports:{}};(function(t,e){var r=typeof self<"u"?self:Vr,i=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(a){var u={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function h(d){return d&&DataView.prototype.isPrototypeOf(d)}if(u.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],b=ArrayBuffer.isView||function(d){return d&&l.indexOf(Object.prototype.toString.call(d))>-1};function w(d){if(typeof d!="string"&&(d=String(d)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(d))throw new TypeError("Invalid character in header field name");return d.toLowerCase()}function I(d){return typeof d!="string"&&(d=String(d)),d}function S(d){var v={next:function(){var E=d.shift();return{done:E===void 0,value:E}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function D(d){this.map={},d instanceof D?d.forEach(function(v,E){this.append(E,v)},this):Array.isArray(d)?d.forEach(function(v){this.append(v[0],v[1])},this):d&&Object.getOwnPropertyNames(d).forEach(function(v){this.append(v,d[v])},this)}D.prototype.append=function(d,v){d=w(d),v=I(v);var E=this.map[d];this.map[d]=E?E+", "+v:v},D.prototype.delete=function(d){delete this.map[w(d)]},D.prototype.get=function(d){return d=w(d),this.has(d)?this.map[d]:null},D.prototype.has=function(d){return this.map.hasOwnProperty(w(d))},D.prototype.set=function(d,v){this.map[w(d)]=I(v)},D.prototype.forEach=function(d,v){for(var E in this.map)this.map.hasOwnProperty(E)&&d.call(v,this.map[E],E,this)},D.prototype.keys=function(){var d=[];return this.forEach(function(v,E){d.push(E)}),S(d)},D.prototype.values=function(){var d=[];return this.forEach(function(v){d.push(v)}),S(d)},D.prototype.entries=function(){var d=[];return this.forEach(function(v,E){d.push([E,v])}),S(d)},u.iterable&&(D.prototype[Symbol.iterator]=D.prototype.entries);function T(d){if(d.bodyUsed)return Promise.reject(new TypeError("Already read"));d.bodyUsed=!0}function q(d){return new Promise(function(v,E){d.onload=function(){v(d.result)},d.onerror=function(){E(d.error)}})}function K(d){var v=new FileReader,E=q(v);return v.readAsArrayBuffer(d),E}function F(d){var v=new FileReader,E=q(v);return v.readAsText(d),E}function W(d){for(var v=new Uint8Array(d),E=new Array(v.length),C=0;C<v.length;C++)E[C]=String.fromCharCode(v[C]);return E.join("")}function R(d){if(d.slice)return d.slice(0);var v=new Uint8Array(d.byteLength);return v.set(new Uint8Array(d)),v.buffer}function k(){return this.bodyUsed=!1,this._initBody=function(d){this._bodyInit=d,d?typeof d=="string"?this._bodyText=d:u.blob&&Blob.prototype.isPrototypeOf(d)?this._bodyBlob=d:u.formData&&FormData.prototype.isPrototypeOf(d)?this._bodyFormData=d:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(d)?this._bodyText=d.toString():u.arrayBuffer&&u.blob&&h(d)?(this._bodyArrayBuffer=R(d.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(d)||b(d))?this._bodyArrayBuffer=R(d):this._bodyText=d=Object.prototype.toString.call(d):this._bodyText="",this.headers.get("content-type")||(typeof d=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(d)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var d=T(this);if(d)return d;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?T(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(K)}),this.text=function(){var d=T(this);if(d)return d;if(this._bodyBlob)return F(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(W(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(ee)}),this.json=function(){return this.text().then(JSON.parse)},this}var H=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function _(d){var v=d.toUpperCase();return H.indexOf(v)>-1?v:d}function B(d,v){v=v||{};var E=v.body;if(d instanceof B){if(d.bodyUsed)throw new TypeError("Already read");this.url=d.url,this.credentials=d.credentials,v.headers||(this.headers=new D(d.headers)),this.method=d.method,this.mode=d.mode,this.signal=d.signal,!E&&d._bodyInit!=null&&(E=d._bodyInit,d.bodyUsed=!0)}else this.url=String(d);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new D(v.headers)),this.method=_(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}B.prototype.clone=function(){return new B(this,{body:this._bodyInit})};function ee(d){var v=new FormData;return d.trim().split("&").forEach(function(E){if(E){var C=E.split("="),O=C.shift().replace(/\+/g," "),M=C.join("=").replace(/\+/g," ");v.append(decodeURIComponent(O),decodeURIComponent(M))}}),v}function ie(d){var v=new D,E=d.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var O=C.split(":"),M=O.shift().trim();if(M){var g=O.join(":").trim();v.append(M,g)}}),v}k.call(B.prototype);function L(d,v){v||(v={}),this.type="default",this.status=v.status===void 0?200:v.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in v?v.statusText:"OK",this.headers=new D(v.headers),this.url=v.url||"",this._initBody(d)}k.call(L.prototype),L.prototype.clone=function(){return new L(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new D(this.headers),url:this.url})},L.error=function(){var d=new L(null,{status:0,statusText:""});return d.type="error",d};var y=[301,302,303,307,308];L.redirect=function(d,v){if(y.indexOf(v)===-1)throw new RangeError("Invalid status code");return new L(null,{status:v,headers:{location:d}})},a.DOMException=s.DOMException;try{new a.DOMException}catch{a.DOMException=function(v,E){this.message=v,this.name=E;var C=Error(v);this.stack=C.stack},a.DOMException.prototype=Object.create(Error.prototype),a.DOMException.prototype.constructor=a.DOMException}function f(d,v){return new Promise(function(E,C){var O=new B(d,v);if(O.signal&&O.signal.aborted)return C(new a.DOMException("Aborted","AbortError"));var M=new XMLHttpRequest;function g(){M.abort()}M.onload=function(){var m={status:M.status,statusText:M.statusText,headers:ie(M.getAllResponseHeaders()||"")};m.url="responseURL"in M?M.responseURL:m.headers.get("X-Request-URL");var N="response"in M?M.response:M.responseText;E(new L(N,m))},M.onerror=function(){C(new TypeError("Network request failed"))},M.ontimeout=function(){C(new TypeError("Network request failed"))},M.onabort=function(){C(new a.DOMException("Aborted","AbortError"))},M.open(O.method,O.url,!0),O.credentials==="include"?M.withCredentials=!0:O.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&u.blob&&(M.responseType="blob"),O.headers.forEach(function(m,N){M.setRequestHeader(N,m)}),O.signal&&(O.signal.addEventListener("abort",g),M.onreadystatechange=function(){M.readyState===4&&O.signal.removeEventListener("abort",g)}),M.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return f.polyfill=!0,s.fetch||(s.fetch=f,s.Headers=D,s.Request=B,s.Response=L),a.Headers=D,a.Request=B,a.Response=L,a.fetch=f,Object.defineProperty(a,"__esModule",{value:!0}),a})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=i;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,t.exports=e})(h1,h1.exports);var Q3=V5(h1.exports),L$=Object.defineProperty,B$=Object.defineProperties,F$=Object.getOwnPropertyDescriptors,Z3=Object.getOwnPropertySymbols,U$=Object.prototype.hasOwnProperty,k$=Object.prototype.propertyIsEnumerable,X3=(t,e,r)=>e in t?L$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,e6=(t,e)=>{for(var r in e||(e={}))U$.call(e,r)&&X3(t,r,e[r]);if(Z3)for(var r of Z3(e))k$.call(e,r)&&X3(t,r,e[r]);return t},t6=(t,e)=>B$(t,F$(e));const q$={Accept:"application/json","Content-Type":"application/json"},j$="POST",r6={headers:q$,method:j$},i6=10;class gs{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new kr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!t3(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=Cs(e),i=await(await Q3(this.url,t6(e6({},r6),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!t3(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=Cs({id:1,jsonrpc:"2.0",method:"test",params:[]});await Q3(e,t6(e6({},r6),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?jo(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Ph(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Jb(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>i6&&this.events.setMaxListeners(i6)}}const n6="error",z$="wss://relay.walletconnect.com",H$="wc",K$="universal_provider",s6=`${H$}@2:${K$}:`,o6="https://rpc.walletconnect.com/v1/",dc="generic",W$=`${o6}bundler`,Cn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Uu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},l1={exports:{}};/**
|
|
43
|
+
***************************************************************************** */var Jd=function(t,e){return Jd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},Jd(t,e)};function BC(t,e){Jd(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Yd=function(){return Yd=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Yd.apply(this,arguments)};function FC(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function UC(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var u=t.length-1;u>=0;u--)(a=t[u])&&(s=(n<3?a(s):n>3?a(e,r,s):a(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function kC(t,e){return function(r,i){e(r,i,t)}}function qC(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function jC(t,e,r,i){function n(s){return s instanceof r?s:new r(function(a){a(s)})}return new(r||(r=Promise))(function(s,a){function u(b){try{l(i.next(b))}catch(w){a(w)}}function h(b){try{l(i.throw(b))}catch(w){a(w)}}function l(b){b.done?s(b.value):n(b.value).then(u,h)}l((i=i.apply(t,e||[])).next())})}function zC(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,a;return a={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function u(l){return function(b){return h([l,b])}}function h(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=l[0]&2?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,n=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(b){l=[6,b],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function HC(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function KC(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Qd(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Qb(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],a;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(u){a={error:u}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(a)throw a.error}}return s}function WC(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Qb(arguments[e]));return t}function VC(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],a=0,u=s.length;a<u;a++,n++)i[n]=s[a];return i}function $u(t){return this instanceof $u?(this.v=t,this):new $u(t)}function GC(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},a("next"),a("throw"),a("return"),n[Symbol.asyncIterator]=function(){return this},n;function a(I){i[I]&&(n[I]=function(S){return new Promise(function(D,T){s.push([I,S,D,T])>1||u(I,S)})})}function u(I,S){try{h(i[I](S))}catch(D){w(s[0][3],D)}}function h(I){I.value instanceof $u?Promise.resolve(I.value.v).then(l,b):w(s[0][2],I)}function l(I){u("next",I)}function b(I){u("throw",I)}function w(I,S){I(S),s.shift(),s.length&&u(s[0][0],s[0][1])}}function JC(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(a){return(r=!r)?{value:$u(t[n](a)),done:n==="return"}:s?s(a):a}:s}}function YC(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Qd=="function"?Qd(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[s]=t[s]&&function(a){return new Promise(function(u,h){a=t[s](a),n(u,h,a.done,a.value)})}}function n(s,a,u,h){Promise.resolve(h).then(function(l){s({value:l,done:u})},a)}}function QC(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ZC(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function XC(t){return t&&t.__esModule?t:{default:t}}function eD(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function tD(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var rD=Object.freeze({__proto__:null,__extends:BC,get __assign(){return Yd},__rest:FC,__decorate:UC,__param:kC,__metadata:qC,__awaiter:jC,__generator:zC,__createBinding:HC,__exportStar:KC,__values:Qd,__read:Qb,__spread:WC,__spreadArrays:VC,__await:$u,__asyncGenerator:GC,__asyncDelegator:JC,__asyncValues:YC,__makeTemplateObject:QC,__importStar:ZC,__importDefault:XC,__classPrivateFieldGet:eD,__classPrivateFieldSet:tD}),iD=m0(rD),Ts={},Zb;function nD(){if(Zb)return Ts;Zb=1,Object.defineProperty(Ts,"__esModule",{value:!0}),Ts.isBrowserCryptoAvailable=Ts.getSubtleCrypto=Ts.getBrowerCrypto=void 0;function t(){return Vr?.crypto||Vr?.msCrypto||{}}Ts.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Ts.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Ts.isBrowserCryptoAvailable=r,Ts}var Ls={},Xb;function sD(){if(Xb)return Ls;Xb=1,Object.defineProperty(Ls,"__esModule",{value:!0}),Ls.isBrowser=Ls.isNode=Ls.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ls.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Ls.isNode=e;function r(){return!t()&&!e()}return Ls.isBrowser=r,Ls}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=iD;e.__exportStar(nD(),t),e.__exportStar(sD(),t)})(Yb);function co(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Qo(t=6){return BigInt(co(t))}function uo(t,e,r){return{id:r||co(),jsonrpc:"2.0",method:t,params:e}}function Oh(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Ph(t,e,r){return{id:t,jsonrpc:"2.0",error:oD(e,r)}}function oD(t,e){return typeof t>"u"?Gb(Wb):(typeof t=="string"&&(t=Object.assign(Object.assign({},Gb(Gd)),{message:t})),typeof e<"u"&&(t.data=e),TC(t.code)&&(t=LC(t.code)),t)}class aD{}class cD extends aD{constructor(){super()}}class uD extends cD{constructor(e){super()}}const fD="^https?:",hD="^wss?:";function lD(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function e3(t,e){const r=lD(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function t3(t){return e3(t,fD)}function r3(t){return e3(t,hD)}function dD(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function i3(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Zd(t){return i3(t)&&"method"in t}function $h(t){return i3(t)&&(fs(t)||rn(t))}function fs(t){return"result"in t}function rn(t){return"error"in t}class xn extends uD{constructor(e){super(e),this.events=new kr.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(uo(e.method,e.params||[],e.id||Qo().toString()),r)}async requestStrict(e,r){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{rn(s)?n(s.error):i(s.result)});try{await this.connection.send(e,r)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),$h(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const pD=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),gD=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",n3=t=>t.split("?")[0],s3=10,vD=pD();class mD{constructor(e){if(this.url=e,this.events=new kr.exports.EventEmitter,this.registering=!1,!r3(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Cs(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!r3(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const n=new URLSearchParams(e).get("origin"),s=Yb.isReactNative()?{headers:{origin:n}}:{rejectUnauthorized:!dD(e)},a=new vD(e,[],s);gD()?a.onerror=u=>{const h=u;i(this.emitError(h.error))}:a.on("error",u=>{i(this.emitError(u))}),a.onopen=()=>{this.onOpen(a),r(a)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?jo(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Ph(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Jb(e,n3(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>s3&&this.events.setMaxListeners(s3)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${n3(this.url)}`));return this.events.emit("register_error",r),r}}var Xd={exports:{}};(function(t,e){var r=200,i="__lodash_hash_undefined__",n=1,s=2,a=9007199254740991,u="[object Arguments]",h="[object Array]",l="[object AsyncFunction]",b="[object Boolean]",w="[object Date]",I="[object Error]",S="[object Function]",D="[object GeneratorFunction]",T="[object Map]",q="[object Number]",K="[object Null]",F="[object Object]",W="[object Promise]",R="[object Proxy]",k="[object RegExp]",H="[object Set]",_="[object String]",B="[object Symbol]",ee="[object Undefined]",ie="[object WeakMap]",L="[object ArrayBuffer]",y="[object DataView]",f="[object Float32Array]",d="[object Float64Array]",v="[object Int8Array]",E="[object Int16Array]",C="[object Int32Array]",O="[object Uint8Array]",M="[object Uint8ClampedArray]",g="[object Uint16Array]",m="[object Uint32Array]",N=/[\\^$.*+?()[\]{}|]/g,X=/^\[object .+?Constructor\]$/,ae=/^(?:0|[1-9]\d*)$/,P={};P[f]=P[d]=P[v]=P[E]=P[C]=P[O]=P[M]=P[g]=P[m]=!0,P[u]=P[h]=P[L]=P[b]=P[y]=P[w]=P[I]=P[S]=P[T]=P[q]=P[F]=P[k]=P[H]=P[_]=P[ie]=!1;var te=typeof Vr=="object"&&Vr&&Vr.Object===Object&&Vr,z=typeof self=="object"&&self&&self.Object===Object&&self,G=te||z||Function("return this")(),J=e&&!e.nodeType&&e,A=J&&!0&&t&&!t.nodeType&&t,V=A&&A.exports===J,oe=V&&te.process,ue=function(){try{return oe&&oe.binding&&oe.binding("util")}catch{}}(),he=ue&&ue.isTypedArray;function ye(Y,re){for(var pe=-1,ke=Y==null?0:Y.length,er=0,bt=[];++pe<ke;){var ar=Y[pe];re(ar,pe,Y)&&(bt[er++]=ar)}return bt}function we(Y,re){for(var pe=-1,ke=re.length,er=Y.length;++pe<ke;)Y[er+pe]=re[pe];return Y}function Re(Y,re){for(var pe=-1,ke=Y==null?0:Y.length;++pe<ke;)if(re(Y[pe],pe,Y))return!0;return!1}function Xe(Y,re){for(var pe=-1,ke=Array(Y);++pe<Y;)ke[pe]=re(pe);return ke}function Oe(Y){return function(re){return Y(re)}}function Ne(Y,re){return Y.has(re)}function Me(Y,re){return Y?.[re]}function be(Y){var re=-1,pe=Array(Y.size);return Y.forEach(function(ke,er){pe[++re]=[er,ke]}),pe}function Pe(Y,re){return function(pe){return Y(re(pe))}}function Te(Y){var re=-1,pe=Array(Y.size);return Y.forEach(function(ke){pe[++re]=ke}),pe}var ve=Array.prototype,$e=Function.prototype,Se=Object.prototype,me=G["__core-js_shared__"],Ue=$e.toString,Ce=Se.hasOwnProperty,_e=function(){var Y=/[^.]+$/.exec(me&&me.keys&&me.keys.IE_PROTO||"");return Y?"Symbol(src)_1."+Y:""}(),Ke=Se.toString,Ve=RegExp("^"+Ue.call(Ce).replace(N,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ae=V?G.Buffer:void 0,We=G.Symbol,pt=G.Uint8Array,Ge=Se.propertyIsEnumerable,It=ve.splice,gt=We?We.toStringTag:void 0,Ye=Object.getOwnPropertySymbols,Ot=Ae?Ae.isBuffer:void 0,Tt=Pe(Object.keys,Object),Le=ji(G,"DataView"),et=ji(G,"Map"),it=ji(G,"Promise"),Be=ji(G,"Set"),rt=ji(G,"WeakMap"),tt=ji(Object,"create"),qe=qs(Le),ht=qs(et),nt=qs(it),je=qs(Be),st=qs(rt),at=We?We.prototype:void 0,Fe=at?at.valueOf:void 0;function Ze(Y){var re=-1,pe=Y==null?0:Y.length;for(this.clear();++re<pe;){var ke=Y[re];this.set(ke[0],ke[1])}}function lt(){this.__data__=tt?tt(null):{},this.size=0}function ze(Y){var re=this.has(Y)&&delete this.__data__[Y];return this.size-=re?1:0,re}function qt(Y){var re=this.__data__;if(tt){var pe=re[Y];return pe===i?void 0:pe}return Ce.call(re,Y)?re[Y]:void 0}function jt(Y){var re=this.__data__;return tt?re[Y]!==void 0:Ce.call(re,Y)}function ct(Y,re){var pe=this.__data__;return this.size+=this.has(Y)?0:1,pe[Y]=tt&&re===void 0?i:re,this}Ze.prototype.clear=lt,Ze.prototype.delete=ze,Ze.prototype.get=qt,Ze.prototype.has=jt,Ze.prototype.set=ct;function _t(Y){var re=-1,pe=Y==null?0:Y.length;for(this.clear();++re<pe;){var ke=Y[re];this.set(ke[0],ke[1])}}function Zr(){this.__data__=[],this.size=0}function Xr(Y){var re=this.__data__,pe=ma(re,Y);if(pe<0)return!1;var ke=re.length-1;return pe==ke?re.pop():It.call(re,pe,1),--this.size,!0}function ei(Y){var re=this.__data__,pe=ma(re,Y);return pe<0?void 0:re[pe][1]}function ti(Y){return ma(this.__data__,Y)>-1}function ri(Y,re){var pe=this.__data__,ke=ma(pe,Y);return ke<0?(++this.size,pe.push([Y,re])):pe[ke][1]=re,this}_t.prototype.clear=Zr,_t.prototype.delete=Xr,_t.prototype.get=ei,_t.prototype.has=ti,_t.prototype.set=ri;function vr(Y){var re=-1,pe=Y==null?0:Y.length;for(this.clear();++re<pe;){var ke=Y[re];this.set(ke[0],ke[1])}}function Ii(){this.size=0,this.__data__={hash:new Ze,map:new(et||_t),string:new Ze}}function On(Y){var re=Ao(this,Y).delete(Y);return this.size-=re?1:0,re}function Mi(Y){return Ao(this,Y).get(Y)}function Pn(Y){return Ao(this,Y).has(Y)}function $n(Y,re){var pe=Ao(this,Y),ke=pe.size;return pe.set(Y,re),this.size+=pe.size==ke?0:1,this}vr.prototype.clear=Ii,vr.prototype.delete=On,vr.prototype.get=Mi,vr.prototype.has=Pn,vr.prototype.set=$n;function Ci(Y){var re=-1,pe=Y==null?0:Y.length;for(this.__data__=new vr;++re<pe;)this.add(Y[re])}function an(Y){return this.__data__.set(Y,i),this}function cn(Y){return this.__data__.has(Y)}Ci.prototype.add=Ci.prototype.push=an,Ci.prototype.has=cn;function Cr(Y){var re=this.__data__=new _t(Y);this.size=re.size}function Rn(){this.__data__=new _t,this.size=0}function Nn(Y){var re=this.__data__,pe=re.delete(Y);return this.size=re.size,pe}function Tn(Y){return this.__data__.get(Y)}function va(Y){return this.__data__.has(Y)}function gl(Y,re){var pe=this.__data__;if(pe instanceof _t){var ke=pe.__data__;if(!et||ke.length<r-1)return ke.push([Y,re]),this.size=++pe.size,this;pe=this.__data__=new vr(ke)}return pe.set(Y,re),this.size=pe.size,this}Cr.prototype.clear=Rn,Cr.prototype.delete=Nn,Cr.prototype.get=Tn,Cr.prototype.has=va,Cr.prototype.set=gl;function vl(Y,re){var pe=Nc(Y),ke=!pe&&Cl(Y),er=!pe&&!ke&&cf(Y),bt=!pe&&!ke&&!er&&Pl(Y),ar=pe||ke||er||bt,xr=ar?Xe(Y.length,String):[],Ft=xr.length;for(var tr in Y)(re||Ce.call(Y,tr))&&!(ar&&(tr=="length"||er&&(tr=="offset"||tr=="parent")||bt&&(tr=="buffer"||tr=="byteLength"||tr=="byteOffset")||Al(tr,Ft)))&&xr.push(tr);return xr}function ma(Y,re){for(var pe=Y.length;pe--;)if(Ml(Y[pe][0],re))return pe;return-1}function of(Y,re,pe){var ke=re(Y);return Nc(Y)?ke:we(ke,pe(Y))}function ba(Y){return Y==null?Y===void 0?ee:K:gt&> in Object(Y)?_l(Y):Op(Y)}function af(Y){return wa(Y)&&ba(Y)==u}function ya(Y,re,pe,ke,er){return Y===re?!0:Y==null||re==null||!wa(Y)&&!wa(re)?Y!==Y&&re!==re:ml(Y,re,pe,ke,ya,er)}function ml(Y,re,pe,ke,er,bt){var ar=Nc(Y),xr=Nc(re),Ft=ar?h:ws(Y),tr=xr?h:ws(re);Ft=Ft==u?F:Ft,tr=tr==u?F:tr;var _r=Ft==F,Di=tr==F,Sr=Ft==tr;if(Sr&&cf(Y)){if(!cf(re))return!1;ar=!0,_r=!1}if(Sr&&!_r)return bt||(bt=new Cr),ar||Pl(Y)?$c(Y,re,pe,ke,er,bt):Dp(Y,re,Ft,pe,ke,er,bt);if(!(pe&n)){var cr=_r&&Ce.call(Y,"__wrapped__"),di=Di&&Ce.call(re,"__wrapped__");if(cr||di){var Ln=cr?Y.value():Y,un=di?re.value():re;return bt||(bt=new Cr),er(Ln,un,pe,ke,bt)}}return Sr?(bt||(bt=new Cr),wl(Y,re,pe,ke,er,bt)):!1}function Cp(Y){if(!Ol(Y)||Sl(Y))return!1;var re=Tc(Y)?Ve:X;return re.test(qs(Y))}function bl(Y){return wa(Y)&&Dl(Y.length)&&!!P[ba(Y)]}function yl(Y){if(!Il(Y))return Tt(Y);var re=[];for(var pe in Object(Y))Ce.call(Y,pe)&&pe!="constructor"&&re.push(pe);return re}function $c(Y,re,pe,ke,er,bt){var ar=pe&n,xr=Y.length,Ft=re.length;if(xr!=Ft&&!(ar&&Ft>xr))return!1;var tr=bt.get(Y);if(tr&&bt.get(re))return tr==re;var _r=-1,Di=!0,Sr=pe&s?new Ci:void 0;for(bt.set(Y,re),bt.set(re,Y);++_r<xr;){var cr=Y[_r],di=re[_r];if(ke)var Ln=ar?ke(di,cr,_r,re,Y,bt):ke(cr,di,_r,Y,re,bt);if(Ln!==void 0){if(Ln)continue;Di=!1;break}if(Sr){if(!Re(re,function(un,_s){if(!Ne(Sr,_s)&&(cr===un||er(cr,un,pe,ke,bt)))return Sr.push(_s)})){Di=!1;break}}else if(!(cr===di||er(cr,di,pe,ke,bt))){Di=!1;break}}return bt.delete(Y),bt.delete(re),Di}function Dp(Y,re,pe,ke,er,bt,ar){switch(pe){case y:if(Y.byteLength!=re.byteLength||Y.byteOffset!=re.byteOffset)return!1;Y=Y.buffer,re=re.buffer;case L:return!(Y.byteLength!=re.byteLength||!bt(new pt(Y),new pt(re)));case b:case w:case q:return Ml(+Y,+re);case I:return Y.name==re.name&&Y.message==re.message;case k:case _:return Y==re+"";case T:var xr=be;case H:var Ft=ke&n;if(xr||(xr=Te),Y.size!=re.size&&!Ft)return!1;var tr=ar.get(Y);if(tr)return tr==re;ke|=s,ar.set(Y,re);var _r=$c(xr(Y),xr(re),ke,er,bt,ar);return ar.delete(Y),_r;case B:if(Fe)return Fe.call(Y)==Fe.call(re)}return!1}function wl(Y,re,pe,ke,er,bt){var ar=pe&n,xr=Rc(Y),Ft=xr.length,tr=Rc(re),_r=tr.length;if(Ft!=_r&&!ar)return!1;for(var Di=Ft;Di--;){var Sr=xr[Di];if(!(ar?Sr in re:Ce.call(re,Sr)))return!1}var cr=bt.get(Y);if(cr&&bt.get(re))return cr==re;var di=!0;bt.set(Y,re),bt.set(re,Y);for(var Ln=ar;++Di<Ft;){Sr=xr[Di];var un=Y[Sr],_s=re[Sr];if(ke)var uf=ar?ke(_s,un,Sr,re,Y,bt):ke(un,_s,Sr,Y,re,bt);if(!(uf===void 0?un===_s||er(un,_s,pe,ke,bt):uf)){di=!1;break}Ln||(Ln=Sr=="constructor")}if(di&&!Ln){var _a=Y.constructor,Fr=re.constructor;_a!=Fr&&"constructor"in Y&&"constructor"in re&&!(typeof _a=="function"&&_a instanceof _a&&typeof Fr=="function"&&Fr instanceof Fr)&&(di=!1)}return bt.delete(Y),bt.delete(re),di}function Rc(Y){return of(Y,Rp,El)}function Ao(Y,re){var pe=Y.__data__;return xl(re)?pe[typeof re=="string"?"string":"hash"]:pe.map}function ji(Y,re){var pe=Me(Y,re);return Cp(pe)?pe:void 0}function _l(Y){var re=Ce.call(Y,gt),pe=Y[gt];try{Y[gt]=void 0;var ke=!0}catch{}var er=Ke.call(Y);return ke&&(re?Y[gt]=pe:delete Y[gt]),er}var El=Ye?function(Y){return Y==null?[]:(Y=Object(Y),ye(Ye(Y),function(re){return Ge.call(Y,re)}))}:Xt,ws=ba;(Le&&ws(new Le(new ArrayBuffer(1)))!=y||et&&ws(new et)!=T||it&&ws(it.resolve())!=W||Be&&ws(new Be)!=H||rt&&ws(new rt)!=ie)&&(ws=function(Y){var re=ba(Y),pe=re==F?Y.constructor:void 0,ke=pe?qs(pe):"";if(ke)switch(ke){case qe:return y;case ht:return T;case nt:return W;case je:return H;case st:return ie}return re});function Al(Y,re){return re=re??a,!!re&&(typeof Y=="number"||ae.test(Y))&&Y>-1&&Y%1==0&&Y<re}function xl(Y){var re=typeof Y;return re=="string"||re=="number"||re=="symbol"||re=="boolean"?Y!=="__proto__":Y===null}function Sl(Y){return!!_e&&_e in Y}function Il(Y){var re=Y&&Y.constructor,pe=typeof re=="function"&&re.prototype||Se;return Y===pe}function Op(Y){return Ke.call(Y)}function qs(Y){if(Y!=null){try{return Ue.call(Y)}catch{}try{return Y+""}catch{}}return""}function Ml(Y,re){return Y===re||Y!==Y&&re!==re}var Cl=af(function(){return arguments}())?af:function(Y){return wa(Y)&&Ce.call(Y,"callee")&&!Ge.call(Y,"callee")},Nc=Array.isArray;function Pp(Y){return Y!=null&&Dl(Y.length)&&!Tc(Y)}var cf=Ot||Qt;function $p(Y,re){return ya(Y,re)}function Tc(Y){if(!Ol(Y))return!1;var re=ba(Y);return re==S||re==D||re==l||re==R}function Dl(Y){return typeof Y=="number"&&Y>-1&&Y%1==0&&Y<=a}function Ol(Y){var re=typeof Y;return Y!=null&&(re=="object"||re=="function")}function wa(Y){return Y!=null&&typeof Y=="object"}var Pl=he?Oe(he):bl;function Rp(Y){return Pp(Y)?vl(Y):yl(Y)}function Xt(){return[]}function Qt(){return!1}t.exports=$p})(Xd,Xd.exports);var bD=Xd.exports,yD=Object.defineProperty,o3=Object.getOwnPropertySymbols,wD=Object.prototype.hasOwnProperty,_D=Object.prototype.propertyIsEnumerable,a3=(t,e,r)=>e in t?yD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fi=(t,e)=>{for(var r in e||(e={}))wD.call(e,r)&&a3(t,r,e[r]);if(o3)for(var r of o3(e))_D.call(e,r)&&a3(t,r,e[r]);return t};const c3="wc",u3=2,e1="core",hs=`${c3}@2:${e1}:`,ED={name:e1,logger:"error"},AD={database:":memory:"},xD="crypto",f3="client_ed25519_seed",SD=xe.ONE_DAY,ID="keychain",MD="0.3",CD="messages",DD="0.3",OD=xe.SIX_HOURS,PD="publisher",h3="irn",$D="error",l3="wss://relay.walletconnect.org",RD="relayer",hi={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},ND="_subscription",nn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},TD=.1,t1="2.16.3",Zt={link_mode:"link_mode",relay:"relay"},LD="0.3",BD="WALLETCONNECT_CLIENT_ID",d3="WALLETCONNECT_LINK_MODE_APPS",ls={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},FD="subscription",UD="0.3",kD=xe.FIVE_SECONDS*1e3,qD="pairing",jD="0.3",Ru={wc_pairingDelete:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:xe.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:xe.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:0},res:{ttl:xe.ONE_DAY,prompt:!1,tag:0}}},fc={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Sn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},zD="history",HD="0.3",KD="expirer",sn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},WD="0.3",VD="verify-api",GD="https://verify.walletconnect.com",p3="https://verify.walletconnect.org",Nu=p3,JD=`${Nu}/v3`,YD=[GD,p3],QD="echo",ZD="https://echo.walletconnect.com",ds={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Bs={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},In={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Zo={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Xo={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Tu={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},XD=.1,eO="event-client",tO=86400,rO="https://pulse.walletconnect.org/batch";function iO(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),a=s.charCodeAt(0);if(r[a]!==255)throw new TypeError(s+" is ambiguous");r[a]=n}var u=t.length,h=t.charAt(0),l=Math.log(u)/Math.log(256),b=Math.log(256)/Math.log(u);function w(D){if(D instanceof Uint8Array||(ArrayBuffer.isView(D)?D=new Uint8Array(D.buffer,D.byteOffset,D.byteLength):Array.isArray(D)&&(D=Uint8Array.from(D))),!(D instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(D.length===0)return"";for(var T=0,q=0,K=0,F=D.length;K!==F&&D[K]===0;)K++,T++;for(var W=(F-K)*b+1>>>0,R=new Uint8Array(W);K!==F;){for(var k=D[K],H=0,_=W-1;(k!==0||H<q)&&_!==-1;_--,H++)k+=256*R[_]>>>0,R[_]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");q=H,K++}for(var B=W-q;B!==W&&R[B]===0;)B++;for(var ee=h.repeat(T);B<W;++B)ee+=t.charAt(R[B]);return ee}function I(D){if(typeof D!="string")throw new TypeError("Expected String");if(D.length===0)return new Uint8Array;var T=0;if(D[T]!==" "){for(var q=0,K=0;D[T]===h;)q++,T++;for(var F=(D.length-T)*l+1>>>0,W=new Uint8Array(F);D[T];){var R=r[D.charCodeAt(T)];if(R===255)return;for(var k=0,H=F-1;(R!==0||k<K)&&H!==-1;H--,k++)R+=u*W[H]>>>0,W[H]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");K=k,T++}if(D[T]!==" "){for(var _=F-K;_!==F&&W[_]===0;)_++;for(var B=new Uint8Array(q+(F-_)),ee=q;_!==F;)B[ee++]=W[_++];return B}}}function S(D){var T=I(D);if(T)return T;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:I,decode:S}}var nO=iO,sO=nO;const g3=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},oO=t=>new TextEncoder().encode(t),aO=t=>new TextDecoder().decode(t);class cO{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class uO{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return v3(this,e)}}class fO{constructor(e){this.decoders=e}or(e){return v3(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const v3=(t,e)=>new fO(fi(fi({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class hO{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new cO(e,r,i),this.decoder=new uO(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Rh=({name:t,prefix:e,encode:r,decode:i})=>new hO(t,e,r,i),Lu=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=sO(r,e);return Rh({prefix:t,name:e,encode:i,decode:s=>g3(n(s))})},lO=(t,e,r,i)=>{const n={};for(let b=0;b<e.length;++b)n[e[b]]=b;let s=t.length;for(;t[s-1]==="=";)--s;const a=new Uint8Array(s*r/8|0);let u=0,h=0,l=0;for(let b=0;b<s;++b){const w=n[t[b]];if(w===void 0)throw new SyntaxError(`Non-${i} character`);h=h<<r|w,u+=r,u>=8&&(u-=8,a[l++]=255&h>>u)}if(u>=r||255&h<<8-u)throw new SyntaxError("Unexpected end of data");return a},dO=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",a=0,u=0;for(let h=0;h<t.length;++h)for(u=u<<8|t[h],a+=8;a>r;)a-=r,s+=e[n&u>>a];if(a&&(s+=e[n&u<<r-a]),i)for(;s.length*r&7;)s+="=";return s},Kr=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Rh({prefix:e,name:t,encode(n){return dO(n,i,r)},decode(n){return lO(n,i,r,t)}}),pO=Rh({prefix:"\0",name:"identity",encode:t=>aO(t),decode:t=>oO(t)});var gO=Object.freeze({__proto__:null,identity:pO});const vO=Kr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var mO=Object.freeze({__proto__:null,base2:vO});const bO=Kr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var yO=Object.freeze({__proto__:null,base8:bO});const wO=Lu({prefix:"9",name:"base10",alphabet:"0123456789"});var _O=Object.freeze({__proto__:null,base10:wO});const EO=Kr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),AO=Kr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var xO=Object.freeze({__proto__:null,base16:EO,base16upper:AO});const SO=Kr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),IO=Kr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),MO=Kr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),CO=Kr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),DO=Kr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),OO=Kr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),PO=Kr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$O=Kr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),RO=Kr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var NO=Object.freeze({__proto__:null,base32:SO,base32upper:IO,base32pad:MO,base32padupper:CO,base32hex:DO,base32hexupper:OO,base32hexpad:PO,base32hexpadupper:$O,base32z:RO});const TO=Lu({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),LO=Lu({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var BO=Object.freeze({__proto__:null,base36:TO,base36upper:LO});const FO=Lu({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),UO=Lu({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var kO=Object.freeze({__proto__:null,base58btc:FO,base58flickr:UO});const qO=Kr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jO=Kr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),zO=Kr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),HO=Kr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var KO=Object.freeze({__proto__:null,base64:qO,base64pad:jO,base64url:zO,base64urlpad:HO});const m3=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}"),WO=m3.reduce((t,e,r)=>(t[r]=e,t),[]),VO=m3.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function GO(t){return t.reduce((e,r)=>(e+=WO[r],e),"")}function JO(t){const e=[];for(const r of t){const i=VO[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const YO=Rh({prefix:"\u{1F680}",name:"base256emoji",encode:GO,decode:JO});var QO=Object.freeze({__proto__:null,base256emoji:YO}),ZO=y3,b3=128,XO=127,eP=~XO,tP=Math.pow(2,31);function y3(t,e,r){e=e||[],r=r||0;for(var i=r;t>=tP;)e[r++]=t&255|b3,t/=128;for(;t&eP;)e[r++]=t&255|b3,t>>>=7;return e[r]=t|0,y3.bytes=r-i+1,e}var rP=r1,iP=128,w3=127;function r1(t,i){var r=0,i=i||0,n=0,s=i,a,u=t.length;do{if(s>=u)throw r1.bytes=0,new RangeError("Could not decode varint");a=t[s++],r+=n<28?(a&w3)<<n:(a&w3)*Math.pow(2,n),n+=7}while(a>=iP);return r1.bytes=s-i,r}var nP=Math.pow(2,7),sP=Math.pow(2,14),oP=Math.pow(2,21),aP=Math.pow(2,28),cP=Math.pow(2,35),uP=Math.pow(2,42),fP=Math.pow(2,49),hP=Math.pow(2,56),lP=Math.pow(2,63),dP=function(t){return t<nP?1:t<sP?2:t<oP?3:t<aP?4:t<cP?5:t<uP?6:t<fP?7:t<hP?8:t<lP?9:10},pP={encode:ZO,decode:rP,encodingLength:dP},_3=pP;const E3=(t,e,r=0)=>(_3.encode(t,e,r),e),A3=t=>_3.encodingLength(t),i1=(t,e)=>{const r=e.byteLength,i=A3(t),n=i+A3(r),s=new Uint8Array(n+r);return E3(t,s,0),E3(r,s,i),s.set(e,n),new gP(t,r,e,s)};class gP{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const x3=({name:t,code:e,encode:r})=>new vP(t,e,r);class vP{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?i1(this.code,r):r.then(i=>i1(this.code,i))}else throw Error("Unknown type, must be binary type")}}const S3=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),mP=x3({name:"sha2-256",code:18,encode:S3("SHA-256")}),bP=x3({name:"sha2-512",code:19,encode:S3("SHA-512")});var yP=Object.freeze({__proto__:null,sha256:mP,sha512:bP});const I3=0,wP="identity",M3=g3;var _P=Object.freeze({__proto__:null,identity:{code:I3,name:wP,encode:M3,digest:t=>i1(I3,M3(t))}});new TextEncoder,new TextDecoder;const C3=fi(fi(fi(fi(fi(fi(fi(fi(fi(fi({},gO),mO),yO),_O),xO),NO),BO),kO),KO),QO);fi(fi({},yP),_P);function EP(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function D3(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const O3=D3("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),n1=D3("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=EP(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),AP=fi({utf8:O3,"utf-8":O3,hex:C3.base16,latin1:n1,ascii:n1,binary:n1},C3);function xP(t,e="utf8"){const r=AP[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}class SP{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=ID,this.version=MD,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}},this.has=i=>(this.isInitialized(),this.keychain.has(i)),this.set=async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()},this.get=i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=Ee("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=ui(r,this.name)}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,W2(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?V2(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class IP{constructor(e,r,i){this.core=e,this.logger=r,this.name=xD,this.randomSessionIdentifier=Nd(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=n=>(this.isInitialized(),this.keychain.has(n)),this.getClientId=async()=>{this.isInitialized();const n=await this.getClientSeed(),s=F2(n);return B2(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const n=oI();return this.setPrivateKey(n.publicKey,n.privateKey)},this.signJWT=async n=>{this.isInitialized();const s=await this.getClientSeed(),a=F2(s),u=this.randomSessionIdentifier;return await zE(u,n,SD,a)},this.generateSharedKey=(n,s,a)=>{this.isInitialized();const u=this.getPrivateKey(n),h=aI(u,s);return this.setSymKey(h,a)},this.setSymKey=async(n,s)=>{this.isInitialized();const a=s||bh(n);return await this.keychain.set(a,n),a},this.deleteKeyPair=async n=>{this.isInitialized(),await this.keychain.del(n)},this.deleteSymKey=async n=>{this.isInitialized(),await this.keychain.del(n)},this.encode=async(n,s,a)=>{this.isInitialized();const u=gb(a),h=Cs(s);if(mb(u))return uI(h,a?.encoding);if(vb(u)){const I=u.senderPublicKey,S=u.receiverPublicKey;n=await this.generateSharedKey(I,S)}const l=this.getSymKey(n),{type:b,senderPublicKey:w}=u;return cI({type:b,symKey:l,message:h,senderPublicKey:w,encoding:a?.encoding})},this.decode=async(n,s,a)=>{this.isInitialized();const u=lI(s,a);if(mb(u)){const h=hI(s,a?.encoding);return jo(h)}if(vb(u)){const h=u.receiverPublicKey,l=u.senderPublicKey;n=await this.generateSharedKey(h,l)}try{const h=this.getSymKey(n),l=fI({symKey:h,encoded:s,encoding:a?.encoding});return jo(l)}catch(h){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=(n,s=ao)=>{const a=Eu({encoded:n,encoding:s});return Go(a.type)},this.getPayloadSenderPublicKey=(n,s=ao)=>{const a=Eu({encoded:n,encoding:s});return a.senderPublicKey?DC(a.senderPublicKey,ai):void 0},this.core=e,this.logger=ui(r,this.name),this.keychain=i||new SP(this.core,this.logger)}get context(){return Ai(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(f3)}catch{e=Nd(),await this.keychain.set(f3,e)}return xP(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class MP extends vC{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=CD,this.version=DD,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}},this.set=async(i,n)=>{this.isInitialized();const s=Ns(n);let a=this.messages.get(i);return typeof a>"u"&&(a={}),typeof a[s]<"u"||(a[s]=n,this.messages.set(i,a),await this.persist()),s},this.get=i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n},this.has=(i,n)=>{this.isInitialized();const s=this.get(i),a=Ns(n);return typeof s[a]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=ui(e,this.name),this.core=r}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,W2(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?V2(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class CP extends mC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new kr.exports.EventEmitter,this.name=PD,this.queue=new Map,this.publishTimeout=xe.toMiliseconds(xe.ONE_MINUTE),this.failedPublishTimeout=xe.toMiliseconds(xe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(i,n,s)=>{var a;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const u=s?.ttl||OD,h=Td(s),l=s?.prompt||!1,b=s?.tag||0,w=s?.id||Qo().toString(),I={topic:i,message:n,opts:{ttl:u,relay:h,prompt:l,tag:b,id:w,attestation:s?.attestation}},S=`Failed to publish payload, please try again. id:${w} tag:${b}`,D=Date.now();let T,q=1;try{for(;T===void 0;){if(Date.now()-D>this.publishTimeout)throw new Error(S);this.logger.trace({id:w,attempts:q},`publisher.publish - attempt ${q}`),T=await await Ga(this.rpcPublish(i,n,u,h,l,b,w,s?.attestation).catch(K=>this.logger.warn(K)),this.publishTimeout,S),q++,T||await new Promise(K=>setTimeout(K,this.failedPublishTimeout))}this.relayer.events.emit(hi.publish,I),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:w,topic:i,message:n,opts:s}})}catch(K){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(K),(a=s?.internal)!=null&&a.throwOnFailedPublish)throw K;this.queue.set(w,I)}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.relayer=e,this.logger=ui(r,this.name),this.registerEventListeners()}get context(){return Ai(this.logger)}rpcPublish(e,r,i,n,s,a,u,h){var l,b,w,I;const S={method:Au(n.protocol).publish,params:{topic:e,message:r,ttl:i,prompt:s,tag:a,attestation:h},id:u};return ci((l=S.params)==null?void 0:l.prompt)&&((b=S.params)==null||delete b.prompt),ci((w=S.params)==null?void 0:w.tag)&&((I=S.params)==null||delete I.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:S}),this.relayer.request(S)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:i,opts:n}=e;await this.publish(r,i,n)})}registerEventListeners(){this.relayer.core.heartbeat.on(ac.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(hi.connection_stalled);return}this.checkQueue()}),this.relayer.on(hi.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class DP{constructor(){this.map=new Map,this.set=(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var OP=Object.defineProperty,PP=Object.defineProperties,$P=Object.getOwnPropertyDescriptors,P3=Object.getOwnPropertySymbols,RP=Object.prototype.hasOwnProperty,NP=Object.prototype.propertyIsEnumerable,$3=(t,e,r)=>e in t?OP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bu=(t,e)=>{for(var r in e||(e={}))RP.call(e,r)&&$3(t,r,e[r]);if(P3)for(var r of P3(e))NP.call(e,r)&&$3(t,r,e[r]);return t},s1=(t,e)=>PP(t,$P(e));class TP extends wC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new DP,this.events=new kr.exports.EventEmitter,this.name=FD,this.version=UD,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=hs,this.subscribeTimeout=xe.toMiliseconds(xe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.pendingBatchMessages=[],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(i,n)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const s=Td(n),a={topic:i,relay:s,transportType:n?.transportType};this.pending.set(i,a);const u=await this.rpcSubscribe(i,s,n?.transportType);return typeof u=="string"&&(this.onSubscribe(u,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),u}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(i,n)=>{await this.restartToComplete(),this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)},this.isSubscribed=async i=>{if(this.topics.includes(i))return!0;const n=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((s,a)=>{const u=new xe.Watch;u.start(n);const h=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(h),u.stop(n),s(!0)),u.elapsed(n)>=kD&&(clearInterval(h),u.stop(n),a(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=ui(r,this.name),this.clientId=""}get context(){return Ai(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,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=Td(i);await this.rpcUnsubscribe(e,r,n);const s=Gt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i=Zt.relay){i===Zt.relay&&await this.restartToComplete();const n={method:Au(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{const s=Ns(e+this.clientId);return i===Zt.link_mode?(setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(a=>this.logger.warn(a))},xe.toMiliseconds(xe.ONE_SECOND)),s):await await Ga(this.relayer.request(n).catch(a=>this.logger.warn(a)),this.subscribeTimeout)?s:null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(hi.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:Au(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await await Ga(this.relayer.request(i).catch(n=>this.logger.warn(n)),this.subscribeTimeout)}catch{this.relayer.events.emit(hi.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:Au(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Ga(this.relayer.request(i).catch(s=>this.logger.warn(s)),this.subscribeTimeout)}catch{this.relayer.events.emit(hi.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:Au(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,s1(Bu({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Bu({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,Bu({},r)),this.topicMap.set(r.topic,e),this.events.emit(ls.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(ls.deleted,s1(Bu({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ls.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const i=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchFetchMessages(i),await this.batchSubscribe(i)}}this.events.emit(ls.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}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){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);as(r)&&this.onBatchSubscribe(r.map((i,n)=>s1(Bu({},e[n]),{id:i})))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(this.pendingBatchMessages=this.pendingBatchMessages.concat(r.messages))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e),this.pendingBatchMessages.length&&(await this.relayer.handleBatchMessageEvents(this.pendingBatchMessages),this.pendingBatchMessages=[])}registerEventListeners(){this.relayer.core.heartbeat.on(ac.pulse,async()=>{await this.checkPending()}),this.events.on(ls.created,async e=>{const r=ls.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(ls.deleted,async e=>{const r=ls.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen(),this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var LP=Object.defineProperty,R3=Object.getOwnPropertySymbols,BP=Object.prototype.hasOwnProperty,FP=Object.prototype.propertyIsEnumerable,N3=(t,e,r)=>e in t?LP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,UP=(t,e)=>{for(var r in e||(e={}))BP.call(e,r)&&N3(t,r,e[r]);if(R3)for(var r of R3(e))FP.call(e,r)&&N3(t,r,e[r]);return t};class kP extends bC{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new kr.exports.EventEmitter,this.name=RD,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=xe.toMiliseconds(xe.THIRTY_SECONDS+xe.ONE_SECOND),this.request=async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||Qo().toString();await this.toEstablishConnection();try{const a=this.provider.request(r);this.requestsInFlight.set(s,{promise:a,request:r}),this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - attempt to publish...");const u=await new Promise(async(h,l)=>{const b=()=>{l(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(nn.disconnect,b);const w=await a;this.provider.off(nn.disconnect,b),h(w)});return this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - published"),u}catch(a){throw this.logger.debug(`Failed to Publish Request: ${s}`),a}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(th())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,n;(n=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||n.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.trace("relayer connected"),this.startPingTimeout(),this.events.emit(hi.connect)},this.onDisconnectHandler=()=>{this.logger.trace("relayer disconnected"),this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(hi.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(nn.payload,this.onPayloadHandler),this.provider.on(nn.connect,this.onConnectHandler),this.provider.on(nn.disconnect,this.onDisconnectHandler),this.provider.on(nn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ui(e.logger,this.name):cs(Dh({level:e.logger||$D})),this.messages=new MP(this.logger,e.core),this.subscriber=new TP(this,this.logger),this.publisher=new CP(this,this.logger),this.relayUrl=e?.relayUrl||l3,this.projectId=e.projectId,this.bundleId=QE(),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)}}get context(){return Ai(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:Zt.relay})}async subscribe(e,r){var i;this.isInitialized(),r?.transportType==="relay"&&await this.toEstablishConnection();let n=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",s;const a=u=>{u.topic===e&&(this.subscriber.off(ls.created,a),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(ls.created,a)}),new Promise(async u=>{n=await this.subscriber.subscribe(e,r)||n,u()})]),n}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await Ga(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),await this.createProvider(),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,i)=>{const n=()=>{this.provider.off(nn.disconnect,n),i(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(nn.disconnect,n),await Ga(this.provider.connect(),xe.toMiliseconds(xe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{i(s)}).finally(()=>{clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),this.subscriber.start().catch(s=>{this.logger.error(s),this.onDisconnectHandler()}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);const i=r;if(this.hasExperiencedNetworkDisruption=!0,!this.isConnectionStalled(i.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Db())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 r=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.trace(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=Ir(xe.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(hi.message,e),await this.recordMessageEvent(e)}startPingTimeout(){var e,r,i,n,s;if(th())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null||s.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(a){this.logger.warn(a)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new xn(new mD(tA({sdkVersion:t1,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:r,message:i}=e;await this.messages.set(r,i)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.debug(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Zd(e)){if(!e.method.endsWith(ND))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:a}=r.data,u={topic:i,message:n,publishedAt:s,transportType:Zt.relay,attestation:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(UP({type:"event",event:r.id},u)),this.events.emit(r.id,u),await this.acknowledgePayload(e),await this.onMessageEvent(u)}else $h(e)&&this.events.emit(hi.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(hi.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Oh(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(nn.payload,this.onPayloadHandler),this.provider.off(nn.connect,this.onConnectHandler),this.provider.off(nn.disconnect,this.onDisconnectHandler),this.provider.off(nn.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Db();oM(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(i=>this.logger.error(i)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.requestsInFlight.clear(),clearTimeout(this.pingTimeout),this.events.emit(hi.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},xe.toMiliseconds(TD))))}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}}var qP=Object.defineProperty,T3=Object.getOwnPropertySymbols,jP=Object.prototype.hasOwnProperty,zP=Object.prototype.propertyIsEnumerable,L3=(t,e,r)=>e in t?qP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,B3=(t,e)=>{for(var r in e||(e={}))jP.call(e,r)&&L3(t,r,e[r]);if(T3)for(var r of T3(e))zP.call(e,r)&&L3(t,r,e[r]);return t};class ea extends yC{constructor(e,r,i,n=hs,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,this.map=new Map,this.version=LD,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(a=>{this.getKey&&a!==null&&!ci(a)?this.map.set(this.getKey(a),a):BI(a)?this.map.set(a.id,a):FI(a)&&this.map.set(a.topic,a)}),this.cached=[],this.initialized=!0)},this.set=async(a,u)=>{this.isInitialized(),this.map.has(a)?await this.update(a,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:a,value:u}),this.map.set(a,u),await this.persist())},this.get=a=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:a}),this.getData(a)),this.getAll=a=>(this.isInitialized(),a?this.values.filter(u=>Object.keys(a).every(h=>bD(u[h],a[h]))):this.values),this.update=async(a,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:a,update:u});const h=B3(B3({},this.getData(a)),u);this.map.set(a,h),await this.persist()},this.delete=async(a,u)=>{this.isInitialized(),this.map.has(a)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:a,reason:u}),this.map.delete(a),this.addToRecentlyDeleted(a),await this.persist())},this.logger=ui(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return Ai(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 r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:n}=Ee("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}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:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class HP{constructor(e,r){this.core=e,this.logger=r,this.name=qD,this.version=jD,this.events=new kr.exports,this.initialized=!1,this.storagePrefix=hs,this.ignoredPayloadTypes=[Rs],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:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async i=>{this.isInitialized();const n=Nd(),s=await this.core.crypto.setSymKey(n),a=Ir(xe.FIVE_MINUTES),u={protocol:h3},h={topic:s,expiry:a,relay:u,active:!1},l=MI({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:u,expiryTimestamp:a,methods:i?.methods});return this.core.expirer.set(s,a),await this.pairings.set(s,h),await this.core.relayer.subscribe(s,{transportType:i?.transportType}),{topic:s,uri:l}},this.pair=async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[ds.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:a,relay:u,expiryTimestamp:h,methods:l}=_b(i.uri);n.props.properties.topic=s,n.addTrace(ds.pairing_uri_validation_success),n.addTrace(ds.pairing_uri_not_expired);let b;if(this.pairings.keys.includes(s)){if(b=this.pairings.get(s),n.addTrace(ds.existing_pairing),b.active)throw n.setError(Bs.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(ds.pairing_not_expired)}const w=h||Ir(xe.FIVE_MINUTES),I={topic:s,relay:u,expiry:w,active:!1,methods:l};this.core.expirer.set(s,w),await this.pairings.set(s,I),n.addTrace(ds.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(fc.create,I),n.addTrace(ds.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(a,s),n.addTrace(ds.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(Bs.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:u})}catch(S){throw n.setError(Bs.subscribe_pairing_topic_failure),S}return n.addTrace(ds.subscribe_pairing_topic_success),I},this.activate=async({topic:i})=>{this.isInitialized();const n=Ir(xe.THIRTY_DAYS);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i);const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:a,resolve:u,reject:h}=Ho();this.events.once(Dt("pairing_ping",s),({error:l})=>{l?h(l):u()}),await a()}},this.updateExpiry=async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})},this.updateMetadata=async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",Gt("USER_DISCONNECTED")),await this.deletePairing(n))},this.sendRequest=async(i,n,s)=>{const a=uo(n,s),u=await this.core.crypto.encode(i,a),h=Ru[n].req;return this.core.history.set(i,a),this.core.relayer.publish(i,u,h),a.id},this.sendResult=async(i,n,s)=>{const a=Oh(i,s),u=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),l=Ru[h.request.method].res;await this.core.relayer.publish(n,u,l),await this.core.history.resolve(a)},this.sendError=async(i,n,s)=>{const a=Ph(i,s),u=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),l=Ru[h.request.method]?Ru[h.request.method].res:Ru.unregistered_method.res;await this.core.relayer.publish(n,u,l),await this.core.history.resolve(a)},this.deletePairing=async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Gt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(n=>io(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))},this.onRelayEventRequest=i=>{const{topic:n,payload:s}=i;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(n,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(n,s);default:return this.onUnknownRpcMethodRequest(n,s)}},this.onRelayEventResponse=async i=>{const{topic:n,payload:s}=i,a=(await this.core.history.get(n,s.id)).request.method;switch(a){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(a)}},this.onPairingPingRequest=async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(fc.ping,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onPairingPingResponse=(i,n)=>{const{id:s}=n;setTimeout(()=>{fs(n)?this.events.emit(Dt("pairing_ping",s),{}):rn(n)&&this.events.emit(Dt("pairing_ping",s),{error:n.error})},500)},this.onPairingDeleteRequest=async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(fc.delete,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onUnknownRpcMethodRequest=async(i,n)=>{const{id:s,method:a}=n;try{if(this.registeredMethods.includes(a))return;const u=Gt("WC_METHOD_UNSUPPORTED",a);await this.sendError(s,i,u),this.logger.error(u)}catch(u){await this.sendError(s,i,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(Gt("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=(i,n)=>{var s;if(!_i(i)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(!LI(i.uri)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(Bs.malformed_pairing_uri),new Error(u)}const a=_b(i?.uri);if(!((s=a?.relay)!=null&&s.protocol)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(!(a!=null&&a.symKey)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(a!=null&&a.expiryTimestamp&&xe.toMiliseconds(a?.expiryTimestamp)<Date.now()){n.setError(Bs.pairing_expired);const{message:u}=Ee("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(u)}},this.isValidPing=async i=>{if(!_i(i)){const{message:s}=Ee("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidDisconnect=async i=>{if(!_i(i)){const{message:s}=Ee("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidPairingTopic=async i=>{if(!yr(i,!1)){const{message:n}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(io(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=Ee("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}},this.core=e,this.logger=ui(r,this.name),this.pairings=new ea(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ai(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(hi.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(!this.pairings.keys.includes(r)||n===Zt.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(r,i);try{Zd(s)?(this.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):$h(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id))}catch(a){this.logger.error(a)}})}registerExpirerEvents(){this.core.expirer.on(sn.expired,async e=>{const{topic:r}=J2(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(fc.expire,{topic:r}))})}}class KP extends gC{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new kr.exports.EventEmitter,this.name=zD,this.version=HD,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const a={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:Ir(xe.THIRTY_DAYS)};this.records.set(a.id,a),this.persist(),this.events.emit(Sn.created,a)},this.resolve=async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=rn(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Sn.updated,n))},this.get=async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n)),this.delete=(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Sn.deleted,s)}}),this.persist()},this.exists=async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1),this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ui(r,this.name)}get context(){return Ai(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(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:uo(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),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 r=this.records.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Sn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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(Sn.created,e=>{const r=Sn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Sn.updated,e=>{const r=Sn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Sn.deleted,e=>{const r=Sn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(ac.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{xe.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Sn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class WP extends _C{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new kr.exports.EventEmitter,this.name=KD,this.version=WD,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}},this.set=(i,n)=>{this.isInitialized();const s=this.formatTarget(i),a={target:s,expiry:n};this.expirations.set(s,a),this.checkExpiry(s,a),this.events.emit(sn.created,{target:s,expiration:a})},this.get=i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)},this.del=i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(sn.deleted,{target:n,expiration:s})}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ui(r,this.name)}get context(){return Ai(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 rA(e);if(typeof e=="number")return iA(e);const{message:r}=Ee("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}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(sn.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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 r=this.expirations.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;xe.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(sn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ac.pulse,()=>this.checkExpirations()),this.events.on(sn.created,e=>{const r=sn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(sn.expired,e=>{const r=sn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(sn.deleted,e=>{const r=sn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var or={};Object.defineProperty(or,"__esModule",{value:!0}),or.getLocalStorage=or.getLocalStorageOrThrow=or.getCrypto=or.getCryptoOrThrow=or.getLocation=or.getLocationOrThrow=or.getNavigator=or.getNavigatorOrThrow=F3=or.getDocument=or.getDocumentOrThrow=or.getFromWindowOrThrow=or.getFromWindow=void 0;function ta(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}or.getFromWindow=ta;function hc(t){const e=ta(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}or.getFromWindowOrThrow=hc;function VP(){return hc("document")}or.getDocumentOrThrow=VP;function GP(){return ta("document")}var F3=or.getDocument=GP;function JP(){return hc("navigator")}or.getNavigatorOrThrow=JP;function YP(){return ta("navigator")}or.getNavigator=YP;function QP(){return hc("location")}or.getLocationOrThrow=QP;function ZP(){return ta("location")}or.getLocation=ZP;function XP(){return hc("crypto")}or.getCryptoOrThrow=XP;function e$(){return ta("crypto")}or.getCrypto=e$;function t$(){return hc("localStorage")}or.getLocalStorageOrThrow=t$;function r$(){return ta("localStorage")}or.getLocalStorage=r$;class i$ extends EC{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,this.name=VD,this.verifyUrlV3=JD,this.storagePrefix=hs,this.version=u3,this.init=async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&xe.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async n=>{if(!au()||this.isDevEnv)return;const s=window.location.origin,{id:a,decryptedId:u}=n,h=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${a}&decryptedId=${u}`;try{const l=F3(),b=this.startAbortTimer(xe.ONE_SECOND*5),w=await new Promise((I,S)=>{const D=()=>{window.removeEventListener("message",q),l.body.removeChild(T),S("attestation aborted")};this.abortController.signal.addEventListener("abort",D);const T=l.createElement("iframe");T.src=h,T.style.display="none",T.addEventListener("error",D,{signal:this.abortController.signal});const q=K=>{if(!K.data)return;const F=JSON.parse(K.data);if(F.type==="verify_attestation"){if(od(F.attestation).payload.id!==a)return;clearInterval(b),l.body.removeChild(T),this.abortController.signal.removeEventListener("abort",D),window.removeEventListener("message",q),I(F.attestation===null?"":F.attestation)}};l.body.appendChild(T),window.addEventListener("message",q,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",w),w}catch(l){this.logger.warn(l)}return""},this.resolve=async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:a,encryptedId:u}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(od(s).payload.id!==u)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!a)return;const h=this.getVerifyUrl(n?.verifyUrl);return this.fetchAttestation(a,h)},this.fetchAttestation=async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const a=this.startAbortTimer(xe.ONE_SECOND*5),u=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(a),u.status===200?await u.json():void 0},this.getVerifyUrl=n=>{let s=n||Nu;return YD.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Nu}`),s=Nu),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(xe.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}},this.persistPublicKey=async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n},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 n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(u){this.logger.error(u),this.logger.warn("error validating attestation")}const a=await this.fetchAndPersistPublicKey();try{if(a)return this.validateAttestation(n,a)}catch(u){this.logger.error(u),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 s=>{const a=await this.fetchPublicKey();a&&(await this.persistPublicKey(a),s(a))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n},this.validateAttestation=(n,s)=>{const a=vI(n,s.publicKey),u={hasExpired:xe.toMiliseconds(a.exp)<Date.now(),payload:a};if(u.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:u.payload.origin,isScam:u.payload.isScam,isVerified:u.payload.isVerified}},this.logger=ui(r,this.name),this.abortController=new AbortController,this.isDevEnv=ad(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ai(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),xe.toMiliseconds(e))}}class n$ extends AC{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=QD,this.registerDeviceToken=async i=>{const{clientId:n,token:s,notificationType:a,enableEncrypted:u=!1}=i,h=`${ZD}/${this.projectId}/clients`;await fetch(h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:a,token:s,always_raw:u})})},this.logger=ui(r,this.context)}}var s$=Object.defineProperty,U3=Object.getOwnPropertySymbols,o$=Object.prototype.hasOwnProperty,a$=Object.prototype.propertyIsEnumerable,k3=(t,e,r)=>e in t?s$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fu=(t,e)=>{for(var r in e||(e={}))o$.call(e,r)&&k3(t,r,e[r]);if(U3)for(var r of U3(e))a$.call(e,r)&&k3(t,r,e[r]);return t};class c$ extends xC{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,this.context=eO,this.storagePrefix=hs,this.storageVersion=XD,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!ad())try{const n={eventId:Q2(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:K2(this.core.relayer.protocol,this.core.relayer.version,t1)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}},this.createEvent=n=>{const{event:s="ERROR",type:a="",properties:{topic:u,trace:h}}=n,l=Q2(),b=this.core.projectId||"",w=Date.now(),I=Fu({eventId:l,timestamp:w,props:{event:s,type:a,properties:{topic:u,trace:h}},bundleId:b,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,I),this.shouldPersist=!0),I},this.getEvent=n=>{const{eventId:s,topic:a}=n;if(s)return this.events.get(s);const u=Array.from(this.events.values()).find(h=>h.props.properties.topic===a);if(u)return Fu(Fu({},u),this.setMethods(u.eventId))},this.deleteEvent=n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(ac.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{xe.fromMiliseconds(Date.now())-xe.fromMiliseconds(n.timestamp)>tO&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})},this.setMethods=n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)}),this.addTrace=(n,s)=>{const a=this.events.get(n);a&&(a.props.properties.trace.push(s),this.events.set(n,a),this.shouldPersist=!0)},this.setError=(n,s)=>{const a=this.events.get(n);a&&(a.props.type=s,a.timestamp=Date.now(),this.events.set(n,a),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 n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,Fu(Fu({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,a]of this.events)a.props.type&&n.push(a);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}},this.sendEvent=async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${rO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${t1}${s}`,{method:"POST",body:JSON.stringify(n)})},this.getAppDomain=()=>H2().url,this.logger=ui(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var u$=Object.defineProperty,q3=Object.getOwnPropertySymbols,f$=Object.prototype.hasOwnProperty,h$=Object.prototype.propertyIsEnumerable,j3=(t,e,r)=>e in t?u$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,z3=(t,e)=>{for(var r in e||(e={}))f$.call(e,r)&&j3(t,r,e[r]);if(q3)for(var r of q3(e))h$.call(e,r)&&j3(t,r,e[r]);return t};class o1 extends pC{constructor(e){var r;super(e),this.protocol=c3,this.version=u3,this.name=e1,this.events=new kr.exports.EventEmitter,this.initialized=!1,this.on=(a,u)=>this.events.on(a,u),this.once=(a,u)=>this.events.once(a,u),this.off=(a,u)=>this.events.off(a,u),this.removeListener=(a,u)=>this.events.removeListener(a,u),this.dispatchEnvelope=({topic:a,message:u,sessionExists:h})=>{if(!a||!u)return;const l={topic:a,message:u,publishedAt:Date.now(),transportType:Zt.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})},this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||l3,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Dh({level:typeof e?.logger=="string"&&e.logger?e.logger:ED.logger}),{logger:n,chunkLoggerController:s}=dC({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,u;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=ui(n,this.name),this.heartbeat=new kd,this.crypto=new IP(this,this.logger,e?.keychain),this.history=new KP(this,this.logger),this.expirer=new WP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new UM(z3(z3({},AD),e?.storageOptions)),this.relayer=new kP({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new HP(this,this.logger),this.verify=new i$(this,this.logger,this.storage),this.echoClient=new n$(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new c$(this,this.logger,e?.telemetryEnabled)}static async init(e){const r=new o1(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(BD,i),r}get context(){return Ai(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(d3,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(d3)||[],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 l$=o1,H3="wc",K3=2,W3="client",a1=`${H3}@${K3}:${W3}:`,c1={name:W3,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},V3="WALLETCONNECT_DEEPLINK_CHOICE",d$="proposal",G3="Proposal expired",p$="session",lc=xe.SEVEN_DAYS,g$="engine",Lr={wc_sessionPropose:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1104},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1106},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1112},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1114},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:xe.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:xe.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1119}}},u1={min:xe.FIVE_MINUTES,max:xe.SEVEN_DAYS},ps={idle:"IDLE",active:"ACTIVE"},v$="request",m$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],b$="wc",y$="auth",w$="authKeys",_$="pairingTopics",E$="requests",Nh=`${b$}@${1.5}:${y$}:`,Th=`${Nh}:PUB_KEY`;var A$=Object.defineProperty,x$=Object.defineProperties,S$=Object.getOwnPropertyDescriptors,J3=Object.getOwnPropertySymbols,I$=Object.prototype.hasOwnProperty,M$=Object.prototype.propertyIsEnumerable,Y3=(t,e,r)=>e in t?A$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pr=(t,e)=>{for(var r in e||(e={}))I$.call(e,r)&&Y3(t,r,e[r]);if(J3)for(var r of J3(e))M$.call(e,r)&&Y3(t,r,e[r]);return t},Mn=(t,e)=>x$(t,S$(e));class C$ extends IC{constructor(e){super(e),this.name=g$,this.events=new kr.exports,this.initialized=!1,this.requestQueue={state:ps.idle,queue:[]},this.sessionRequestQueue={state:ps.idle,queue:[]},this.requestQueueDelay=xe.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(Lr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},xe.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Mn(pr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:a,sessionProperties:u,relays:h}=i;let l=n,b,w=!1;try{l&&(w=this.client.core.pairing.pairings.get(l).active)}catch(R){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),R}if(!l||!w){const{topic:R,uri:k}=await this.client.core.pairing.create();l=R,b=k}if(!l){const{message:R}=Ee("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(R)}const I=await this.client.core.crypto.generateKeyPair(),S=Lr.wc_sessionPropose.req.ttl||xe.FIVE_MINUTES,D=Ir(S),T=pr({requiredNamespaces:s,optionalNamespaces:a,relays:h??[{protocol:h3}],proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:D,pairingTopic:l},u&&{sessionProperties:u}),{reject:q,resolve:K,done:F}=Ho(S,G3);this.events.once(Dt("session_connect"),async({error:R,session:k})=>{if(R)q(R);else if(k){k.self.publicKey=I;const H=Mn(pr({},k),{pairingTopic:T.pairingTopic,requiredNamespaces:T.requiredNamespaces,optionalNamespaces:T.optionalNamespaces,transportType:Zt.relay});await this.client.session.set(k.topic,H),await this.setExpiry(k.topic,k.expiry),l&&await this.client.core.pairing.updateMetadata({topic:l,metadata:k.peer.metadata}),this.cleanupDuplicatePairings(H),K(H)}});const W=await this.sendRequest({topic:l,method:"wc_sessionPropose",params:T,throwOnFailedPublish:!0});return await this.setProposal(W,pr({id:W},T)),{uri:b,approval:F}},this.pair=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}},this.approve=async r=>{var i,n,s;const a=this.client.core.eventClient.createEvent({properties:{topic:(i=r?.id)==null?void 0:i.toString(),trace:[In.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(B){throw a.setError(Zo.no_internet_connection),B}try{await this.isValidProposalId(r?.id)}catch(B){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),a.setError(Zo.proposal_not_found),B}try{await this.isValidApprove(r)}catch(B){throw this.client.logger.error("approve() -> isValidApprove() failed"),a.setError(Zo.session_approve_namespace_validation_failure),B}const{id:u,relayProtocol:h,namespaces:l,sessionProperties:b,sessionConfig:w}=r,I=this.client.proposal.get(u);this.client.core.eventClient.deleteEvent({eventId:a.eventId});const{pairingTopic:S,proposer:D,requiredNamespaces:T,optionalNamespaces:q}=I;let K=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:S});K||(K=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:In.session_approve_started,properties:{topic:S,trace:[In.session_approve_started,In.session_namespaces_validation_success]}}));const F=await this.client.core.crypto.generateKeyPair(),W=D.publicKey,R=await this.client.core.crypto.generateSharedKey(F,W),k=pr(pr({relay:{protocol:h??"irn"},namespaces:l,controller:{publicKey:F,metadata:this.client.metadata},expiry:Ir(lc)},b&&{sessionProperties:b}),w&&{sessionConfig:w}),H=Zt.relay;K.addTrace(In.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:H})}catch(B){throw K.setError(Zo.subscribe_session_topic_failure),B}K.addTrace(In.subscribe_session_topic_success);const _=Mn(pr({},k),{topic:R,requiredNamespaces:T,optionalNamespaces:q,pairingTopic:S,acknowledged:!1,self:k.controller,peer:{publicKey:D.publicKey,metadata:D.metadata},controller:F,transportType:Zt.relay});await this.client.session.set(R,_),K.addTrace(In.store_session);try{K.addTrace(In.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:k,throwOnFailedPublish:!0}).catch(B=>{throw K?.setError(Zo.session_settle_publish_failure),B}),K.addTrace(In.session_settle_publish_success),K.addTrace(In.publishing_session_approve),await this.sendResult({id:u,topic:S,result:{relay:{protocol:h??"irn"},responderPublicKey:F},throwOnFailedPublish:!0}).catch(B=>{throw K?.setError(Zo.session_approve_publish_failure),B}),K.addTrace(In.session_approve_publish_success)}catch(B){throw this.client.logger.error(B),this.client.session.delete(R,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),B}return this.client.core.eventClient.deleteEvent({eventId:K.eventId}),await this.client.core.pairing.updateMetadata({topic:S,metadata:D.metadata}),await this.client.proposal.delete(u,Gt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:S}),await this.setExpiry(R,Ir(lc)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}},this.reject=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(a){throw this.client.logger.error("reject() -> isValidReject() failed"),a}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(a){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),a}s&&(await this.sendError({id:i,topic:s,error:n,rpcOpts:Lr.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(w){throw this.client.logger.error("update() -> isValidUpdate() failed"),w}const{topic:i,namespaces:n}=r,{done:s,resolve:a,reject:u}=Ho(),h=co(),l=Qo().toString(),b=this.client.session.get(i).namespaces;return this.events.once(Dt("session_update",h),({error:w})=>{w?u(w):a()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:h,relayRpcId:l}).catch(w=>{this.client.logger.error(w),this.client.session.update(i,{namespaces:b}),u(w)}),{acknowledged:s}},this.extend=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(h){throw this.client.logger.error("extend() -> isValidExtend() failed"),h}const{topic:i}=r,n=co(),{done:s,resolve:a,reject:u}=Ho();return this.events.once(Dt("session_extend",n),({error:h})=>{h?u(h):a()}),await this.setExpiry(i,Ir(lc)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(h=>{u(h)}),{acknowledged:s}},this.request=async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(D){throw this.client.logger.error("request() -> isValidRequest() failed"),D}const{chainId:i,request:n,topic:s,expiry:a=Lr.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s);u?.transportType===Zt.relay&&await this.confirmOnlineStateOrThrow();const h=co(),l=Qo().toString(),{done:b,resolve:w,reject:I}=Ho(a,"Request expired. Please try again.");this.events.once(Dt("session_request",h),({error:D,result:T})=>{D?I(D):w(T)});const S=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);return S?(await this.sendRequest({clientRpcId:h,relayRpcId:l,topic:s,method:"wc_sessionRequest",params:{request:Mn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0,appLink:S}).catch(D=>I(D)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),await b()):await Promise.all([new Promise(async D=>{await this.sendRequest({clientRpcId:h,relayRpcId:l,topic:s,method:"wc_sessionRequest",params:{request:Mn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0}).catch(T=>I(T)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),D()}),new Promise(async D=>{var T;if(!((T=u.sessionConfig)!=null&&T.disableDeepLink)){const q=await sA(this.client.core.storage,V3);nA({id:h,topic:s,wcDeepLink:q})}D()}),b()]).then(D=>D[2])},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:n}=r,{id:s}=n,a=this.client.session.get(i);a.transportType===Zt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);fs(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:u}):rn(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:u}),this.cleanupAfterResponse(r)},this.ping=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=co(),s=Qo().toString(),{done:a,resolve:u,reject:h}=Ho();this.events.once(Dt("session_ping",n),({error:l})=>{l?h(l):u()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),a()])}else this.client.core.pairing.pairings.keys.includes(i)&&await this.client.core.pairing.ping({topic:i})},this.emit=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,a=Qo().toString();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:a})},this.disconnect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Gt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=Ee("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(i=>NI(i,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),a=s?Zt.link_mode:Zt.relay;a===Zt.relay&&await this.confirmOnlineStateOrThrow();const{chains:u,statement:h="",uri:l,domain:b,nonce:w,type:I,exp:S,nbf:D,methods:T=[],expiry:q}=r,K=[...r.resources||[]],{topic:F,uri:W}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:a});this.client.logger.info({message:"Generated new pairing",pairing:{topic:F,uri:W}});const R=await this.client.core.crypto.generateKeyPair(),k=bh(R);if(await Promise.all([this.client.auth.authKeys.set(Th,{responseTopic:k,publicKey:R}),this.client.auth.pairingTopics.set(k,{topic:k,pairingTopic:F})]),await this.client.core.relayer.subscribe(k,{transportType:a}),this.client.logger.info(`sending request to new pairing topic: ${F}`),T.length>0){const{namespace:O}=ou(u[0]);let M=eI(O,"request",T);mh(K)&&(M=rI(M,K.pop())),K.push(M)}const H=q&&q>Lr.wc_sessionAuthenticate.req.ttl?q:Lr.wc_sessionAuthenticate.req.ttl,_={authPayload:{type:I??"caip122",chains:u,statement:h,aud:l,domain:b,version:"1",nonce:w,iat:new Date().toISOString(),exp:S,nbf:D,resources:K},requester:{publicKey:R,metadata:this.client.metadata},expiryTimestamp:Ir(H)},B={eip155:{chains:u,methods:[...new Set(["personal_sign",...T])],events:["chainChanged","accountsChanged"]}},ee={requiredNamespaces:{},optionalNamespaces:B,relays:[{protocol:"irn"}],pairingTopic:F,proposer:{publicKey:R,metadata:this.client.metadata},expiryTimestamp:Ir(Lr.wc_sessionPropose.req.ttl)},{done:ie,resolve:L,reject:y}=Ho(H,"Request expired"),f=async({error:O,session:M})=>{if(this.events.off(Dt("session_request",v),d),O)y(O);else if(M){M.self.publicKey=R,await this.client.session.set(M.topic,M),await this.setExpiry(M.topic,M.expiry),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:M.peer.metadata});const g=this.client.session.get(M.topic);await this.deleteProposal(E),L({session:g})}},d=async O=>{var M,g,m;if(await this.deletePendingAuthRequest(v,{message:"fulfilled",code:0}),O.error){const G=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===G.code?void 0:(this.events.off(Dt("session_connect"),f),y(O.error.message))}await this.deleteProposal(E),this.events.off(Dt("session_connect"),f);const{cacaos:N,responder:X}=O.result,ae=[],P=[];for(const G of N){await sb({cacao:G,projectId:this.client.core.projectId})||(this.client.logger.error(G,"Signature verification failed"),y(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:J}=G,A=mh(J.resources),V=[nb(J.iss)],oe=vh(J.iss);if(A){const ue=cb(A),he=ub(A);ae.push(...ue),V.push(...he)}for(const ue of V)P.push(`${ue}:${oe}`)}const te=await this.client.core.crypto.generateSharedKey(R,X.publicKey);let z;ae.length>0&&(z={topic:te,acknowledged:!0,self:{publicKey:R,metadata:this.client.metadata},peer:X,controller:X.publicKey,expiry:Ir(lc),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:F,namespaces:Eb([...new Set(ae)],[...new Set(P)]),transportType:a},await this.client.core.relayer.subscribe(te,{transportType:a}),await this.client.session.set(te,z),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:X.metadata}),z=this.client.session.get(te)),(M=this.client.metadata.redirect)!=null&&M.linkMode&&(g=X.metadata.redirect)!=null&&g.linkMode&&(m=X.metadata.redirect)!=null&&m.universal&&i&&(this.client.core.addLinkModeSupportedApp(X.metadata.redirect.universal),this.client.session.update(te,{transportType:Zt.link_mode})),L({auths:N,session:z})},v=co(),E=co();this.events.once(Dt("session_connect"),f),this.events.once(Dt("session_request",v),d);let C;try{if(s){const O=uo("wc_sessionAuthenticate",_,v);this.client.core.history.set(F,O);const M=await this.client.core.crypto.encode("",O,{type:wu,encoding:bu});C=yh(i,F,M)}else await Promise.all([this.sendRequest({topic:F,method:"wc_sessionAuthenticate",params:_,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:v}),this.sendRequest({topic:F,method:"wc_sessionPropose",params:ee,expiry:Lr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E})])}catch(O){throw this.events.off(Dt("session_connect"),f),this.events.off(Dt("session_request",v),d),O}return await this.setProposal(E,pr({id:E},ee)),await this.setAuthRequest(v,{request:Mn(pr({},_),{verifyContext:{}}),pairingTopic:F,transportType:a}),{uri:C??W,response:ie}},this.approveSessionAuthenticate=async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Xo.authenticated_session_approve_started]}});try{this.isInitialized()}catch(q){throw s.setError(Tu.no_internet_connection),q}const a=this.getPendingAuthRequest(i);if(!a)throw s.setError(Tu.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const u=a.transportType||Zt.relay;u===Zt.relay&&await this.confirmOnlineStateOrThrow();const h=a.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),b=bh(h),w={type:Rs,receiverPublicKey:h,senderPublicKey:l},I=[],S=[];for(const q of n){if(!await sb({cacao:q,projectId:this.client.core.projectId})){s.setError(Tu.invalid_cacao);const k=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:b,error:k,encodeOpts:w}),new Error(k.message)}s.addTrace(Xo.cacaos_verified);const{p:K}=q,F=mh(K.resources),W=[nb(K.iss)],R=vh(K.iss);if(F){const k=cb(F),H=ub(F);I.push(...k),W.push(...H)}for(const k of W)S.push(`${k}:${R}`)}const D=await this.client.core.crypto.generateSharedKey(l,h);s.addTrace(Xo.create_authenticated_session_topic);let T;if(I?.length>0){T={topic:D,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:h,metadata:a.requester.metadata},controller:h,expiry:Ir(lc),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:a.pairingTopic,namespaces:Eb([...new Set(I)],[...new Set(S)]),transportType:u},s.addTrace(Xo.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(D,{transportType:u})}catch(q){throw s.setError(Tu.subscribe_authenticated_session_topic_failure),q}s.addTrace(Xo.subscribe_authenticated_session_topic_success),await this.client.session.set(D,T),s.addTrace(Xo.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:a.pairingTopic,metadata:a.requester.metadata})}s.addTrace(Xo.publishing_authenticated_session_approve);try{await this.sendResult({topic:b,id:i,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:w,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(a.requester.metadata,u)})}catch(q){throw s.setError(Tu.authenticated_session_approve_publish_failure),q}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:a.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:T}},this.rejectSessionAuthenticate=async r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===Zt.relay&&await this.confirmOnlineStateOrThrow();const a=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=bh(a),l={type:Rs,receiverPublicKey:a,senderPublicKey:u};await this.sendError({id:i,topic:h,error:n,encodeOpts:l,rpcOpts:Lr.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();const{request:i,iss:n}=r;return ob(i,n)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var a,u;return((a=s.peerMetadata)==null?void 0:a.url)&&((u=s.peerMetadata)==null?void 0:u.url)===r.peer.metadata.url&&s.topic&&s.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}},this.deleteSession=async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:a=!0,id:u=0}=r,{self:h}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,Gt("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(h.publicKey)&&await this.client.core.crypto.deleteKeyPair(h.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(V3).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===n&&this.deletePendingSessionRequest(l.id,Gt("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=ps.idle),a&&this.client.events.emit("session_delete",{id:u,topic:n})},this.deleteProposal=async(r,i)=>{if(i)try{const n=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s?.setError(Zo.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Gt("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=ps.idle,this.client.events.emit("session_request_expire",{id:r}))},this.deletePendingAuthRequest=async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))},this.setProposal=async(r,i)=>{this.client.core.expirer.set(r,Ir(Lr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)},this.setAuthRequest=async(r,i)=>{const{request:n,pairingTopic:s,transportType:a=Zt.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:a})},this.setPendingSessionRequest=async r=>{const{id:i,topic:n,params:s,verifyContext:a}=r,u=s.request.expiryTimestamp||Ir(Lr.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,u),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:a})},this.sendRequest=async r=>{const{topic:i,method:n,params:s,expiry:a,relayRpcId:u,clientRpcId:h,throwOnFailedPublish:l,appLink:b}=r,w=uo(n,s,h);let I;const S=!!b;try{const q=S?bu:ao;I=await this.client.core.crypto.encode(i,w,{encoding:q})}catch(q){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),q}let D;if(m$.includes(n)){const q=Ns(JSON.stringify(w)),K=Ns(I);D=await this.client.core.verify.register({id:K,decryptedId:q})}const T=Lr[n].req;if(T.attestation=D,a&&(T.ttl=a),u&&(T.id=u),this.client.core.history.set(i,w),S){const q=yh(b,i,I);await global.Linking.openURL(q,this.client.name)}else{const q=Lr[n].req;a&&(q.ttl=a),u&&(q.id=u),l?(q.internal=Mn(pr({},q.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,I,q)):this.client.core.relayer.publish(i,I,q).catch(K=>this.client.logger.error(K))}return w.id},this.sendResult=async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:a,encodeOpts:u,appLink:h}=r,l=Oh(i,s);let b;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const S=w?bu:ao;b=await this.client.core.crypto.encode(n,l,Mn(pr({},u||{}),{encoding:S}))}catch(S){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),S}let I;try{I=await this.client.core.history.get(n,i)}catch(S){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),S}if(w){const S=yh(h,n,b);await global.Linking.openURL(S,this.client.name)}else{const S=Lr[I.request.method].res;a?(S.internal=Mn(pr({},S.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,b,S)):this.client.core.relayer.publish(n,b,S).catch(D=>this.client.logger.error(D))}await this.client.core.history.resolve(l)},this.sendError=async r=>{const{id:i,topic:n,error:s,encodeOpts:a,rpcOpts:u,appLink:h}=r,l=Ph(i,s);let b;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const S=w?bu:ao;b=await this.client.core.crypto.encode(n,l,Mn(pr({},a||{}),{encoding:S}))}catch(S){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),S}let I;try{I=await this.client.core.history.get(n,i)}catch(S){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),S}if(w){const S=yh(h,n,b);await global.Linking.openURL(S,this.client.name)}else{const S=u||Lr[I.request.method].res;this.client.core.relayer.publish(n,b,S)}await this.client.core.history.resolve(l)},this.cleanup=async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;io(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{io(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===ps.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=ps.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=ps.idle},this.processRequest=async r=>{const{topic:i,payload:n,attestation:s,transportType:a,encryptedId:u}=r,h=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:h}))switch(h){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:u});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:u,transportType:a});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:u,transportType:a});default:return this.client.logger.info(`Unsupported request method ${h}`)}},this.onRelayEventResponse=async r=>{const{topic:i,payload:n,transportType:s}=r,a=(await this.client.core.history.get(i,n.id)).request.method;switch(a){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${a}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:i}=r,{message:n}=Ee("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)},this.shouldIgnorePairingRequest=r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async r=>{const{topic:i,payload:n,attestation:s,encryptedId:a}=r,{params:u,id:h}=n;try{const l=this.client.core.eventClient.getEvent({topic:i});this.isValidConnect(pr({},n.params));const b=u.expiryTimestamp||Ir(Lr.wc_sessionPropose.req.ttl),w=pr({id:h,pairingTopic:i,expiryTimestamp:b},u);await this.setProposal(h,w);const I=await this.getVerifyContext({attestationId:s,hash:Ns(JSON.stringify(n)),encryptedId:a,metadata:w.proposer.metadata});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(Bs.proposal_listener_not_found)),l?.addTrace(ds.emit_session_proposal),this.client.events.emit("session_proposal",{id:h,params:w,verifyContext:I})}catch(l){await this.sendError({id:h,topic:i,error:l,rpcOpts:Lr.wc_sessionPropose.autoReject}),this.client.logger.error(l)}},this.onSessionProposeResponse=async(r,i,n)=>{const{id:s}=i;if(fs(i)){const{result:a}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:a});const u=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:u});const h=u.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:h});const l=a.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const b=await this.client.core.crypto.generateSharedKey(h,l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:b});const w=await this.client.core.relayer.subscribe(b,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:r})}else if(rn(i)){await this.client.proposal.delete(s,Gt("USER_DISCONNECTED"));const a=Dt("session_connect");if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners, 954`);this.events.emit(Dt("session_connect"),{error:i.error})}},this.onSessionSettleRequest=async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:a,controller:u,expiry:h,namespaces:l,sessionProperties:b,sessionConfig:w}=i.params,I=Mn(pr(pr({topic:r,relay:a,expiry:h,namespaces:l,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},b&&{sessionProperties:b}),w&&{sessionConfig:w}),{transportType:Zt.relay}),S=Dt("session_connect");if(this.events.listenerCount(S)===0)throw new Error(`emitting ${S} without any listeners 997`);this.events.emit(Dt("session_connect"),{session:I}),await this.sendResult({id:i.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(a){await this.sendError({id:n,topic:r,error:a}),this.client.logger.error(a)}},this.onSessionSettleResponse=async(r,i)=>{const{id:n}=i;fs(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Dt("session_approve",n),{})):rn(i)&&(await this.client.session.delete(r,Gt("USER_DISCONNECTED")),this.events.emit(Dt("session_approve",n),{error:i.error}))},this.onSessionUpdateRequest=async(r,i)=>{const{params:n,id:s}=i;try{const a=`${r}_session_update`,u=Iu.get(a);if(u&&this.isRequestOutOfSync(u,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Gt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(pr({topic:r},n));try{Iu.set(a,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(h){throw Iu.delete(a),h}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(a){await this.sendError({id:s,topic:r,error:a}),this.client.logger.error(a)}},this.isRequestOutOfSync=(r,i)=>parseInt(i.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,i)=>{const{id:n}=i,s=Dt("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_update",n),{}):rn(i)&&this.events.emit(Dt("session_update",n),{error:i.error})},this.onSessionExtendRequest=async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Ir(lc)),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,i)=>{const{id:n}=i,s=Dt("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_extend",n),{}):rn(i)&&this.events.emit(Dt("session_extend",n),{error:i.error})},this.onSessionPingRequest=async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,i)=>{const{id:n}=i,s=Dt("session_ping",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{fs(i)?this.events.emit(Dt("session_ping",n),{}):rn(i)&&this.events.emit(Dt("session_ping",n),{error:i.error})},500)},this.onSessionDeleteRequest=async(r,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:r,reason:i.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(hi.publish,async()=>{s(await this.deleteSession({topic:r,id:n}))})}),this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Gt("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async r=>{var i,n,s;const{topic:a,payload:u,attestation:h,encryptedId:l,transportType:b}=r,{id:w,params:I}=u;try{await this.isValidRequest(pr({topic:a},I));const S=this.client.session.get(a),D=await this.getVerifyContext({attestationId:h,hash:Ns(JSON.stringify(uo("wc_sessionRequest",I,w))),encryptedId:l,metadata:S.peer.metadata,transportType:b}),T={id:w,topic:a,params:I,verifyContext:D};await this.setPendingSessionRequest(T),b===Zt.link_mode&&(i=S.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=S.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(T):(this.addSessionRequestToSessionRequestQueue(T),this.processSessionRequestQueue())}catch(S){await this.sendError({id:w,topic:a,error:S}),this.client.logger.error(S)}},this.onSessionRequestResponse=(r,i)=>{const{id:n}=i,s=Dt("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):rn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionEventRequest=async(r,i)=>{const{id:n,params:s}=i;try{const a=`${r}_session_event_${s.event.name}`,u=Iu.get(a);if(u&&this.isRequestOutOfSync(u,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(pr({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Iu.set(a,n)}catch(a){await this.sendError({id:n,topic:r,error:a}),this.client.logger.error(a)}},this.onSessionAuthenticateResponse=(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),fs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):rn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionAuthenticateRequest=async r=>{var i;const{topic:n,payload:s,attestation:a,encryptedId:u,transportType:h}=r;try{const{requester:l,authPayload:b,expiryTimestamp:w}=s.params,I=await this.getVerifyContext({attestationId:a,hash:Ns(JSON.stringify(s)),encryptedId:u,metadata:l.metadata,transportType:h}),S={requester:l,pairingTopic:n,id:s.id,authPayload:b,verifyContext:I,expiryTimestamp:w};await this.setAuthRequest(s.id,{request:S,pairingTopic:n,transportType:h}),h===Zt.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:I})}catch(l){this.client.logger.error(l);const b=s.params.requester.publicKey,w=await this.client.core.crypto.generateKeyPair(),I=this.getAppLinkIfEnabled(s.params.requester.metadata,h),S={type:Rs,receiverPublicKey:b,senderPublicKey:w};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:S,rpcOpts:Lr.wc_sessionAuthenticate.autoReject,appLink:I})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ps.idle,this.processSessionRequestQueue()},xe.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const a=s.request.id,u=Dt("session_request",a);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(Dt("session_request",s.request.id),{error:i})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===ps.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=ps.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}},this.emitSessionRequest=r=>{this.client.events.emit("session_request",r)},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:uo("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})},this.isValidConnect=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(h)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:a,relays:u}=r;if(ci(i)||await this.isValidPairingTopic(i),!WI(u,!0)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(h)}!ci(n)&&Su(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!ci(s)&&Su(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ci(a)||this.validateSessionProps(a,"sessionProperties")},this.validateNamespaces=(r,i)=>{const n=KI(r,"connect()",i);if(n)throw new Error(n.message)},this.isValidApprove=async r=>{if(!_i(r))throw new Error(Ee("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const u=this.client.proposal.get(i),h=Fd(n,"approve()");if(h)throw new Error(h.message);const l=Mb(u.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!yr(s,!0)){const{message:b}=Ee("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(b)}ci(a)||this.validateSessionProps(a,"sessionProperties")},this.isValidReject=async r=>{if(!_i(r)){const{message:s}=Ee("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!GI(n)){const{message:s}=Ee("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!_i(r)){const{message:l}=Ee("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:a}=r;if(!Sb(i)){const{message:l}=Ee("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const u=UI(n,"onSessionSettleRequest()");if(u)throw new Error(u.message);const h=Fd(s,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(io(a)){const{message:l}=Ee("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(h)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),a=Fd(n,"update()");if(a)throw new Error(a.message);const u=Mb(s.requiredNamespaces,n,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)},this.isValidRequest=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(h)}const{topic:i,request:n,chainId:s,expiry:a}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:u}=this.client.session.get(i);if(!Ib(u,s)){const{message:h}=Ee("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(h)}if(!JI(n)){const{message:h}=Ee("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(h)}if(!ZI(u,s,n.method)){const{message:h}=Ee("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(h)}if(a&&!rM(a,u1)){const{message:h}=Ee("MISSING_OR_INVALID",`request() expiry: ${a}. Expiry must be a number (in seconds) between ${u1.min} and ${u1.max}`);throw new Error(h)}},this.isValidRespond=async r=>{var i;if(!_i(r)){const{message:a}=Ee("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(a){throw(i=r?.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!YI(s)){const{message:a}=Ee("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidPing=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)},this.isValidEmit=async r=>{if(!_i(r)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(u)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!Ib(a,s)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!QI(n)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(u)}if(!XI(a,s,n.name)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(u)}},this.isValidDisconnect=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)},this.isValidAuthenticate=r=>{const{chains:i,uri:n,domain:s,nonce:a}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!yr(n,!1))throw new Error("uri is required parameter");if(!yr(s,!1))throw new Error("domain is required parameter");if(!yr(a,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(h=>ou(h).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:u}=ou(i[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:a,transportType:u}=r,h={verified:{verifyUrl:a.verifyUrl||Nu,validation:"UNKNOWN",origin:a.url||""}};try{if(u===Zt.link_mode){const b=this.getAppLinkIfEnabled(a,u);return h.verified.validation=b&&new URL(b).origin===new URL(a.url).origin?"VALID":"INVALID",h}const l=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:a.verifyUrl});l&&(h.verified.origin=l.origin,h.verified.isScam=l.isScam,h.verified.validation=l.origin===new URL(a.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(h)}`),h},this.validateSessionProps=(r,i)=>{Object.values(r).forEach(n=>{if(!yr(n,!1)){const{message:s}=Ee("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(n)}`);throw new Error(s)}})},this.getPendingAuthRequest=r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0},this.addToRecentlyDeleted=(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const a of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(a)}}},this.checkRecentlyDeleted=r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=Ee("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}},this.isLinkModeEnabled=(r,i)=>{var n,s,a,u,h,l,b,w,I;return!r||i!==Zt.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((u=(a=this.client.metadata)==null?void 0:a.redirect)==null?void 0:u.universal)!==void 0&&((l=(h=this.client.metadata)==null?void 0:h.redirect)==null?void 0:l.universal)!==""&&((b=r?.redirect)==null?void 0:b.universal)!==void 0&&((w=r?.redirect)==null?void 0:w.universal)!==""&&((I=r?.redirect)==null?void 0:I.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"},this.getAppLinkIfEnabled=(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r?.redirect)==null?void 0:n.universal:void 0},this.handleLinkModeMessage=({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Y2(r,"topic")||"",n=decodeURIComponent(Y2(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:Zt.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})},this.registerLinkModeListeners=async()=>{var r;if(ad()||Va()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(hi.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:n,transportType:s}=e,{publicKey:a}=this.client.auth.authKeys.keys.includes(Th)?this.client.auth.authKeys.get(Th):{responseTopic:void 0,publicKey:void 0},u=await this.client.core.crypto.decode(r,i,{receiverPublicKey:a,encoding:s===Zt.link_mode?bu:ao});try{Zd(u)?(this.client.core.history.set(r,u),this.onRelayEventRequest({topic:r,payload:u,attestation:n,transportType:s,encryptedId:Ns(i)})):$h(u)?(await this.client.core.history.resolve(u),await this.onRelayEventResponse({topic:r,payload:u,transportType:s}),this.client.core.history.delete(r,u.id)):this.onRelayEventUnknownPayload({topic:r,payload:u,transportType:s})}catch(h){this.client.logger.error(h)}}registerExpirerEvents(){this.client.core.expirer.on(sn.expired,async e=>{const{topic:r,id:i}=J2(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,Ee("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,Ee("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(fc.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(fc.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!yr(e,!1)){const{message:r}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=Ee("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!yr(e,!1)){const{message:r}=Ee("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=Ee("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=Ee("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(yr(e,!1)){const{message:r}=Ee("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=Ee("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!VI(e)){const{message:r}=Ee("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=Ee("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class D$ extends ea{constructor(e,r){super(e,r,d$,a1),this.core=e,this.logger=r}}class O$ extends ea{constructor(e,r){super(e,r,p$,a1),this.core=e,this.logger=r}}class P$ extends ea{constructor(e,r){super(e,r,v$,a1,i=>i.id),this.core=e,this.logger=r}}class $$ extends ea{constructor(e,r){super(e,r,w$,Nh,()=>Th),this.core=e,this.logger=r}}class R$ extends ea{constructor(e,r){super(e,r,_$,Nh),this.core=e,this.logger=r}}class N$ extends ea{constructor(e,r){super(e,r,E$,Nh,i=>i.id),this.core=e,this.logger=r}}class T${constructor(e,r){this.core=e,this.logger=r,this.authKeys=new $$(this.core,this.logger),this.pairingTopics=new R$(this.core,this.logger),this.requests=new N$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class f1 extends SC{constructor(e){super(e),this.protocol=H3,this.version=K3,this.name=c1.name,this.events=new kr.exports.EventEmitter,this.on=(i,n)=>this.events.on(i,n),this.once=(i,n)=>this.events.once(i,n),this.off=(i,n)=>this.events.off(i,n),this.removeListener=(i,n)=>this.events.removeListener(i,n),this.removeAllListeners=i=>this.events.removeAllListeners(i),this.connect=async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}},this.pair=async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}},this.approve=async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}},this.reject=async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}},this.update=async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}},this.extend=async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}},this.request=async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}},this.respond=async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}},this.ping=async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}},this.emit=async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}},this.disconnect=async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}},this.find=i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}},this.authenticate=async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}},this.formatAuthMessage=i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}},this.approveSessionAuthenticate=async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.rejectSessionAuthenticate=async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||c1.name,this.metadata=e?.metadata||H2(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:cs(Dh({level:e?.logger||c1.logger}));this.core=e?.core||new l$(e),this.logger=ui(r,this.name),this.session=new O$(this.core,this.logger),this.proposal=new D$(this.core,this.logger),this.pendingRequest=new P$(this.core,this.logger),this.engine=new C$(this),this.auth=new T$(this.core,this.logger)}static async init(e){const r=new f1(e);return await r.initialize(),r}get context(){return Ai(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(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var h1={exports:{}};(function(t,e){var r=typeof self<"u"?self:Vr,i=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(a){var u={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function h(d){return d&&DataView.prototype.isPrototypeOf(d)}if(u.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],b=ArrayBuffer.isView||function(d){return d&&l.indexOf(Object.prototype.toString.call(d))>-1};function w(d){if(typeof d!="string"&&(d=String(d)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(d))throw new TypeError("Invalid character in header field name");return d.toLowerCase()}function I(d){return typeof d!="string"&&(d=String(d)),d}function S(d){var v={next:function(){var E=d.shift();return{done:E===void 0,value:E}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function D(d){this.map={},d instanceof D?d.forEach(function(v,E){this.append(E,v)},this):Array.isArray(d)?d.forEach(function(v){this.append(v[0],v[1])},this):d&&Object.getOwnPropertyNames(d).forEach(function(v){this.append(v,d[v])},this)}D.prototype.append=function(d,v){d=w(d),v=I(v);var E=this.map[d];this.map[d]=E?E+", "+v:v},D.prototype.delete=function(d){delete this.map[w(d)]},D.prototype.get=function(d){return d=w(d),this.has(d)?this.map[d]:null},D.prototype.has=function(d){return this.map.hasOwnProperty(w(d))},D.prototype.set=function(d,v){this.map[w(d)]=I(v)},D.prototype.forEach=function(d,v){for(var E in this.map)this.map.hasOwnProperty(E)&&d.call(v,this.map[E],E,this)},D.prototype.keys=function(){var d=[];return this.forEach(function(v,E){d.push(E)}),S(d)},D.prototype.values=function(){var d=[];return this.forEach(function(v){d.push(v)}),S(d)},D.prototype.entries=function(){var d=[];return this.forEach(function(v,E){d.push([E,v])}),S(d)},u.iterable&&(D.prototype[Symbol.iterator]=D.prototype.entries);function T(d){if(d.bodyUsed)return Promise.reject(new TypeError("Already read"));d.bodyUsed=!0}function q(d){return new Promise(function(v,E){d.onload=function(){v(d.result)},d.onerror=function(){E(d.error)}})}function K(d){var v=new FileReader,E=q(v);return v.readAsArrayBuffer(d),E}function F(d){var v=new FileReader,E=q(v);return v.readAsText(d),E}function W(d){for(var v=new Uint8Array(d),E=new Array(v.length),C=0;C<v.length;C++)E[C]=String.fromCharCode(v[C]);return E.join("")}function R(d){if(d.slice)return d.slice(0);var v=new Uint8Array(d.byteLength);return v.set(new Uint8Array(d)),v.buffer}function k(){return this.bodyUsed=!1,this._initBody=function(d){this._bodyInit=d,d?typeof d=="string"?this._bodyText=d:u.blob&&Blob.prototype.isPrototypeOf(d)?this._bodyBlob=d:u.formData&&FormData.prototype.isPrototypeOf(d)?this._bodyFormData=d:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(d)?this._bodyText=d.toString():u.arrayBuffer&&u.blob&&h(d)?(this._bodyArrayBuffer=R(d.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(d)||b(d))?this._bodyArrayBuffer=R(d):this._bodyText=d=Object.prototype.toString.call(d):this._bodyText="",this.headers.get("content-type")||(typeof d=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(d)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var d=T(this);if(d)return d;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?T(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(K)}),this.text=function(){var d=T(this);if(d)return d;if(this._bodyBlob)return F(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(W(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(ee)}),this.json=function(){return this.text().then(JSON.parse)},this}var H=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function _(d){var v=d.toUpperCase();return H.indexOf(v)>-1?v:d}function B(d,v){v=v||{};var E=v.body;if(d instanceof B){if(d.bodyUsed)throw new TypeError("Already read");this.url=d.url,this.credentials=d.credentials,v.headers||(this.headers=new D(d.headers)),this.method=d.method,this.mode=d.mode,this.signal=d.signal,!E&&d._bodyInit!=null&&(E=d._bodyInit,d.bodyUsed=!0)}else this.url=String(d);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new D(v.headers)),this.method=_(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}B.prototype.clone=function(){return new B(this,{body:this._bodyInit})};function ee(d){var v=new FormData;return d.trim().split("&").forEach(function(E){if(E){var C=E.split("="),O=C.shift().replace(/\+/g," "),M=C.join("=").replace(/\+/g," ");v.append(decodeURIComponent(O),decodeURIComponent(M))}}),v}function ie(d){var v=new D,E=d.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var O=C.split(":"),M=O.shift().trim();if(M){var g=O.join(":").trim();v.append(M,g)}}),v}k.call(B.prototype);function L(d,v){v||(v={}),this.type="default",this.status=v.status===void 0?200:v.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in v?v.statusText:"OK",this.headers=new D(v.headers),this.url=v.url||"",this._initBody(d)}k.call(L.prototype),L.prototype.clone=function(){return new L(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new D(this.headers),url:this.url})},L.error=function(){var d=new L(null,{status:0,statusText:""});return d.type="error",d};var y=[301,302,303,307,308];L.redirect=function(d,v){if(y.indexOf(v)===-1)throw new RangeError("Invalid status code");return new L(null,{status:v,headers:{location:d}})},a.DOMException=s.DOMException;try{new a.DOMException}catch{a.DOMException=function(v,E){this.message=v,this.name=E;var C=Error(v);this.stack=C.stack},a.DOMException.prototype=Object.create(Error.prototype),a.DOMException.prototype.constructor=a.DOMException}function f(d,v){return new Promise(function(E,C){var O=new B(d,v);if(O.signal&&O.signal.aborted)return C(new a.DOMException("Aborted","AbortError"));var M=new XMLHttpRequest;function g(){M.abort()}M.onload=function(){var m={status:M.status,statusText:M.statusText,headers:ie(M.getAllResponseHeaders()||"")};m.url="responseURL"in M?M.responseURL:m.headers.get("X-Request-URL");var N="response"in M?M.response:M.responseText;E(new L(N,m))},M.onerror=function(){C(new TypeError("Network request failed"))},M.ontimeout=function(){C(new TypeError("Network request failed"))},M.onabort=function(){C(new a.DOMException("Aborted","AbortError"))},M.open(O.method,O.url,!0),O.credentials==="include"?M.withCredentials=!0:O.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&u.blob&&(M.responseType="blob"),O.headers.forEach(function(m,N){M.setRequestHeader(N,m)}),O.signal&&(O.signal.addEventListener("abort",g),M.onreadystatechange=function(){M.readyState===4&&O.signal.removeEventListener("abort",g)}),M.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return f.polyfill=!0,s.fetch||(s.fetch=f,s.Headers=D,s.Request=B,s.Response=L),a.Headers=D,a.Request=B,a.Response=L,a.fetch=f,Object.defineProperty(a,"__esModule",{value:!0}),a})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=i;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,t.exports=e})(h1,h1.exports);var Q3=V5(h1.exports),L$=Object.defineProperty,B$=Object.defineProperties,F$=Object.getOwnPropertyDescriptors,Z3=Object.getOwnPropertySymbols,U$=Object.prototype.hasOwnProperty,k$=Object.prototype.propertyIsEnumerable,X3=(t,e,r)=>e in t?L$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,e6=(t,e)=>{for(var r in e||(e={}))U$.call(e,r)&&X3(t,r,e[r]);if(Z3)for(var r of Z3(e))k$.call(e,r)&&X3(t,r,e[r]);return t},t6=(t,e)=>B$(t,F$(e));const q$={Accept:"application/json","Content-Type":"application/json"},j$="POST",r6={headers:q$,method:j$},i6=10;class gs{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new kr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!t3(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=Cs(e),i=await(await Q3(this.url,t6(e6({},r6),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!t3(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=Cs({id:1,jsonrpc:"2.0",method:"test",params:[]});await Q3(e,t6(e6({},r6),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?jo(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Ph(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Jb(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>i6&&this.events.setMaxListeners(i6)}}const n6="error",z$="wss://relay.walletconnect.org",H$="wc",K$="universal_provider",s6=`${H$}@2:${K$}:`,o6="https://rpc.walletconnect.org/v1/",dc="generic",W$=`${o6}bundler`,Cn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Uu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},l1={exports:{}};/**
|
|
44
44
|
* @license
|
|
45
45
|
* Lodash <https://lodash.com/>
|
|
46
46
|
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
|
|
@@ -66,7 +66,7 @@ __p += '`),Ut&&(ge+=`' +
|
|
|
66
66
|
function print() { __p += __j.call(arguments, '') }
|
|
67
67
|
`:`;
|
|
68
68
|
`)+ge+`return __p
|
|
69
|
-
}`;var St=H5(function(){return Ht(j,Je+"return "+ge).apply(r,Q)});if(St.source=ge,Ig(St))throw St;return St}function Vz(o){return Vt(o).toLowerCase()}function Gz(o){return Vt(o).toUpperCase()}function Jz(o,c,p){if(o=Vt(o),o&&(p||c===r))return Xy(o);if(!o||!(c=Hi(c)))return o;var x=Bn(o),$=Bn(c),j=ew(x,$),Q=tw(x,$)+1;return Po(x,j,Q).join("")}function Yz(o,c,p){if(o=Vt(o),o&&(p||c===r))return o.slice(0,iw(o)+1);if(!o||!(c=Hi(c)))return o;var x=Bn(o),$=tw(x,Bn(c))+1;return Po(x,0,$).join("")}function Qz(o,c,p){if(o=Vt(o),o&&(p||c===r))return o.replace(st,"");if(!o||!(c=Hi(c)))return o;var x=Bn(o),$=ew(x,Bn(c));return Po(x,$).join("")}function Zz(o,c){var p=ie,x=L;if(hr(c)){var $="separator"in c?c.separator:$;p="length"in c?xt(c.length):p,x="omission"in c?Hi(c.omission):x}o=Vt(o);var j=o.length;if(Bc(o)){var Q=Bn(o);j=Q.length}if(p>=j)return o;var Z=p-Fc(x);if(Z<1)return x;var se=Q?Po(Q,0,Z).join(""):o.slice(0,Z);if($===r)return se+x;if(Q&&(Z+=se.length-Z),Mg($)){if(o.slice(Z).search($)){var le,de=se;for($.global||($=zp($.source,Vt(_t.exec($))+"g")),$.lastIndex=0;le=$.exec(de);)var ge=le.index;se=se.slice(0,ge===r?Z:ge)}}else if(o.indexOf(Hi($),Z)!=Z){var De=se.lastIndexOf($);De>-1&&(se=se.slice(0,De))}return se+x}function Xz(o){return o=Vt(o),o&&Le.test(o)?o.replace(Ot,CF):o}var eH=Kc(function(o,c,p){return o+(p?" ":"")+c.toUpperCase()}),Og=Kw("toUpperCase");function z5(o,c,p){return o=Vt(o),c=p?r:c,c===r?AF(o)?PF(o):pF(o):o.match(c)||[]}var H5=Mt(function(o,c){try{return Fr(o,r,c)}catch(p){return Ig(p)?p:new vt(p)}}),tH=Ws(function(o,c){return fn(c,function(p){p=xs(p),Hs(o,p,xg(o[p],o))}),o});function rH(o){var c=o==null?0:o.length,p=ot();return o=c?ur(o,function(x){if(typeof x[1]!="function")throw new hn(a);return[p(x[0]),x[1]]}):[],Mt(function(x){for(var $=-1;++$<c;){var j=o[$];if(Fr(j[0],this,x))return Fr(j[1],this,x)}})}function iH(o){return CU(dn(o,w))}function Pg(o){return function(){return o}}function nH(o,c){return o==null||o!==o?c:o}var sH=Vw(),oH=Vw(!0);function Ri(o){return o}function $g(o){return Aw(typeof o=="function"?o:dn(o,w))}function aH(o){return Sw(dn(o,w))}function cH(o,c){return Iw(o,dn(c,w))}var uH=Mt(function(o,c){return function(p){return bf(p,o,c)}}),fH=Mt(function(o,c){return function(p){return bf(o,p,c)}});function Rg(o,c,p){var x=Ur(c),$=Ql(c,x);p==null&&!(hr(c)&&($.length||!x.length))&&(p=c,c=o,o=this,$=Ql(c,Ur(c)));var j=!(hr(p)&&"chain"in p)||!!p.chain,Q=Gs(o);return fn($,function(Z){var se=c[Z];o[Z]=se,Q&&(o.prototype[Z]=function(){var le=this.__chain__;if(j||le){var de=o(this.__wrapped__),ge=de.__actions__=Oi(this.__actions__);return ge.push({func:se,args:arguments,thisArg:o}),de.__chain__=le,de}return se.apply(o,So([this.value()],arguments))})}),o}function hH(){return Ft._===this&&(Ft._=BF),this}function Ng(){}function lH(o){return o=xt(o),Mt(function(c){return Mw(c,o)})}var dH=hg(ur),pH=hg(Gy),gH=hg(Lp);function K5(o){return bg(o)?Bp(xs(o)):KU(o)}function vH(o){return function(c){return o==null?r:Ia(o,c)}}var mH=Jw(),bH=Jw(!0);function Tg(){return[]}function Lg(){return!1}function yH(){return{}}function wH(){return""}function _H(){return!0}function EH(o,c){if(o=xt(o),o<1||o>O)return[];var p=m,x=ii(o,m);c=ot(c),o-=m;for(var $=kp(x,c);++p<o;)c(p);return $}function AH(o){return yt(o)?ur(o,xs):Ki(o)?[o]:Oi(h5(Vt(o)))}function xH(o){var c=++TF;return Vt(o)+c}var SH=i0(function(o,c){return o+c},0),IH=lg("ceil"),MH=i0(function(o,c){return o/c},1),CH=lg("floor");function DH(o){return o&&o.length?Yl(o,Ri,Qp):r}function OH(o,c){return o&&o.length?Yl(o,ot(c,2),Qp):r}function PH(o){return Qy(o,Ri)}function $H(o,c){return Qy(o,ot(c,2))}function RH(o){return o&&o.length?Yl(o,Ri,tg):r}function NH(o,c){return o&&o.length?Yl(o,ot(c,2),tg):r}var TH=i0(function(o,c){return o*c},1),LH=lg("round"),BH=i0(function(o,c){return o-c},0);function FH(o){return o&&o.length?Up(o,Ri):0}function UH(o,c){return o&&o.length?Up(o,ot(c,2)):0}return U.after=aj,U.ary=E5,U.assign=Gj,U.assignIn=L5,U.assignInWith=v0,U.assignWith=Jj,U.at=Yj,U.before=A5,U.bind=xg,U.bindAll=tH,U.bindKey=x5,U.castArray=yj,U.chain=y5,U.chunk=Ck,U.compact=Dk,U.concat=Ok,U.cond=rH,U.conforms=iH,U.constant=Pg,U.countBy=Fq,U.create=Qj,U.curry=S5,U.curryRight=I5,U.debounce=M5,U.defaults=Zj,U.defaultsDeep=Xj,U.defer=cj,U.delay=uj,U.difference=Pk,U.differenceBy=$k,U.differenceWith=Rk,U.drop=Nk,U.dropRight=Tk,U.dropRightWhile=Lk,U.dropWhile=Bk,U.fill=Fk,U.filter=kq,U.flatMap=zq,U.flatMapDeep=Hq,U.flatMapDepth=Kq,U.flatten=g5,U.flattenDeep=Uk,U.flattenDepth=kk,U.flip=fj,U.flow=sH,U.flowRight=oH,U.fromPairs=qk,U.functions=oz,U.functionsIn=az,U.groupBy=Wq,U.initial=zk,U.intersection=Hk,U.intersectionBy=Kk,U.intersectionWith=Wk,U.invert=uz,U.invertBy=fz,U.invokeMap=Gq,U.iteratee=$g,U.keyBy=Jq,U.keys=Ur,U.keysIn=$i,U.map=f0,U.mapKeys=lz,U.mapValues=dz,U.matches=aH,U.matchesProperty=cH,U.memoize=l0,U.merge=pz,U.mergeWith=B5,U.method=uH,U.methodOf=fH,U.mixin=Rg,U.negate=d0,U.nthArg=lH,U.omit=gz,U.omitBy=vz,U.once=hj,U.orderBy=Yq,U.over=dH,U.overArgs=lj,U.overEvery=pH,U.overSome=gH,U.partial=Sg,U.partialRight=C5,U.partition=Qq,U.pick=mz,U.pickBy=F5,U.property=K5,U.propertyOf=vH,U.pull=Yk,U.pullAll=m5,U.pullAllBy=Qk,U.pullAllWith=Zk,U.pullAt=Xk,U.range=mH,U.rangeRight=bH,U.rearg=dj,U.reject=ej,U.remove=eq,U.rest=pj,U.reverse=Eg,U.sampleSize=rj,U.set=yz,U.setWith=wz,U.shuffle=ij,U.slice=tq,U.sortBy=oj,U.sortedUniq=cq,U.sortedUniqBy=uq,U.split=zz,U.spread=gj,U.tail=fq,U.take=hq,U.takeRight=lq,U.takeRightWhile=dq,U.takeWhile=pq,U.tap=Dq,U.throttle=vj,U.thru=u0,U.toArray=R5,U.toPairs=U5,U.toPairsIn=k5,U.toPath=AH,U.toPlainObject=T5,U.transform=_z,U.unary=mj,U.union=gq,U.unionBy=vq,U.unionWith=mq,U.uniq=bq,U.uniqBy=yq,U.uniqWith=wq,U.unset=Ez,U.unzip=Ag,U.unzipWith=b5,U.update=Az,U.updateWith=xz,U.values=Gc,U.valuesIn=Sz,U.without=_q,U.words=z5,U.wrap=bj,U.xor=Eq,U.xorBy=Aq,U.xorWith=xq,U.zip=Sq,U.zipObject=Iq,U.zipObjectDeep=Mq,U.zipWith=Cq,U.entries=U5,U.entriesIn=k5,U.extend=L5,U.extendWith=v0,Rg(U,U),U.add=SH,U.attempt=H5,U.camelCase=Dz,U.capitalize=q5,U.ceil=IH,U.clamp=Iz,U.clone=wj,U.cloneDeep=Ej,U.cloneDeepWith=Aj,U.cloneWith=_j,U.conformsTo=xj,U.deburr=j5,U.defaultTo=nH,U.divide=MH,U.endsWith=Oz,U.eq=Un,U.escape=Pz,U.escapeRegExp=$z,U.every=Uq,U.find=qq,U.findIndex=d5,U.findKey=ez,U.findLast=jq,U.findLastIndex=p5,U.findLastKey=tz,U.floor=CH,U.forEach=w5,U.forEachRight=_5,U.forIn=rz,U.forInRight=iz,U.forOwn=nz,U.forOwnRight=sz,U.get=Cg,U.gt=Sj,U.gte=Ij,U.has=cz,U.hasIn=Dg,U.head=v5,U.identity=Ri,U.includes=Vq,U.indexOf=jk,U.inRange=Mz,U.invoke=hz,U.isArguments=Da,U.isArray=yt,U.isArrayBuffer=Mj,U.isArrayLike=Pi,U.isArrayLikeObject=Er,U.isBoolean=Cj,U.isBuffer=$o,U.isDate=Dj,U.isElement=Oj,U.isEmpty=Pj,U.isEqual=$j,U.isEqualWith=Rj,U.isError=Ig,U.isFinite=Nj,U.isFunction=Gs,U.isInteger=D5,U.isLength=p0,U.isMap=O5,U.isMatch=Tj,U.isMatchWith=Lj,U.isNaN=Bj,U.isNative=Fj,U.isNil=kj,U.isNull=Uj,U.isNumber=P5,U.isObject=hr,U.isObjectLike=mr,U.isPlainObject=xf,U.isRegExp=Mg,U.isSafeInteger=qj,U.isSet=$5,U.isString=g0,U.isSymbol=Ki,U.isTypedArray=Vc,U.isUndefined=jj,U.isWeakMap=zj,U.isWeakSet=Hj,U.join=Vk,U.kebabCase=Rz,U.last=gn,U.lastIndexOf=Gk,U.lowerCase=Nz,U.lowerFirst=Tz,U.lt=Kj,U.lte=Wj,U.max=DH,U.maxBy=OH,U.mean=PH,U.meanBy=$H,U.min=RH,U.minBy=NH,U.stubArray=Tg,U.stubFalse=Lg,U.stubObject=yH,U.stubString=wH,U.stubTrue=_H,U.multiply=TH,U.nth=Jk,U.noConflict=hH,U.noop=Ng,U.now=h0,U.pad=Lz,U.padEnd=Bz,U.padStart=Fz,U.parseInt=Uz,U.random=Cz,U.reduce=Zq,U.reduceRight=Xq,U.repeat=kz,U.replace=qz,U.result=bz,U.round=LH,U.runInContext=ne,U.sample=tj,U.size=nj,U.snakeCase=jz,U.some=sj,U.sortedIndex=rq,U.sortedIndexBy=iq,U.sortedIndexOf=nq,U.sortedLastIndex=sq,U.sortedLastIndexBy=oq,U.sortedLastIndexOf=aq,U.startCase=Hz,U.startsWith=Kz,U.subtract=BH,U.sum=FH,U.sumBy=UH,U.template=Wz,U.times=EH,U.toFinite=Js,U.toInteger=xt,U.toLength=N5,U.toLower=Vz,U.toNumber=vn,U.toSafeInteger=Vj,U.toString=Vt,U.toUpper=Gz,U.trim=Jz,U.trimEnd=Yz,U.trimStart=Qz,U.truncate=Zz,U.unescape=Xz,U.uniqueId=xH,U.upperCase=eH,U.upperFirst=Og,U.each=w5,U.eachRight=_5,U.first=v5,Rg(U,function(){var o={};return Es(U,function(c,p){Jt.call(U.prototype,p)||(o[p]=c)}),o}(),{chain:!1}),U.VERSION=i,fn(["bind","bindKey","curry","curryRight","partial","partialRight"],function(o){U[o].placeholder=U}),fn(["drop","take"],function(o,c){Lt.prototype[o]=function(p){p=p===r?1:Or(xt(p),0);var x=this.__filtered__&&!c?new Lt(this):this.clone();return x.__filtered__?x.__takeCount__=ii(p,x.__takeCount__):x.__views__.push({size:ii(p,m),type:o+(x.__dir__<0?"Right":"")}),x},Lt.prototype[o+"Right"]=function(p){return this.reverse()[o](p).reverse()}}),fn(["filter","map","takeWhile"],function(o,c){var p=c+1,x=p==d||p==E;Lt.prototype[o]=function($){var j=this.clone();return j.__iteratees__.push({iteratee:ot($,3),type:p}),j.__filtered__=j.__filtered__||x,j}}),fn(["head","last"],function(o,c){var p="take"+(c?"Right":"");Lt.prototype[o]=function(){return this[p](1).value()[0]}}),fn(["initial","tail"],function(o,c){var p="drop"+(c?"":"Right");Lt.prototype[o]=function(){return this.__filtered__?new Lt(this):this[p](1)}}),Lt.prototype.compact=function(){return this.filter(Ri)},Lt.prototype.find=function(o){return this.filter(o).head()},Lt.prototype.findLast=function(o){return this.reverse().find(o)},Lt.prototype.invokeMap=Mt(function(o,c){return typeof o=="function"?new Lt(this):this.map(function(p){return bf(p,o,c)})}),Lt.prototype.reject=function(o){return this.filter(d0(ot(o)))},Lt.prototype.slice=function(o,c){o=xt(o);var p=this;return p.__filtered__&&(o>0||c<0)?new Lt(p):(o<0?p=p.takeRight(-o):o&&(p=p.drop(o)),c!==r&&(c=xt(c),p=c<0?p.dropRight(-c):p.take(c-o)),p)},Lt.prototype.takeRightWhile=function(o){return this.reverse().takeWhile(o).reverse()},Lt.prototype.toArray=function(){return this.take(m)},Es(Lt.prototype,function(o,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),x=/^(?:head|last)$/.test(c),$=U[x?"take"+(c=="last"?"Right":""):c],j=x||/^find/.test(c);$&&(U.prototype[c]=function(){var Q=this.__wrapped__,Z=x?[1]:arguments,se=Q instanceof Lt,le=Z[0],de=se||yt(Q),ge=function(Pt){var Ut=$.apply(U,So([Pt],Z));return x&&De?Ut[0]:Ut};de&&p&&typeof le=="function"&&le.length!=1&&(se=de=!1);var De=this.__chain__,Je=!!this.__actions__.length,ut=j&&!De,St=se&&!Je;if(!j&&de){Q=St?Q:new Lt(this);var ft=o.apply(Q,Z);return ft.__actions__.push({func:u0,args:[ge],thisArg:r}),new ln(ft,De)}return ut&&St?o.apply(this,Z):(ft=this.thru(ge),ut?x?ft.value()[0]:ft.value():ft)})}),fn(["pop","push","shift","sort","splice","unshift"],function(o){var c=Tl[o],p=/^(?:push|sort|unshift)$/.test(o)?"tap":"thru",x=/^(?:pop|shift)$/.test(o);U.prototype[o]=function(){var $=arguments;if(x&&!this.__chain__){var j=this.value();return c.apply(yt(j)?j:[],$)}return this[p](function(Q){return c.apply(yt(Q)?Q:[],$)})}}),Es(Lt.prototype,function(o,c){var p=U[c];if(p){var x=p.name+"";Jt.call(jc,x)||(jc[x]=[]),jc[x].push({name:c,func:p})}}),jc[r0(r,K).name]=[{name:"wrapper",func:r}],Lt.prototype.clone=XF,Lt.prototype.reverse=eU,Lt.prototype.value=tU,U.prototype.at=Oq,U.prototype.chain=Pq,U.prototype.commit=$q,U.prototype.next=Rq,U.prototype.plant=Tq,U.prototype.reverse=Lq,U.prototype.toJSON=U.prototype.valueOf=U.prototype.value=Bq,U.prototype.first=U.prototype.head,hf&&(U.prototype[hf]=Nq),U},Uc=$F();_r?((_r.exports=Uc)._=Uc,tr._=Uc):Ft._=Uc}).call(Uu)})(l1,l1.exports);var V$=Object.defineProperty,G$=Object.defineProperties,J$=Object.getOwnPropertyDescriptors,a6=Object.getOwnPropertySymbols,Y$=Object.prototype.hasOwnProperty,Q$=Object.prototype.propertyIsEnumerable,c6=(t,e,r)=>e in t?V$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lh=(t,e)=>{for(var r in e||(e={}))Y$.call(e,r)&&c6(t,r,e[r]);if(a6)for(var r of a6(e))Q$.call(e,r)&&c6(t,r,e[r]);return t},Z$=(t,e)=>G$(t,J$(e));function Dn(t,e,r){var i;const n=ou(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${o6}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function ra(t){return t.includes(":")?t.split(":")[1]:t}function u6(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function X$(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function d1(t={},e={}){const r=f6(t),i=f6(e);return l1.exports.merge(r,i)}function f6(t){var e,r,i,n;const s={};if(!Su(t))return s;for(const[a,u]of Object.entries(t)){const h=Ld(a)?[a]:u.chains,l=u.methods||[],b=u.events||[],w=u.rpcMap||{},I=xu(a);s[I]=Z$(Lh(Lh({},s[I]),u),{chains:rh(h,(e=s[I])==null?void 0:e.chains),methods:rh(l,(r=s[I])==null?void 0:r.methods),events:rh(b,(i=s[I])==null?void 0:i.events),rpcMap:Lh(Lh({},w),(n=s[I])==null?void 0:n.rpcMap)})}return s}function eR(t){return t.includes(":")?t.split(":")[2]:t}function h6(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],a=i.accounts||[],u=Ld(r)?[r]:i.chains?i.chains:u6(i.accounts);e[r]={chains:u,methods:n,events:s,accounts:a}}return e}function p1(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const l6={},Kt=t=>l6[t],g1=(t,e)=>{l6[t]=e};class tR{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=ra(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}var rR=Object.defineProperty,iR=Object.defineProperties,nR=Object.getOwnPropertyDescriptors,d6=Object.getOwnPropertySymbols,sR=Object.prototype.hasOwnProperty,oR=Object.prototype.propertyIsEnumerable,p6=(t,e,r)=>e in t?rR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,g6=(t,e)=>{for(var r in e||(e={}))sR.call(e,r)&&p6(t,r,e[r]);if(d6)for(var r of d6(e))oR.call(e,r)&&p6(t,r,e[r]);return t},v6=(t,e)=>iR(t,nR(e));class aR{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const i=r||Dn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(ra(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,n;const s=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0];if(!s)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const a=this.client.session.get(e.topic),u=((n=a?.sessionProperties)==null?void 0:n.capabilities)||{};if(u!=null&&u[s])return u?.[s];const h=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:v6(g6({},a.sessionProperties||{}),{capabilities:v6(g6({},u||{}),{[s]:h})})})}catch(l){console.warn("Failed to update session with capabilities",l)}return h}async getCallStatus(e){var r,i;const n=this.client.session.get(e.topic),s=(r=n.sessionProperties)==null?void 0:r.bundler_name;if(s){const u=this.getBundlerUrl(e.chainId,s);try{return await this.getUserOperationReceipt(u,e)}catch(h){console.warn("Failed to fetch call status from bundler",h,u)}}const a=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(u){console.warn("Failed to fetch call status from custom bundler",u,a)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(uo("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${W$}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}class cR{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=ra(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}class uR{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=ra(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}class fR{constructor(e){this.name="algorand",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const i=r||Dn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new xn(new gs(i,Kt("disableProviderPing")))}}class hR{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const i=this.getCardanoRPCUrl(r),n=ra(r);e[n]=this.createHttpProvider(n,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}class lR{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=ra(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}class dR{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=ra(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}class pR{constructor(e){this.name="near",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Dn(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace);return typeof i>"u"?void 0:new xn(new gs(i,Kt("disableProviderPing")))}}class gR{constructor(e){this.name=dc,this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(n=>{const s=ou(n);i[`${s.namespace}:${s.reference}`]=this.createHttpProvider(n)}),i}getHttpProvider(e){const r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}var vR=Object.defineProperty,mR=Object.defineProperties,bR=Object.getOwnPropertyDescriptors,m6=Object.getOwnPropertySymbols,yR=Object.prototype.hasOwnProperty,wR=Object.prototype.propertyIsEnumerable,b6=(t,e,r)=>e in t?vR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bh=(t,e)=>{for(var r in e||(e={}))yR.call(e,r)&&b6(t,r,e[r]);if(m6)for(var r of m6(e))wR.call(e,r)&&b6(t,r,e[r]);return t},v1=(t,e)=>mR(t,bR(e));class m1{constructor(e){this.events=new kr.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:cs(Dh({level:e?.logger||n6})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new m1(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:Bh({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(a=>r(null,Oh(s,a))).catch(a=>r(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 e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Gt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const a=h6(this.session.namespaces);this.namespaces=d1(this.namespaces,a),this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:i,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});i&&(this.uri=i,this.events.emit("display_uri",i)),await n().then(s=>{this.session=s;const a=h6(s.namespaces);this.namespaces=d1(this.namespaces,a),this.persist("namespaces",this.namespaces)}).catch(s=>{if(s.message!==G3)throw s;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,n]=this.validateChain(e),s=this.getProvider(i);s.name===dc?s.setDefaultChain(`${i}:${n}`,r):s.setDefaultChain(n,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(as(r)){for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.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 e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await f1.init({core:this.providerOpts.core,logger:this.providerOpts.logger||n6,relayUrl:this.providerOpts.relayUrl||z$,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 e=[...new Set(Object.keys(this.session.namespaces).map(r=>xu(r)))];g1("client",this.client),g1("events",this.events),g1("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=X$(r,this.session),n=u6(i),s=d1(this.namespaces,this.optionalNamespaces),a=v1(Bh({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new aR({namespace:a});break;case"algorand":this.rpcProviders[r]=new fR({namespace:a});break;case"solana":this.rpcProviders[r]=new cR({namespace:a});break;case"cosmos":this.rpcProviders[r]=new uR({namespace:a});break;case"polkadot":this.rpcProviders[r]=new tR({namespace:a});break;case"cip34":this.rpcProviders[r]=new hR({namespace:a});break;case"elrond":this.rpcProviders[r]=new lR({namespace:a});break;case"multiversx":this.rpcProviders[r]=new dR({namespace:a});break;case"near":this.rpcProviders[r]=new pR({namespace:a});break;default:this.rpcProviders[dc]?this.rpcProviders[dc].updateNamespace(a):this.rpcProviders[dc]=new gR({namespace:a})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:i}=r;if(i.name==="accountsChanged"){const n=i.data;n&&as(n)&&this.events.emit("accountsChanged",n.map(eR))}else if(i.name==="chainChanged"){const n=r.chainId,s=r.event.data,a=xu(n),u=p1(n)!==p1(s)?`${a}:${p1(s)}`:n;this.onChainChanged(u)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i;const{namespaces:n}=r,s=(i=this.client)==null?void 0:i.session.get(e);this.session=v1(Bh({},s),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",v1(Bh({},Gt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(Cn.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[dc]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:i,sessionProperties:n}=e;r&&Object.keys(r).length&&(this.namespaces=r),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=n,this.persist("namespaces",r),this.persist("optionalNamespaces",i)}validateChain(e){const[r,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(a=>xu(a)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=xu(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){if(!this.namespaces)return;const[i,n]=this.validateChain(e);n&&(r||this.getProvider(i).setDefaultChain(n),this.namespaces[i]?this.namespaces[i].defaultChain=n:this.namespaces[`${i}:${n}`]?this.namespaces[`${i}:${n}`].defaultChain=n:this.namespaces[`${i}:${n}`]={defaultChain:n},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",n))}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(e,r){this.client.core.storage.setItem(`${s6}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${s6}/${e}`)}}const _R=m1,ER="wc",AR="ethereum_provider",xR=`${ER}@2:${AR}:`,SR="https://rpc.walletconnect.com/v1/",Fh=["eth_sendTransaction","personal_sign"],y6=["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"],Uh=["chainChanged","accountsChanged"],w6=["chainChanged","accountsChanged","message","disconnect","connect"];var IR=Object.defineProperty,MR=Object.defineProperties,CR=Object.getOwnPropertyDescriptors,_6=Object.getOwnPropertySymbols,DR=Object.prototype.hasOwnProperty,OR=Object.prototype.propertyIsEnumerable,E6=(t,e,r)=>e in t?IR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pc=(t,e)=>{for(var r in e||(e={}))DR.call(e,r)&&E6(t,r,e[r]);if(_6)for(var r of _6(e))OR.call(e,r)&&E6(t,r,e[r]);return t},b1=(t,e)=>MR(t,CR(e));function kh(t){return Number(t[0].split(":")[1])}function qh(t){return`0x${t.toString(16)}`}function PR(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:a,rpcMap:u}=t;if(!as(e))throw new Error("Invalid chains");const h={chains:e,methods:i||Fh,events:s||Uh,rpcMap:pc({},e.length?{[kh(e)]:u[kh(e)]}:{})},l=s?.filter(S=>!Uh.includes(S)),b=i?.filter(S=>!Fh.includes(S));if(!r&&!a&&!n&&!(l!=null&&l.length)&&!(b!=null&&b.length))return{required:e.length?h:void 0};const w=l?.length&&b?.length||!r,I={chains:[...new Set(w?h.chains.concat(r||[]):r)],methods:[...new Set(h.methods.concat(n!=null&&n.length?n:y6))],events:[...new Set(h.events.concat(a!=null&&a.length?a:w6))],rpcMap:u};return{required:e.length?h:void 0,optional:r.length?I:void 0}}class jh{constructor(){this.events=new kr.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=xR,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new jh;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,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(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:i}=PR(this.rpc);try{const n=await new Promise(async(a,u)=>{var h;this.rpc.showQrModal&&((h=this.modal)==null||h.subscribeModal(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),u(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(b1(pc({namespaces:pc({},r&&{[this.namespace]:r})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e?.pairingTopic})).then(l=>{a(l)}).catch(l=>{u(new Error(l.message))})});if(!n)return;const s=U2(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:qh(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async authenticate(e,r){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise(async(s,a)=>{var u;this.rpc.showQrModal&&((u=this.modal)==null||u.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(b1(pc({},e),{chains:this.rpc.chains}),r).then(h=>{s(h)}).catch(h=>{a(new Error(h.message))})}),n=i.session;if(n){const s=U2(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:qh(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",e=>{const{params:r}=e,{event:i}=r;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",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",qh(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",b1(pc({},Gt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,i;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(i=this.modal)==null||i.openModal({uri:e})),this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",qh(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const n=(r=e?.chains)!=null?r:[],s=(i=e?.optionalChains)!=null?i:[],a=n.concat(s);if(!a.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const u=n.length?e?.methods||Fh:[],h=n.length?e?.events||Uh:[],l=e?.optionalMethods||[],b=e?.optionalEvents||[],w=e?.rpcMap||this.buildRpcMap(a,e.projectId),I=e?.qrModalOptions||void 0;return{chains:n?.map(S=>this.formatChainId(S)),optionalChains:s.map(S=>this.formatChainId(S)),methods:u,events:h,optionalMethods:l,optionalEvents:b,rpcMap:w,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:I,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?kh(this.rpc.chains):kh(this.rpc.optionalChains),this.signer=await _R.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const{WalletConnectModal:i}=await Promise.resolve().then(function(){return eN});r=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(pc({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&as(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)})),i&&as(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${SR}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r?.accounts),this.setAccounts(r?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const $R=jh,RR=Symbol(),A6=Object.getPrototypeOf,y1=new WeakMap,NR=t=>t&&(y1.has(t)?y1.get(t):A6(t)===Object.prototype||A6(t)===Array.prototype),TR=t=>NR(t)&&t[RR]||null,x6=(t,e=!0)=>{y1.set(t,e)},w1=t=>typeof t=="object"&&t!==null,fo=new WeakMap,zh=new WeakSet,LR=(t=Object.is,e=(l,b)=>new Proxy(l,b),r=l=>w1(l)&&!zh.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),i=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},n=new WeakMap,s=(l,b,w=i)=>{const I=n.get(l);if(I?.[0]===b)return I[1];const S=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return x6(S,!0),n.set(l,[b,S]),Reflect.ownKeys(l).forEach(D=>{if(Object.getOwnPropertyDescriptor(S,D))return;const T=Reflect.get(l,D),q={value:T,enumerable:!0,configurable:!0};if(zh.has(T))x6(T,!1);else if(T instanceof Promise)delete q.value,q.get=()=>w(T);else if(fo.has(T)){const[K,F]=fo.get(T);q.value=s(K,F(),w)}Object.defineProperty(S,D,q)}),Object.preventExtensions(S)},a=new WeakMap,u=[1,1],h=l=>{if(!w1(l))throw new Error("object required");const b=a.get(l);if(b)return b;let w=u[0];const I=new Set,S=(ee,ie=++u[0])=>{w!==ie&&(w=ie,I.forEach(L=>L(ee,ie)))};let D=u[1];const T=(ee=++u[1])=>(D!==ee&&!I.size&&(D=ee,K.forEach(([ie])=>{const L=ie[1](ee);L>w&&(w=L)})),w),q=ee=>(ie,L)=>{const y=[...ie];y[1]=[ee,...y[1]],S(y,L)},K=new Map,F=(ee,ie)=>{if(K.has(ee))throw new Error("prop listener already exists");if(I.size){const L=ie[3](q(ee));K.set(ee,[ie,L])}else K.set(ee,[ie])},W=ee=>{var ie;const L=K.get(ee);L&&(K.delete(ee),(ie=L[1])==null||ie.call(L))},R=ee=>(I.add(ee),I.size===1&&K.forEach(([L,y],f)=>{if(y)throw new Error("remove already exists");const d=L[3](q(f));K.set(f,[L,d])}),()=>{I.delete(ee),I.size===0&&K.forEach(([L,y],f)=>{y&&(y(),K.set(f,[L]))})}),k=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),_=e(k,{deleteProperty(ee,ie){const L=Reflect.get(ee,ie);W(ie);const y=Reflect.deleteProperty(ee,ie);return y&&S(["delete",[ie],L]),y},set(ee,ie,L,y){const f=Reflect.has(ee,ie),d=Reflect.get(ee,ie,y);if(f&&(t(d,L)||a.has(L)&&t(d,a.get(L))))return!0;W(ie),w1(L)&&(L=TR(L)||L);let v=L;if(L instanceof Promise)L.then(E=>{L.status="fulfilled",L.value=E,S(["resolve",[ie],E])}).catch(E=>{L.status="rejected",L.reason=E,S(["reject",[ie],E])});else{!fo.has(L)&&r(L)&&(v=h(L));const E=!zh.has(v)&&fo.get(v);E&&F(ie,E)}return Reflect.set(ee,ie,v,y),S(["set",[ie],L,d]),!0}});a.set(l,_);const B=[k,T,s,R];return fo.set(_,B),Reflect.ownKeys(l).forEach(ee=>{const ie=Object.getOwnPropertyDescriptor(l,ee);"value"in ie&&(_[ee]=l[ee],delete ie.value,delete ie.writable),Object.defineProperty(k,ee,ie)}),_})=>[h,fo,zh,t,e,r,i,n,s,a,u],[BR]=LR();function ho(t={}){return BR(t)}function ia(t,e,r){const i=fo.get(t);i||console.warn("Please use proxy object");let n;const s=[],a=i[3];let u=!1;const l=a(b=>{if(s.push(b),r){e(s.splice(0));return}n||(n=Promise.resolve().then(()=>{n=void 0,u&&e(s.splice(0))}))});return u=!0,()=>{u=!1,l()}}function FR(t,e){const r=fo.get(t);r||console.warn("Please use proxy object");const[i,n,s]=r;return s(i,n(),e)}const Br=ho({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),fr={state:Br,subscribe(t){return ia(Br,()=>t(Br))},push(t,e){t!==Br.view&&(Br.view=t,e&&(Br.data=e),Br.history.push(t))},reset(t){Br.view=t,Br.history=[t]},replace(t){Br.history.length>1&&(Br.history[Br.history.length-1]=t,Br.view=t)},goBack(){if(Br.history.length>1){Br.history.pop();const[t]=Br.history.slice(-1);Br.view=t}},setData(t){Br.data=t}},Qe={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return Qe.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const t=navigator.userAgent.toLowerCase();return Qe.isMobile()&&(t.includes("iphone")||t.includes("ipad"))},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},isArray(t){return Array.isArray(t)&&t.length>0},formatNativeUrl(t,e,r){if(Qe.isHttpUrl(t))return this.formatUniversalUrl(t,e,r);let i=t;i.includes("://")||(i=t.replaceAll("/","").replaceAll(":",""),i=`${i}://`),i.endsWith("/")||(i=`${i}/`),this.setWalletConnectDeepLink(i,r);const n=encodeURIComponent(e);return`${i}wc?uri=${n}`},formatUniversalUrl(t,e,r){if(!Qe.isHttpUrl(t))return this.formatNativeUrl(t,e,r);let i=t;i.endsWith("/")||(i=`${i}/`),this.setWalletConnectDeepLink(i,r);const n=encodeURIComponent(e);return`${i}wc?uri=${n}`},async wait(t){return new Promise(e=>{setTimeout(e,t)})},openHref(t,e){window.open(t,e,"noreferrer noopener")},setWalletConnectDeepLink(t,e){try{localStorage.setItem(Qe.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(t){try{const[e]=t.split("?");localStorage.setItem(Qe.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(Qe.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(Qe.WCM_VERSION,"2.6.2")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var t;const e=(t=fr.state.data)==null?void 0:t.Wallet;if(!e)throw new Error('Missing "Wallet" view data');return e}},UR=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),Qr=ho({enabled:UR,userSessionId:"",events:[],connectedWalletId:void 0}),S6={state:Qr,subscribe(t){return ia(Qr.events,()=>t(FR(Qr.events[Qr.events.length-1])))},initialize(){Qr.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(Qr.userSessionId=crypto.randomUUID())},setConnectedWalletId(t){Qr.connectedWalletId=t},click(t){if(Qr.enabled){const e={type:"CLICK",name:t.name,userSessionId:Qr.userSessionId,timestamp:Date.now(),data:t};Qr.events.push(e)}},track(t){if(Qr.enabled){const e={type:"TRACK",name:t.name,userSessionId:Qr.userSessionId,timestamp:Date.now(),data:t};Qr.events.push(e)}},view(t){if(Qr.enabled){const e={type:"VIEW",name:t.name,userSessionId:Qr.userSessionId,timestamp:Date.now(),data:t};Qr.events.push(e)}}},vs=ho({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),wr={state:vs,subscribe(t){return ia(vs,()=>t(vs))},setChains(t){vs.chains=t},setWalletConnectUri(t){vs.walletConnectUri=t},setIsCustomDesktop(t){vs.isCustomDesktop=t},setIsCustomMobile(t){vs.isCustomMobile=t},setIsDataLoaded(t){vs.isDataLoaded=t},setIsUiLoaded(t){vs.isUiLoaded=t},setIsAuth(t){vs.isAuth=t}},Hh=ho({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),ki={state:Hh,subscribe(t){return ia(Hh,()=>t(Hh))},setConfig(t){var e,r;S6.initialize(),wr.setChains(t.chains),wr.setIsAuth(!!t.enableAuthMode),wr.setIsCustomMobile(!!((e=t.mobileWallets)!=null&&e.length)),wr.setIsCustomDesktop(!!((r=t.desktopWallets)!=null&&r.length)),Qe.setModalVersionInStorage(),Object.assign(Hh,t)}};var kR=Object.defineProperty,I6=Object.getOwnPropertySymbols,qR=Object.prototype.hasOwnProperty,jR=Object.prototype.propertyIsEnumerable,M6=(t,e,r)=>e in t?kR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zR=(t,e)=>{for(var r in e||(e={}))qR.call(e,r)&&M6(t,r,e[r]);if(I6)for(var r of I6(e))jR.call(e,r)&&M6(t,r,e[r]);return t};const _1="https://explorer-api.walletconnect.com",E1="wcm",A1="js-2.6.2";async function Kh(t,e){const r=zR({sdkType:E1,sdkVersion:A1},e),i=new URL(t,_1);return i.searchParams.append("projectId",ki.state.projectId),Object.entries(r).forEach(([n,s])=>{s&&i.searchParams.append(n,String(s))}),(await fetch(i)).json()}const na={async getDesktopListings(t){return Kh("/w3m/v1/getDesktopListings",t)},async getMobileListings(t){return Kh("/w3m/v1/getMobileListings",t)},async getInjectedListings(t){return Kh("/w3m/v1/getInjectedListings",t)},async getAllListings(t){return Kh("/w3m/v1/getAllListings",t)},getWalletImageUrl(t){return`${_1}/w3m/v1/getWalletImage/${t}?projectId=${ki.state.projectId}&sdkType=${E1}&sdkVersion=${A1}`},getAssetImageUrl(t){return`${_1}/w3m/v1/getAssetImage/${t}?projectId=${ki.state.projectId}&sdkType=${E1}&sdkVersion=${A1}`}};var HR=Object.defineProperty,C6=Object.getOwnPropertySymbols,KR=Object.prototype.hasOwnProperty,WR=Object.prototype.propertyIsEnumerable,D6=(t,e,r)=>e in t?HR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,VR=(t,e)=>{for(var r in e||(e={}))KR.call(e,r)&&D6(t,r,e[r]);if(C6)for(var r of C6(e))WR.call(e,r)&&D6(t,r,e[r]);return t};const O6=Qe.isMobile(),ms=ho({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),xi={state:ms,async getRecomendedWallets(){const{explorerRecommendedWalletIds:t,explorerExcludedWalletIds:e}=ki.state;if(t==="NONE"||e==="ALL"&&!t)return ms.recomendedWallets;if(Qe.isArray(t)){const r={recommendedIds:t.join(",")},{listings:i}=await na.getAllListings(r),n=Object.values(i);n.sort((s,a)=>{const u=t.indexOf(s.id),h=t.indexOf(a.id);return u-h}),ms.recomendedWallets=n}else{const{chains:r,isAuth:i}=wr.state,n=r?.join(","),s=Qe.isArray(e),a={page:1,sdks:i?"auth_v1":void 0,entries:Qe.RECOMMENDED_WALLET_AMOUNT,chains:n,version:2,excludedIds:s?e.join(","):void 0},{listings:u}=O6?await na.getMobileListings(a):await na.getDesktopListings(a);ms.recomendedWallets=Object.values(u)}return ms.recomendedWallets},async getWallets(t){const e=VR({},t),{explorerRecommendedWalletIds:r,explorerExcludedWalletIds:i}=ki.state,{recomendedWallets:n}=ms;if(i==="ALL")return ms.wallets;n.length?e.excludedIds=n.map(w=>w.id).join(","):Qe.isArray(r)&&(e.excludedIds=r.join(",")),Qe.isArray(i)&&(e.excludedIds=[e.excludedIds,i].filter(Boolean).join(",")),wr.state.isAuth&&(e.sdks="auth_v1");const{page:s,search:a}=t,{listings:u,total:h}=O6?await na.getMobileListings(e):await na.getDesktopListings(e),l=Object.values(u),b=a?"search":"wallets";return ms[b]={listings:[...ms[b].listings,...l],total:h,page:s??1},{listings:l,total:h}},getWalletImageUrl(t){return na.getWalletImageUrl(t)},getAssetImageUrl(t){return na.getAssetImageUrl(t)},resetSearch(){ms.search={listings:[],total:0,page:1}}},gc=ho({open:!1}),sa={state:gc,subscribe(t){return ia(gc,()=>t(gc))},async open(t){return new Promise(e=>{const{isUiLoaded:r,isDataLoaded:i}=wr.state;if(Qe.removeWalletConnectDeepLink(),wr.setWalletConnectUri(t?.uri),wr.setChains(t?.chains),fr.reset("ConnectWallet"),r&&i)gc.open=!0,e();else{const n=setInterval(()=>{const s=wr.state;s.isUiLoaded&&s.isDataLoaded&&(clearInterval(n),gc.open=!0,e())},200)}})},close(){gc.open=!1}};var GR=Object.defineProperty,P6=Object.getOwnPropertySymbols,JR=Object.prototype.hasOwnProperty,YR=Object.prototype.propertyIsEnumerable,$6=(t,e,r)=>e in t?GR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,QR=(t,e)=>{for(var r in e||(e={}))JR.call(e,r)&&$6(t,r,e[r]);if(P6)for(var r of P6(e))YR.call(e,r)&&$6(t,r,e[r]);return t};function ZR(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const ku=ho({themeMode:ZR()?"dark":"light"}),lo={state:ku,subscribe(t){return ia(ku,()=>t(ku))},setThemeConfig(t){const{themeMode:e,themeVariables:r}=t;e&&(ku.themeMode=e),r&&(ku.themeVariables=QR({},r))}},oa=ho({open:!1,message:"",variant:"success"}),po={state:oa,subscribe(t){return ia(oa,()=>t(oa))},openToast(t,e){oa.open=!0,oa.message=t,oa.variant=e},closeToast(){oa.open=!1}};class XR{constructor(e){this.openModal=sa.open,this.closeModal=sa.close,this.subscribeModal=sa.subscribe,this.setTheme=lo.setThemeConfig,lo.setThemeConfig(e),ki.setConfig(e),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(function(){return cF});const e=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",e),wr.setIsUiLoaded(!0)}}}var eN=Object.freeze({__proto__:null,WalletConnectModal:XR});/**
|
|
69
|
+
}`;var St=H5(function(){return Ht(j,Je+"return "+ge).apply(r,Q)});if(St.source=ge,Ig(St))throw St;return St}function Vz(o){return Vt(o).toLowerCase()}function Gz(o){return Vt(o).toUpperCase()}function Jz(o,c,p){if(o=Vt(o),o&&(p||c===r))return Xy(o);if(!o||!(c=Hi(c)))return o;var x=Bn(o),$=Bn(c),j=ew(x,$),Q=tw(x,$)+1;return Po(x,j,Q).join("")}function Yz(o,c,p){if(o=Vt(o),o&&(p||c===r))return o.slice(0,iw(o)+1);if(!o||!(c=Hi(c)))return o;var x=Bn(o),$=tw(x,Bn(c))+1;return Po(x,0,$).join("")}function Qz(o,c,p){if(o=Vt(o),o&&(p||c===r))return o.replace(st,"");if(!o||!(c=Hi(c)))return o;var x=Bn(o),$=ew(x,Bn(c));return Po(x,$).join("")}function Zz(o,c){var p=ie,x=L;if(hr(c)){var $="separator"in c?c.separator:$;p="length"in c?xt(c.length):p,x="omission"in c?Hi(c.omission):x}o=Vt(o);var j=o.length;if(Bc(o)){var Q=Bn(o);j=Q.length}if(p>=j)return o;var Z=p-Fc(x);if(Z<1)return x;var se=Q?Po(Q,0,Z).join(""):o.slice(0,Z);if($===r)return se+x;if(Q&&(Z+=se.length-Z),Mg($)){if(o.slice(Z).search($)){var le,de=se;for($.global||($=zp($.source,Vt(_t.exec($))+"g")),$.lastIndex=0;le=$.exec(de);)var ge=le.index;se=se.slice(0,ge===r?Z:ge)}}else if(o.indexOf(Hi($),Z)!=Z){var De=se.lastIndexOf($);De>-1&&(se=se.slice(0,De))}return se+x}function Xz(o){return o=Vt(o),o&&Le.test(o)?o.replace(Ot,CF):o}var eH=Kc(function(o,c,p){return o+(p?" ":"")+c.toUpperCase()}),Og=Kw("toUpperCase");function z5(o,c,p){return o=Vt(o),c=p?r:c,c===r?AF(o)?PF(o):pF(o):o.match(c)||[]}var H5=Mt(function(o,c){try{return Fr(o,r,c)}catch(p){return Ig(p)?p:new vt(p)}}),tH=Ws(function(o,c){return fn(c,function(p){p=xs(p),Hs(o,p,xg(o[p],o))}),o});function rH(o){var c=o==null?0:o.length,p=ot();return o=c?ur(o,function(x){if(typeof x[1]!="function")throw new hn(a);return[p(x[0]),x[1]]}):[],Mt(function(x){for(var $=-1;++$<c;){var j=o[$];if(Fr(j[0],this,x))return Fr(j[1],this,x)}})}function iH(o){return CU(dn(o,w))}function Pg(o){return function(){return o}}function nH(o,c){return o==null||o!==o?c:o}var sH=Vw(),oH=Vw(!0);function Ri(o){return o}function $g(o){return Aw(typeof o=="function"?o:dn(o,w))}function aH(o){return Sw(dn(o,w))}function cH(o,c){return Iw(o,dn(c,w))}var uH=Mt(function(o,c){return function(p){return bf(p,o,c)}}),fH=Mt(function(o,c){return function(p){return bf(o,p,c)}});function Rg(o,c,p){var x=Ur(c),$=Ql(c,x);p==null&&!(hr(c)&&($.length||!x.length))&&(p=c,c=o,o=this,$=Ql(c,Ur(c)));var j=!(hr(p)&&"chain"in p)||!!p.chain,Q=Gs(o);return fn($,function(Z){var se=c[Z];o[Z]=se,Q&&(o.prototype[Z]=function(){var le=this.__chain__;if(j||le){var de=o(this.__wrapped__),ge=de.__actions__=Oi(this.__actions__);return ge.push({func:se,args:arguments,thisArg:o}),de.__chain__=le,de}return se.apply(o,So([this.value()],arguments))})}),o}function hH(){return Ft._===this&&(Ft._=BF),this}function Ng(){}function lH(o){return o=xt(o),Mt(function(c){return Mw(c,o)})}var dH=hg(ur),pH=hg(Gy),gH=hg(Lp);function K5(o){return bg(o)?Bp(xs(o)):KU(o)}function vH(o){return function(c){return o==null?r:Ia(o,c)}}var mH=Jw(),bH=Jw(!0);function Tg(){return[]}function Lg(){return!1}function yH(){return{}}function wH(){return""}function _H(){return!0}function EH(o,c){if(o=xt(o),o<1||o>O)return[];var p=m,x=ii(o,m);c=ot(c),o-=m;for(var $=kp(x,c);++p<o;)c(p);return $}function AH(o){return yt(o)?ur(o,xs):Ki(o)?[o]:Oi(h5(Vt(o)))}function xH(o){var c=++TF;return Vt(o)+c}var SH=i0(function(o,c){return o+c},0),IH=lg("ceil"),MH=i0(function(o,c){return o/c},1),CH=lg("floor");function DH(o){return o&&o.length?Yl(o,Ri,Qp):r}function OH(o,c){return o&&o.length?Yl(o,ot(c,2),Qp):r}function PH(o){return Qy(o,Ri)}function $H(o,c){return Qy(o,ot(c,2))}function RH(o){return o&&o.length?Yl(o,Ri,tg):r}function NH(o,c){return o&&o.length?Yl(o,ot(c,2),tg):r}var TH=i0(function(o,c){return o*c},1),LH=lg("round"),BH=i0(function(o,c){return o-c},0);function FH(o){return o&&o.length?Up(o,Ri):0}function UH(o,c){return o&&o.length?Up(o,ot(c,2)):0}return U.after=aj,U.ary=E5,U.assign=Gj,U.assignIn=L5,U.assignInWith=v0,U.assignWith=Jj,U.at=Yj,U.before=A5,U.bind=xg,U.bindAll=tH,U.bindKey=x5,U.castArray=yj,U.chain=y5,U.chunk=Ck,U.compact=Dk,U.concat=Ok,U.cond=rH,U.conforms=iH,U.constant=Pg,U.countBy=Fq,U.create=Qj,U.curry=S5,U.curryRight=I5,U.debounce=M5,U.defaults=Zj,U.defaultsDeep=Xj,U.defer=cj,U.delay=uj,U.difference=Pk,U.differenceBy=$k,U.differenceWith=Rk,U.drop=Nk,U.dropRight=Tk,U.dropRightWhile=Lk,U.dropWhile=Bk,U.fill=Fk,U.filter=kq,U.flatMap=zq,U.flatMapDeep=Hq,U.flatMapDepth=Kq,U.flatten=g5,U.flattenDeep=Uk,U.flattenDepth=kk,U.flip=fj,U.flow=sH,U.flowRight=oH,U.fromPairs=qk,U.functions=oz,U.functionsIn=az,U.groupBy=Wq,U.initial=zk,U.intersection=Hk,U.intersectionBy=Kk,U.intersectionWith=Wk,U.invert=uz,U.invertBy=fz,U.invokeMap=Gq,U.iteratee=$g,U.keyBy=Jq,U.keys=Ur,U.keysIn=$i,U.map=f0,U.mapKeys=lz,U.mapValues=dz,U.matches=aH,U.matchesProperty=cH,U.memoize=l0,U.merge=pz,U.mergeWith=B5,U.method=uH,U.methodOf=fH,U.mixin=Rg,U.negate=d0,U.nthArg=lH,U.omit=gz,U.omitBy=vz,U.once=hj,U.orderBy=Yq,U.over=dH,U.overArgs=lj,U.overEvery=pH,U.overSome=gH,U.partial=Sg,U.partialRight=C5,U.partition=Qq,U.pick=mz,U.pickBy=F5,U.property=K5,U.propertyOf=vH,U.pull=Yk,U.pullAll=m5,U.pullAllBy=Qk,U.pullAllWith=Zk,U.pullAt=Xk,U.range=mH,U.rangeRight=bH,U.rearg=dj,U.reject=ej,U.remove=eq,U.rest=pj,U.reverse=Eg,U.sampleSize=rj,U.set=yz,U.setWith=wz,U.shuffle=ij,U.slice=tq,U.sortBy=oj,U.sortedUniq=cq,U.sortedUniqBy=uq,U.split=zz,U.spread=gj,U.tail=fq,U.take=hq,U.takeRight=lq,U.takeRightWhile=dq,U.takeWhile=pq,U.tap=Dq,U.throttle=vj,U.thru=u0,U.toArray=R5,U.toPairs=U5,U.toPairsIn=k5,U.toPath=AH,U.toPlainObject=T5,U.transform=_z,U.unary=mj,U.union=gq,U.unionBy=vq,U.unionWith=mq,U.uniq=bq,U.uniqBy=yq,U.uniqWith=wq,U.unset=Ez,U.unzip=Ag,U.unzipWith=b5,U.update=Az,U.updateWith=xz,U.values=Gc,U.valuesIn=Sz,U.without=_q,U.words=z5,U.wrap=bj,U.xor=Eq,U.xorBy=Aq,U.xorWith=xq,U.zip=Sq,U.zipObject=Iq,U.zipObjectDeep=Mq,U.zipWith=Cq,U.entries=U5,U.entriesIn=k5,U.extend=L5,U.extendWith=v0,Rg(U,U),U.add=SH,U.attempt=H5,U.camelCase=Dz,U.capitalize=q5,U.ceil=IH,U.clamp=Iz,U.clone=wj,U.cloneDeep=Ej,U.cloneDeepWith=Aj,U.cloneWith=_j,U.conformsTo=xj,U.deburr=j5,U.defaultTo=nH,U.divide=MH,U.endsWith=Oz,U.eq=Un,U.escape=Pz,U.escapeRegExp=$z,U.every=Uq,U.find=qq,U.findIndex=d5,U.findKey=ez,U.findLast=jq,U.findLastIndex=p5,U.findLastKey=tz,U.floor=CH,U.forEach=w5,U.forEachRight=_5,U.forIn=rz,U.forInRight=iz,U.forOwn=nz,U.forOwnRight=sz,U.get=Cg,U.gt=Sj,U.gte=Ij,U.has=cz,U.hasIn=Dg,U.head=v5,U.identity=Ri,U.includes=Vq,U.indexOf=jk,U.inRange=Mz,U.invoke=hz,U.isArguments=Da,U.isArray=yt,U.isArrayBuffer=Mj,U.isArrayLike=Pi,U.isArrayLikeObject=Er,U.isBoolean=Cj,U.isBuffer=$o,U.isDate=Dj,U.isElement=Oj,U.isEmpty=Pj,U.isEqual=$j,U.isEqualWith=Rj,U.isError=Ig,U.isFinite=Nj,U.isFunction=Gs,U.isInteger=D5,U.isLength=p0,U.isMap=O5,U.isMatch=Tj,U.isMatchWith=Lj,U.isNaN=Bj,U.isNative=Fj,U.isNil=kj,U.isNull=Uj,U.isNumber=P5,U.isObject=hr,U.isObjectLike=mr,U.isPlainObject=xf,U.isRegExp=Mg,U.isSafeInteger=qj,U.isSet=$5,U.isString=g0,U.isSymbol=Ki,U.isTypedArray=Vc,U.isUndefined=jj,U.isWeakMap=zj,U.isWeakSet=Hj,U.join=Vk,U.kebabCase=Rz,U.last=gn,U.lastIndexOf=Gk,U.lowerCase=Nz,U.lowerFirst=Tz,U.lt=Kj,U.lte=Wj,U.max=DH,U.maxBy=OH,U.mean=PH,U.meanBy=$H,U.min=RH,U.minBy=NH,U.stubArray=Tg,U.stubFalse=Lg,U.stubObject=yH,U.stubString=wH,U.stubTrue=_H,U.multiply=TH,U.nth=Jk,U.noConflict=hH,U.noop=Ng,U.now=h0,U.pad=Lz,U.padEnd=Bz,U.padStart=Fz,U.parseInt=Uz,U.random=Cz,U.reduce=Zq,U.reduceRight=Xq,U.repeat=kz,U.replace=qz,U.result=bz,U.round=LH,U.runInContext=ne,U.sample=tj,U.size=nj,U.snakeCase=jz,U.some=sj,U.sortedIndex=rq,U.sortedIndexBy=iq,U.sortedIndexOf=nq,U.sortedLastIndex=sq,U.sortedLastIndexBy=oq,U.sortedLastIndexOf=aq,U.startCase=Hz,U.startsWith=Kz,U.subtract=BH,U.sum=FH,U.sumBy=UH,U.template=Wz,U.times=EH,U.toFinite=Js,U.toInteger=xt,U.toLength=N5,U.toLower=Vz,U.toNumber=vn,U.toSafeInteger=Vj,U.toString=Vt,U.toUpper=Gz,U.trim=Jz,U.trimEnd=Yz,U.trimStart=Qz,U.truncate=Zz,U.unescape=Xz,U.uniqueId=xH,U.upperCase=eH,U.upperFirst=Og,U.each=w5,U.eachRight=_5,U.first=v5,Rg(U,function(){var o={};return Es(U,function(c,p){Jt.call(U.prototype,p)||(o[p]=c)}),o}(),{chain:!1}),U.VERSION=i,fn(["bind","bindKey","curry","curryRight","partial","partialRight"],function(o){U[o].placeholder=U}),fn(["drop","take"],function(o,c){Lt.prototype[o]=function(p){p=p===r?1:Or(xt(p),0);var x=this.__filtered__&&!c?new Lt(this):this.clone();return x.__filtered__?x.__takeCount__=ii(p,x.__takeCount__):x.__views__.push({size:ii(p,m),type:o+(x.__dir__<0?"Right":"")}),x},Lt.prototype[o+"Right"]=function(p){return this.reverse()[o](p).reverse()}}),fn(["filter","map","takeWhile"],function(o,c){var p=c+1,x=p==d||p==E;Lt.prototype[o]=function($){var j=this.clone();return j.__iteratees__.push({iteratee:ot($,3),type:p}),j.__filtered__=j.__filtered__||x,j}}),fn(["head","last"],function(o,c){var p="take"+(c?"Right":"");Lt.prototype[o]=function(){return this[p](1).value()[0]}}),fn(["initial","tail"],function(o,c){var p="drop"+(c?"":"Right");Lt.prototype[o]=function(){return this.__filtered__?new Lt(this):this[p](1)}}),Lt.prototype.compact=function(){return this.filter(Ri)},Lt.prototype.find=function(o){return this.filter(o).head()},Lt.prototype.findLast=function(o){return this.reverse().find(o)},Lt.prototype.invokeMap=Mt(function(o,c){return typeof o=="function"?new Lt(this):this.map(function(p){return bf(p,o,c)})}),Lt.prototype.reject=function(o){return this.filter(d0(ot(o)))},Lt.prototype.slice=function(o,c){o=xt(o);var p=this;return p.__filtered__&&(o>0||c<0)?new Lt(p):(o<0?p=p.takeRight(-o):o&&(p=p.drop(o)),c!==r&&(c=xt(c),p=c<0?p.dropRight(-c):p.take(c-o)),p)},Lt.prototype.takeRightWhile=function(o){return this.reverse().takeWhile(o).reverse()},Lt.prototype.toArray=function(){return this.take(m)},Es(Lt.prototype,function(o,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),x=/^(?:head|last)$/.test(c),$=U[x?"take"+(c=="last"?"Right":""):c],j=x||/^find/.test(c);$&&(U.prototype[c]=function(){var Q=this.__wrapped__,Z=x?[1]:arguments,se=Q instanceof Lt,le=Z[0],de=se||yt(Q),ge=function(Pt){var Ut=$.apply(U,So([Pt],Z));return x&&De?Ut[0]:Ut};de&&p&&typeof le=="function"&&le.length!=1&&(se=de=!1);var De=this.__chain__,Je=!!this.__actions__.length,ut=j&&!De,St=se&&!Je;if(!j&&de){Q=St?Q:new Lt(this);var ft=o.apply(Q,Z);return ft.__actions__.push({func:u0,args:[ge],thisArg:r}),new ln(ft,De)}return ut&&St?o.apply(this,Z):(ft=this.thru(ge),ut?x?ft.value()[0]:ft.value():ft)})}),fn(["pop","push","shift","sort","splice","unshift"],function(o){var c=Tl[o],p=/^(?:push|sort|unshift)$/.test(o)?"tap":"thru",x=/^(?:pop|shift)$/.test(o);U.prototype[o]=function(){var $=arguments;if(x&&!this.__chain__){var j=this.value();return c.apply(yt(j)?j:[],$)}return this[p](function(Q){return c.apply(yt(Q)?Q:[],$)})}}),Es(Lt.prototype,function(o,c){var p=U[c];if(p){var x=p.name+"";Jt.call(jc,x)||(jc[x]=[]),jc[x].push({name:c,func:p})}}),jc[r0(r,K).name]=[{name:"wrapper",func:r}],Lt.prototype.clone=XF,Lt.prototype.reverse=eU,Lt.prototype.value=tU,U.prototype.at=Oq,U.prototype.chain=Pq,U.prototype.commit=$q,U.prototype.next=Rq,U.prototype.plant=Tq,U.prototype.reverse=Lq,U.prototype.toJSON=U.prototype.valueOf=U.prototype.value=Bq,U.prototype.first=U.prototype.head,hf&&(U.prototype[hf]=Nq),U},Uc=$F();_r?((_r.exports=Uc)._=Uc,tr._=Uc):Ft._=Uc}).call(Uu)})(l1,l1.exports);var V$=Object.defineProperty,G$=Object.defineProperties,J$=Object.getOwnPropertyDescriptors,a6=Object.getOwnPropertySymbols,Y$=Object.prototype.hasOwnProperty,Q$=Object.prototype.propertyIsEnumerable,c6=(t,e,r)=>e in t?V$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lh=(t,e)=>{for(var r in e||(e={}))Y$.call(e,r)&&c6(t,r,e[r]);if(a6)for(var r of a6(e))Q$.call(e,r)&&c6(t,r,e[r]);return t},Z$=(t,e)=>G$(t,J$(e));function Dn(t,e,r){var i;const n=ou(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${o6}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function ra(t){return t.includes(":")?t.split(":")[1]:t}function u6(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function X$(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function d1(t={},e={}){const r=f6(t),i=f6(e);return l1.exports.merge(r,i)}function f6(t){var e,r,i,n;const s={};if(!Su(t))return s;for(const[a,u]of Object.entries(t)){const h=Ld(a)?[a]:u.chains,l=u.methods||[],b=u.events||[],w=u.rpcMap||{},I=xu(a);s[I]=Z$(Lh(Lh({},s[I]),u),{chains:rh(h,(e=s[I])==null?void 0:e.chains),methods:rh(l,(r=s[I])==null?void 0:r.methods),events:rh(b,(i=s[I])==null?void 0:i.events),rpcMap:Lh(Lh({},w),(n=s[I])==null?void 0:n.rpcMap)})}return s}function eR(t){return t.includes(":")?t.split(":")[2]:t}function h6(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],a=i.accounts||[],u=Ld(r)?[r]:i.chains?i.chains:u6(i.accounts);e[r]={chains:u,methods:n,events:s,accounts:a}}return e}function p1(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const l6={},Kt=t=>l6[t],g1=(t,e)=>{l6[t]=e};class tR{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=ra(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}var rR=Object.defineProperty,iR=Object.defineProperties,nR=Object.getOwnPropertyDescriptors,d6=Object.getOwnPropertySymbols,sR=Object.prototype.hasOwnProperty,oR=Object.prototype.propertyIsEnumerable,p6=(t,e,r)=>e in t?rR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,g6=(t,e)=>{for(var r in e||(e={}))sR.call(e,r)&&p6(t,r,e[r]);if(d6)for(var r of d6(e))oR.call(e,r)&&p6(t,r,e[r]);return t},v6=(t,e)=>iR(t,nR(e));class aR{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const i=r||Dn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(ra(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,n;const s=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0];if(!s)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const a=this.client.session.get(e.topic),u=((n=a?.sessionProperties)==null?void 0:n.capabilities)||{};if(u!=null&&u[s])return u?.[s];const h=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:v6(g6({},a.sessionProperties||{}),{capabilities:v6(g6({},u||{}),{[s]:h})})})}catch(l){console.warn("Failed to update session with capabilities",l)}return h}async getCallStatus(e){var r,i;const n=this.client.session.get(e.topic),s=(r=n.sessionProperties)==null?void 0:r.bundler_name;if(s){const u=this.getBundlerUrl(e.chainId,s);try{return await this.getUserOperationReceipt(u,e)}catch(h){console.warn("Failed to fetch call status from bundler",h,u)}}const a=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(u){console.warn("Failed to fetch call status from custom bundler",u,a)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(uo("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${W$}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}class cR{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=ra(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}class uR{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=ra(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}class fR{constructor(e){this.name="algorand",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const i=r||Dn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new xn(new gs(i,Kt("disableProviderPing")))}}class hR{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const i=this.getCardanoRPCUrl(r),n=ra(r);e[n]=this.createHttpProvider(n,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}class lR{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=ra(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}class dR{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=ra(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}class pR{constructor(e){this.name="near",this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Dn(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace);return typeof i>"u"?void 0:new xn(new gs(i,Kt("disableProviderPing")))}}class gR{constructor(e){this.name=dc,this.namespace=e.namespace,this.events=Kt("events"),this.client=Kt("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Cn.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(n=>{const s=ou(n);i[`${s.namespace}:${s.reference}`]=this.createHttpProvider(n)}),i}getHttpProvider(e){const r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Dn(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new xn(new gs(i,Kt("disableProviderPing")))}}var vR=Object.defineProperty,mR=Object.defineProperties,bR=Object.getOwnPropertyDescriptors,m6=Object.getOwnPropertySymbols,yR=Object.prototype.hasOwnProperty,wR=Object.prototype.propertyIsEnumerable,b6=(t,e,r)=>e in t?vR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bh=(t,e)=>{for(var r in e||(e={}))yR.call(e,r)&&b6(t,r,e[r]);if(m6)for(var r of m6(e))wR.call(e,r)&&b6(t,r,e[r]);return t},v1=(t,e)=>mR(t,bR(e));class m1{constructor(e){this.events=new kr.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:cs(Dh({level:e?.logger||n6})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new m1(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:Bh({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(a=>r(null,Oh(s,a))).catch(a=>r(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 e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Gt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const a=h6(this.session.namespaces);this.namespaces=d1(this.namespaces,a),this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:i,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});i&&(this.uri=i,this.events.emit("display_uri",i)),await n().then(s=>{this.session=s;const a=h6(s.namespaces);this.namespaces=d1(this.namespaces,a),this.persist("namespaces",this.namespaces)}).catch(s=>{if(s.message!==G3)throw s;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,n]=this.validateChain(e),s=this.getProvider(i);s.name===dc?s.setDefaultChain(`${i}:${n}`,r):s.setDefaultChain(n,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(as(r)){for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.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 e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await f1.init({core:this.providerOpts.core,logger:this.providerOpts.logger||n6,relayUrl:this.providerOpts.relayUrl||z$,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 e=[...new Set(Object.keys(this.session.namespaces).map(r=>xu(r)))];g1("client",this.client),g1("events",this.events),g1("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=X$(r,this.session),n=u6(i),s=d1(this.namespaces,this.optionalNamespaces),a=v1(Bh({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new aR({namespace:a});break;case"algorand":this.rpcProviders[r]=new fR({namespace:a});break;case"solana":this.rpcProviders[r]=new cR({namespace:a});break;case"cosmos":this.rpcProviders[r]=new uR({namespace:a});break;case"polkadot":this.rpcProviders[r]=new tR({namespace:a});break;case"cip34":this.rpcProviders[r]=new hR({namespace:a});break;case"elrond":this.rpcProviders[r]=new lR({namespace:a});break;case"multiversx":this.rpcProviders[r]=new dR({namespace:a});break;case"near":this.rpcProviders[r]=new pR({namespace:a});break;default:this.rpcProviders[dc]?this.rpcProviders[dc].updateNamespace(a):this.rpcProviders[dc]=new gR({namespace:a})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:i}=r;if(i.name==="accountsChanged"){const n=i.data;n&&as(n)&&this.events.emit("accountsChanged",n.map(eR))}else if(i.name==="chainChanged"){const n=r.chainId,s=r.event.data,a=xu(n),u=p1(n)!==p1(s)?`${a}:${p1(s)}`:n;this.onChainChanged(u)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i;const{namespaces:n}=r,s=(i=this.client)==null?void 0:i.session.get(e);this.session=v1(Bh({},s),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",v1(Bh({},Gt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(Cn.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[dc]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:i,sessionProperties:n}=e;r&&Object.keys(r).length&&(this.namespaces=r),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=n,this.persist("namespaces",r),this.persist("optionalNamespaces",i)}validateChain(e){const[r,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(a=>xu(a)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=xu(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){if(!this.namespaces)return;const[i,n]=this.validateChain(e);n&&(r||this.getProvider(i).setDefaultChain(n),this.namespaces[i]?this.namespaces[i].defaultChain=n:this.namespaces[`${i}:${n}`]?this.namespaces[`${i}:${n}`].defaultChain=n:this.namespaces[`${i}:${n}`]={defaultChain:n},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",n))}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(e,r){this.client.core.storage.setItem(`${s6}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${s6}/${e}`)}}const _R=m1,ER="wc",AR="ethereum_provider",xR=`${ER}@2:${AR}:`,SR="https://rpc.walletconnect.org/v1/",Fh=["eth_sendTransaction","personal_sign"],y6=["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"],Uh=["chainChanged","accountsChanged"],w6=["chainChanged","accountsChanged","message","disconnect","connect"];var IR=Object.defineProperty,MR=Object.defineProperties,CR=Object.getOwnPropertyDescriptors,_6=Object.getOwnPropertySymbols,DR=Object.prototype.hasOwnProperty,OR=Object.prototype.propertyIsEnumerable,E6=(t,e,r)=>e in t?IR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pc=(t,e)=>{for(var r in e||(e={}))DR.call(e,r)&&E6(t,r,e[r]);if(_6)for(var r of _6(e))OR.call(e,r)&&E6(t,r,e[r]);return t},b1=(t,e)=>MR(t,CR(e));function kh(t){return Number(t[0].split(":")[1])}function qh(t){return`0x${t.toString(16)}`}function PR(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:a,rpcMap:u}=t;if(!as(e))throw new Error("Invalid chains");const h={chains:e,methods:i||Fh,events:s||Uh,rpcMap:pc({},e.length?{[kh(e)]:u[kh(e)]}:{})},l=s?.filter(S=>!Uh.includes(S)),b=i?.filter(S=>!Fh.includes(S));if(!r&&!a&&!n&&!(l!=null&&l.length)&&!(b!=null&&b.length))return{required:e.length?h:void 0};const w=l?.length&&b?.length||!r,I={chains:[...new Set(w?h.chains.concat(r||[]):r)],methods:[...new Set(h.methods.concat(n!=null&&n.length?n:y6))],events:[...new Set(h.events.concat(a!=null&&a.length?a:w6))],rpcMap:u};return{required:e.length?h:void 0,optional:r.length?I:void 0}}class jh{constructor(){this.events=new kr.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=xR,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new jh;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,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(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:i}=PR(this.rpc);try{const n=await new Promise(async(a,u)=>{var h;this.rpc.showQrModal&&((h=this.modal)==null||h.subscribeModal(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),u(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(b1(pc({namespaces:pc({},r&&{[this.namespace]:r})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e?.pairingTopic})).then(l=>{a(l)}).catch(l=>{u(new Error(l.message))})});if(!n)return;const s=U2(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:qh(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async authenticate(e,r){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise(async(s,a)=>{var u;this.rpc.showQrModal&&((u=this.modal)==null||u.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(b1(pc({},e),{chains:this.rpc.chains}),r).then(h=>{s(h)}).catch(h=>{a(new Error(h.message))})}),n=i.session;if(n){const s=U2(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:qh(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",e=>{const{params:r}=e,{event:i}=r;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",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",qh(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",b1(pc({},Gt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,i;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(i=this.modal)==null||i.openModal({uri:e})),this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",qh(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const n=(r=e?.chains)!=null?r:[],s=(i=e?.optionalChains)!=null?i:[],a=n.concat(s);if(!a.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const u=n.length?e?.methods||Fh:[],h=n.length?e?.events||Uh:[],l=e?.optionalMethods||[],b=e?.optionalEvents||[],w=e?.rpcMap||this.buildRpcMap(a,e.projectId),I=e?.qrModalOptions||void 0;return{chains:n?.map(S=>this.formatChainId(S)),optionalChains:s.map(S=>this.formatChainId(S)),methods:u,events:h,optionalMethods:l,optionalEvents:b,rpcMap:w,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:I,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?kh(this.rpc.chains):kh(this.rpc.optionalChains),this.signer=await _R.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const{WalletConnectModal:i}=await Promise.resolve().then(function(){return eN});r=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(pc({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&as(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)})),i&&as(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${SR}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r?.accounts),this.setAccounts(r?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const $R=jh,RR=Symbol(),A6=Object.getPrototypeOf,y1=new WeakMap,NR=t=>t&&(y1.has(t)?y1.get(t):A6(t)===Object.prototype||A6(t)===Array.prototype),TR=t=>NR(t)&&t[RR]||null,x6=(t,e=!0)=>{y1.set(t,e)},w1=t=>typeof t=="object"&&t!==null,fo=new WeakMap,zh=new WeakSet,LR=(t=Object.is,e=(l,b)=>new Proxy(l,b),r=l=>w1(l)&&!zh.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),i=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},n=new WeakMap,s=(l,b,w=i)=>{const I=n.get(l);if(I?.[0]===b)return I[1];const S=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return x6(S,!0),n.set(l,[b,S]),Reflect.ownKeys(l).forEach(D=>{if(Object.getOwnPropertyDescriptor(S,D))return;const T=Reflect.get(l,D),q={value:T,enumerable:!0,configurable:!0};if(zh.has(T))x6(T,!1);else if(T instanceof Promise)delete q.value,q.get=()=>w(T);else if(fo.has(T)){const[K,F]=fo.get(T);q.value=s(K,F(),w)}Object.defineProperty(S,D,q)}),Object.preventExtensions(S)},a=new WeakMap,u=[1,1],h=l=>{if(!w1(l))throw new Error("object required");const b=a.get(l);if(b)return b;let w=u[0];const I=new Set,S=(ee,ie=++u[0])=>{w!==ie&&(w=ie,I.forEach(L=>L(ee,ie)))};let D=u[1];const T=(ee=++u[1])=>(D!==ee&&!I.size&&(D=ee,K.forEach(([ie])=>{const L=ie[1](ee);L>w&&(w=L)})),w),q=ee=>(ie,L)=>{const y=[...ie];y[1]=[ee,...y[1]],S(y,L)},K=new Map,F=(ee,ie)=>{if(K.has(ee))throw new Error("prop listener already exists");if(I.size){const L=ie[3](q(ee));K.set(ee,[ie,L])}else K.set(ee,[ie])},W=ee=>{var ie;const L=K.get(ee);L&&(K.delete(ee),(ie=L[1])==null||ie.call(L))},R=ee=>(I.add(ee),I.size===1&&K.forEach(([L,y],f)=>{if(y)throw new Error("remove already exists");const d=L[3](q(f));K.set(f,[L,d])}),()=>{I.delete(ee),I.size===0&&K.forEach(([L,y],f)=>{y&&(y(),K.set(f,[L]))})}),k=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),_=e(k,{deleteProperty(ee,ie){const L=Reflect.get(ee,ie);W(ie);const y=Reflect.deleteProperty(ee,ie);return y&&S(["delete",[ie],L]),y},set(ee,ie,L,y){const f=Reflect.has(ee,ie),d=Reflect.get(ee,ie,y);if(f&&(t(d,L)||a.has(L)&&t(d,a.get(L))))return!0;W(ie),w1(L)&&(L=TR(L)||L);let v=L;if(L instanceof Promise)L.then(E=>{L.status="fulfilled",L.value=E,S(["resolve",[ie],E])}).catch(E=>{L.status="rejected",L.reason=E,S(["reject",[ie],E])});else{!fo.has(L)&&r(L)&&(v=h(L));const E=!zh.has(v)&&fo.get(v);E&&F(ie,E)}return Reflect.set(ee,ie,v,y),S(["set",[ie],L,d]),!0}});a.set(l,_);const B=[k,T,s,R];return fo.set(_,B),Reflect.ownKeys(l).forEach(ee=>{const ie=Object.getOwnPropertyDescriptor(l,ee);"value"in ie&&(_[ee]=l[ee],delete ie.value,delete ie.writable),Object.defineProperty(k,ee,ie)}),_})=>[h,fo,zh,t,e,r,i,n,s,a,u],[BR]=LR();function ho(t={}){return BR(t)}function ia(t,e,r){const i=fo.get(t);i||console.warn("Please use proxy object");let n;const s=[],a=i[3];let u=!1;const l=a(b=>{if(s.push(b),r){e(s.splice(0));return}n||(n=Promise.resolve().then(()=>{n=void 0,u&&e(s.splice(0))}))});return u=!0,()=>{u=!1,l()}}function FR(t,e){const r=fo.get(t);r||console.warn("Please use proxy object");const[i,n,s]=r;return s(i,n(),e)}const Br=ho({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),fr={state:Br,subscribe(t){return ia(Br,()=>t(Br))},push(t,e){t!==Br.view&&(Br.view=t,e&&(Br.data=e),Br.history.push(t))},reset(t){Br.view=t,Br.history=[t]},replace(t){Br.history.length>1&&(Br.history[Br.history.length-1]=t,Br.view=t)},goBack(){if(Br.history.length>1){Br.history.pop();const[t]=Br.history.slice(-1);Br.view=t}},setData(t){Br.data=t}},Qe={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return Qe.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const t=navigator.userAgent.toLowerCase();return Qe.isMobile()&&(t.includes("iphone")||t.includes("ipad"))},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},isArray(t){return Array.isArray(t)&&t.length>0},formatNativeUrl(t,e,r){if(Qe.isHttpUrl(t))return this.formatUniversalUrl(t,e,r);let i=t;i.includes("://")||(i=t.replaceAll("/","").replaceAll(":",""),i=`${i}://`),i.endsWith("/")||(i=`${i}/`),this.setWalletConnectDeepLink(i,r);const n=encodeURIComponent(e);return`${i}wc?uri=${n}`},formatUniversalUrl(t,e,r){if(!Qe.isHttpUrl(t))return this.formatNativeUrl(t,e,r);let i=t;i.endsWith("/")||(i=`${i}/`),this.setWalletConnectDeepLink(i,r);const n=encodeURIComponent(e);return`${i}wc?uri=${n}`},async wait(t){return new Promise(e=>{setTimeout(e,t)})},openHref(t,e){window.open(t,e,"noreferrer noopener")},setWalletConnectDeepLink(t,e){try{localStorage.setItem(Qe.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(t){try{const[e]=t.split("?");localStorage.setItem(Qe.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(Qe.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(Qe.WCM_VERSION,"2.6.2")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var t;const e=(t=fr.state.data)==null?void 0:t.Wallet;if(!e)throw new Error('Missing "Wallet" view data');return e}},UR=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),Qr=ho({enabled:UR,userSessionId:"",events:[],connectedWalletId:void 0}),S6={state:Qr,subscribe(t){return ia(Qr.events,()=>t(FR(Qr.events[Qr.events.length-1])))},initialize(){Qr.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(Qr.userSessionId=crypto.randomUUID())},setConnectedWalletId(t){Qr.connectedWalletId=t},click(t){if(Qr.enabled){const e={type:"CLICK",name:t.name,userSessionId:Qr.userSessionId,timestamp:Date.now(),data:t};Qr.events.push(e)}},track(t){if(Qr.enabled){const e={type:"TRACK",name:t.name,userSessionId:Qr.userSessionId,timestamp:Date.now(),data:t};Qr.events.push(e)}},view(t){if(Qr.enabled){const e={type:"VIEW",name:t.name,userSessionId:Qr.userSessionId,timestamp:Date.now(),data:t};Qr.events.push(e)}}},vs=ho({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),wr={state:vs,subscribe(t){return ia(vs,()=>t(vs))},setChains(t){vs.chains=t},setWalletConnectUri(t){vs.walletConnectUri=t},setIsCustomDesktop(t){vs.isCustomDesktop=t},setIsCustomMobile(t){vs.isCustomMobile=t},setIsDataLoaded(t){vs.isDataLoaded=t},setIsUiLoaded(t){vs.isUiLoaded=t},setIsAuth(t){vs.isAuth=t}},Hh=ho({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),ki={state:Hh,subscribe(t){return ia(Hh,()=>t(Hh))},setConfig(t){var e,r;S6.initialize(),wr.setChains(t.chains),wr.setIsAuth(!!t.enableAuthMode),wr.setIsCustomMobile(!!((e=t.mobileWallets)!=null&&e.length)),wr.setIsCustomDesktop(!!((r=t.desktopWallets)!=null&&r.length)),Qe.setModalVersionInStorage(),Object.assign(Hh,t)}};var kR=Object.defineProperty,I6=Object.getOwnPropertySymbols,qR=Object.prototype.hasOwnProperty,jR=Object.prototype.propertyIsEnumerable,M6=(t,e,r)=>e in t?kR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zR=(t,e)=>{for(var r in e||(e={}))qR.call(e,r)&&M6(t,r,e[r]);if(I6)for(var r of I6(e))jR.call(e,r)&&M6(t,r,e[r]);return t};const _1="https://explorer-api.walletconnect.com",E1="wcm",A1="js-2.6.2";async function Kh(t,e){const r=zR({sdkType:E1,sdkVersion:A1},e),i=new URL(t,_1);return i.searchParams.append("projectId",ki.state.projectId),Object.entries(r).forEach(([n,s])=>{s&&i.searchParams.append(n,String(s))}),(await fetch(i)).json()}const na={async getDesktopListings(t){return Kh("/w3m/v1/getDesktopListings",t)},async getMobileListings(t){return Kh("/w3m/v1/getMobileListings",t)},async getInjectedListings(t){return Kh("/w3m/v1/getInjectedListings",t)},async getAllListings(t){return Kh("/w3m/v1/getAllListings",t)},getWalletImageUrl(t){return`${_1}/w3m/v1/getWalletImage/${t}?projectId=${ki.state.projectId}&sdkType=${E1}&sdkVersion=${A1}`},getAssetImageUrl(t){return`${_1}/w3m/v1/getAssetImage/${t}?projectId=${ki.state.projectId}&sdkType=${E1}&sdkVersion=${A1}`}};var HR=Object.defineProperty,C6=Object.getOwnPropertySymbols,KR=Object.prototype.hasOwnProperty,WR=Object.prototype.propertyIsEnumerable,D6=(t,e,r)=>e in t?HR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,VR=(t,e)=>{for(var r in e||(e={}))KR.call(e,r)&&D6(t,r,e[r]);if(C6)for(var r of C6(e))WR.call(e,r)&&D6(t,r,e[r]);return t};const O6=Qe.isMobile(),ms=ho({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),xi={state:ms,async getRecomendedWallets(){const{explorerRecommendedWalletIds:t,explorerExcludedWalletIds:e}=ki.state;if(t==="NONE"||e==="ALL"&&!t)return ms.recomendedWallets;if(Qe.isArray(t)){const r={recommendedIds:t.join(",")},{listings:i}=await na.getAllListings(r),n=Object.values(i);n.sort((s,a)=>{const u=t.indexOf(s.id),h=t.indexOf(a.id);return u-h}),ms.recomendedWallets=n}else{const{chains:r,isAuth:i}=wr.state,n=r?.join(","),s=Qe.isArray(e),a={page:1,sdks:i?"auth_v1":void 0,entries:Qe.RECOMMENDED_WALLET_AMOUNT,chains:n,version:2,excludedIds:s?e.join(","):void 0},{listings:u}=O6?await na.getMobileListings(a):await na.getDesktopListings(a);ms.recomendedWallets=Object.values(u)}return ms.recomendedWallets},async getWallets(t){const e=VR({},t),{explorerRecommendedWalletIds:r,explorerExcludedWalletIds:i}=ki.state,{recomendedWallets:n}=ms;if(i==="ALL")return ms.wallets;n.length?e.excludedIds=n.map(w=>w.id).join(","):Qe.isArray(r)&&(e.excludedIds=r.join(",")),Qe.isArray(i)&&(e.excludedIds=[e.excludedIds,i].filter(Boolean).join(",")),wr.state.isAuth&&(e.sdks="auth_v1");const{page:s,search:a}=t,{listings:u,total:h}=O6?await na.getMobileListings(e):await na.getDesktopListings(e),l=Object.values(u),b=a?"search":"wallets";return ms[b]={listings:[...ms[b].listings,...l],total:h,page:s??1},{listings:l,total:h}},getWalletImageUrl(t){return na.getWalletImageUrl(t)},getAssetImageUrl(t){return na.getAssetImageUrl(t)},resetSearch(){ms.search={listings:[],total:0,page:1}}},gc=ho({open:!1}),sa={state:gc,subscribe(t){return ia(gc,()=>t(gc))},async open(t){return new Promise(e=>{const{isUiLoaded:r,isDataLoaded:i}=wr.state;if(Qe.removeWalletConnectDeepLink(),wr.setWalletConnectUri(t?.uri),wr.setChains(t?.chains),fr.reset("ConnectWallet"),r&&i)gc.open=!0,e();else{const n=setInterval(()=>{const s=wr.state;s.isUiLoaded&&s.isDataLoaded&&(clearInterval(n),gc.open=!0,e())},200)}})},close(){gc.open=!1}};var GR=Object.defineProperty,P6=Object.getOwnPropertySymbols,JR=Object.prototype.hasOwnProperty,YR=Object.prototype.propertyIsEnumerable,$6=(t,e,r)=>e in t?GR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,QR=(t,e)=>{for(var r in e||(e={}))JR.call(e,r)&&$6(t,r,e[r]);if(P6)for(var r of P6(e))YR.call(e,r)&&$6(t,r,e[r]);return t};function ZR(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const ku=ho({themeMode:ZR()?"dark":"light"}),lo={state:ku,subscribe(t){return ia(ku,()=>t(ku))},setThemeConfig(t){const{themeMode:e,themeVariables:r}=t;e&&(ku.themeMode=e),r&&(ku.themeVariables=QR({},r))}},oa=ho({open:!1,message:"",variant:"success"}),po={state:oa,subscribe(t){return ia(oa,()=>t(oa))},openToast(t,e){oa.open=!0,oa.message=t,oa.variant=e},closeToast(){oa.open=!1}};class XR{constructor(e){this.openModal=sa.open,this.closeModal=sa.close,this.subscribeModal=sa.subscribe,this.setTheme=lo.setThemeConfig,lo.setThemeConfig(e),ki.setConfig(e),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(function(){return cF});const e=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",e),wr.setIsUiLoaded(!0)}}}var eN=Object.freeze({__proto__:null,WalletConnectModal:XR});/**
|
|
70
70
|
* @license
|
|
71
71
|
* Copyright 2019 Google LLC
|
|
72
72
|
* SPDX-License-Identifier: BSD-3-Clause
|