@walletconnect/ethereum-provider 2.23.6 → 2.23.7
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.umd.js +5 -5
- package/dist/index.umd.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
|
@@ -16,10 +16,10 @@
|
|
|
16
16
|
`);super(a,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${RD()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=i,this.shortMessage=t}walk(t){return XA(this,t)}}function XA(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?XA(e.cause,t):t?null:e}const Pd=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function R2(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Xl(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Oa(e,...t){if(!R2(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function JA(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Xl(e.outputLen),Xl(e.blockLen)}function Od(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function QA(e,t){Oa(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function BD(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function qs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function w6(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Zs(e,t){return e<<32-t|e>>>t}function B2(e,t){return e<<t|e>>>32-t>>>0}const MD=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function DD(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function UD(e){for(let t=0;t<e.length;t++)e[t]=DD(e[t]);return e}const e9=MD?e=>e:UD,t9=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",LD=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function kd(e){if(Oa(e),t9)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=LD[e[n]];return t}const ka={_0:48,_9:57,A:65,F:70,a:97,f:102};function n9(e){if(e>=ka._0&&e<=ka._9)return e-ka._0;if(e>=ka.A&&e<=ka.F)return e-(ka.A-10);if(e>=ka.a&&e<=ka.f)return e-(ka.a-10)}function M2(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(t9)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=n9(e.charCodeAt(s)),a=n9(e.charCodeAt(s+1));if(o===void 0||a===void 0){const c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function b6(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function D2(e){return typeof e=="string"&&(e=b6(e)),Oa(e),e}function Gs(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];Oa(i),t+=i.length}const n=new Uint8Array(t);for(let r=0,i=0;r<e.length;r++){const s=e[r];n.set(s,i),i+=s.length}return n}class v6{}function Of(e){const t=r=>e().update(D2(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Rd(e=32){if(Pd&&typeof Pd.getRandomValues=="function")return Pd.getRandomValues(new Uint8Array(e));if(Pd&&typeof Pd.randomBytes=="function")return Uint8Array.from(Pd.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function FD(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}function HD(e,t,n){return e&t^~e&n}function jD(e,t,n){return e&t^e&n^t&n}class E6 extends v6{constructor(t,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=w6(this.buffer)}update(t){Od(this),t=D2(t),Oa(t);const{view:n,buffer:r,blockLen:i}=this,s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=w6(t);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Od(this),QA(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,qs(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let d=o;d<i;d++)n[d]=0;FD(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=w6(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=a,i%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}}const Ra=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ir=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),sr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),zD=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),r9=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),VD=r9.map(e=>(9*e+5)%16),i9=(()=>{const n=[[r9],[VD]];for(let r=0;r<4;r++)for(let i of n)i.push(i[r].map(s=>zD[s]));return n})(),s9=i9[0],o9=i9[1],a9=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),WD=s9.map((e,t)=>e.map(n=>a9[t][n])),qD=o9.map((e,t)=>e.map(n=>a9[t][n])),ZD=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),GD=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function c9(e,t,n,r){return e===0?t^n^r:e===1?t&n|~t&r:e===2?(t|~n)^r:e===3?t&r|n&~r:t^(n|~r)}const U2=new Uint32Array(16);class KD extends E6{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:n,h2:r,h3:i,h4:s}=this;return[t,n,r,i,s]}set(t,n,r,i,s){this.h0=t|0,this.h1=n|0,this.h2=r|0,this.h3=i|0,this.h4=s|0}process(t,n){for(let f=0;f<16;f++,n+=4)U2[f]=t.getUint32(n,!0);let r=this.h0|0,i=r,s=this.h1|0,o=s,a=this.h2|0,c=a,l=this.h3|0,u=l,d=this.h4|0,h=d;for(let f=0;f<5;f++){const p=4-f,g=ZD[f],y=GD[f],A=s9[f],_=o9[f],v=WD[f],w=qD[f];for(let T=0;T<16;T++){const O=B2(r+c9(f,s,a,l)+U2[A[T]]+g,v[T])+d|0;r=d,d=l,l=B2(a,10)|0,a=s,s=O}for(let T=0;T<16;T++){const O=B2(i+c9(p,o,c,u)+U2[_[T]]+y,w[T])+h|0;i=h,h=u,u=B2(c,10)|0,c=o,o=O}}this.set(this.h1+a+u|0,this.h2+l+h|0,this.h3+d+i|0,this.h4+r+o|0,this.h0+s+c|0)}roundClean(){qs(U2)}destroy(){this.destroyed=!0,qs(this.buffer),this.set(0,0,0,0,0)}}const YD=Of(()=>new KD),L2=BigInt(2**32-1),l9=BigInt(32);function XD(e,t=!1){return t?{h:Number(e&L2),l:Number(e>>l9&L2)}:{h:Number(e>>l9&L2)|0,l:Number(e&L2)|0}}function u9(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=XD(e[s],t);[r[s],i[s]]=[o,a]}return[r,i]}const d9=(e,t,n)=>e>>>n,f9=(e,t,n)=>e<<32-n|t>>>n,Bd=(e,t,n)=>e>>>n|t<<32-n,Md=(e,t,n)=>e<<32-n|t>>>n,F2=(e,t,n)=>e<<64-n|t>>>n-32,H2=(e,t,n)=>e>>>n-32|t<<64-n,JD=(e,t,n)=>e<<n|t>>>32-n,QD=(e,t,n)=>t<<n|e>>>32-n,eU=(e,t,n)=>t<<n-32|e>>>64-n,tU=(e,t,n)=>e<<n-32|t>>>64-n;function Ba(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}const nU=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),rU=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,iU=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),sU=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,oU=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),aU=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,cU=BigInt(0),kf=BigInt(1),lU=BigInt(2),uU=BigInt(7),dU=BigInt(256),fU=BigInt(113),h9=[],p9=[],g9=[];for(let e=0,t=kf,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],h9.push(2*(5*r+n)),p9.push((e+1)*(e+2)/2%64);let i=cU;for(let s=0;s<7;s++)t=(t<<kf^(t>>uU)*fU)%dU,t&lU&&(i^=kf<<(kf<<BigInt(s))-kf);g9.push(i)}const m9=u9(g9,!0),hU=m9[0],pU=m9[1],y9=(e,t,n)=>n>32?eU(e,t,n):JD(e,t,n),w9=(e,t,n)=>n>32?tU(e,t,n):QD(e,t,n);function gU(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let o=0;o<10;o++)n[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=n[c],u=n[c+1],d=y9(l,u,1)^n[a],h=w9(l,u,1)^n[a+1];for(let f=0;f<50;f+=10)e[o+f]^=d,e[o+f+1]^=h}let i=e[2],s=e[3];for(let o=0;o<24;o++){const a=p9[o],c=y9(i,s,a),l=w9(i,s,a),u=h9[o];i=e[u],s=e[u+1],e[u]=c,e[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=e[o+a];for(let a=0;a<10;a++)e[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}e[0]^=hU[r],e[1]^=pU[r]}qs(n)}class A6 extends v6{constructor(t,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,Xl(r),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=BD(this.state)}clone(){return this._cloneInto()}keccak(){e9(this.state32),gU(this.state32,this.rounds),e9(this.state32),this.posOut=0,this.pos=0}update(t){Od(this),t=D2(t),Oa(t);const{blockLen:n,state:r}=this,i=t.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=t[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:n,pos:r,blockLen:i}=this;t[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){Od(this,!1),Oa(t),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=t.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);t.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Xl(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(QA(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,qs(this.state)}_cloneInto(t){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return t||(t=new A6(n,r,i,o,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=r,t.outputLen=i,t.enableXOF=o,t.destroyed=this.destroyed,t}}const mU=(e,t,n)=>Of(()=>new A6(t,e,n)),C6=mU(1,136,256/8),yU=Uint32Array.from([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]),xc=new Uint32Array(64);class wU extends E6{constructor(t=32){super(64,t,8,!1),this.A=Ra[0]|0,this.B=Ra[1]|0,this.C=Ra[2]|0,this.D=Ra[3]|0,this.E=Ra[4]|0,this.F=Ra[5]|0,this.G=Ra[6]|0,this.H=Ra[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[t,n,r,i,s,o,a,c]}set(t,n,r,i,s,o,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,n){for(let d=0;d<16;d++,n+=4)xc[d]=t.getUint32(n,!1);for(let d=16;d<64;d++){const h=xc[d-15],f=xc[d-2],p=Zs(h,7)^Zs(h,18)^h>>>3,g=Zs(f,17)^Zs(f,19)^f>>>10;xc[d]=g+xc[d-7]+p+xc[d-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const h=Zs(a,6)^Zs(a,11)^Zs(a,25),f=u+h+HD(a,c,l)+yU[d]+xc[d]|0,g=(Zs(r,2)^Zs(r,13)^Zs(r,22))+jD(r,i,s)|0;u=l,l=c,c=a,a=o+f|0,o=s,s=i,i=r,r=f+g|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,i,s,o,a,c,l,u)}roundClean(){qs(xc)}destroy(){this.set(0,0,0,0,0,0,0,0),qs(this.buffer)}}const b9=u9(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),bU=b9[0],vU=b9[1],_c=new Uint32Array(80),Sc=new Uint32Array(80);class v9 extends E6{constructor(t=64){super(128,t,16,!1),this.Ah=sr[0]|0,this.Al=sr[1]|0,this.Bh=sr[2]|0,this.Bl=sr[3]|0,this.Ch=sr[4]|0,this.Cl=sr[5]|0,this.Dh=sr[6]|0,this.Dl=sr[7]|0,this.Eh=sr[8]|0,this.El=sr[9]|0,this.Fh=sr[10]|0,this.Fl=sr[11]|0,this.Gh=sr[12]|0,this.Gl=sr[13]|0,this.Hh=sr[14]|0,this.Hl=sr[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:h,Gh:f,Gl:p,Hh:g,Hl:y}=this;return[t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y]}set(t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=h|0,this.Gh=f|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}process(t,n){for(let v=0;v<16;v++,n+=4)_c[v]=t.getUint32(n),Sc[v]=t.getUint32(n+=4);for(let v=16;v<80;v++){const w=_c[v-15]|0,T=Sc[v-15]|0,O=Bd(w,T,1)^Bd(w,T,8)^d9(w,T,7),D=Md(w,T,1)^Md(w,T,8)^f9(w,T,7),F=_c[v-2]|0,U=Sc[v-2]|0,j=Bd(F,U,19)^F2(F,U,61)^d9(F,U,6),W=Md(F,U,19)^H2(F,U,61)^f9(F,U,6),S=iU(D,W,Sc[v-7],Sc[v-16]),x=sU(S,O,j,_c[v-7],_c[v-16]);_c[v]=x|0,Sc[v]=S|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:h,Fh:f,Fl:p,Gh:g,Gl:y,Hh:A,Hl:_}=this;for(let v=0;v<80;v++){const w=Bd(d,h,14)^Bd(d,h,18)^F2(d,h,41),T=Md(d,h,14)^Md(d,h,18)^H2(d,h,41),O=d&f^~d&g,D=h&p^~h&y,F=oU(_,T,D,vU[v],Sc[v]),U=aU(F,A,w,O,bU[v],_c[v]),j=F|0,W=Bd(r,i,28)^F2(r,i,34)^F2(r,i,39),S=Md(r,i,28)^H2(r,i,34)^H2(r,i,39),x=r&s^r&a^s&a,I=i&o^i&c^o&c;A=g|0,_=y|0,g=f|0,y=p|0,f=d|0,p=h|0,{h:d,l:h}=Ba(l|0,u|0,U|0,j|0),l=a|0,u=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const m=nU(j,S,I);r=rU(m,U,W,x),i=m|0}({h:r,l:i}=Ba(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=Ba(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Ba(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Ba(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:h}=Ba(this.Eh|0,this.El|0,d|0,h|0),{h:f,l:p}=Ba(this.Fh|0,this.Fl|0,f|0,p|0),{h:g,l:y}=Ba(this.Gh|0,this.Gl|0,g|0,y|0),{h:A,l:_}=Ba(this.Hh|0,this.Hl|0,A|0,_|0),this.set(r,i,s,o,a,c,l,u,d,h,f,p,g,y,A,_)}roundClean(){qs(_c,Sc)}destroy(){qs(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class EU extends v9{constructor(){super(48),this.Ah=ir[0]|0,this.Al=ir[1]|0,this.Bh=ir[2]|0,this.Bl=ir[3]|0,this.Ch=ir[4]|0,this.Cl=ir[5]|0,this.Dh=ir[6]|0,this.Dl=ir[7]|0,this.Eh=ir[8]|0,this.El=ir[9]|0,this.Fh=ir[10]|0,this.Fl=ir[11]|0,this.Gh=ir[12]|0,this.Gl=ir[13]|0,this.Hh=ir[14]|0,this.Hl=ir[15]|0}}const ls=Of(()=>new wU),AU=Of(()=>new v9),CU=Of(()=>new EU),xU=ls;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const x6=BigInt(0),j2=BigInt(1);function Rf(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ic(e){if(!Rf(e))throw new Error("Uint8Array expected")}function Bf(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function z2(e){const t=e.toString(16);return t.length&1?"0"+t:t}function E9(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?x6:BigInt("0x"+e)}const A9=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",_U=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Jl(e){if(Ic(e),A9)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=_U[e[n]];return t}const Ma={_0:48,_9:57,A:65,F:70,a:97,f:102};function C9(e){if(e>=Ma._0&&e<=Ma._9)return e-Ma._0;if(e>=Ma.A&&e<=Ma.F)return e-(Ma.A-10);if(e>=Ma.a&&e<=Ma.f)return e-(Ma.a-10)}function V2(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(A9)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=C9(e.charCodeAt(s)),a=C9(e.charCodeAt(s+1));if(o===void 0||a===void 0){const c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function Cr(e){return E9(Jl(e))}function x9(e){return Ic(e),E9(Jl(Uint8Array.from(e).reverse()))}function _n(e,t){return V2(e.toString(16).padStart(t*2,"0"))}function _9(e,t){return _n(e,t).reverse()}function or(e,t,n){let r;if(typeof t=="string")try{r=V2(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(Rf(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}function dn(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];Ic(i),t+=i.length}const n=new Uint8Array(t);for(let r=0,i=0;r<e.length;r++){const s=e[r];n.set(s,i),i+=s.length}return n}function _6(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}const S6=e=>typeof e=="bigint"&&x6<=e;function I6(e,t,n){return S6(e)&&S6(t)&&S6(n)&&t<=e&&e<n}function Dd(e,t,n,r){if(!I6(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Mf(e){let t;for(t=0;e>x6;e>>=j2,t+=1);return t}function SU(e,t){return e>>BigInt(t)&j2}const Ql=e=>(j2<<BigInt(e))-j2,$6=e=>new Uint8Array(e),S9=e=>Uint8Array.from(e);function IU(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=$6(e),i=$6(e),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},a=(...d)=>n(i,r,...d),c=(d=$6(0))=>{i=a(S9([0]),d),r=a(),d.length!==0&&(i=a(S9([1]),d),r=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const h=[];for(;d<t;){r=a();const f=r.slice();h.push(f),d+=r.length}return dn(...h)};return(d,h)=>{o(),c(d);let f;for(;!(f=h(l()));)c();return o(),f}}const $U={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||Rf(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function Df(e,t,n={}){const r=(i,s,o)=>{const a=$U[s];if(typeof a!="function")throw new Error("invalid validator function");const c=e[i];if(!(o&&c===void 0)&&!a(c,e))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(t))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return e}const I9=()=>{throw new Error("not implemented")};function T6(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(i!==void 0)return i;const s=e(n,...r);return t.set(n,s),s}}function TU(e,t){if(k9(e)>t)throw new XU({givenSize:k9(e),maxSize:t})}const Da={zero:48,nine:57,A:65,F:70,a:97,f:102};function $9(e){if(e>=Da.zero&&e<=Da.nine)return e-Da.zero;if(e>=Da.A&&e<=Da.F)return e-(Da.A-10);if(e>=Da.a&&e<=Da.f)return e-(Da.a-10)}function NU(e,t={}){const{dir:n,size:r=32}=t;if(r===0)return e;if(e.length>r)throw new JU({size:e.length,targetSize:r,type:"Bytes"});const i=new Uint8Array(r);for(let s=0;s<r;s++){const o=n==="right";i[o?s:r-s-1]=e[o?s:e.length-s-1]}return i}function N6(e,t){if(La(e)>t)throw new HU({givenSize:La(e),maxSize:t})}function PU(e,t){if(typeof t=="number"&&t>0&&t>La(e)-1)throw new O9({offset:t,position:"start",size:La(e)})}function OU(e,t,n){if(typeof t=="number"&&typeof n=="number"&&La(e)!==n-t)throw new O9({offset:n,position:"end",size:La(e)})}function T9(e,t={}){const{dir:n,size:r=32}=t;if(r===0)return e;const i=e.replace("0x","");if(i.length>r*2)throw new jU({size:Math.ceil(i.length/2),targetSize:r,type:"Hex"});return`0x${i[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const kU="#__bigint";function P6(e,t,n){return JSON.stringify(e,(r,i)=>typeof t=="function"?t(r,i):typeof i=="bigint"?i.toString()+kU:i,n)}const RU=new TextEncoder,BU=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function MU(e,t={}){const{strict:n=!1}=t;if(!e)throw new N9(e);if(typeof e!="string")throw new N9(e);if(n&&!/^0x[0-9a-fA-F]*$/.test(e))throw new P9(e);if(!e.startsWith("0x"))throw new P9(e)}function O6(...e){return`0x${e.reduce((t,n)=>t+n.replace("0x",""),"")}`}function k6(e){return e instanceof Uint8Array?Uf(e):Array.isArray(e)?Uf(new Uint8Array(e)):e}function DU(e,t={}){const n=`0x${Number(e)}`;return typeof t.size=="number"?(N6(n,t.size),q2(n,t.size)):n}function Uf(e,t={}){let n="";for(let i=0;i<e.length;i++)n+=BU[e[i]];const r=`0x${n}`;return typeof t.size=="number"?(N6(r,t.size),R6(r,t.size)):r}function W2(e,t={}){const{signed:n,size:r}=t,i=BigInt(e);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const l=typeof e=="bigint"?"n":"";throw new FU({max:s?`${s}${l}`:void 0,min:`${o}${l}`,signed:n,size:r,value:`${e}${l}`})}const c=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?q2(c,r):c}function UU(e,t={}){return Uf(RU.encode(e),t)}function q2(e,t){return T9(e,{dir:"left",size:t})}function R6(e,t){return T9(e,{dir:"right",size:t})}function Ua(e,t,n,r={}){const{strict:i}=r;PU(e,t);const s=`0x${e.replace("0x","").slice((t??0)*2,(n??e.length)*2)}`;return i&&OU(s,t,n),s}function La(e){return Math.ceil((e.length-2)/2)}function LU(e,t={}){const{strict:n=!1}=t;try{return MU(e,{strict:n}),!0}catch{return!1}}class FU extends Ht{constructor({max:t,min:n,signed:r,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${r?" signed":" unsigned"} integer range ${t?`(\`${n}\` to \`${t}\`)`:`(above \`${n}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class N9 extends Ht{constructor(t){super(`Value \`${typeof t=="object"?P6(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class P9 extends Ht{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class HU extends Ht{constructor({givenSize:t,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class O9 extends Ht{constructor({offset:t,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class jU extends Ht{constructor({size:t,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}const zU=new TextEncoder;function VU(e){if(!(e instanceof Uint8Array)){if(!e)throw new Z2(e);if(typeof e!="object")throw new Z2(e);if(!("BYTES_PER_ELEMENT"in e))throw new Z2(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new Z2(e)}}function WU(e){return e instanceof Uint8Array?e:typeof e=="string"?ZU(e):qU(e)}function qU(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function ZU(e,t={}){const{size:n}=t;let r=e;n&&(N6(e,n),r=R6(e,n));let i=r.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const l=$9(i.charCodeAt(c++)),u=$9(i.charCodeAt(c++));if(l===void 0||u===void 0)throw new Ht(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=l*16+u}return o}function GU(e,t={}){const{size:n}=t,r=zU.encode(e);return typeof n=="number"?(TU(r,n),KU(r,n)):r}function KU(e,t){return NU(e,{dir:"right",size:t})}function k9(e){return e.length}function YU(e){try{return VU(e),!0}catch{return!1}}class Z2 extends Ht{constructor(t){super(`Value \`${typeof t=="object"?P6(t):t}\` of type \`${typeof t}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class XU extends Ht{constructor({givenSize:t,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class JU extends Ht{constructor({size:t,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function R9(e,t={}){const{as:n=typeof e=="string"?"Hex":"Bytes"}=t,r=C6(WU(e));return n==="Bytes"?r:Uf(r)}class QU extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const n=super.get(t);return super.has(t)&&n!==void 0&&(this.delete(t),super.set(t,n)),n}set(t,n){if(super.set(t,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const B6={checksum:new QU(8192)}.checksum;function B9(e,t={}){const{compressed:n}=t,{prefix:r,x:i,y:s}=e;if(n===!1||typeof i=="bigint"&&typeof s=="bigint"){if(r!==4)throw new D9({prefix:r,cause:new sL});return}if(n===!0||typeof i=="bigint"&&typeof s>"u"){if(r!==3&&r!==2)throw new D9({prefix:r,cause:new iL});return}throw new rL({publicKey:e})}function eL(e){const t=(()=>{if(LU(e))return M9(e);if(YU(e))return tL(e);const{prefix:n,x:r,y:i}=e;return typeof r=="bigint"&&typeof i=="bigint"?{prefix:n??4,x:r,y:i}:{prefix:n,x:r}})();return B9(t),t}function tL(e){return M9(Uf(e))}function M9(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new oL({publicKey:e});if(e.length===130){const r=BigInt(Ua(e,0,32)),i=BigInt(Ua(e,32,64));return{prefix:4,x:r,y:i}}if(e.length===132){const r=Number(Ua(e,0,1)),i=BigInt(Ua(e,1,33)),s=BigInt(Ua(e,33,65));return{prefix:r,x:i,y:s}}const t=Number(Ua(e,0,1)),n=BigInt(Ua(e,1,33));return{prefix:t,x:n}}function nL(e,t={}){B9(e);const{prefix:n,x:r,y:i}=e,{includePrefix:s=!0}=t;return O6(s?W2(n,{size:1}):"0x",W2(r,{size:32}),typeof i=="bigint"?W2(i,{size:32}):"0x")}class rL extends Ht{constructor({publicKey:t}){super(`Value \`${P6(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class D9 extends Ht{constructor({prefix:t,cause:n}){super(`Prefix "${t}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class iL extends Ht{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class sL extends Ht{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class oL extends Ht{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${La(k6(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}const aL=/^0x[a-fA-F0-9]{40}$/;function M6(e,t={}){const{strict:n=!0}=t;if(!aL.test(e))throw new L9({address:e,cause:new uL});if(n){if(e.toLowerCase()===e)return;if(U9(e)!==e)throw new L9({address:e,cause:new dL})}}function U9(e){if(B6.has(e))return B6.get(e);M6(e,{strict:!1});const t=e.substring(2).toLowerCase(),n=R9(GU(t),{as:"Bytes"}),r=t.split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&r[s]&&(r[s]=r[s].toUpperCase()),(n[s>>1]&15)>=8&&r[s+1]&&(r[s+1]=r[s+1].toUpperCase());const i=`0x${r.join("")}`;return B6.set(e,i),i}function cL(e,t={}){const{checksum:n=!1}=t;return M6(e),n?U9(e):e}function lL(e,t={}){const n=R9(`0x${nL(e).slice(4)}`).substring(26);return cL(`0x${n}`,t)}class L9 extends Ht{constructor({address:t,cause:n}){super(`Address "${t}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class uL extends Ht{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class dL extends Ht{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const fL=/^(.*)\[([0-9]*)\]$/,hL=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,pL=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function D6(e,t){if(e.length!==t.length)throw new mL({expectedLength:e.length,givenLength:t.length});const n=[];for(let r=0;r<e.length;r++){const i=e[r],s=t[r];n.push(D6.encode(i,s))}return O6(...n)}(function(e){function t(n,r,i=!1){if(n==="address"){const c=r;return M6(c),q2(c.toLowerCase(),i?32:0)}if(n==="string")return UU(r);if(n==="bytes")return r;if(n==="bool")return q2(DU(r),i?32:1);const s=n.match(pL);if(s){const[c,l,u="256"]=s,d=Number.parseInt(u,10)/8;return W2(r,{size:i?32:d,signed:l==="int"})}const o=n.match(hL);if(o){const[c,l]=o;if(Number.parseInt(l,10)!==(r.length-2)/2)throw new gL({expectedSize:Number.parseInt(l,10),value:r});return R6(r,i?32:0)}const a=n.match(fL);if(a&&Array.isArray(r)){const[c,l]=a,u=[];for(let d=0;d<r.length;d++)u.push(t(l,r[d],!0));return u.length===0?"0x":O6(...u)}throw new yL(n)}e.encode=t})(D6||(D6={}));class gL extends Ht{constructor({expectedSize:t,value:n}){super(`Size of bytes "${n}" (bytes${La(n)}) does not match expected size (bytes${t}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class mL extends Ht{constructor({expectedLength:t,givenLength:n}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${t}`,`Given length (values): ${n}`].join(`
|
|
17
17
|
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class yL extends Ht{constructor(t){super(`Type \`${t}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class F9 extends v6{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,JA(t);const r=D2(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),qs(s)}update(t){return Od(this),this.iHash.update(t),this}digestInto(t){Od(this),Oa(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const G2=(e,t,n)=>new F9(e,t).update(n).digest();G2.create=(e,t)=>new F9(e,t);const jr=BigInt(0),xr=BigInt(1),eu=BigInt(2),wL=BigInt(3),H9=BigInt(4),j9=BigInt(5),z9=BigInt(8);function _r(e,t){const n=e%t;return n>=jr?n:t+n}function Ri(e,t,n){let r=e;for(;t-- >jr;)r*=r,r%=n;return r}function U6(e,t){if(e===jr)throw new Error("invert: expected non-zero number");if(t<=jr)throw new Error("invert: expected positive modulus, got "+t);let n=_r(e,t),r=t,i=jr,s=xr;for(;n!==jr;){const a=r/n,c=r%n,l=i-s*a;r=n,n=c,i=s,s=l}if(r!==xr)throw new Error("invert: does not exist");return _r(i,t)}function V9(e,t){const n=(e.ORDER+xr)/H9,r=e.pow(t,n);if(!e.eql(e.sqr(r),t))throw new Error("Cannot find square root");return r}function bL(e,t){const n=(e.ORDER-j9)/z9,r=e.mul(t,eu),i=e.pow(r,n),s=e.mul(t,i),o=e.mul(e.mul(s,eu),i),a=e.mul(s,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function vL(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-xr,n=0;for(;t%eu===jr;)t/=eu,n++;let r=eu;const i=$c(e);for(;Y2(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return V9;let s=i.pow(r,t);const o=(t+xr)/eu;return function(c,l){if(c.is0(l))return l;if(Y2(c,l)!==1)throw new Error("Cannot find square root");let u=n,d=c.mul(c.ONE,s),h=c.pow(l,t),f=c.pow(l,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let p=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===u)throw new Error("Cannot find square root");const y=xr<<BigInt(u-p-1),A=c.pow(d,y);u=p,d=c.sqr(A),h=c.mul(h,d),f=c.mul(f,A)}return f}}function EL(e){return e%H9===wL?V9:e%z9===j9?bL:vL(e)}const AL=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function W9(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=AL.reduce((r,i)=>(r[i]="function",r),t);return Df(e,n)}function K2(e,t,n){if(n<jr)throw new Error("invalid exponent, negatives unsupported");if(n===jr)return e.ONE;if(n===xr)return t;let r=e.ONE,i=t;for(;n>jr;)n&xr&&(r=e.mul(r,i)),i=e.sqr(i),n>>=xr;return r}function tu(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((o,a,c)=>e.is0(a)?o:(r[c]=o,e.mul(o,a)),e.ONE),s=e.inv(i);return t.reduceRight((o,a,c)=>e.is0(a)?o:(r[c]=e.mul(o,r[c]),e.mul(o,a)),s),r}function Y2(e,t){const n=(e.ORDER-xr)/eu,r=e.pow(t,n),i=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function q9(e,t){t!==void 0&&Xl(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function $c(e,t,n=!1,r={}){if(e<=jr)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:i,nByteLength:s}=q9(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:n,BITS:i,BYTES:s,MASK:Ql(i),ZERO:jr,ONE:xr,create:c=>_r(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return jr<=c&&c<e},is0:c=>c===jr,isOdd:c=>(c&xr)===xr,neg:c=>_r(-c,e),eql:(c,l)=>c===l,sqr:c=>_r(c*c,e),add:(c,l)=>_r(c+l,e),sub:(c,l)=>_r(c-l,e),mul:(c,l)=>_r(c*l,e),pow:(c,l)=>K2(a,c,l),div:(c,l)=>_r(c*U6(l,e),e),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>U6(c,e),sqrt:r.sqrt||(c=>(o||(o=EL(e)),o(a,c))),toBytes:c=>n?_9(c,s):_n(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?x9(c):Cr(c)},invertBatch:c=>tu(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function Z9(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function L6(e){const t=Z9(e);return t+Math.ceil(t/2)}function G9(e,t,n=!1){const r=e.length,i=Z9(t),s=L6(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?x9(e):Cr(e),a=_r(o,t-xr)+xr;return n?_9(a,i):_n(a,i)}const K9=BigInt(0),F6=BigInt(1);function H6(e,t){const n=t.negate();return e?n:t}function Y9(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function j6(e,t){Y9(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e,s=Ql(e),o=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function X9(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(e&i),c=e>>o;a>r&&(a-=s,c+=F6);const l=t*r,u=l+Math.abs(a)-1,d=a===0,h=a<0,f=t%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:l}}function CL(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function xL(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const z6=new WeakMap,J9=new WeakMap;function V6(e){return J9.get(e)||1}function _L(e,t){return{constTimeNegate:H6,hasPrecomputes(n){return V6(n)!==1},unsafeLadder(n,r,i=e.ZERO){let s=n;for(;r>K9;)r&F6&&(i=i.add(s)),s=s.double(),r>>=F6;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=j6(r,t),o=[];let a=n,c=a;for(let l=0;l<i;l++){c=a,o.push(c);for(let u=1;u<s;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,i){let s=e.ZERO,o=e.BASE;const a=j6(n,t);for(let c=0;c<a.windows;c++){const{nextN:l,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:p}=X9(i,c,a);i=l,d?o=o.add(H6(f,r[p])):s=s.add(H6(h,r[u]))}return{p:s,f:o}},wNAFUnsafe(n,r,i,s=e.ZERO){const o=j6(n,t);for(let a=0;a<o.windows&&i!==K9;a++){const{nextN:c,offset:l,isZero:u,isNeg:d}=X9(i,a,o);if(i=c,!u){const h=r[l];s=s.add(d?h.negate():h)}}return s},getPrecomputes(n,r,i){let s=z6.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&z6.set(r,i(s))),s},wNAFCached(n,r,i){const s=V6(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=V6(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){Y9(r,t),J9.set(n,r),z6.delete(n)}}}function SL(e,t,n,r){CL(n,e),xL(r,t);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Mf(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Ql(c),u=new Array(Number(l)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c;let h=o;for(let f=d;f>=0;f-=c){u.fill(o);for(let g=0;g<s;g++){const y=r[g],A=Number(y>>BigInt(f)&l);u[A]=u[A].add(n[g])}let p=o;for(let g=u.length-1,y=o;g>0;g--)y=y.add(u[g]),p=p.add(y);if(h=h.add(p),f!==0)for(let g=0;g<c;g++)h=h.double()}return h}function Q9(e){return W9(e.Fp),Df(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...q9(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}function eC(e){e.lowS!==void 0&&Bf("lowS",e.lowS),e.prehash!==void 0&&Bf("prehash",e.prehash)}function IL(e){const t=Q9(e);Df(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:n,Fp:r,a:i}=t;if(n){if(!r.eql(i,r.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}class $L extends Error{constructor(t=""){super(t)}}const Fa={Err:$L,_tlv:{encode:(e,t)=>{const{Err:n}=Fa;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const r=t.length/2,i=z2(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?z2(i.length/2|128):"";return z2(e)+s+i+t},decode(e,t){const{Err:n}=Fa;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const i=t[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=t.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+o)}}},_int:{encode(e){const{Err:t}=Fa;if(e<us)throw new t("integer: negative integers are not allowed");let n=z2(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Fa;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Cr(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Fa,i=or("signature",e),{v:s,l:o}=r.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=Fa,r=t.encode(2,n.encode(e.r)),i=t.encode(2,n.encode(e.s)),s=r+i;return t.encode(48,s)}};function W6(e,t){return Jl(_n(e,t))}const us=BigInt(0),Ut=BigInt(1),Tc=BigInt(2),Lf=BigInt(3),q6=BigInt(4);function Z6(e){const t=IL(e),{Fp:n}=t,r=$c(t.n,t.nBitLength),i=t.toBytes||((v,w,T)=>{const O=w.toAffine();return dn(Uint8Array.from([4]),n.toBytes(O.x),n.toBytes(O.y))}),s=t.fromBytes||(v=>{const w=v.subarray(1),T=n.fromBytes(w.subarray(0,n.BYTES)),O=n.fromBytes(w.subarray(n.BYTES,2*n.BYTES));return{x:T,y:O}});function o(v){const{a:w,b:T}=t,O=n.sqr(v),D=n.mul(O,v);return n.add(n.add(D,n.mul(v,w)),T)}function a(v,w){const T=n.sqr(w),O=o(v);return n.eql(T,O)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");const c=n.mul(n.pow(t.a,Lf),q6),l=n.mul(n.sqr(t.b),BigInt(27));if(n.is0(n.add(c,l)))throw new Error("bad curve params: a or b");function u(v){return I6(v,Ut,t.n)}function d(v){const{allowedPrivateKeyLengths:w,nByteLength:T,wrapPrivateKey:O,n:D}=t;if(w&&typeof v!="bigint"){if(Rf(v)&&(v=Jl(v)),typeof v!="string"||!w.includes(v.length))throw new Error("invalid private key");v=v.padStart(T*2,"0")}let F;try{F=typeof v=="bigint"?v:Cr(or("private key",v,T))}catch{throw new Error("invalid private key, expected hex or "+T+" bytes, got "+typeof v)}return O&&(F=_r(F,D)),Dd("private key",F,Ut,D),F}function h(v){if(!(v instanceof g))throw new Error("ProjectivePoint expected")}const f=T6((v,w)=>{const{px:T,py:O,pz:D}=v;if(n.eql(D,n.ONE))return{x:T,y:O};const F=v.is0();w==null&&(w=F?n.ONE:n.inv(D));const U=n.mul(T,w),j=n.mul(O,w),W=n.mul(D,w);if(F)return{x:n.ZERO,y:n.ZERO};if(!n.eql(W,n.ONE))throw new Error("invZ was invalid");return{x:U,y:j}}),p=T6(v=>{if(v.is0()){if(t.allowInfinityPoint&&!n.is0(v.py))return;throw new Error("bad point: ZERO")}const{x:w,y:T}=v.toAffine();if(!n.isValid(w)||!n.isValid(T))throw new Error("bad point: x or y not FE");if(!a(w,T))throw new Error("bad point: equation left != right");if(!v.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(w,T,O){if(w==null||!n.isValid(w))throw new Error("x required");if(T==null||!n.isValid(T)||n.is0(T))throw new Error("y required");if(O==null||!n.isValid(O))throw new Error("z required");this.px=w,this.py=T,this.pz=O,Object.freeze(this)}static fromAffine(w){const{x:T,y:O}=w||{};if(!w||!n.isValid(T)||!n.isValid(O))throw new Error("invalid affine point");if(w instanceof g)throw new Error("projective point not allowed");const D=F=>n.eql(F,n.ZERO);return D(T)&&D(O)?g.ZERO:new g(T,O,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){const T=tu(n,w.map(O=>O.pz));return w.map((O,D)=>O.toAffine(T[D])).map(g.fromAffine)}static fromHex(w){const T=g.fromAffine(s(or("pointHex",w)));return T.assertValidity(),T}static fromPrivateKey(w){return g.BASE.multiply(d(w))}static msm(w,T){return SL(g,r,w,T)}_setWindowSize(w){_.setWindowSize(this,w)}assertValidity(){p(this)}hasEvenY(){const{y:w}=this.toAffine();if(n.isOdd)return!n.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){h(w);const{px:T,py:O,pz:D}=this,{px:F,py:U,pz:j}=w,W=n.eql(n.mul(T,j),n.mul(F,D)),S=n.eql(n.mul(O,j),n.mul(U,D));return W&&S}negate(){return new g(this.px,n.neg(this.py),this.pz)}double(){const{a:w,b:T}=t,O=n.mul(T,Lf),{px:D,py:F,pz:U}=this;let j=n.ZERO,W=n.ZERO,S=n.ZERO,x=n.mul(D,D),I=n.mul(F,F),m=n.mul(U,U),b=n.mul(D,F);return b=n.add(b,b),S=n.mul(D,U),S=n.add(S,S),j=n.mul(w,S),W=n.mul(O,m),W=n.add(j,W),j=n.sub(I,W),W=n.add(I,W),W=n.mul(j,W),j=n.mul(b,j),S=n.mul(O,S),m=n.mul(w,m),b=n.sub(x,m),b=n.mul(w,b),b=n.add(b,S),S=n.add(x,x),x=n.add(S,x),x=n.add(x,m),x=n.mul(x,b),W=n.add(W,x),m=n.mul(F,U),m=n.add(m,m),x=n.mul(m,b),j=n.sub(j,x),S=n.mul(m,I),S=n.add(S,S),S=n.add(S,S),new g(j,W,S)}add(w){h(w);const{px:T,py:O,pz:D}=this,{px:F,py:U,pz:j}=w;let W=n.ZERO,S=n.ZERO,x=n.ZERO;const I=t.a,m=n.mul(t.b,Lf);let b=n.mul(T,F),$=n.mul(O,U),N=n.mul(D,j),P=n.add(T,O),B=n.add(F,U);P=n.mul(P,B),B=n.add(b,$),P=n.sub(P,B),B=n.add(T,D);let V=n.add(F,j);return B=n.mul(B,V),V=n.add(b,N),B=n.sub(B,V),V=n.add(O,D),W=n.add(U,j),V=n.mul(V,W),W=n.add($,N),V=n.sub(V,W),x=n.mul(I,B),W=n.mul(m,N),x=n.add(W,x),W=n.sub($,x),x=n.add($,x),S=n.mul(W,x),$=n.add(b,b),$=n.add($,b),N=n.mul(I,N),B=n.mul(m,B),$=n.add($,N),N=n.sub(b,N),N=n.mul(I,N),B=n.add(B,N),b=n.mul($,B),S=n.add(S,b),b=n.mul(V,B),W=n.mul(P,W),W=n.sub(W,b),b=n.mul(P,$),x=n.mul(V,x),x=n.add(x,b),new g(W,S,x)}subtract(w){return this.add(w.negate())}is0(){return this.equals(g.ZERO)}wNAF(w){return _.wNAFCached(this,w,g.normalizeZ)}multiplyUnsafe(w){const{endo:T,n:O}=t;Dd("scalar",w,us,O);const D=g.ZERO;if(w===us)return D;if(this.is0()||w===Ut)return this;if(!T||_.hasPrecomputes(this))return _.wNAFCachedUnsafe(this,w,g.normalizeZ);let{k1neg:F,k1:U,k2neg:j,k2:W}=T.splitScalar(w),S=D,x=D,I=this;for(;U>us||W>us;)U&Ut&&(S=S.add(I)),W&Ut&&(x=x.add(I)),I=I.double(),U>>=Ut,W>>=Ut;return F&&(S=S.negate()),j&&(x=x.negate()),x=new g(n.mul(x.px,T.beta),x.py,x.pz),S.add(x)}multiply(w){const{endo:T,n:O}=t;Dd("scalar",w,Ut,O);let D,F;if(T){const{k1neg:U,k1:j,k2neg:W,k2:S}=T.splitScalar(w);let{p:x,f:I}=this.wNAF(j),{p:m,f:b}=this.wNAF(S);x=_.constTimeNegate(U,x),m=_.constTimeNegate(W,m),m=new g(n.mul(m.px,T.beta),m.py,m.pz),D=x.add(m),F=I.add(b)}else{const{p:U,f:j}=this.wNAF(w);D=U,F=j}return g.normalizeZ([D,F])[0]}multiplyAndAddUnsafe(w,T,O){const D=g.BASE,F=(j,W)=>W===us||W===Ut||!j.equals(D)?j.multiplyUnsafe(W):j.multiply(W),U=F(this,T).add(F(w,O));return U.is0()?void 0:U}toAffine(w){return f(this,w)}isTorsionFree(){const{h:w,isTorsionFree:T}=t;if(w===Ut)return!0;if(T)return T(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:w,clearCofactor:T}=t;return w===Ut?this:T?T(g,this):this.multiplyUnsafe(t.h)}toRawBytes(w=!0){return Bf("isCompressed",w),this.assertValidity(),i(g,this,w)}toHex(w=!0){return Bf("isCompressed",w),Jl(this.toRawBytes(w))}}g.BASE=new g(t.Gx,t.Gy,n.ONE),g.ZERO=new g(n.ZERO,n.ONE,n.ZERO);const{endo:y,nBitLength:A}=t,_=_L(g,y?Math.ceil(A/2):A);return{CURVE:t,ProjectivePoint:g,normPrivateKeyToScalar:d,weierstrassEquation:o,isWithinCurveOrder:u}}function TL(e){const t=Q9(e);return Df(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function NL(e){const t=TL(e),{Fp:n,n:r,nByteLength:i,nBitLength:s}=t,o=n.BYTES+1,a=2*n.BYTES+1;function c(m){return _r(m,r)}function l(m){return U6(m,r)}const{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:h,isWithinCurveOrder:f}=Z6({...t,toBytes(m,b,$){const N=b.toAffine(),P=n.toBytes(N.x),B=dn;return Bf("isCompressed",$),$?B(Uint8Array.from([b.hasEvenY()?2:3]),P):B(Uint8Array.from([4]),P,n.toBytes(N.y))},fromBytes(m){const b=m.length,$=m[0],N=m.subarray(1);if(b===o&&($===2||$===3)){const P=Cr(N);if(!I6(P,Ut,n.ORDER))throw new Error("Point is not on curve");const B=h(P);let V;try{V=n.sqrt(B)}catch(X){const G=X instanceof Error?": "+X.message:"";throw new Error("Point is not on curve"+G)}const Z=(V&Ut)===Ut;return($&1)===1!==Z&&(V=n.neg(V)),{x:P,y:V}}else if(b===a&&$===4){const P=n.fromBytes(N.subarray(0,n.BYTES)),B=n.fromBytes(N.subarray(n.BYTES,2*n.BYTES));return{x:P,y:B}}else{const P=o,B=a;throw new Error("invalid Point, expected length of "+P+", or uncompressed "+B+", got "+b)}}});function p(m){const b=r>>Ut;return m>b}function g(m){return p(m)?c(-m):m}const y=(m,b,$)=>Cr(m.slice(b,$));class A{constructor(b,$,N){Dd("r",b,Ut,r),Dd("s",$,Ut,r),this.r=b,this.s=$,N!=null&&(this.recovery=N),Object.freeze(this)}static fromCompact(b){const $=i;return b=or("compactSignature",b,$*2),new A(y(b,0,$),y(b,$,2*$))}static fromDER(b){const{r:$,s:N}=Fa.toSig(or("DER",b));return new A($,N)}assertValidity(){}addRecoveryBit(b){return new A(this.r,this.s,b)}recoverPublicKey(b){const{r:$,s:N,recovery:P}=this,B=D(or("msgHash",b));if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");const V=P===2||P===3?$+t.n:$;if(V>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const Z=(P&1)===0?"02":"03",Y=u.fromHex(Z+W6(V,n.BYTES)),X=l(V),G=c(-B*X),ne=c(N*X),se=u.BASE.multiplyAndAddUnsafe(Y,G,ne);if(!se)throw new Error("point at infinify");return se.assertValidity(),se}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new A(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return V2(this.toDERHex())}toDERHex(){return Fa.hexFromSig(this)}toCompactRawBytes(){return V2(this.toCompactHex())}toCompactHex(){const b=i;return W6(this.r,b)+W6(this.s,b)}}const _={isValidPrivateKey(m){try{return d(m),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{const m=L6(t.n);return G9(t.randomBytes(m),t.n)},precompute(m=8,b=u.BASE){return b._setWindowSize(m),b.multiply(BigInt(3)),b}};function v(m,b=!0){return u.fromPrivateKey(m).toRawBytes(b)}function w(m){if(typeof m=="bigint")return!1;if(m instanceof u)return!0;const $=or("key",m).length,N=n.BYTES,P=N+1,B=2*N+1;if(!(t.allowedPrivateKeyLengths||i===P))return $===P||$===B}function T(m,b,$=!0){if(w(m)===!0)throw new Error("first arg must be private key");if(w(b)===!1)throw new Error("second arg must be public key");return u.fromHex(b).multiply(d(m)).toRawBytes($)}const O=t.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const b=Cr(m),$=m.length*8-s;return $>0?b>>BigInt($):b},D=t.bits2int_modN||function(m){return c(O(m))},F=Ql(s);function U(m){return Dd("num < 2^"+s,m,us,F),_n(m,i)}function j(m,b,$=W){if(["recovered","canonical"].some(ue=>ue in $))throw new Error("sign() legacy options not supported");const{hash:N,randomBytes:P}=t;let{lowS:B,prehash:V,extraEntropy:Z}=$;B==null&&(B=!0),m=or("msgHash",m),eC($),V&&(m=or("prehashed msgHash",N(m)));const Y=D(m),X=d(b),G=[U(X),U(Y)];if(Z!=null&&Z!==!1){const ue=Z===!0?P(n.BYTES):Z;G.push(or("extraEntropy",ue))}const ne=dn(...G),se=Y;function we(ue){const ge=O(ue);if(!f(ge))return;const Be=l(ge),Fe=u.BASE.multiply(ge).toAffine(),qe=c(Fe.x);if(qe===us)return;const ct=c(Be*c(se+qe*X));if(ct===us)return;let St=(Fe.x===qe?0:2)|Number(Fe.y&Ut),gi=ct;return B&&p(ct)&&(gi=g(ct),St^=1),new A(qe,gi,St)}return{seed:ne,k2sig:we}}const W={lowS:t.lowS,prehash:!1},S={lowS:t.lowS,prehash:!1};function x(m,b,$=W){const{seed:N,k2sig:P}=j(m,b,$),B=t;return IU(B.hash.outputLen,B.nByteLength,B.hmac)(N,P)}u.BASE._setWindowSize(8);function I(m,b,$,N=S){const P=m;b=or("msgHash",b),$=or("publicKey",$);const{lowS:B,prehash:V,format:Z}=N;if(eC(N),"strict"in N)throw new Error("options.strict was renamed to lowS");if(Z!==void 0&&Z!=="compact"&&Z!=="der")throw new Error("format must be compact or der");const Y=typeof P=="string"||Rf(P),X=!Y&&!Z&&typeof P=="object"&&P!==null&&typeof P.r=="bigint"&&typeof P.s=="bigint";if(!Y&&!X)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let G,ne;try{if(X&&(G=new A(P.r,P.s)),Y){try{Z!=="compact"&&(G=A.fromDER(P))}catch(St){if(!(St instanceof Fa.Err))throw St}!G&&Z!=="der"&&(G=A.fromCompact(P))}ne=u.fromHex($)}catch{return!1}if(!G||B&&G.hasHighS())return!1;V&&(b=t.hash(b));const{r:se,s:we}=G,ue=D(b),ge=l(we),Be=c(ue*ge),Fe=c(se*ge),qe=u.BASE.multiplyAndAddUnsafe(ne,Be,Fe)?.toAffine();return qe?c(qe.x)===se:!1}return{CURVE:t,getPublicKey:v,getSharedSecret:T,sign:x,verify:I,ProjectivePoint:u,Signature:A,utils:_}}function PL(e,t){const n=e.ORDER;let r=us;for(let p=n-Ut;p%Tc===us;p/=Tc)r+=Ut;const i=r,s=Tc<<i-Ut-Ut,o=s*Tc,a=(n-Ut)/o,c=(a-Ut)/Tc,l=o-Ut,u=s,d=e.pow(t,a),h=e.pow(t,(a+Ut)/Tc);let f=(p,g)=>{let y=d,A=e.pow(g,l),_=e.sqr(A);_=e.mul(_,g);let v=e.mul(p,_);v=e.pow(v,c),v=e.mul(v,A),A=e.mul(v,g),_=e.mul(v,p);let w=e.mul(_,A);v=e.pow(w,u);let T=e.eql(v,e.ONE);A=e.mul(_,h),v=e.mul(w,y),_=e.cmov(A,_,T),w=e.cmov(v,w,T);for(let O=i;O>Ut;O--){let D=O-Tc;D=Tc<<D-Ut;let F=e.pow(w,D);const U=e.eql(F,e.ONE);A=e.mul(_,y),y=e.mul(y,y),F=e.mul(w,y),_=e.cmov(A,_,U),w=e.cmov(F,w,U)}return{isValid:T,value:_}};if(e.ORDER%q6===Lf){const p=(e.ORDER-Lf)/q6,g=e.sqrt(e.neg(t));f=(y,A)=>{let _=e.sqr(A);const v=e.mul(y,A);_=e.mul(_,v);let w=e.pow(_,p);w=e.mul(w,v);const T=e.mul(w,g),O=e.mul(e.sqr(w),A),D=e.eql(O,y);let F=e.cmov(T,w,D);return{isValid:D,value:F}}}return f}function tC(e,t){if(W9(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const n=PL(e,t.Z);if(!e.isOdd)throw new Error("Fp.isOdd is not implemented!");return r=>{let i,s,o,a,c,l,u,d;i=e.sqr(r),i=e.mul(i,t.Z),s=e.sqr(i),s=e.add(s,i),o=e.add(s,e.ONE),o=e.mul(o,t.B),a=e.cmov(t.Z,e.neg(s),!e.eql(s,e.ZERO)),a=e.mul(a,t.A),s=e.sqr(o),l=e.sqr(a),c=e.mul(l,t.A),s=e.add(s,c),s=e.mul(s,o),l=e.mul(l,a),c=e.mul(l,t.B),s=e.add(s,c),u=e.mul(i,o);const{isValid:h,value:f}=n(s,l);d=e.mul(i,r),d=e.mul(d,f),u=e.cmov(u,o,h),d=e.cmov(d,f,h);const p=e.isOdd(r)===e.isOdd(d);d=e.cmov(e.neg(d),d,p);const g=tu(e,[a],!0)[0];return u=e.mul(u,g),{x:u,y:d}}}function OL(e){return{hash:e,hmac:(t,...n)=>G2(e,t,Gs(...n)),randomBytes:Rd}}function X2(e,t){const n=r=>NL({...e,...OL(r)});return{...n(t),create:n}}const kL=Cr;function Nc(e,t){if(Ff(e),Ff(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);const n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function RL(e,t){const n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}function Ff(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function BL(e,t,n,r){Ic(e),Ic(t),Ff(n),t.length>255&&(t=r(dn(_6("H2C-OVERSIZE-DST-"),t)));const{outputLen:i,blockLen:s}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const a=dn(t,Nc(t.length,1)),c=Nc(0,s),l=Nc(n,2),u=new Array(o),d=r(dn(c,e,l,Nc(0,1),a));u[0]=r(dn(d,Nc(1,1),a));for(let f=1;f<=o;f++){const p=[RL(d,u[f-1]),Nc(f+1,1),a];u[f]=r(dn(...p))}return dn(...u).slice(0,n)}function ML(e,t,n,r,i){if(Ic(e),Ic(t),Ff(n),t.length>255){const s=Math.ceil(2*r/8);t=i.create({dkLen:s}).update(_6("H2C-OVERSIZE-DST-")).update(t).digest()}if(n>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:n}).update(e).update(Nc(n,2)).update(t).update(Nc(t.length,1)).digest()}function nC(e,t,n){Df(n,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});const{p:r,k:i,m:s,hash:o,expand:a,DST:c}=n;Ic(e),Ff(t);const l=typeof c=="string"?_6(c):c,u=r.toString(2).length,d=Math.ceil((u+i)/8),h=t*s*d;let f;if(a==="xmd")f=BL(e,l,h,o);else if(a==="xof")f=ML(e,l,h,i,o);else if(a==="_internal_pass")f=e;else throw new Error('expand must be "xmd" or "xof"');const p=new Array(t);for(let g=0;g<t;g++){const y=new Array(s);for(let A=0;A<s;A++){const _=d*(A+g*s),v=f.subarray(_,_+d);y[A]=_r(kL(v),r)}p[g]=y}return p}function rC(e,t){const n=t.map(r=>Array.from(r).reverse());return(r,i)=>{const[s,o,a,c]=n.map(d=>d.reduce((h,f)=>e.add(e.mul(h,r),f))),[l,u]=tu(e,[o,c],!0);return r=e.mul(s,l),i=e.mul(i,e.mul(a,u)),{x:r,y:i}}}function iC(e,t,n){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function r(s){return e.fromAffine(t(s))}function i(s){const o=s.clearCofactor();return o.equals(e.ZERO)?e.ZERO:(o.assertValidity(),o)}return{defaults:n,hashToCurve(s,o){const a=nC(s,2,{...n,DST:n.DST,...o}),c=r(a[0]),l=r(a[1]);return i(c.add(l))},encodeToCurve(s,o){const a=nC(s,1,{...n,DST:n.encodeDST,...o});return i(r(a[0]))},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(const o of s)if(typeof o!="bigint")throw new Error("expected array of bigints");return i(r(s))}}}const sC=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),oC=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),DL=BigInt(0),UL=BigInt(1),G6=BigInt(2),aC=(e,t)=>(e+t/G6)/t;function LL(e){const t=sC,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=Ri(u,n,t)*u%t,h=Ri(d,n,t)*u%t,f=Ri(h,G6,t)*l%t,p=Ri(f,i,t)*f%t,g=Ri(p,s,t)*p%t,y=Ri(g,a,t)*g%t,A=Ri(y,c,t)*y%t,_=Ri(A,a,t)*g%t,v=Ri(_,n,t)*u%t,w=Ri(v,o,t)*p%t,T=Ri(w,r,t)*l%t,O=Ri(T,G6,t);if(!K6.eql(K6.sqr(O),e))throw new Error("Cannot find square root");return O}const K6=$c(sC,void 0,void 0,{sqrt:LL}),FL=X2({a:DL,b:BigInt(7),Fp:K6,n:oC,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=oC,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-UL*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=aC(s*e,t),c=aC(-r*e,t);let l=_r(e-a*n-c*i,t),u=_r(-a*r-c*s,t);const d=l>o,h=u>o;if(d&&(l=t-l),h&&(u=t-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}}},ls);function HL(e){if(e.length!==130&&e.length!==132)throw new zL({signature:e});const t=BigInt(Ua(e,0,32)),n=BigInt(Ua(e,32,64)),r=(()=>{const i=+`0x${e.slice(130)}`;if(!Number.isNaN(i))try{return jL(i)}catch{throw new VL({value:i})}})();return typeof r>"u"?{r:t,s:n}:{r:t,s:n,yParity:r}}function jL(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new WL({value:e})}class zL extends Ht{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${La(k6(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class VL extends Ht{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class WL extends Ht{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}Object.freeze({1:0n,2:1n,3:2n,4:3n,5:4n,6:5n,7:6n,8:7n,9:8n,A:9n,B:10n,C:11n,D:12n,E:13n,F:14n,G:15n,H:16n,J:17n,K:18n,L:19n,M:20n,N:21n,P:22n,Q:23n,R:24n,S:25n,T:26n,U:27n,V:28n,W:29n,X:30n,Y:31n,Z:32n,a:33n,b:34n,c:35n,d:36n,e:37n,f:38n,g:39n,h:40n,i:41n,j:42n,k:43n,m:44n,n:45n,o:46n,p:47n,q:48n,r:49n,s:50n,t:51n,u:52n,v:53n,w:54n,x:55n,y:56n,z:57n}),Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)]),{...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t]))},Ra.slice();const qL=BigInt(0),J2=BigInt(1),cC=BigInt(2),Ud=BigInt(3);function ZL(e){const t=[];for(;e>J2;e>>=J2)(e&J2)===qL?t.unshift(0):(e&Ud)===Ud?(t.unshift(-1),e+=J2):t.unshift(1);return t}function GL(e){const{Fp:t,Fr:n,Fp2:r,Fp6:i,Fp12:s}=e.fields,o=e.params.xNegative,a=e.params.twistType,c=Z6({n:n.ORDER,...e.G1}),l=Object.assign(c,iC(c.ProjectivePoint,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),u=Z6({n:n.ORDER,...e.G2}),d=Object.assign(u,iC(u.ProjectivePoint,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults}));let h;if(a==="multiplicative")h=(Y,X,G,ne,se,we)=>s.mul014(ne,Y,r.mul(X,se),r.mul(G,we));else if(a==="divisive")h=(Y,X,G,ne,se,we)=>s.mul034(ne,r.mul(G,we),r.mul(X,se),Y);else throw new Error("bls: unknown twist type");const f=r.div(r.ONE,r.mul(r.ONE,cC));function p(Y,X,G,ne){const se=r.sqr(G),we=r.sqr(ne),ue=r.mulByB(r.mul(we,Ud)),ge=r.mul(ue,Ud),Be=r.sub(r.sub(r.sqr(r.add(G,ne)),we),se),Fe=r.sub(ue,se),qe=r.mul(r.sqr(X),Ud),ct=r.neg(Be);return Y.push([Fe,qe,ct]),X=r.mul(r.mul(r.mul(r.sub(se,ge),X),G),f),G=r.sub(r.sqr(r.mul(r.add(se,ge),f)),r.mul(r.sqr(ue),Ud)),ne=r.mul(se,Be),{Rx:X,Ry:G,Rz:ne}}function g(Y,X,G,ne,se,we){const ue=r.sub(G,r.mul(we,ne)),ge=r.sub(X,r.mul(se,ne)),Be=r.sub(r.mul(ue,se),r.mul(ge,we)),Fe=r.neg(ue),qe=ge;Y.push([Be,Fe,qe]);const ct=r.sqr(ge),St=r.mul(ct,ge),gi=r.mul(ct,X),Vl=r.add(r.sub(St,r.mul(gi,cC)),r.mul(r.sqr(ue),ne));return X=r.mul(ge,Vl),G=r.sub(r.mul(r.sub(gi,Vl),ue),r.mul(St,G)),ne=r.mul(ne,St),{Rx:X,Ry:G,Rz:ne}}const y=ZL(e.params.ateLoopSize),A=T6(Y=>{const X=Y,{x:G,y:ne}=X.toAffine(),se=G,we=ne,ue=r.neg(ne);let ge=se,Be=we,Fe=r.ONE;const qe=[];for(const ct of y){const St=[];({Rx:ge,Ry:Be,Rz:Fe}=p(St,ge,Be,Fe)),ct&&({Rx:ge,Ry:Be,Rz:Fe}=g(St,ge,Be,Fe,se,ct===-1?ue:we)),qe.push(St)}if(e.postPrecompute){const ct=qe[qe.length-1];e.postPrecompute(ge,Be,Fe,se,we,g.bind(null,ct))}return qe});function _(Y,X=!1){let G=s.ONE;if(Y.length){const ne=Y[0][0].length;for(let se=0;se<ne;se++){G=s.sqr(G);for(const[we,ue,ge]of Y)for(const[Be,Fe,qe]of we[se])G=h(Be,Fe,qe,G,ue,ge)}}return o&&(G=s.conjugate(G)),X?s.finalExponentiate(G):G}function v(Y,X=!0){const G=[];l.ProjectivePoint.normalizeZ(Y.map(({g1:ne})=>ne)),d.ProjectivePoint.normalizeZ(Y.map(({g2:ne})=>ne));for(const{g1:ne,g2:se}of Y){if(ne.equals(l.ProjectivePoint.ZERO)||se.equals(d.ProjectivePoint.ZERO))throw new Error("pairing is not available for ZERO point");ne.assertValidity(),se.assertValidity();const we=ne.toAffine();G.push([A(se),we.x,we.y])}return _(G,X)}function w(Y,X,G=!0){return v([{g1:Y,g2:X}],G)}const T={randomPrivateKey:()=>{const Y=L6(n.ORDER);return G9(e.randomBytes(Y),n.ORDER)},calcPairingPrecomputes:A},{ShortSignature:O}=e.G1,{Signature:D}=e.G2;function F(Y){return Y instanceof l.ProjectivePoint?Y:l.ProjectivePoint.fromHex(Y)}function U(Y,X){return Y instanceof l.ProjectivePoint?Y:l.hashToCurve(or("point",Y),X)}function j(Y){return Y instanceof d.ProjectivePoint?Y:D.fromHex(Y)}function W(Y,X){return Y instanceof d.ProjectivePoint?Y:d.hashToCurve(or("point",Y),X)}function S(Y){return l.ProjectivePoint.fromPrivateKey(Y).toRawBytes(!0)}function x(Y){return d.ProjectivePoint.fromPrivateKey(Y).toRawBytes(!0)}function I(Y,X,G){const ne=W(Y,G);ne.assertValidity();const se=ne.multiply(l.normPrivateKeyToScalar(X));return Y instanceof d.ProjectivePoint?se:D.toRawBytes(se)}function m(Y,X,G){const ne=U(Y,G);ne.assertValidity();const se=ne.multiply(l.normPrivateKeyToScalar(X));return Y instanceof l.ProjectivePoint?se:O.toRawBytes(se)}function b(Y,X,G,ne){const se=F(G),we=W(X,ne),ue=l.ProjectivePoint.BASE,ge=j(Y),Be=v([{g1:se.negate(),g2:we},{g1:ue,g2:ge}]);return s.eql(Be,s.ONE)}function $(Y,X,G,ne){const se=j(G),we=U(X,ne),ue=d.ProjectivePoint.BASE,ge=F(Y),Be=v([{g1:we,g2:se},{g1:ge,g2:ue.negate()}]);return s.eql(Be,s.ONE)}function N(Y){if(!Array.isArray(Y)||Y.length===0)throw new Error("expected non-empty array")}function P(Y){N(Y);const G=Y.map(F).reduce((ne,se)=>ne.add(se),l.ProjectivePoint.ZERO);return Y[0]instanceof l.ProjectivePoint?(G.assertValidity(),G):G.toRawBytes(!0)}function B(Y){N(Y);const G=Y.map(j).reduce((ne,se)=>ne.add(se),d.ProjectivePoint.ZERO);return Y[0]instanceof d.ProjectivePoint?(G.assertValidity(),G):D.toRawBytes(G)}function V(Y){N(Y);const G=Y.map(F).reduce((ne,se)=>ne.add(se),l.ProjectivePoint.ZERO);return Y[0]instanceof l.ProjectivePoint?(G.assertValidity(),G):O.toRawBytes(G)}function Z(Y,X,G,ne){if(N(X),G.length!==X.length)throw new Error("amount of public keys and messages should be equal");const se=j(Y),we=X.map(Fe=>W(Fe,ne)),ue=G.map(F),ge=new Map;for(let Fe=0;Fe<ue.length;Fe++){const qe=ue[Fe],ct=we[Fe];let St=ge.get(ct);St===void 0&&(St=[],ge.set(ct,St)),St.push(qe)}const Be=[];try{for(const[Fe,qe]of ge){const ct=qe.reduce((St,gi)=>St.add(gi));Be.push({g1:ct,g2:Fe})}return Be.push({g1:l.ProjectivePoint.BASE.negate(),g2:se}),s.eql(v(Be),s.ONE)}catch{return!1}}return l.ProjectivePoint.BASE._setWindowSize(4),{getPublicKey:S,getPublicKeyForShortSignatures:x,sign:I,signShortSignature:m,verify:b,verifyBatch:Z,verifyShortSignature:$,aggregatePublicKeys:P,aggregateSignatures:B,aggregateShortSignatures:V,millerLoopBatch:_,pairing:w,pairingBatch:v,G1:l,G2:d,Signature:D,ShortSignature:O,fields:{Fr:n,Fp:t,Fp2:r,Fp6:i,Fp12:s},params:{ateLoopSize:e.params.ateLoopSize,r:e.params.r,G1b:e.G1.b,G2b:e.G2.b},utils:T}}const KL=BigInt(0),Ld=BigInt(1),Ha=BigInt(2),lC=BigInt(3);function Y6(e,t,n,r,i=1,s){const o=BigInt(s===void 0?r:s),a=n**BigInt(r),c=[];for(let l=0;l<i;l++){const u=BigInt(l+1),d=[];for(let h=0,f=Ld;h<r;h++){const p=(u*f-u)/o%a;d.push(e.pow(t,p)),f*=n}c.push(d)}return c}function YL(e,t,n){const r=t.pow(n,(e.ORDER-Ld)/lC),i=t.pow(n,(e.ORDER-Ld)/Ha);function s(h,f){const p=t.mul(t.frobeniusMap(h,1),r),g=t.mul(t.frobeniusMap(f,1),i);return[p,g]}const o=t.pow(n,(e.ORDER**Ha-Ld)/lC),a=t.pow(n,(e.ORDER**Ha-Ld)/Ha);if(!t.eql(a,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(h,f){return[t.mul(h,o),t.neg(f)]}const l=h=>(f,p)=>{const g=p.toAffine(),y=h(g.x,g.y);return f.fromAffine({x:y[0],y:y[1]})},u=l(s),d=l(c);return{psi:s,psi2:c,G2psi:u,G2psi2:d,PSI_X:r,PSI_Y:i,PSI2_X:o,PSI2_Y:a}}function XL(e){const{ORDER:t}=e,n=$c(t),r=n.create(e.NONRESIDUE||BigInt(-1)),i=n.div(n.ONE,Ha),s=Y6(n,r,n.ORDER,2)[0],o=({c0:S,c1:x},{c0:I,c1:m})=>({c0:n.add(S,I),c1:n.add(x,m)}),a=({c0:S,c1:x},{c0:I,c1:m})=>({c0:n.sub(S,I),c1:n.sub(x,m)}),c=({c0:S,c1:x},I)=>{if(typeof I=="bigint")return{c0:n.mul(S,I),c1:n.mul(x,I)};const{c0:m,c1:b}=I;let $=n.mul(S,m),N=n.mul(x,b);const P=n.sub($,N),B=n.sub(n.mul(n.add(S,x),n.add(m,b)),n.add($,N));return{c0:P,c1:B}},l=({c0:S,c1:x})=>{const I=n.add(S,x),m=n.sub(S,x),b=n.add(S,S);return{c0:n.mul(I,m),c1:n.mul(b,x)}},u=S=>{if(S.length!==2)throw new Error("invalid tuple");const x=S.map(I=>n.create(I));return{c0:x[0],c1:x[1]}},d=t*t,h=u(e.FP2_NONRESIDUE),f={ORDER:d,isLE:n.isLE,NONRESIDUE:h,BITS:Mf(d),BYTES:Math.ceil(Mf(d)/8),MASK:Ql(Mf(d)),ZERO:{c0:n.ZERO,c1:n.ZERO},ONE:{c0:n.ONE,c1:n.ZERO},create:S=>S,isValid:({c0:S,c1:x})=>typeof S=="bigint"&&typeof x=="bigint",is0:({c0:S,c1:x})=>n.is0(S)&&n.is0(x),eql:({c0:S,c1:x},{c0:I,c1:m})=>n.eql(S,I)&&n.eql(x,m),neg:({c0:S,c1:x})=>({c0:n.neg(S),c1:n.neg(x)}),pow:(S,x)=>K2(f,S,x),invertBatch:S=>tu(f,S),add:o,sub:a,mul:c,sqr:l,addN:o,subN:a,mulN:c,sqrN:l,div:(S,x)=>f.mul(S,typeof x=="bigint"?n.inv(n.create(x)):f.inv(x)),inv:({c0:S,c1:x})=>{const I=n.inv(n.create(S*S+x*x));return{c0:n.mul(I,n.create(S)),c1:n.mul(I,n.create(-x))}},sqrt:S=>{if(e.Fp2sqrt)return e.Fp2sqrt(S);const{c0:x,c1:I}=S;if(n.is0(I))return Y2(n,x)===1?f.create({c0:n.sqrt(x),c1:n.ZERO}):f.create({c0:n.ZERO,c1:n.sqrt(n.div(x,r))});const m=n.sqrt(n.sub(n.sqr(x),n.mul(n.sqr(I),r)));let b=n.mul(n.add(m,x),i);Y2(n,b)===-1&&(b=n.sub(b,m));const N=n.sqrt(b),P=f.create({c0:N,c1:n.div(n.mul(I,i),N)});if(!f.eql(f.sqr(P),S))throw new Error("Cannot find square root");const B=P,V=f.neg(B),{re:Z,im:Y}=f.reim(B),{re:X,im:G}=f.reim(V);return Y>G||Y===G&&Z>X?B:V},isOdd:S=>{const{re:x,im:I}=f.reim(S),m=x%Ha,b=x===KL,$=I%Ha;return BigInt(m||b&&$)==Ld},fromBytes(S){if(S.length!==f.BYTES)throw new Error("fromBytes invalid length="+S.length);return{c0:n.fromBytes(S.subarray(0,n.BYTES)),c1:n.fromBytes(S.subarray(n.BYTES))}},toBytes:({c0:S,c1:x})=>dn(n.toBytes(S),n.toBytes(x)),cmov:({c0:S,c1:x},{c0:I,c1:m},b)=>({c0:n.cmov(S,I,b),c1:n.cmov(x,m,b)}),reim:({c0:S,c1:x})=>({re:S,im:x}),mulByNonresidue:({c0:S,c1:x})=>f.mul({c0:S,c1:x},h),mulByB:e.Fp2mulByB,fromBigTuple:u,frobeniusMap:({c0:S,c1:x},I)=>({c0:S,c1:n.mul(x,s[I%2])})},p=({c0:S,c1:x,c2:I},{c0:m,c1:b,c2:$})=>({c0:f.add(S,m),c1:f.add(x,b),c2:f.add(I,$)}),g=({c0:S,c1:x,c2:I},{c0:m,c1:b,c2:$})=>({c0:f.sub(S,m),c1:f.sub(x,b),c2:f.sub(I,$)}),y=({c0:S,c1:x,c2:I},m)=>{if(typeof m=="bigint")return{c0:f.mul(S,m),c1:f.mul(x,m),c2:f.mul(I,m)};const{c0:b,c1:$,c2:N}=m,P=f.mul(S,b),B=f.mul(x,$),V=f.mul(I,N);return{c0:f.add(P,f.mulByNonresidue(f.sub(f.mul(f.add(x,I),f.add($,N)),f.add(B,V)))),c1:f.add(f.sub(f.mul(f.add(S,x),f.add(b,$)),f.add(P,B)),f.mulByNonresidue(V)),c2:f.sub(f.add(B,f.mul(f.add(S,I),f.add(b,N))),f.add(P,V))}},A=({c0:S,c1:x,c2:I})=>{let m=f.sqr(S),b=f.mul(f.mul(S,x),Ha),$=f.mul(f.mul(x,I),Ha),N=f.sqr(I);return{c0:f.add(f.mulByNonresidue($),m),c1:f.add(f.mulByNonresidue(N),b),c2:f.sub(f.sub(f.add(f.add(b,f.sqr(f.add(f.sub(S,x),I))),$),m),N)}},[_,v]=Y6(f,h,n.ORDER,6,2,3),w={ORDER:f.ORDER,isLE:f.isLE,BITS:3*f.BITS,BYTES:3*f.BYTES,MASK:Ql(3*f.BITS),ZERO:{c0:f.ZERO,c1:f.ZERO,c2:f.ZERO},ONE:{c0:f.ONE,c1:f.ZERO,c2:f.ZERO},create:S=>S,isValid:({c0:S,c1:x,c2:I})=>f.isValid(S)&&f.isValid(x)&&f.isValid(I),is0:({c0:S,c1:x,c2:I})=>f.is0(S)&&f.is0(x)&&f.is0(I),neg:({c0:S,c1:x,c2:I})=>({c0:f.neg(S),c1:f.neg(x),c2:f.neg(I)}),eql:({c0:S,c1:x,c2:I},{c0:m,c1:b,c2:$})=>f.eql(S,m)&&f.eql(x,b)&&f.eql(I,$),sqrt:I9,div:(S,x)=>w.mul(S,typeof x=="bigint"?n.inv(n.create(x)):w.inv(x)),pow:(S,x)=>K2(w,S,x),invertBatch:S=>tu(w,S),add:p,sub:g,mul:y,sqr:A,addN:p,subN:g,mulN:y,sqrN:A,inv:({c0:S,c1:x,c2:I})=>{let m=f.sub(f.sqr(S),f.mulByNonresidue(f.mul(I,x))),b=f.sub(f.mulByNonresidue(f.sqr(I)),f.mul(S,x)),$=f.sub(f.sqr(x),f.mul(S,I)),N=f.inv(f.add(f.mulByNonresidue(f.add(f.mul(I,b),f.mul(x,$))),f.mul(S,m)));return{c0:f.mul(N,m),c1:f.mul(N,b),c2:f.mul(N,$)}},fromBytes:S=>{if(S.length!==w.BYTES)throw new Error("fromBytes invalid length="+S.length);return{c0:f.fromBytes(S.subarray(0,f.BYTES)),c1:f.fromBytes(S.subarray(f.BYTES,2*f.BYTES)),c2:f.fromBytes(S.subarray(2*f.BYTES))}},toBytes:({c0:S,c1:x,c2:I})=>dn(f.toBytes(S),f.toBytes(x),f.toBytes(I)),cmov:({c0:S,c1:x,c2:I},{c0:m,c1:b,c2:$},N)=>({c0:f.cmov(S,m,N),c1:f.cmov(x,b,N),c2:f.cmov(I,$,N)}),fromBigSix:S=>{if(!Array.isArray(S)||S.length!==6)throw new Error("invalid Fp6 usage");return{c0:f.fromBigTuple(S.slice(0,2)),c1:f.fromBigTuple(S.slice(2,4)),c2:f.fromBigTuple(S.slice(4,6))}},frobeniusMap:({c0:S,c1:x,c2:I},m)=>({c0:f.frobeniusMap(S,m),c1:f.mul(f.frobeniusMap(x,m),_[m%6]),c2:f.mul(f.frobeniusMap(I,m),v[m%6])}),mulByFp2:({c0:S,c1:x,c2:I},m)=>({c0:f.mul(S,m),c1:f.mul(x,m),c2:f.mul(I,m)}),mulByNonresidue:({c0:S,c1:x,c2:I})=>({c0:f.mulByNonresidue(I),c1:S,c2:x}),mul1:({c0:S,c1:x,c2:I},m)=>({c0:f.mulByNonresidue(f.mul(I,m)),c1:f.mul(S,m),c2:f.mul(x,m)}),mul01({c0:S,c1:x,c2:I},m,b){let $=f.mul(S,m),N=f.mul(x,b);return{c0:f.add(f.mulByNonresidue(f.sub(f.mul(f.add(x,I),b),N)),$),c1:f.sub(f.sub(f.mul(f.add(m,b),f.add(S,x)),$),N),c2:f.add(f.sub(f.mul(f.add(S,I),m),$),N)}}},T=Y6(f,h,n.ORDER,12,1,6)[0],O=({c0:S,c1:x},{c0:I,c1:m})=>({c0:w.add(S,I),c1:w.add(x,m)}),D=({c0:S,c1:x},{c0:I,c1:m})=>({c0:w.sub(S,I),c1:w.sub(x,m)}),F=({c0:S,c1:x},I)=>{if(typeof I=="bigint")return{c0:w.mul(S,I),c1:w.mul(x,I)};let{c0:m,c1:b}=I,$=w.mul(S,m),N=w.mul(x,b);return{c0:w.add($,w.mulByNonresidue(N)),c1:w.sub(w.mul(w.add(S,x),w.add(m,b)),w.add($,N))}},U=({c0:S,c1:x})=>{let I=w.mul(S,x);return{c0:w.sub(w.sub(w.mul(w.add(w.mulByNonresidue(x),S),w.add(S,x)),I),w.mulByNonresidue(I)),c1:w.add(I,I)}};function j(S,x){const I=f.sqr(S),m=f.sqr(x);return{first:f.add(f.mulByNonresidue(m),I),second:f.sub(f.sub(f.sqr(f.add(S,x)),I),m)}}const W={ORDER:f.ORDER,isLE:w.isLE,BITS:2*w.BITS,BYTES:2*w.BYTES,MASK:Ql(2*w.BITS),ZERO:{c0:w.ZERO,c1:w.ZERO},ONE:{c0:w.ONE,c1:w.ZERO},create:S=>S,isValid:({c0:S,c1:x})=>w.isValid(S)&&w.isValid(x),is0:({c0:S,c1:x})=>w.is0(S)&&w.is0(x),neg:({c0:S,c1:x})=>({c0:w.neg(S),c1:w.neg(x)}),eql:({c0:S,c1:x},{c0:I,c1:m})=>w.eql(S,I)&&w.eql(x,m),sqrt:I9,inv:({c0:S,c1:x})=>{let I=w.inv(w.sub(w.sqr(S),w.mulByNonresidue(w.sqr(x))));return{c0:w.mul(S,I),c1:w.neg(w.mul(x,I))}},div:(S,x)=>W.mul(S,typeof x=="bigint"?n.inv(n.create(x)):W.inv(x)),pow:(S,x)=>K2(W,S,x),invertBatch:S=>tu(W,S),add:O,sub:D,mul:F,sqr:U,addN:O,subN:D,mulN:F,sqrN:U,fromBytes:S=>{if(S.length!==W.BYTES)throw new Error("fromBytes invalid length="+S.length);return{c0:w.fromBytes(S.subarray(0,w.BYTES)),c1:w.fromBytes(S.subarray(w.BYTES))}},toBytes:({c0:S,c1:x})=>dn(w.toBytes(S),w.toBytes(x)),cmov:({c0:S,c1:x},{c0:I,c1:m},b)=>({c0:w.cmov(S,I,b),c1:w.cmov(x,m,b)}),fromBigTwelve:S=>({c0:w.fromBigSix(S.slice(0,6)),c1:w.fromBigSix(S.slice(6,12))}),frobeniusMap(S,x){const{c0:I,c1:m,c2:b}=w.frobeniusMap(S.c1,x),$=T[x%12];return{c0:w.frobeniusMap(S.c0,x),c1:w.create({c0:f.mul(I,$),c1:f.mul(m,$),c2:f.mul(b,$)})}},mulByFp2:({c0:S,c1:x},I)=>({c0:w.mulByFp2(S,I),c1:w.mulByFp2(x,I)}),conjugate:({c0:S,c1:x})=>({c0:S,c1:w.neg(x)}),mul014:({c0:S,c1:x},I,m,b)=>{let $=w.mul01(S,I,m),N=w.mul1(x,b);return{c0:w.add(w.mulByNonresidue(N),$),c1:w.sub(w.sub(w.mul01(w.add(x,S),I,f.add(m,b)),$),N)}},mul034:({c0:S,c1:x},I,m,b)=>{const $=w.create({c0:f.mul(S.c0,I),c1:f.mul(S.c1,I),c2:f.mul(S.c2,I)}),N=w.mul01(x,m,b),P=w.mul01(w.add(S,x),f.add(I,m),b);return{c0:w.add(w.mulByNonresidue(N),$),c1:w.sub(P,w.add($,N))}},_cyclotomicSquare:e.Fp12cyclotomicSquare,_cyclotomicExp:e.Fp12cyclotomicExp,finalExponentiate:e.Fp12finalExponentiate};return{Fp:n,Fp2:f,Fp6:w,Fp4Square:j,Fp12:W}}const Sr=BigInt(0),Q2=BigInt(1),kn=BigInt(2),eg=BigInt(3),Hf=BigInt(4),Pc=BigInt("0xd201000000010000"),JL=Mf(Pc),{Fp:Me,Fp2:He,Fp6:X6,Fp4Square:J6,Fp12:mt}=XL({ORDER:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),FP2_NONRESIDUE:[Q2,Q2],Fp2mulByB:({c0:e,c1:t})=>{const n=Me.mul(e,Hf),r=Me.mul(t,Hf);return{c0:Me.sub(n,r),c1:Me.add(n,r)}},Fp12cyclotomicSquare:({c0:e,c1:t})=>{const{c0:n,c1:r,c2:i}=e,{c0:s,c1:o,c2:a}=t,{first:c,second:l}=J6(n,o),{first:u,second:d}=J6(s,i),{first:h,second:f}=J6(r,a),p=He.mulByNonresidue(f);return{c0:X6.create({c0:He.add(He.mul(He.sub(c,n),kn),c),c1:He.add(He.mul(He.sub(u,r),kn),u),c2:He.add(He.mul(He.sub(h,i),kn),h)}),c1:X6.create({c0:He.add(He.mul(He.add(p,s),kn),p),c1:He.add(He.mul(He.add(l,o),kn),l),c2:He.add(He.mul(He.add(d,a),kn),d)})}},Fp12cyclotomicExp(e,t){let n=mt.ONE;for(let r=JL-1;r>=0;r--)n=mt._cyclotomicSquare(n),SU(t,r)&&(n=mt.mul(n,e));return n},Fp12finalExponentiate:e=>{const t=Pc,n=mt.div(mt.frobeniusMap(e,6),e),r=mt.mul(mt.frobeniusMap(n,2),n),i=mt.conjugate(mt._cyclotomicExp(r,t)),s=mt.mul(mt.conjugate(mt._cyclotomicSquare(r)),i),o=mt.conjugate(mt._cyclotomicExp(s,t)),a=mt.conjugate(mt._cyclotomicExp(o,t)),c=mt.mul(mt.conjugate(mt._cyclotomicExp(a,t)),mt._cyclotomicSquare(i)),l=mt.conjugate(mt._cyclotomicExp(c,t)),u=mt.frobeniusMap(mt.mul(i,a),2),d=mt.frobeniusMap(mt.mul(o,r),3),h=mt.frobeniusMap(mt.mul(c,mt.conjugate(r)),1),f=mt.mul(mt.mul(l,mt.conjugate(s)),r);return mt.mul(mt.mul(mt.mul(u,d),h),f)}}),uC=$c(BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")),QL=rC(He,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(e=>e.map(t=>He.fromBigTuple(t.map(BigInt))))),eF=rC(Me,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),tF=tC(He,{A:He.create({c0:Me.create(Sr),c1:Me.create(BigInt(240))}),B:He.create({c0:Me.create(BigInt(1012)),c1:Me.create(BigInt(1012))}),Z:He.create({c0:Me.create(BigInt(-2)),c1:Me.create(BigInt(-1))})}),nF=tC(Me,{A:Me.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:Me.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:Me.create(BigInt(11))}),{G2psi:dC,G2psi2:rF}=YL(Me,He,He.div(He.ONE,He.NONRESIDUE)),Q6=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:Me.ORDER,m:2,k:128,expand:"xmd",hash:ls}),tg=jf(Me.toBytes(Sr),{infinity:!0,compressed:!0});function ng(e){e=e.slice();const t=e[0]&224,n=!!(t>>7&1),r=!!(t>>6&1),i=!!(t>>5&1);return e[0]&=31,{compressed:n,infinity:r,sort:i,value:e}}function jf(e,t){if(e[0]&224)throw new Error("setMask: non-empty mask");return t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}function fC(e){e.assertValidity();const t=e.equals(ds.G1.ProjectivePoint.ZERO),{x:n,y:r}=e.toAffine();if(t)return tg.slice();const i=Me.ORDER,s=!!(r*kn/i);return jf(_n(n,Me.BYTES),{compressed:!0,sort:s})}function hC(e){e.assertValidity();const t=Me.BYTES;if(e.equals(ds.G2.ProjectivePoint.ZERO))return dn(tg,_n(Sr,t));const{x:n,y:r}=e.toAffine(),{re:i,im:s}=He.reim(n),{re:o,im:a}=He.reim(r),l=!!((a>Sr?a*kn:o*kn)/Me.ORDER&Q2),u=i;return dn(jf(_n(s,t),{sort:l,compressed:!0}),_n(u,t))}const ds=GL({fields:{Fp:Me,Fp2:He,Fp6:X6,Fp12:mt,Fr:uC},G1:{Fp:Me,h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1"),a:Me.ZERO,b:Hf,htfDefaults:{...Q6,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(e,t)=>{const n=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),r=new e(Me.mul(t.px,n),t.py,t.pz);return t.multiplyUnsafe(Pc).negate().multiplyUnsafe(Pc).equals(r)},clearCofactor:(e,t)=>t.multiplyUnsafe(Pc).add(t),mapToCurve:e=>{const{x:t,y:n}=nF(Me.create(e[0]));return eF(t,n)},fromBytes:e=>{const{compressed:t,infinity:n,sort:r,value:i}=ng(e);if(i.length===48&&t){const s=Me.ORDER,o=Cr(i),a=Me.create(o&Me.MASK);if(n){if(a!==Sr)throw new Error("G1: non-empty compressed point at infinity");return{x:Sr,y:Sr}}const c=Me.add(Me.pow(a,eg),Me.create(ds.params.G1b));let l=Me.sqrt(c);if(!l)throw new Error("invalid compressed G1 point");return l*kn/s!==BigInt(r)&&(l=Me.neg(l)),{x:Me.create(a),y:Me.create(l)}}else if(i.length===96&&!t){const s=Cr(i.subarray(0,Me.BYTES)),o=Cr(i.subarray(Me.BYTES));if(n){if(s!==Sr||o!==Sr)throw new Error("G1: non-empty point at infinity");return ds.G1.ProjectivePoint.ZERO.toAffine()}return{x:Me.create(s),y:Me.create(o)}}else throw new Error("invalid point G1, expected 48/96 bytes")},toBytes:(e,t,n)=>{const r=t.equals(e.ZERO),{x:i,y:s}=t.toAffine();if(n){if(r)return tg.slice();const o=Me.ORDER,a=!!(s*kn/o);return jf(_n(i,Me.BYTES),{compressed:!0,sort:a})}else return r?dn(new Uint8Array([64]),new Uint8Array(2*Me.BYTES-1)):dn(_n(i,Me.BYTES),_n(s,Me.BYTES))},ShortSignature:{fromHex(e){const{infinity:t,sort:n,value:r}=ng(or("signatureHex",e,48)),i=Me.ORDER,s=Cr(r);if(t)return ds.G1.ProjectivePoint.ZERO;const o=Me.create(s&Me.MASK),a=Me.add(Me.pow(o,eg),Me.create(ds.params.G1b));let c=Me.sqrt(a);if(!c)throw new Error("invalid compressed G1 point");const l=BigInt(n);c*kn/i!==l&&(c=Me.neg(c));const u=ds.G1.ProjectivePoint.fromAffine({x:o,y:c});return u.assertValidity(),u},toRawBytes(e){return fC(e)},toHex(e){return Jl(fC(e))}}},G2:{Fp:He,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),Gx:He.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:He.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")]),a:He.ZERO,b:He.fromBigTuple([Hf,Hf]),hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...Q6},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:e=>{const{x:t,y:n}=tF(He.fromBigTuple(e));return QL(t,n)},isTorsionFree:(e,t)=>t.multiplyUnsafe(Pc).negate().equals(dC(e,t)),clearCofactor:(e,t)=>{const n=Pc;let r=t.multiplyUnsafe(n).negate(),i=dC(e,t),s=t.double();return s=rF(e,s),s=s.subtract(i),i=r.add(i),i=i.multiplyUnsafe(n).negate(),s=s.add(i),s=s.subtract(r),s.subtract(t)},fromBytes:e=>{const{compressed:t,infinity:n,sort:r,value:i}=ng(e);if(!t&&!n&&r||!t&&n&&r||r&&n&&t)throw new Error("invalid encoding flag: "+(e[0]&224));const s=Me.BYTES,o=(a,c,l)=>Cr(a.slice(c,l));if(i.length===96&&t){const a=ds.params.G2b,c=Me.ORDER;if(n){if(i.reduce((g,y)=>g!==0?y+1:y,0)>0)throw new Error("invalid compressed G2 point");return{x:He.ZERO,y:He.ZERO}}const l=o(i,0,s),u=o(i,s,2*s),d=He.create({c0:Me.create(u),c1:Me.create(l)}),h=He.add(He.pow(d,eg),a);let f=He.sqrt(h);const p=f.c1===Sr?f.c0*kn/c:f.c1*kn/c?Q2:Sr;return f=r&&p>0?f:He.neg(f),{x:d,y:f}}else if(i.length===192&&!t){if(n){if(i.reduce((d,h)=>d!==0?h+1:h,0)>0)throw new Error("invalid uncompressed G2 point");return{x:He.ZERO,y:He.ZERO}}const a=o(i,0,s),c=o(i,s,2*s),l=o(i,2*s,3*s),u=o(i,3*s,4*s);return{x:He.fromBigTuple([c,a]),y:He.fromBigTuple([u,l])}}else throw new Error("invalid point G2, expected 96/192 bytes")},toBytes:(e,t,n)=>{const{BYTES:r,ORDER:i}=Me,s=t.equals(e.ZERO),{x:o,y:a}=t.toAffine();if(n){if(s)return dn(tg,_n(Sr,r));const c=!!(a.c1===Sr?a.c0*kn/i:a.c1*kn/i);return dn(jf(_n(o.c1,r),{compressed:!0,sort:c}),_n(o.c0,r))}else{if(s)return dn(new Uint8Array([64]),new Uint8Array(4*r-1));const{re:c,im:l}=He.reim(o),{re:u,im:d}=He.reim(a);return dn(_n(l,r),_n(c,r),_n(d,r),_n(u,r))}},Signature:{fromHex(e){const{infinity:t,sort:n,value:r}=ng(or("signatureHex",e)),i=Me.ORDER,s=r.length/2;if(s!==48&&s!==96)throw new Error("invalid compressed signature length, must be 96 or 192");const o=Cr(r.slice(0,s)),a=Cr(r.slice(s));if(t)return ds.G2.ProjectivePoint.ZERO;const c=Me.create(o&Me.MASK),l=Me.create(a),u=He.create({c0:l,c1:c}),d=He.add(He.pow(u,eg),ds.params.G2b);let h=He.sqrt(d);if(!h)throw new Error("Failed to find a square root");const{re:f,im:p}=He.reim(h),g=BigInt(n),y=p>Sr&&p*kn/i!==g,A=p===Sr&&f*kn/i!==g;(y||A)&&(h=He.neg(h));const _=ds.G2.ProjectivePoint.fromAffine({x:u,y:h});return _.assertValidity(),_},toRawBytes(e){return hC(e)},toHex(e){return Jl(hC(e))}}},params:{ateLoopSize:Pc,r:uC.ORDER,xNegative:!0,twistType:"multiplicative"},htfDefaults:Q6,hash:ls,randomBytes:Rd});BigInt(0),BigInt(1),BigInt(2),BigInt(8),BigInt(0),BigInt(1),BigInt(2),BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),BigInt(0),BigInt(1),BigInt(2),BigInt(3),BigInt(5),BigInt(8);const eb=BigInt(0),tb=BigInt(1);function rg(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function nu(e,t,n=""){const r=R2(e),i=e?.length,s=t!==void 0;if(!r||s&&i!==t){const o=n&&`"${n}" `,a=s?` of length ${t}`:"",c=r?`length=${i}`:`type=${typeof e}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return e}function ig(e){const t=e.toString(16);return t.length&1?"0"+t:t}function pC(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?eb:BigInt("0x"+e)}function sg(e){return pC(kd(e))}function gC(e){return Oa(e),pC(kd(Uint8Array.from(e).reverse()))}function nb(e,t){return M2(e.toString(16).padStart(t*2,"0"))}function mC(e,t){return nb(e,t).reverse()}function zr(e,t,n){let r;if(typeof t=="string")try{r=M2(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(R2(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}const rb=e=>typeof e=="bigint"&&eb<=e;function iF(e,t,n){return rb(e)&&rb(t)&&rb(n)&&t<=e&&e<n}function sF(e,t,n,r){if(!iF(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function yC(e){let t;for(t=0;e>eb;e>>=tb,t+=1);return t}const zf=e=>(tb<<BigInt(e))-tb;function oF(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=f=>new Uint8Array(f),i=f=>Uint8Array.of(f);let s=r(e),o=r(e),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},l=(...f)=>n(o,s,...f),u=(f=r(0))=>{o=l(i(0),f),s=l(),f.length!==0&&(o=l(i(1),f),s=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<t;){s=l();const g=s.slice();p.push(g),f+=s.length}return Gs(...p)};return(f,p)=>{c(),u(f);let g;for(;!(g=p(d()));)u();return c(),g}}function ib(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(i,s,o){const a=e[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function wC(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(i!==void 0)return i;const s=e(n,...r);return t.set(n,s),s}}const Vr=BigInt(0),Ir=BigInt(1),ru=BigInt(2),bC=BigInt(3),vC=BigInt(4),EC=BigInt(5),aF=BigInt(7),AC=BigInt(8),cF=BigInt(9),CC=BigInt(16);function fs(e,t){const n=e%t;return n>=Vr?n:t+n}function Bi(e,t,n){let r=e;for(;t-- >Vr;)r*=r,r%=n;return r}function xC(e,t){if(e===Vr)throw new Error("invert: expected non-zero number");if(t<=Vr)throw new Error("invert: expected positive modulus, got "+t);let n=fs(e,t),r=t,i=Vr,s=Ir;for(;n!==Vr;){const a=r/n,c=r%n,l=i-s*a;r=n,n=c,i=s,s=l}if(r!==Ir)throw new Error("invert: does not exist");return fs(i,t)}function sb(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function _C(e,t){const n=(e.ORDER+Ir)/vC,r=e.pow(t,n);return sb(e,r,t),r}function lF(e,t){const n=(e.ORDER-EC)/AC,r=e.mul(t,ru),i=e.pow(r,n),s=e.mul(t,i),o=e.mul(e.mul(s,ru),i),a=e.mul(s,e.sub(o,e.ONE));return sb(e,a,t),a}function uF(e){const t=Vf(e),n=SC(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+aF)/CC;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,r);const d=a.mul(l,i),h=a.mul(l,s),f=a.eql(a.sqr(u),c),p=a.eql(a.sqr(d),c);l=a.cmov(l,u,f),u=a.cmov(h,d,p);const g=a.eql(a.sqr(u),c),y=a.cmov(l,u,g);return sb(a,y,c),y}}function SC(e){if(e<bC)throw new Error("sqrt is not defined for small field");let t=e-Ir,n=0;for(;t%ru===Vr;)t/=ru,n++;let r=ru;const i=Vf(e);for(;$C(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return _C;let s=i.pow(r,t);const o=(t+Ir)/ru;return function(c,l){if(c.is0(l))return l;if($C(c,l)!==1)throw new Error("Cannot find square root");let u=n,d=c.mul(c.ONE,s),h=c.pow(l,t),f=c.pow(l,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let p=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===u)throw new Error("Cannot find square root");const y=Ir<<BigInt(u-p-1),A=c.pow(d,y);u=p,d=c.sqr(A),h=c.mul(h,d),f=c.mul(f,A)}return f}}function dF(e){return e%vC===bC?_C:e%AC===EC?lF:e%CC===cF?uF(e):SC(e)}const fF=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hF(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=fF.reduce((r,i)=>(r[i]="function",r),t);return ib(e,n),e}function pF(e,t,n){if(n<Vr)throw new Error("invalid exponent, negatives unsupported");if(n===Vr)return e.ONE;if(n===Ir)return t;let r=e.ONE,i=t;for(;n>Vr;)n&Ir&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Ir;return r}function IC(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((o,a,c)=>e.is0(a)?o:(r[c]=o,e.mul(o,a)),e.ONE),s=e.inv(i);return t.reduceRight((o,a,c)=>e.is0(a)?o:(r[c]=e.mul(o,r[c]),e.mul(o,a)),s),r}function $C(e,t){const n=(e.ORDER-Ir)/ru,r=e.pow(t,n),i=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function TC(e,t){t!==void 0&&Xl(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Vf(e,t,n=!1,r={}){if(e<=Vr)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s,o=!1,a;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const h=t;h.BITS&&(i=h.BITS),h.sqrt&&(s=h.sqrt),typeof h.isLE=="boolean"&&(n=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof t=="number"&&(i=t),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=TC(e,i);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:zf(c),ZERO:Vr,ONE:Ir,allowedLengths:a,create:h=>fs(h,e),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Vr<=h&&h<e},is0:h=>h===Vr,isValidNot0:h=>!d.is0(h)&&d.isValid(h),isOdd:h=>(h&Ir)===Ir,neg:h=>fs(-h,e),eql:(h,f)=>h===f,sqr:h=>fs(h*h,e),add:(h,f)=>fs(h+f,e),sub:(h,f)=>fs(h-f,e),mul:(h,f)=>fs(h*f,e),pow:(h,f)=>pF(d,h,f),div:(h,f)=>fs(h*xC(f,e),e),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>xC(h,e),sqrt:s||(h=>(u||(u=dF(e)),u(d,h))),toBytes:h=>n?mC(h,l):nb(h,l),fromBytes:(h,f=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(l);g.set(h,n?0:g.length-h.length),h=g}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let p=n?gC(h):sg(h);if(o&&(p=fs(p,e)),!f&&!d.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>IC(d,h),cmov:(h,f,p)=>p?f:h});return Object.freeze(d)}function NC(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function PC(e){const t=NC(e);return t+Math.ceil(t/2)}function gF(e,t,n=!1){const r=e.length,i=NC(t),s=PC(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?gC(e):sg(e),a=fs(o,t-Ir)+Ir;return n?mC(a,i):nb(a,i)}const Fd=BigInt(0),iu=BigInt(1);function og(e,t){const n=t.negate();return e?n:t}function ob(e,t){const n=IC(e.Fp,t.map(r=>r.Z));return t.map((r,i)=>e.fromAffine(r.toAffine(n[i])))}function OC(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ab(e,t){OC(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e,s=zf(e),o=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function kC(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(e&i),c=e>>o;a>r&&(a-=s,c+=iu);const l=t*r,u=l+Math.abs(a)-1,d=a===0,h=a<0,f=t%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:l}}function mF(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function yF(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const cb=new WeakMap,RC=new WeakMap;function lb(e){return RC.get(e)||1}function BC(e){if(e!==Fd)throw new Error("invalid wNAF")}class wF{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let i=t;for(;n>Fd;)n&iu&&(r=r.add(i)),i=i.double(),n>>=iu;return r}precomputeWindow(t,n){const{windows:r,windowSize:i}=ab(n,this.bits),s=[];let o=t,a=o;for(let c=0;c<r;c++){a=o,s.push(a);for(let l=1;l<i;l++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=ab(t,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:h,offsetF:f}=kC(r,a,o);r=c,u?s=s.add(og(h,n[f])):i=i.add(og(d,n[l]))}return BC(r),{p:i,f:s}}wNAFUnsafe(t,n,r,i=this.ZERO){const s=ab(t,this.bits);for(let o=0;o<s.windows&&r!==Fd;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=kC(r,o,s);if(r=a,!l){const d=n[c];i=i.add(u?d.negate():d)}}return BC(r),i}getPrecomputes(t,n,r){let i=cb.get(n);return i||(i=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(i=r(i)),cb.set(n,i))),i}cached(t,n,r){const i=lb(t);return this.wNAF(i,this.getPrecomputes(i,t,r),n)}unsafe(t,n,r,i){const s=lb(t);return s===1?this._unsafeLadder(t,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,i)}createCache(t,n){OC(n,this.bits),RC.set(t,n),cb.delete(t)}hasCache(t){return lb(t)!==1}}function bF(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>Fd||r>Fd;)n&iu&&(s=s.add(i)),r&iu&&(o=o.add(i)),i=i.double(),n>>=iu,r>>=iu;return{p1:s,p2:o}}function vF(e,t,n,r){mF(n,e),yF(r,t);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=yC(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=zf(c),u=new Array(Number(l)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c;let h=o;for(let f=d;f>=0;f-=c){u.fill(o);for(let g=0;g<s;g++){const y=r[g],A=Number(y>>BigInt(f)&l);u[A]=u[A].add(n[g])}let p=o;for(let g=u.length-1,y=o;g>0;g--)y=y.add(u[g]),p=p.add(y);if(h=h.add(p),f!==0)for(let g=0;g<c;g++)h=h.double()}return h}function MC(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return hF(t),t}else return Vf(e,{isLE:n})}function EF(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const c of["p","n","h"]){const l=t[c];if(!(typeof l=="bigint"&&l>Fd))throw new Error(`CURVE.${c} must be positive bigint`)}const i=MC(t.p,n.Fp,r),s=MC(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(const c of a)if(!i.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:s}}const DC=(e,t)=>(e+(e>=0?t:-t)/UC)/t;function AF(e,t,n){const[[r,i],[s,o]]=t,a=DC(o*e,n),c=DC(-i*e,n);let l=e-a*r-c*s,u=-a*i-c*o;const d=l<za,h=u<za;d&&(l=-l),h&&(u=-u);const f=zf(Math.ceil(yC(n)/2))+Hd;if(l<za||l>=f||u<za||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}function ub(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function db(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return rg(n.lowS,"lowS"),rg(n.prehash,"prehash"),n.format!==void 0&&ub(n.format),n}class CF extends Error{constructor(t=""){super(t)}}const ja={Err:CF,_tlv:{encode:(e,t)=>{const{Err:n}=ja;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const r=t.length/2,i=ig(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?ig(i.length/2|128):"";return ig(e)+s+i+t},decode(e,t){const{Err:n}=ja;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const i=t[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=t.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+o)}}},_int:{encode(e){const{Err:t}=ja;if(e<za)throw new t("integer: negative integers are not allowed");let n=ig(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=ja;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return sg(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=ja,i=zr("signature",e),{v:s,l:o}=r.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=ja,r=t.encode(2,n.encode(e.r)),i=t.encode(2,n.encode(e.s)),s=r+i;return t.encode(48,s)}},za=BigInt(0),Hd=BigInt(1),UC=BigInt(2),ag=BigInt(3),xF=BigInt(4);function jd(e,t){const{BYTES:n}=e;let r;if(typeof t=="bigint")r=t;else{let i=zr("private key",t);try{r=e.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function _F(e,t={}){const n=EF("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;ib(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=FC(r,i);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(S,x,I){const{x:m,y:b}=x.toAffine(),$=r.toBytes(m);if(rg(I,"isCompressed"),I){u();const N=!r.isOdd(b);return Gs(LC(N),$)}else return Gs(Uint8Array.of(4),$,r.toBytes(b))}function h(S){nu(S,void 0,"Point");const{publicKey:x,publicKeyUncompressed:I}=l,m=S.length,b=S[0],$=S.subarray(1);if(m===x&&(b===2||b===3)){const N=r.fromBytes($);if(!r.isValid(N))throw new Error("bad point: is not on curve, wrong x");const P=g(N);let B;try{B=r.sqrt(P)}catch(Y){const X=Y instanceof Error?": "+Y.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}u();const V=r.isOdd(B);return(b&1)===1!==V&&(B=r.neg(B)),{x:N,y:B}}else if(m===I&&b===4){const N=r.BYTES,P=r.fromBytes($.subarray(0,N)),B=r.fromBytes($.subarray(N,N*2));if(!y(P,B))throw new Error("bad point: is not on curve");return{x:P,y:B}}else throw new Error(`bad point: got length ${m}, expected compressed=${x} or uncompressed=${I}`)}const f=t.toBytes||d,p=t.fromBytes||h;function g(S){const x=r.sqr(S),I=r.mul(x,S);return r.add(r.add(I,r.mul(S,s.a)),s.b)}function y(S,x){const I=r.sqr(x),m=g(S);return r.eql(I,m)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const A=r.mul(r.pow(s.a,ag),xF),_=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(A,_)))throw new Error("bad curve params: a or b");function v(S,x,I=!1){if(!r.isValid(x)||I&&r.is0(x))throw new Error(`bad point coordinate ${S}`);return x}function w(S){if(!(S instanceof U))throw new Error("ProjectivePoint expected")}function T(S){if(!c||!c.basises)throw new Error("no endo");return AF(S,c.basises,i.ORDER)}const O=wC((S,x)=>{const{X:I,Y:m,Z:b}=S;if(r.eql(b,r.ONE))return{x:I,y:m};const $=S.is0();x==null&&(x=$?r.ONE:r.inv(b));const N=r.mul(I,x),P=r.mul(m,x),B=r.mul(b,x);if($)return{x:r.ZERO,y:r.ZERO};if(!r.eql(B,r.ONE))throw new Error("invZ was invalid");return{x:N,y:P}}),D=wC(S=>{if(S.is0()){if(t.allowInfinityPoint&&!r.is0(S.Y))return;throw new Error("bad point: ZERO")}const{x,y:I}=S.toAffine();if(!r.isValid(x)||!r.isValid(I))throw new Error("bad point: x or y not field elements");if(!y(x,I))throw new Error("bad point: equation left != right");if(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function F(S,x,I,m,b){return I=new U(r.mul(I.X,S),I.Y,I.Z),x=og(m,x),I=og(b,I),x.add(I)}class U{constructor(x,I,m){this.X=v("x",x),this.Y=v("y",I,!0),this.Z=v("z",m),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){const{x:I,y:m}=x||{};if(!x||!r.isValid(I)||!r.isValid(m))throw new Error("invalid affine point");if(x instanceof U)throw new Error("projective point not allowed");return r.is0(I)&&r.is0(m)?U.ZERO:new U(I,m,r.ONE)}static fromBytes(x){const I=U.fromAffine(p(nu(x,void 0,"point")));return I.assertValidity(),I}static fromHex(x){return U.fromBytes(zr("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,I=!0){return W.createCache(this,x),I||this.multiply(ag),this}assertValidity(){D(this)}hasEvenY(){const{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){w(x);const{X:I,Y:m,Z:b}=this,{X:$,Y:N,Z:P}=x,B=r.eql(r.mul(I,P),r.mul($,b)),V=r.eql(r.mul(m,P),r.mul(N,b));return B&&V}negate(){return new U(this.X,r.neg(this.Y),this.Z)}double(){const{a:x,b:I}=s,m=r.mul(I,ag),{X:b,Y:$,Z:N}=this;let P=r.ZERO,B=r.ZERO,V=r.ZERO,Z=r.mul(b,b),Y=r.mul($,$),X=r.mul(N,N),G=r.mul(b,$);return G=r.add(G,G),V=r.mul(b,N),V=r.add(V,V),P=r.mul(x,V),B=r.mul(m,X),B=r.add(P,B),P=r.sub(Y,B),B=r.add(Y,B),B=r.mul(P,B),P=r.mul(G,P),V=r.mul(m,V),X=r.mul(x,X),G=r.sub(Z,X),G=r.mul(x,G),G=r.add(G,V),V=r.add(Z,Z),Z=r.add(V,Z),Z=r.add(Z,X),Z=r.mul(Z,G),B=r.add(B,Z),X=r.mul($,N),X=r.add(X,X),Z=r.mul(X,G),P=r.sub(P,Z),V=r.mul(X,Y),V=r.add(V,V),V=r.add(V,V),new U(P,B,V)}add(x){w(x);const{X:I,Y:m,Z:b}=this,{X:$,Y:N,Z:P}=x;let B=r.ZERO,V=r.ZERO,Z=r.ZERO;const Y=s.a,X=r.mul(s.b,ag);let G=r.mul(I,$),ne=r.mul(m,N),se=r.mul(b,P),we=r.add(I,m),ue=r.add($,N);we=r.mul(we,ue),ue=r.add(G,ne),we=r.sub(we,ue),ue=r.add(I,b);let ge=r.add($,P);return ue=r.mul(ue,ge),ge=r.add(G,se),ue=r.sub(ue,ge),ge=r.add(m,b),B=r.add(N,P),ge=r.mul(ge,B),B=r.add(ne,se),ge=r.sub(ge,B),Z=r.mul(Y,ue),B=r.mul(X,se),Z=r.add(B,Z),B=r.sub(ne,Z),Z=r.add(ne,Z),V=r.mul(B,Z),ne=r.add(G,G),ne=r.add(ne,G),se=r.mul(Y,se),ue=r.mul(X,ue),ne=r.add(ne,se),se=r.sub(G,se),se=r.mul(Y,se),ue=r.add(ue,se),G=r.mul(ne,ue),V=r.add(V,G),G=r.mul(ge,ue),B=r.mul(we,B),B=r.sub(B,G),G=r.mul(we,ne),Z=r.mul(ge,Z),Z=r.add(Z,G),new U(B,V,Z)}subtract(x){return this.add(x.negate())}is0(){return this.equals(U.ZERO)}multiply(x){const{endo:I}=t;if(!i.isValidNot0(x))throw new Error("invalid scalar: out of range");let m,b;const $=N=>W.cached(this,N,P=>ob(U,P));if(I){const{k1neg:N,k1:P,k2neg:B,k2:V}=T(x),{p:Z,f:Y}=$(P),{p:X,f:G}=$(V);b=Y.add(G),m=F(I.beta,Z,X,N,B)}else{const{p:N,f:P}=$(x);m=N,b=P}return ob(U,[m,b])[0]}multiplyUnsafe(x){const{endo:I}=t,m=this;if(!i.isValid(x))throw new Error("invalid scalar: out of range");if(x===za||m.is0())return U.ZERO;if(x===Hd)return m;if(W.hasCache(this))return this.multiply(x);if(I){const{k1neg:b,k1:$,k2neg:N,k2:P}=T(x),{p1:B,p2:V}=bF(U,m,$,P);return F(I.beta,B,V,b,N)}else return W.unsafe(m,x)}multiplyAndAddUnsafe(x,I,m){const b=this.multiplyUnsafe(I).add(x.multiplyUnsafe(m));return b.is0()?void 0:b}toAffine(x){return O(this,x)}isTorsionFree(){const{isTorsionFree:x}=t;return o===Hd?!0:x?x(U,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:x}=t;return o===Hd?this:x?x(U,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(x=!0){return rg(x,"isCompressed"),this.assertValidity(),f(U,this,x)}toHex(x=!0){return kd(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return ob(U,x)}static msm(x,I){return vF(U,i,x,I)}static fromPrivateKey(x){return U.BASE.multiply(jd(i,x))}}U.BASE=new U(s.Gx,s.Gy,r.ONE),U.ZERO=new U(r.ZERO,r.ONE,r.ZERO),U.Fp=r,U.Fn=i;const j=i.BITS,W=new wF(U,t.endo?Math.ceil(j/2):j);return U.BASE.precompute(8),U}function LC(e){return Uint8Array.of(e?2:3)}function FC(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function SF(e,t={}){const{Fn:n}=e,r=t.randomBytes||Rd,i=Object.assign(FC(e.Fp,n),{seed:PC(n.ORDER)});function s(f){try{return!!jd(n,f)}catch{return!1}}function o(f,p){const{publicKey:g,publicKeyUncompressed:y}=i;try{const A=f.length;return p===!0&&A!==g||p===!1&&A!==y?!1:!!e.fromBytes(f)}catch{return!1}}function a(f=r(i.seed)){return gF(nu(f,i.seed,"seed"),n.ORDER)}function c(f,p=!0){return e.BASE.multiply(jd(n,f)).toBytes(p)}function l(f){const p=a(f);return{secretKey:p,publicKey:c(p)}}function u(f){if(typeof f=="bigint")return!1;if(f instanceof e)return!0;const{secretKey:p,publicKey:g,publicKeyUncompressed:y}=i;if(n.allowedLengths||p===g)return;const A=zr("key",f).length;return A===g||A===y}function d(f,p,g=!0){if(u(f)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");const y=jd(n,f);return e.fromHex(p).multiply(y).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:l,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:f=>jd(n,f),precompute(f=8,p=e.BASE){return p.precompute(f,!1)}},lengths:i})}function IF(e,t,n={}){JA(t),ib(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Rd,i=n.hmac||((I,...m)=>G2(t,I,Gs(...m))),{Fp:s,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:f}=SF(e,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function y(I){const m=a>>Hd;return I>m}function A(I,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return m}function _(I,m){ub(m);const b=f.signature,$=m==="compact"?b:m==="recovered"?b+1:void 0;return nu(I,$,`${m} signature`)}class v{constructor(m,b,$){this.r=A("r",m),this.s=A("s",b),$!=null&&(this.recovery=$),Object.freeze(this)}static fromBytes(m,b=g){_(m,b);let $;if(b==="der"){const{r:V,s:Z}=ja.toSig(nu(m));return new v(V,Z)}b==="recovered"&&($=m[0],b="compact",m=m.subarray(1));const N=o.BYTES,P=m.subarray(0,N),B=m.subarray(N,N*2);return new v(o.fromBytes(P),o.fromBytes(B),$)}static fromHex(m,b){return this.fromBytes(M2(m),b)}addRecoveryBit(m){return new v(this.r,this.s,m)}recoverPublicKey(m){const b=s.ORDER,{r:$,s:N,recovery:P}=this;if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");if(a*UC<b&&P>1)throw new Error("recovery id is ambiguous for h>1 curve");const V=P===2||P===3?$+a:$;if(!s.isValid(V))throw new Error("recovery id 2 or 3 invalid");const Z=s.toBytes(V),Y=e.fromBytes(Gs(LC((P&1)===0),Z)),X=o.inv(V),G=T(zr("msgHash",m)),ne=o.create(-G*X),se=o.create(N*X),we=e.BASE.multiplyUnsafe(ne).add(Y.multiplyUnsafe(se));if(we.is0())throw new Error("point at infinify");return we.assertValidity(),we}hasHighS(){return y(this.s)}toBytes(m=g){if(ub(m),m==="der")return M2(ja.hexFromSig(this));const b=o.toBytes(this.r),$=o.toBytes(this.s);if(m==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Gs(Uint8Array.of(this.recovery),b,$)}return Gs(b,$)}toHex(m){return kd(this.toBytes(m))}assertValidity(){}static fromCompact(m){return v.fromBytes(zr("sig",m),"compact")}static fromDER(m){return v.fromBytes(zr("sig",m),"der")}normalizeS(){return this.hasHighS()?new v(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return kd(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return kd(this.toBytes("compact"))}}const w=n.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const b=sg(m),$=m.length*8-c;return $>0?b>>BigInt($):b},T=n.bits2int_modN||function(m){return o.create(w(m))},O=zf(c);function D(I){return sF("num < 2^"+c,I,za,O),o.toBytes(I)}function F(I,m){return nu(I,void 0,"message"),m?nu(t(I),void 0,"prehashed message"):I}function U(I,m,b){if(["recovered","canonical"].some(ne=>ne in b))throw new Error("sign() legacy options not supported");const{lowS:$,prehash:N,extraEntropy:P}=db(b,p);I=F(I,N);const B=T(I),V=jd(o,m),Z=[D(V),D(B)];if(P!=null&&P!==!1){const ne=P===!0?r(f.secretKey):P;Z.push(zr("extraEntropy",ne))}const Y=Gs(...Z),X=B;function G(ne){const se=w(ne);if(!o.isValidNot0(se))return;const we=o.inv(se),ue=e.BASE.multiply(se).toAffine(),ge=o.create(ue.x);if(ge===za)return;const Be=o.create(we*o.create(X+ge*V));if(Be===za)return;let Fe=(ue.x===ge?0:2)|Number(ue.y&Hd),qe=Be;return $&&y(Be)&&(qe=o.neg(Be),Fe^=1),new v(ge,qe,Fe)}return{seed:Y,k2sig:G}}function j(I,m,b={}){I=zr("message",I);const{seed:$,k2sig:N}=U(I,m,b);return oF(t.outputLen,o.BYTES,i)($,N)}function W(I){let m;const b=typeof I=="string"||R2(I),$=!b&&I!==null&&typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint";if(!b&&!$)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if($)m=new v(I.r,I.s);else if(b){try{m=v.fromBytes(zr("sig",I),"der")}catch(N){if(!(N instanceof ja.Err))throw N}if(!m)try{m=v.fromBytes(zr("sig",I),"compact")}catch{return!1}}return m||!1}function S(I,m,b,$={}){const{lowS:N,prehash:P,format:B}=db($,p);if(b=zr("publicKey",b),m=F(zr("message",m),P),"strict"in $)throw new Error("options.strict was renamed to lowS");const V=B===void 0?W(I):v.fromBytes(zr("sig",I),B);if(V===!1)return!1;try{const Z=e.fromBytes(b);if(N&&V.hasHighS())return!1;const{r:Y,s:X}=V,G=T(m),ne=o.inv(X),se=o.create(G*ne),we=o.create(Y*ne),ue=e.BASE.multiplyUnsafe(se).add(Z.multiplyUnsafe(we));return ue.is0()?!1:o.create(ue.x)===Y}catch{return!1}}function x(I,m,b={}){const{prehash:$}=db(b,p);return m=F(m,$),v.fromBytes(I,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:f,Point:e,sign:j,verify:S,recoverPublicKey:x,Signature:v,hash:t})}function $F(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=Vf(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function TF(e){const{CURVE:t,curveOpts:n}=$F(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function NF(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,TC(n.Fn.ORDER,n.Fn.BITS))})}function PF(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=TF(e),s=_F(t,n),o=IF(s,r,i);return NF(e,o)}function OF(e,t){const n=r=>PF({...e,hash:r});return{...n(t),create:n}}b6("HashToScalar-");const fb={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},kF={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},HC=BigInt(2);function RF(e){const t=fb.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=Bi(u,n,t)*u%t,h=Bi(d,n,t)*u%t,f=Bi(h,HC,t)*l%t,p=Bi(f,i,t)*f%t,g=Bi(p,s,t)*p%t,y=Bi(g,a,t)*g%t,A=Bi(y,c,t)*y%t,_=Bi(A,a,t)*g%t,v=Bi(_,n,t)*u%t,w=Bi(v,o,t)*p%t,T=Bi(w,r,t)*l%t,O=Bi(T,HC,t);if(!hb.eql(hb.sqr(O),e))throw new Error("Cannot find square root");return O}const hb=Vf(fb.p,{sqrt:RF});OF({...fb,Fp:hb,lowS:!0,endo:kF},ls);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function zd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function pb(e,...t){if(!zd(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function jC(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(n=>typeof n=="string"):t.every(n=>Number.isSafeInteger(n)):!1}function gb(e){if(typeof e!="function")throw new Error("function expected");return!0}function Oc(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function Vd(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function cg(e){if(!Array.isArray(e))throw new Error("array expected")}function lg(e,t){if(!jC(!0,t))throw new Error(`${e}: array of strings expected`)}function mb(e,t){if(!jC(!1,t))throw new Error(`${e}: array of numbers expected`)}function Wr(...e){const t=s=>s,n=(s,o)=>a=>s(o(a)),r=e.map(s=>s.encode).reduceRight(n,t),i=e.map(s=>s.decode).reduce(n,t);return{encode:r,decode:i}}function yi(e){const t=typeof e=="string"?e.split(""):e,n=t.length;lg("alphabet",t);const r=new Map(t.map((i,s)=>[i,s]));return{encode:i=>(cg(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${e}`);return t[s]})),decode:i=>(cg(i),i.map(s=>{Oc("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${e}`);return o}))}}function wi(e=""){return Oc("join",e),{encode:t=>(lg("join.decode",t),t.join(e)),decode:t=>(Oc("join.decode",t),t.split(e))}}function ug(e,t="="){return Vd(e),Oc("padding",t),{encode(n){for(lg("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){lg("padding.decode",n);let r=n.length;if(r*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--)if((r-1)*e%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}function zC(e){return gb(e),{encode:t=>t,decode:t=>e(t)}}function VC(e,t,n){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(cg(e),!e.length)return[];let r=0;const i=[],s=Array.from(e,a=>{if(Vd(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),o=s.length;for(;;){let a=0,c=!0;for(let l=r;l<o;l++){const u=s[l],d=t*a,h=d+u;if(!Number.isSafeInteger(h)||d/t!==a||h-u!==d)throw new Error("convertRadix: carry overflow");const f=h/n;a=h%n;const p=Math.floor(f);if(s[l]=p,!Number.isSafeInteger(p)||p*n+a!==h)throw new Error("convertRadix: carry overflow");if(c)p?c=!1:r=l;else continue}if(i.push(a),c)break}for(let a=0;a<e.length-1&&e[a]===0;a++)i.push(0);return i.reverse()}const WC=(e,t)=>t===0?e:WC(t,e%t),dg=(e,t)=>e+(t-WC(e,t)),fg=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function yb(e,t,n,r){if(cg(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(dg(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${dg(t,n)}`);let i=0,s=0;const o=fg[t],a=fg[n]-1,c=[];for(const l of e){if(Vd(l),l>=o)throw new Error(`convertRadix2: invalid data word=${l} from=${t}`);if(i=i<<t|l,s+t>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=n;s-=n)c.push((i>>s-n&a)>>>0);const u=fg[s];if(u===void 0)throw new Error("invalid carry");i&=u-1}if(i=i<<n-s&a,!r&&s>=t)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function BF(e){Vd(e);const t=2**8;return{encode:n=>{if(!zd(n))throw new Error("radix.encode input should be Uint8Array");return VC(Array.from(n),t,e)},decode:n=>(mb("radix.decode",n),Uint8Array.from(VC(n,e,t)))}}function Mi(e,t=!1){if(Vd(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(dg(8,e)>32||dg(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!zd(n))throw new Error("radix2.encode input should be Uint8Array");return yb(Array.from(n),8,e,!t)},decode:n=>(mb("radix2.decode",n),Uint8Array.from(yb(n,e,8,t)))}}function qC(e){return gb(e),function(...t){try{return e.apply(null,t)}catch{}}}function MF(e,t){return Vd(e),gb(t),{encode(n){if(!zd(n))throw new Error("checksum.encode: input should be Uint8Array");const r=t(n).slice(0,e),i=new Uint8Array(n.length+e);return i.set(n),i.set(r,n.length),i},decode(n){if(!zd(n))throw new Error("checksum.decode: input should be Uint8Array");const r=n.slice(0,-e),i=n.slice(-e),s=t(r).slice(0,e);for(let o=0;o<e;o++)if(s[o]!==i[o])throw new Error("Invalid checksum");return r}}}const DF=Wr(Mi(5),yi("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ug(5),wi("")),ZC=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",GC=(e,t)=>{Oc("base64",e);const n=t?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=t?"base64url":"base64";if(e.length>0&&!n.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},wb=e=>Wr(BF(58),yi(e),wi("")),Wd=wb("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),UF=e=>Wr(MF(4,t=>e(e(t))),Wd),bb=Wr(yi("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),wi("")),KC=[996825010,642813549,513874426,1027748829,705979059];function Wf(e){const t=e>>25;let n=(e&33554431)<<5;for(let r=0;r<KC.length;r++)(t>>r&1)===1&&(n^=KC[r]);return n}function YC(e,t,n=1){const r=e.length;let i=1;for(let s=0;s<r;s++){const o=e.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${e})`);i=Wf(i)^o>>5}i=Wf(i);for(let s=0;s<r;s++)i=Wf(i)^e.charCodeAt(s)&31;for(let s of t)i=Wf(i)^s;for(let s=0;s<6;s++)i=Wf(i);return i^=n,bb.encode(yb([i%fg[30]],30,5,!1))}function XC(e){const t=e==="bech32"?1:734539939,n=Mi(5),r=n.decode,i=n.encode,s=qC(r);function o(d,h,f=90){Oc("bech32.encode prefix",d),zd(h)&&(h=Array.from(h)),mb("bech32.encode",h);const p=d.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);const g=p+7+h.length;if(f!==!1&&g>f)throw new TypeError(`Length ${g} exceeds limit ${f}`);const y=d.toLowerCase(),A=YC(y,h,t);return`${y}1${bb.encode(h)}${A}`}function a(d,h=90){Oc("bech32.decode input",d);const f=d.length;if(f<8||h!==!1&&f>h)throw new TypeError(`invalid string length: ${f} (${d}). Expected (8..${h})`);const p=d.toLowerCase();if(d!==p&&d!==d.toUpperCase())throw new Error("String must be lowercase or uppercase");const g=p.lastIndexOf("1");if(g===0||g===-1)throw new Error('Letter "1" must be present between prefix and data only');const y=p.slice(0,g),A=p.slice(g+1);if(A.length<6)throw new Error("Data must be at least 6 characters long");const _=bb.decode(A).slice(0,-6),v=YC(y,_,t);if(!A.endsWith(v))throw new Error(`Invalid checksum in ${d}: expected "${v}"`);return{prefix:y,words:_}}const c=qC(a);function l(d){const{prefix:h,words:f}=a(d,!1);return{prefix:h,words:f,bytes:r(f)}}function u(d,h){return o(d,i(h))}return{encode:o,decode:a,encodeFromBytes:u,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:i}}const LF=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",FF={encode(e){return pb(e),e.toHex()},decode(e){return Oc("hex",e),Uint8Array.fromHex(e)}};UF(ls),b6("Bitcoin seed");function HF(e){return lL(jF(e))}function jF(e){const{payload:t,signature:n}=e,{r,s:i,yParity:s}=n,a=new FL.Signature(BigInt(r),BigInt(i)).addRecoveryBit(s).recoverPublicKey(k6(t).substring(2));return eL(a)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function JC(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function hg(e,...t){if(!JC(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function pg(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function QC(e,t){hg(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function qf(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function vb(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function zF(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function VF(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Zf(e){if(typeof e=="string")e=VF(e);else if(JC(e))e=ex(e);else throw new Error("Uint8Array expected, got "+typeof e);return e}function ex(e){return Uint8Array.from(e)}const Va=16,Eb=new Uint8Array(16),Ks=qf(Eb),WF=225,qF=(e,t,n,r)=>{const i=r&1;return{s3:n<<31|r>>>1,s2:t<<31|n>>>1,s1:e<<31|t>>>1,s0:e>>>1^WF<<24&-(i&1)}},Di=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255|0;function ZF(e){e.reverse();const t=e[15]&1;let n=0;for(let r=0;r<e.length;r++){const i=e[r];e[r]=i>>>1|n,n=(i&1)<<7}return e[0]^=-t&225,e}const GF=e=>e>64*1024?8:e>1024?4:2;class tx{constructor(t,n){this.blockLen=Va,this.outputLen=Va,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,t=Zf(t),hg(t,16);const r=zF(t);let i=r.getUint32(0,!1),s=r.getUint32(4,!1),o=r.getUint32(8,!1),a=r.getUint32(12,!1);const c=[];for(let p=0;p<128;p++)c.push({s0:Di(i),s1:Di(s),s2:Di(o),s3:Di(a)}),{s0:i,s1:s,s2:o,s3:a}=qF(i,s,o,a);const l=GF(n||1024);if(![1,2,4,8].includes(l))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=l;const d=128/l,h=this.windowSize=2**l,f=[];for(let p=0;p<d;p++)for(let g=0;g<h;g++){let y=0,A=0,_=0,v=0;for(let w=0;w<l;w++){if(!(g>>>l-w-1&1))continue;const{s0:O,s1:D,s2:F,s3:U}=c[l*p+w];y^=O,A^=D,_^=F,v^=U}f.push({s0:y,s1:A,s2:_,s3:v})}this.t=f}_updateBlock(t,n,r,i){t^=this.s0,n^=this.s1,r^=this.s2,i^=this.s3;const{W:s,t:o,windowSize:a}=this;let c=0,l=0,u=0,d=0;const h=(1<<s)-1;let f=0;for(const p of[t,n,r,i])for(let g=0;g<4;g++){const y=p>>>8*g&255;for(let A=8/s-1;A>=0;A--){const _=y>>>s*A&h,{s0:v,s1:w,s2:T,s3:O}=o[f*a+_];c^=v,l^=w,u^=T,d^=O,f+=1}}this.s0=c,this.s1=l,this.s2=u,this.s3=d}update(t){pg(this),t=Zf(t),hg(t);const n=qf(t),r=Math.floor(t.length/Va),i=t.length%Va;for(let s=0;s<r;s++)this._updateBlock(n[s*4+0],n[s*4+1],n[s*4+2],n[s*4+3]);return i&&(Eb.set(t.subarray(r*Va)),this._updateBlock(Ks[0],Ks[1],Ks[2],Ks[3]),vb(Ks)),this}destroy(){const{t}=this;for(const n of t)n.s0=0,n.s1=0,n.s2=0,n.s3=0}digestInto(t){pg(this),QC(t,this),this.finished=!0;const{s0:n,s1:r,s2:i,s3:s}=this,o=qf(t);return o[0]=n,o[1]=r,o[2]=i,o[3]=s,t}digest(){const t=new Uint8Array(Va);return this.digestInto(t),this.destroy(),t}}class KF extends tx{constructor(t,n){t=Zf(t),hg(t);const r=ZF(ex(t));super(r,n),vb(r)}update(t){t=Zf(t),pg(this);const n=qf(t),r=t.length%Va,i=Math.floor(t.length/Va);for(let s=0;s<i;s++)this._updateBlock(Di(n[s*4+3]),Di(n[s*4+2]),Di(n[s*4+1]),Di(n[s*4+0]));return r&&(Eb.set(t.subarray(i*Va)),this._updateBlock(Di(Ks[3]),Di(Ks[2]),Di(Ks[1]),Di(Ks[0])),vb(Ks)),this}digestInto(t){pg(this),QC(t,this),this.finished=!0;const{s0:n,s1:r,s2:i,s3:s}=this,o=qf(t);return o[0]=n,o[1]=r,o[2]=i,o[3]=s,t.reverse()}}function nx(e){const t=(r,i)=>e(i,r.length).update(Zf(r)).digest(),n=e(new Uint8Array(16),0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=(r,i)=>e(r,i),t}nx((e,t)=>new tx(e,t)),nx((e,t)=>new KF(e,t));const rx=$c(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),YF=rx.create(BigInt("-3")),XF=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");X2({a:YF,b:XF,Fp:rx,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},ls);const ix=$c(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),JF=ix.create(BigInt("-3")),QF=BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef");X2({a:JF,b:QF,Fp:ix,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},CU);const sx=$c(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),eH=sx.create(BigInt("-3")),tH=BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00");X2({a:eH,b:tH,Fp:sx,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1),lowS:!1,allowedPrivateKeyLengths:[130,131,132]},AU);var nH={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(c,l,u){this.fn=c,this.context=l,this.once=u||!1}function s(c,l,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,d||c,h),p=n?n+l:l;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],f]:c._events[p].push(f):(c._events[p]=f,c._eventsCount++),c}function o(c,l){--c._eventsCount===0?c._events=new r:delete c._events[l]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],u,d;if(this._eventsCount===0)return l;for(d in u=this._events)t.call(u,d)&&l.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},a.prototype.listeners=function(l){var u=n?n+l:l,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,p=new Array(f);h<f;h++)p[h]=d[h].fn;return p},a.prototype.listenerCount=function(l){var u=n?n+l:l,d=this._events[u];return d?d.fn?1:d.length:0},a.prototype.emit=function(l,u,d,h,f,p){var g=n?n+l:l;if(!this._events[g])return!1;var y=this._events[g],A=arguments.length,_,v;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),A){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,u),!0;case 3:return y.fn.call(y.context,u,d),!0;case 4:return y.fn.call(y.context,u,d,h),!0;case 5:return y.fn.call(y.context,u,d,h,f),!0;case 6:return y.fn.call(y.context,u,d,h,f,p),!0}for(v=1,_=new Array(A-1);v<A;v++)_[v-1]=arguments[v];y.fn.apply(y.context,_)}else{var w=y.length,T;for(v=0;v<w;v++)switch(y[v].once&&this.removeListener(l,y[v].fn,void 0,!0),A){case 1:y[v].fn.call(y[v].context);break;case 2:y[v].fn.call(y[v].context,u);break;case 3:y[v].fn.call(y[v].context,u,d);break;case 4:y[v].fn.call(y[v].context,u,d,h);break;default:if(!_)for(T=1,_=new Array(A-1);T<A;T++)_[T-1]=arguments[T];y[v].fn.apply(y[v].context,_)}}return!0},a.prototype.on=function(l,u,d){return s(this,l,u,d,!1)},a.prototype.once=function(l,u,d){return s(this,l,u,d,!0)},a.prototype.removeListener=function(l,u,d,h){var f=n?n+l:l;if(!this._events[f])return this;if(!u)return o(this,f),this;var p=this._events[f];if(p.fn)p.fn===u&&(!h||p.once)&&(!d||p.context===d)&&o(this,f);else{for(var g=0,y=[],A=p.length;g<A;g++)(p[g].fn!==u||h&&!p[g].once||d&&p[g].context!==d)&&y.push(p[g]);y.length?this._events[f]=y.length===1?y[0]:y:o(this,f)}return this},a.prototype.removeAllListeners=function(l){var u;return l?(u=n?n+l:l,this._events[u]&&o(this,u)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a})(nH);function rH(e){const t=e.length;let n=0,r=0;for(;r<t;){let i=e.charCodeAt(r++);if((i&4294967168)===0){n++;continue}else if((i&4294965248)===0)n+=2;else{if(i>=55296&&i<=56319&&r<t){const s=e.charCodeAt(r);(s&64512)===56320&&(++r,i=((i&1023)<<10)+(s&1023)+65536)}(i&4294901760)===0?n+=3:n+=4}}return n}function iH(e,t,n){const r=e.length;let i=n,s=0;for(;s<r;){let o=e.charCodeAt(s++);if((o&4294967168)===0){t[i++]=o;continue}else if((o&4294965248)===0)t[i++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<r){const a=e.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(t[i++]=o>>12&15|224,t[i++]=o>>6&63|128):(t[i++]=o>>18&7|240,t[i++]=o>>12&63|128,t[i++]=o>>6&63|128)}t[i++]=o&63|128}}const sH=new TextEncoder,oH=50;function aH(e,t,n){sH.encodeInto(e,t.subarray(n))}function cH(e,t,n){e.length>oH?aH(e,t,n):iH(e,t,n)}const lH=4096;function ox(e,t,n){let r=t;const i=r+n,s=[];let o="";for(;r<i;){const a=e[r++];if((a&128)===0)s.push(a);else if((a&224)===192){const c=e[r++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=e[r++]&63,l=e[r++]&63;s.push((a&31)<<12|c<<6|l)}else if((a&248)===240){const c=e[r++]&63,l=e[r++]&63,u=e[r++]&63;let d=(a&7)<<18|c<<12|l<<6|u;d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|d&1023),s.push(d)}else s.push(a);s.length>=lH&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const uH=new TextDecoder,dH=200;function fH(e,t,n){const r=e.subarray(t,t+n);return uH.decode(r)}function hH(e,t,n){return n>dH?fH(e,t,n):ox(e,t,n)}class gg{type;data;constructor(t,n){this.type=t,this.data=n}}class bi extends Error{constructor(t){super(t);const n=Object.create(bi.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:bi.name})}}const Gf=4294967295;function pH(e,t,n){const r=n/4294967296,i=n;e.setUint32(t,r),e.setUint32(t+4,i)}function ax(e,t,n){const r=Math.floor(n/4294967296),i=n;e.setUint32(t,r),e.setUint32(t+4,i)}function cx(e,t){const n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}function gH(e,t){const n=e.getUint32(t),r=e.getUint32(t+4);return n*4294967296+r}const mH=-1,yH=4294967296-1,wH=17179869184-1;function bH({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=wH)if(t===0&&e<=yH){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e),n}else{const n=e/4294967296,r=e&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,t<<2|n&3),s.setUint32(4,r),i}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,t),ax(r,4,e),n}}function vH(e){const t=e.getTime(),n=Math.floor(t/1e3),r=(t-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function EH(e){if(e instanceof Date){const t=vH(e);return bH(t)}else return null}function AH(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{const n=t.getUint32(0),r=t.getUint32(4),i=(n&3)*4294967296+r,s=n>>>2;return{sec:i,nsec:s}}case 12:{const n=cx(t,4),r=t.getUint32(0);return{sec:n,nsec:r}}default:throw new bi(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function CH(e){const t=AH(e);return new Date(t.sec*1e3+t.nsec/1e6)}const xH={type:mH,encode:EH,decode:CH};class mg{static defaultCodec=new mg;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(xH)}register({type:t,encode:n,decode:r}){if(t>=0)this.encoders[t]=n,this.decoders[t]=r;else{const i=-1-t;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}}tryToEncode(t,n){for(let r=0;r<this.builtInEncoders.length;r++){const i=this.builtInEncoders[r];if(i!=null){const s=i(t,n);if(s!=null){const o=-1-r;return new gg(o,s)}}}for(let r=0;r<this.encoders.length;r++){const i=this.encoders[r];if(i!=null){const s=i(t,n);if(s!=null){const o=r;return new gg(o,s)}}}return t instanceof gg?t:null}decode(t,n,r){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(t,n,r):new gg(n,t)}}function _H(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function Ab(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):_H(e)?new Uint8Array(e):Uint8Array.from(e)}const SH=100,IH=2048;class Cb{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??mg.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??SH,this.initialBufferSize=t?.initialBufferSize??IH,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new Cb({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered)return this.clone().encodeSharedRef(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered)return this.clone().encode(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,n)}ensureBufferSizeToWrite(t){const n=this.pos+t;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(t){const n=new ArrayBuffer(t),r=new Uint8Array(n),i=new DataView(n);r.set(this.bytes),this.view=i,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(t){t===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(t){!this.forceIntegerToFloat&&Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){const r=rH(t);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),cH(t,this.bytes,this.pos),this.pos+=r}encodeObject(t,n){const r=this.extensionCodec.tryToEncode(t,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(t))this.encodeArray(t,n);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){const n=t.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=Ab(t);this.writeU8a(r)}encodeArray(t,n){const r=t.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const i of t)this.doEncode(i,n+1)}countWithoutUndefined(t,n){let r=0;for(const i of n)t[i]!==void 0&&r++;return r}encodeMap(t,n){const r=Object.keys(t);this.sortKeys&&r.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(t,r):r.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of r){const o=t[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,n+1))}}encodeExtension(t){if(typeof t.data=="function"){const r=t.data(this.pos+6),i=r.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(t.type),this.writeU8a(r);return}const n=t.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){const n=t.length;this.ensureBufferSizeToWrite(n),this.bytes.set(t,this.pos),this.pos+=n}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),pH(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),ax(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}function $H(e,t){return new Cb(t).encodeSharedRef(e)}function xb(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}const TH=16,NH=16;class PH{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(t=TH,n=NH){this.maxKeyLength=t,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(t){return t>0&&t<=this.maxKeyLength}find(t,n,r){const i=this.caches[r-1];e:for(const s of i){const o=s.bytes;for(let a=0;a<r;a++)if(o[a]!==t[n+a])continue e;return s.str}return null}store(t,n){const r=this.caches[t.length-1],i={bytes:t,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=i:r.push(i)}decode(t,n,r){const i=this.find(t,n,r);if(i!=null)return this.hit++,i;this.miss++;const s=ox(t,n,r),o=Uint8Array.prototype.slice.call(t,n,n+r);return this.store(o,s),s}}const _b="array",Kf="map_key",lx="map_value",OH=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new bi("The type of key must be string or number but "+typeof e)};class kH{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){const n=this.getUninitializedStateFromPool();n.type=_b,n.position=0,n.size=t,n.array=new Array(t)}pushMapState(t){const n=this.getUninitializedStateFromPool();n.type=Kf,n.readCount=0,n.size=t,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===_b){const r=t;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(t.type===Kf||t.type===lx){const r=t;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Yf=-1,Sb=new DataView(new ArrayBuffer(0)),RH=new Uint8Array(Sb.buffer);try{Sb.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const ux=new RangeError("Insufficient data"),BH=new PH;class Ib{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Sb;bytes=RH;headByte=Yf;stack=new kH;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??mg.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??Gf,this.maxBinLength=t?.maxBinLength??Gf,this.maxArrayLength=t?.maxArrayLength??Gf,this.maxMapLength=t?.maxMapLength??Gf,this.maxExtLength=t?.maxExtLength??Gf,this.keyDecoder=t?.keyDecoder!==void 0?t.keyDecoder:BH,this.mapKeyConverter=t?.mapKeyConverter??OH}clone(){return new Ib({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Yf,this.stack.reset()}setBuffer(t){const n=Ab(t);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(t){if(this.headByte===Yf&&!this.hasRemaining(1))this.setBuffer(t);else{const n=this.bytes.subarray(this.pos),r=Ab(t),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),this.setBuffer(i)}}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered)return this.clone().decode(t);try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){yield*this.clone().decodeMulti(t);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered)return this.clone().decodeAsync(t);try{this.entered=!0;let n=!1,r;for await(const a of t){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:i,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${xb(i)} at ${o} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,n){if(this.entered){yield*this.clone().decodeMultiAsync(t,n);return}try{this.entered=!0;let r=n,i=-1;for await(const s of t){if(n&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),r&&(i=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const t=this.readHeadByte();let n;if(t>=224)n=t-256;else if(t<192)if(t<128)n=t;else if(t<144){const i=t-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(t<160){const i=t-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else{const i=t-160;n=this.decodeString(i,0)}else if(t===192)n=null;else if(t===194)n=!1;else if(t===195)n=!0;else if(t===202)n=this.readF32();else if(t===203)n=this.readF64();else if(t===204)n=this.readU8();else if(t===205)n=this.readU16();else if(t===206)n=this.readU32();else if(t===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(t===208)n=this.readI8();else if(t===209)n=this.readI16();else if(t===210)n=this.readI32();else if(t===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(t===217){const i=this.lookU8();n=this.decodeString(i,1)}else if(t===218){const i=this.lookU16();n=this.decodeString(i,2)}else if(t===219){const i=this.lookU32();n=this.decodeString(i,4)}else if(t===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(t===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(t===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(t===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(t===196){const i=this.lookU8();n=this.decodeBinary(i,1)}else if(t===197){const i=this.lookU16();n=this.decodeBinary(i,2)}else if(t===198){const i=this.lookU32();n=this.decodeBinary(i,4)}else if(t===212)n=this.decodeExtension(1,0);else if(t===213)n=this.decodeExtension(2,0);else if(t===214)n=this.decodeExtension(4,0);else if(t===215)n=this.decodeExtension(8,0);else if(t===216)n=this.decodeExtension(16,0);else if(t===199){const i=this.lookU8();n=this.decodeExtension(i,1)}else if(t===200){const i=this.lookU16();n=this.decodeExtension(i,2)}else if(t===201){const i=this.lookU32();n=this.decodeExtension(i,4)}else throw new bi(`Unrecognized type byte: ${xb(t)}`);this.complete();const r=this.stack;for(;r.length>0;){const i=r.top();if(i.type===_b)if(i.array[i.position]=n,i.position++,i.position===i.size)n=i.array,r.release(i);else continue e;else if(i.type===Kf){if(n==="__proto__")throw new bi("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=lx;continue e}else if(i.map[i.key]=n,i.readCount++,i.readCount===i.size)n=i.map,r.release(i);else{i.key=null,i.type=Kf;continue e}}return n}}readHeadByte(){return this.headByte===Yf&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Yf}readArraySize(){const t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new bi(`Unrecognized array type byte: ${xb(t)}`)}}}pushMapState(t){if(t>this.maxMapLength)throw new bi(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new bi(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,n):this.decodeBinary(t,n)}decodeUtf8String(t,n){if(t>this.maxStrLength)throw new bi(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+t)throw ux;const r=this.pos+n;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(t)?i=this.keyDecoder.decode(this.bytes,r,t):i=hH(this.bytes,r,t),this.pos+=n+t,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Kf:!1}decodeBinary(t,n){if(t>this.maxBinLength)throw new bi(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+n))throw ux;const r=this.pos+n,i=this.bytes.subarray(r,r+t);return this.pos+=n+t,i}decodeExtension(t,n){if(t>this.maxExtLength)throw new bi(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),i=this.decodeBinary(t,n+1);return this.extensionCodec.decode(i,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){const t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){const t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){const t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){const t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){const t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){const t=gH(this.view,this.pos);return this.pos+=8,t}readI64(){const t=cx(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){const t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){const t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){const t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){const t=this.view.getFloat64(this.pos);return this.pos+=8,t}}function MH(e,t){return new Ib(t).decode(e)}const DH=e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString()+"n":n),UH=e=>{const t=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,n=e.replace(t,'$1"$2n"$3');return JSON.parse(n,(r,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)};function su(e){if(typeof e!="string")throw new Error(`Cannot safe json parse value of type ${typeof e}`);try{return UH(e)}catch{return e}}function ou(e){return typeof e=="string"?e:DH(e)||""}function LH(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function dx(e,...t){if(!LH(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function fx(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function FH(e,t){dx(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}const qd=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $b=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);function HH(e){if(typeof e!="string")throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array(new TextEncoder().encode(e))}function hx(e){return typeof e=="string"&&(e=HH(e)),dx(e),e}class jH{clone(){return this._cloneInto()}}function zH(e){const t=r=>e().update(hx(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function px(e=32){if(qd&&typeof qd.getRandomValues=="function")return qd.getRandomValues(new Uint8Array(e));if(qd&&typeof qd.randomBytes=="function")return qd.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}function VH(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}class WH extends jH{constructor(t,n,r,i){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=$b(this.buffer)}update(t){fx(this);const{view:n,buffer:r,blockLen:i}=this;t=hx(t);const s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=$b(t);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){fx(this),FH(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let d=o;d<i;d++)n[d]=0;VH(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=$b(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return t.length=i,t.pos=a,t.finished=s,t.destroyed=o,i%n&&t.buffer.set(r),t}}const yg=BigInt(2**32-1),Tb=BigInt(32);function gx(e,t=!1){return t?{h:Number(e&yg),l:Number(e>>Tb&yg)}:{h:Number(e>>Tb&yg)|0,l:Number(e&yg)|0}}function qH(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=gx(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}const ZH=(e,t)=>BigInt(e>>>0)<<Tb|BigInt(t>>>0),GH=(e,t,n)=>e>>>n,KH=(e,t,n)=>e<<32-n|t>>>n,YH=(e,t,n)=>e>>>n|t<<32-n,XH=(e,t,n)=>e<<32-n|t>>>n,JH=(e,t,n)=>e<<64-n|t>>>n-32,QH=(e,t,n)=>e>>>n-32|t<<64-n,ej=(e,t)=>t,tj=(e,t)=>e,nj=(e,t,n)=>e<<n|t>>>32-n,rj=(e,t,n)=>t<<n|e>>>32-n,ij=(e,t,n)=>t<<n-32|e>>>64-n,sj=(e,t,n)=>e<<n-32|t>>>64-n;function oj(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}const aj=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),cj=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,lj=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),uj=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,dj=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),fj=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,lt={fromBig:gx,split:qH,toBig:ZH,shrSH:GH,shrSL:KH,rotrSH:YH,rotrSL:XH,rotrBH:JH,rotrBL:QH,rotr32H:ej,rotr32L:tj,rotlSH:nj,rotlSL:rj,rotlBH:ij,rotlBL:sj,add:oj,add3L:aj,add3H:cj,add4L:lj,add4H:uj,add5H:fj,add5L:dj},[hj,pj]=lt.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),kc=new Uint32Array(80),Rc=new Uint32Array(80);class gj extends WH{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:t,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:h,Gh:f,Gl:p,Hh:g,Hl:y}=this;return[t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y]}set(t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=h|0,this.Gh=f|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}process(t,n){for(let v=0;v<16;v++,n+=4)kc[v]=t.getUint32(n),Rc[v]=t.getUint32(n+=4);for(let v=16;v<80;v++){const w=kc[v-15]|0,T=Rc[v-15]|0,O=lt.rotrSH(w,T,1)^lt.rotrSH(w,T,8)^lt.shrSH(w,T,7),D=lt.rotrSL(w,T,1)^lt.rotrSL(w,T,8)^lt.shrSL(w,T,7),F=kc[v-2]|0,U=Rc[v-2]|0,j=lt.rotrSH(F,U,19)^lt.rotrBH(F,U,61)^lt.shrSH(F,U,6),W=lt.rotrSL(F,U,19)^lt.rotrBL(F,U,61)^lt.shrSL(F,U,6),S=lt.add4L(D,W,Rc[v-7],Rc[v-16]),x=lt.add4H(S,O,j,kc[v-7],kc[v-16]);kc[v]=x|0,Rc[v]=S|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:h,Fh:f,Fl:p,Gh:g,Gl:y,Hh:A,Hl:_}=this;for(let v=0;v<80;v++){const w=lt.rotrSH(d,h,14)^lt.rotrSH(d,h,18)^lt.rotrBH(d,h,41),T=lt.rotrSL(d,h,14)^lt.rotrSL(d,h,18)^lt.rotrBL(d,h,41),O=d&f^~d&g,D=h&p^~h&y,F=lt.add5L(_,T,D,pj[v],Rc[v]),U=lt.add5H(F,A,w,O,hj[v],kc[v]),j=F|0,W=lt.rotrSH(r,i,28)^lt.rotrBH(r,i,34)^lt.rotrBH(r,i,39),S=lt.rotrSL(r,i,28)^lt.rotrBL(r,i,34)^lt.rotrBL(r,i,39),x=r&s^r&a^s&a,I=i&o^i&c^o&c;A=g|0,_=y|0,g=f|0,y=p|0,f=d|0,p=h|0,{h:d,l:h}=lt.add(l|0,u|0,U|0,j|0),l=a|0,u=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const m=lt.add3L(j,S,I);r=lt.add3H(m,U,W,x),i=m|0}({h:r,l:i}=lt.add(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=lt.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=lt.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=lt.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:h}=lt.add(this.Eh|0,this.El|0,d|0,h|0),{h:f,l:p}=lt.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:g,l:y}=lt.add(this.Gh|0,this.Gl|0,g|0,y|0),{h:A,l:_}=lt.add(this.Hh|0,this.Hl|0,A|0,_|0),this.set(r,i,s,o,a,c,l,u,d,h,f,p,g,y,A,_)}roundClean(){kc.fill(0),Rc.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const mj=zH(()=>new gj);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Nb=BigInt(0),mx=BigInt(1),yj=BigInt(2);function Pb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ob(e){if(!Pb(e))throw new Error("Uint8Array expected")}function kb(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}const wj=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Rb(e){Ob(e);let t="";for(let n=0;n<e.length;n++)t+=wj[e[n]];return t}function yx(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Nb:BigInt("0x"+e)}const Wa={_0:48,_9:57,A:65,F:70,a:97,f:102};function wx(e){if(e>=Wa._0&&e<=Wa._9)return e-Wa._0;if(e>=Wa.A&&e<=Wa.F)return e-(Wa.A-10);if(e>=Wa.a&&e<=Wa.f)return e-(Wa.a-10)}function bx(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=wx(e.charCodeAt(s)),a=wx(e.charCodeAt(s+1));if(o===void 0||a===void 0){const c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function bj(e){return yx(Rb(e))}function wg(e){return Ob(e),yx(Rb(Uint8Array.from(e).reverse()))}function vx(e,t){return bx(e.toString(16).padStart(t*2,"0"))}function Bb(e,t){return vx(e,t).reverse()}function qa(e,t,n){let r;if(typeof t=="string")try{r=bx(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(Pb(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}function Ex(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];Ob(i),t+=i.length}const n=new Uint8Array(t);for(let r=0,i=0;r<e.length;r++){const s=e[r];n.set(s,i),i+=s.length}return n}const Mb=e=>typeof e=="bigint"&&Nb<=e;function vj(e,t,n){return Mb(e)&&Mb(t)&&Mb(n)&&t<=e&&e<n}function Xf(e,t,n,r){if(!vj(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Ej(e){let t;for(t=0;e>Nb;e>>=mx,t+=1);return t}const Aj=e=>(yj<<BigInt(e-1))-mx,Cj={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||Pb(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function Db(e,t,n={}){const r=(i,s,o)=>{const a=Cj[s];if(typeof a!="function")throw new Error("invalid validator function");const c=e[i];if(!(o&&c===void 0)&&!a(c,e))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(t))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return e}function Ax(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(i!==void 0)return i;const s=e(n,...r);return t.set(n,s),s}}const Rn=BigInt(0),fn=BigInt(1),au=BigInt(2),xj=BigInt(3),Ub=BigInt(4),Cx=BigInt(5),xx=BigInt(8);function Sn(e,t){const n=e%t;return n>=Rn?n:t+n}function _j(e,t,n){if(t<Rn)throw new Error("invalid exponent, negatives unsupported");if(n<=Rn)throw new Error("invalid modulus");if(n===fn)return Rn;let r=fn;for(;t>Rn;)t&fn&&(r=r*e%n),e=e*e%n,t>>=fn;return r}function Ys(e,t,n){let r=e;for(;t-- >Rn;)r*=r,r%=n;return r}function _x(e,t){if(e===Rn)throw new Error("invert: expected non-zero number");if(t<=Rn)throw new Error("invert: expected positive modulus, got "+t);let n=Sn(e,t),r=t,i=Rn,s=fn;for(;n!==Rn;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==fn)throw new Error("invert: does not exist");return Sn(i,t)}function Sj(e){const t=(e-fn)/au;let n,r,i;for(n=e-fn,r=0;n%au===Rn;n/=au,r++);for(i=au;i<e&&_j(i,t,e)!==e-fn;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(e+fn)/Ub;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const s=(n+fn)/au;return function(o,a){if(o.pow(a,t)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,l=o.pow(o.mul(o.ONE,i),n),u=o.pow(a,s),d=o.pow(a,n);for(;!o.eql(d,o.ONE);){if(o.eql(d,o.ZERO))return o.ZERO;let h=1;for(let p=o.sqr(d);h<c&&!o.eql(p,o.ONE);h++)p=o.sqr(p);const f=o.pow(l,fn<<BigInt(c-h-1));l=o.sqr(f),u=o.mul(u,f),d=o.mul(d,l),c=h}return u}}function Ij(e){if(e%Ub===xj){const t=(e+fn)/Ub;return function(n,r){const i=n.pow(r,t);if(!n.eql(n.sqr(i),r))throw new Error("Cannot find square root");return i}}if(e%xx===Cx){const t=(e-Cx)/xx;return function(n,r){const i=n.mul(r,au),s=n.pow(i,t),o=n.mul(r,s),a=n.mul(n.mul(o,au),s),c=n.mul(o,n.sub(a,n.ONE));if(!n.eql(n.sqr(c),r))throw new Error("Cannot find square root");return c}}return Sj(e)}const $j=(e,t)=>(Sn(e,t)&fn)===fn,Tj=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Nj(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=Tj.reduce((r,i)=>(r[i]="function",r),t);return Db(e,n)}function Pj(e,t,n){if(n<Rn)throw new Error("invalid exponent, negatives unsupported");if(n===Rn)return e.ONE;if(n===fn)return t;let r=e.ONE,i=t;for(;n>Rn;)n&fn&&(r=e.mul(r,i)),i=e.sqr(i),n>>=fn;return r}function Oj(e,t){const n=new Array(t.length),r=t.reduce((s,o,a)=>e.is0(o)?s:(n[a]=s,e.mul(s,o)),e.ONE),i=e.inv(r);return t.reduceRight((s,o,a)=>e.is0(o)?s:(n[a]=e.mul(s,n[a]),e.mul(s,o)),i),n}function Sx(e,t){const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Ix(e,t,n=!1,r={}){if(e<=Rn)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:i,nByteLength:s}=Sx(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:n,BITS:i,BYTES:s,MASK:Aj(i),ZERO:Rn,ONE:fn,create:c=>Sn(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Rn<=c&&c<e},is0:c=>c===Rn,isOdd:c=>(c&fn)===fn,neg:c=>Sn(-c,e),eql:(c,l)=>c===l,sqr:c=>Sn(c*c,e),add:(c,l)=>Sn(c+l,e),sub:(c,l)=>Sn(c-l,e),mul:(c,l)=>Sn(c*l,e),pow:(c,l)=>Pj(a,c,l),div:(c,l)=>Sn(c*_x(l,e),e),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>_x(c,e),sqrt:r.sqrt||(c=>(o||(o=Ij(e)),o(a,c))),invertBatch:c=>Oj(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>n?Bb(c,s):vx(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?wg(c):bj(c)}});return Object.freeze(a)}const $x=BigInt(0),bg=BigInt(1);function Lb(e,t){const n=t.negate();return e?n:t}function Tx(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Fb(e,t){Tx(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1);return{windows:n,windowSize:r}}function kj(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function Rj(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const Hb=new WeakMap,Nx=new WeakMap;function jb(e){return Nx.get(e)||1}function Bj(e,t){return{constTimeNegate:Lb,hasPrecomputes(n){return jb(n)!==1},unsafeLadder(n,r,i=e.ZERO){let s=n;for(;r>$x;)r&bg&&(i=i.add(s)),s=s.double(),r>>=bg;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=Fb(r,t),o=[];let a=n,c=a;for(let l=0;l<i;l++){c=a,o.push(c);for(let u=1;u<s;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,i){const{windows:s,windowSize:o}=Fb(n,t);let a=e.ZERO,c=e.BASE;const l=BigInt(2**n-1),u=2**n,d=BigInt(n);for(let h=0;h<s;h++){const f=h*o;let p=Number(i&l);i>>=d,p>o&&(p-=u,i+=bg);const g=f,y=f+Math.abs(p)-1,A=h%2!==0,_=p<0;p===0?c=c.add(Lb(A,r[g])):a=a.add(Lb(_,r[y]))}return{p:a,f:c}},wNAFUnsafe(n,r,i,s=e.ZERO){const{windows:o,windowSize:a}=Fb(n,t),c=BigInt(2**n-1),l=2**n,u=BigInt(n);for(let d=0;d<o;d++){const h=d*a;if(i===$x)break;let f=Number(i&c);if(i>>=u,f>a&&(f-=l,i+=bg),f===0)continue;let p=r[h+Math.abs(f)-1];f<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(n,r,i){let s=Hb.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&Hb.set(r,i(s))),s},wNAFCached(n,r,i){const s=jb(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=jb(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){Tx(r,t),Nx.set(n,r),Hb.delete(n)}}}function Mj(e,t,n,r){if(kj(n,e),Rj(r,t),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=e.ZERO,s=Ej(BigInt(n.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),l=Math.floor((t.BITS-1)/o)*o;let u=i;for(let d=l;d>=0;d-=o){c.fill(i);for(let f=0;f<r.length;f++){const p=r[f],g=Number(p>>BigInt(d)&BigInt(a));c[g]=c[g].add(n[f])}let h=i;for(let f=c.length-1,p=i;f>0;f--)p=p.add(c[f]),h=h.add(p);if(u=u.add(h),d!==0)for(let f=0;f<o;f++)u=u.double()}return u}function Dj(e){return Nj(e.Fp),Db(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Sx(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const hs=BigInt(0),qr=BigInt(1),vg=BigInt(2),Uj=BigInt(8),Lj={zip215:!0};function Fj(e){const t=Dj(e);return Db(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Hj(e){const t=Fj(e),{Fp:n,n:r,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=t,l=vg<<BigInt(a*8)-qr,u=n.create,d=Ix(t.n,t.nBitLength),h=t.uvRatio||((m,b)=>{try{return{isValid:!0,value:n.sqrt(m*n.inv(b))}}catch{return{isValid:!1,value:hs}}}),f=t.adjustScalarBytes||(m=>m),p=t.domain||((m,b,$)=>{if(kb("phflag",$),b.length||$)throw new Error("Contexts/pre-hash are not supported");return m});function g(m,b){Xf("coordinate "+m,b,hs,l)}function y(m){if(!(m instanceof v))throw new Error("ExtendedPoint expected")}const A=Ax((m,b)=>{const{ex:$,ey:N,ez:P}=m,B=m.is0();b==null&&(b=B?Uj:n.inv(P));const V=u($*b),Z=u(N*b),Y=u(P*b);if(B)return{x:hs,y:qr};if(Y!==qr)throw new Error("invZ was invalid");return{x:V,y:Z}}),_=Ax(m=>{const{a:b,d:$}=t;if(m.is0())throw new Error("bad point: ZERO");const{ex:N,ey:P,ez:B,et:V}=m,Z=u(N*N),Y=u(P*P),X=u(B*B),G=u(X*X),ne=u(Z*b),se=u(X*u(ne+Y)),we=u(G+u($*u(Z*Y)));if(se!==we)throw new Error("bad point: equation left != right (1)");const ue=u(N*P),ge=u(B*V);if(ue!==ge)throw new Error("bad point: equation left != right (2)");return!0});class v{constructor(b,$,N,P){this.ex=b,this.ey=$,this.ez=N,this.et=P,g("x",b),g("y",$),g("z",N),g("t",P),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof v)throw new Error("extended point not allowed");const{x:$,y:N}=b||{};return g("x",$),g("y",N),new v($,N,qr,u($*N))}static normalizeZ(b){const $=n.invertBatch(b.map(N=>N.ez));return b.map((N,P)=>N.toAffine($[P])).map(v.fromAffine)}static msm(b,$){return Mj(v,d,b,$)}_setWindowSize(b){O.setWindowSize(this,b)}assertValidity(){_(this)}equals(b){y(b);const{ex:$,ey:N,ez:P}=this,{ex:B,ey:V,ez:Z}=b,Y=u($*Z),X=u(B*P),G=u(N*Z),ne=u(V*P);return Y===X&&G===ne}is0(){return this.equals(v.ZERO)}negate(){return new v(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:b}=t,{ex:$,ey:N,ez:P}=this,B=u($*$),V=u(N*N),Z=u(vg*u(P*P)),Y=u(b*B),X=$+N,G=u(u(X*X)-B-V),ne=Y+V,se=ne-Z,we=Y-V,ue=u(G*se),ge=u(ne*we),Be=u(G*we),Fe=u(se*ne);return new v(ue,ge,Fe,Be)}add(b){y(b);const{a:$,d:N}=t,{ex:P,ey:B,ez:V,et:Z}=this,{ex:Y,ey:X,ez:G,et:ne}=b;if($===BigInt(-1)){const Qw=u((B-P)*(X+Y)),I2=u((B+P)*(X-Y)),Wl=u(I2-Qw);if(Wl===hs)return this.double();const ki=u(V*vg*ne),If=u(Z*vg*G),e6=If+ki,Ws=I2+Qw,t6=If-ki,M=u(e6*Wl),E=u(Ws*t6),C=u(e6*t6),z=u(Wl*Ws);return new v(M,E,z,C)}const se=u(P*Y),we=u(B*X),ue=u(Z*N*ne),ge=u(V*G),Be=u((P+B)*(Y+X)-se-we),Fe=ge-ue,qe=ge+ue,ct=u(we-$*se),St=u(Be*Fe),gi=u(qe*ct),Vl=u(Be*ct),YE=u(Fe*qe);return new v(St,gi,YE,Vl)}subtract(b){return this.add(b.negate())}wNAF(b){return O.wNAFCached(this,b,v.normalizeZ)}multiply(b){const $=b;Xf("scalar",$,qr,r);const{p:N,f:P}=this.wNAF($);return v.normalizeZ([N,P])[0]}multiplyUnsafe(b,$=v.ZERO){const N=b;return Xf("scalar",N,hs,r),N===hs?T:this.is0()||N===qr?this:O.wNAFCachedUnsafe(this,N,v.normalizeZ,$)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,r).is0()}toAffine(b){return A(this,b)}clearCofactor(){const{h:b}=t;return b===qr?this:this.multiplyUnsafe(b)}static fromHex(b,$=!1){const{d:N,a:P}=t,B=n.BYTES;b=qa("pointHex",b,B),kb("zip215",$);const V=b.slice(),Z=b[B-1];V[B-1]=Z&-129;const Y=wg(V),X=$?l:n.ORDER;Xf("pointHex.y",Y,hs,X);const G=u(Y*Y),ne=u(G-qr),se=u(N*G-P);let{isValid:we,value:ue}=h(ne,se);if(!we)throw new Error("Point.fromHex: invalid y coordinate");const ge=(ue&qr)===qr,Be=(Z&128)!==0;if(!$&&ue===hs&&Be)throw new Error("Point.fromHex: x=0 and x_0=1");return Be!==ge&&(ue=u(-ue)),v.fromAffine({x:ue,y:Y})}static fromPrivateKey(b){return U(b).point}toRawBytes(){const{x:b,y:$}=this.toAffine(),N=Bb($,n.BYTES);return N[N.length-1]|=b&qr?128:0,N}toHex(){return Rb(this.toRawBytes())}}v.BASE=new v(t.Gx,t.Gy,qr,u(t.Gx*t.Gy)),v.ZERO=new v(hs,qr,qr,hs);const{BASE:w,ZERO:T}=v,O=Bj(v,a*8);function D(m){return Sn(m,r)}function F(m){return D(wg(m))}function U(m){const b=n.BYTES;m=qa("private key",m,b);const $=qa("hashed private key",s(m),2*b),N=f($.slice(0,b)),P=$.slice(b,2*b),B=F(N),V=w.multiply(B),Z=V.toRawBytes();return{head:N,prefix:P,scalar:B,point:V,pointBytes:Z}}function j(m){return U(m).pointBytes}function W(m=new Uint8Array,...b){const $=Ex(...b);return F(s(p($,qa("context",m),!!i)))}function S(m,b,$={}){m=qa("message",m),i&&(m=i(m));const{prefix:N,scalar:P,pointBytes:B}=U(b),V=W($.context,N,m),Z=w.multiply(V).toRawBytes(),Y=W($.context,Z,B,m),X=D(V+Y*P);Xf("signature.s",X,hs,r);const G=Ex(Z,Bb(X,n.BYTES));return qa("result",G,n.BYTES*2)}const x=Lj;function I(m,b,$,N=x){const{context:P,zip215:B}=N,V=n.BYTES;m=qa("signature",m,2*V),b=qa("message",b),$=qa("publicKey",$,V),B!==void 0&&kb("zip215",B),i&&(b=i(b));const Z=wg(m.slice(V,2*V));let Y,X,G;try{Y=v.fromHex($,B),X=v.fromHex(m.slice(0,V),B),G=w.multiplyUnsafe(Z)}catch{return!1}if(!B&&Y.isSmallOrder())return!1;const ne=W(P,X.toRawBytes(),Y.toRawBytes(),b);return X.add(Y.multiplyUnsafe(ne)).subtract(G).clearCofactor().equals(v.ZERO)}return w._setWindowSize(8),{CURVE:t,getPublicKey:j,sign:S,verify:I,ExtendedPoint:v,utils:{getExtendedPublicKey:U,randomPrivateKey:()=>o(n.BYTES),precompute(m=8,b=v.BASE){return b._setWindowSize(m),b.multiply(BigInt(3)),b}}}}BigInt(0),BigInt(1);const zb=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Px=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const jj=BigInt(1),Ox=BigInt(2);BigInt(3);const zj=BigInt(5),Vj=BigInt(8);function Wj(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=zb,o=e*e%s*e%s,a=Ys(o,Ox,s)*o%s,c=Ys(a,jj,s)*e%s,l=Ys(c,zj,s)*c%s,u=Ys(l,t,s)*l%s,d=Ys(u,n,s)*u%s,h=Ys(d,r,s)*d%s,f=Ys(h,i,s)*h%s,p=Ys(f,i,s)*h%s,g=Ys(p,t,s)*l%s;return{pow_p_5_8:Ys(g,Ox,s)*e%s,b2:o}}function qj(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Zj(e,t){const n=zb,r=Sn(t*t*t,n),i=Sn(r*r*t,n),s=Wj(e*i).pow_p_5_8;let o=Sn(e*r*s,n);const a=Sn(t*o*o,n),c=o,l=Sn(o*Px,n),u=a===e,d=a===Sn(-e,n),h=a===Sn(-e*Px,n);return u&&(o=c),(d||h)&&(o=l),$j(o,n)&&(o=Sn(-o,n)),{isValid:u||d,value:o}}const Gj=Ix(zb,void 0,!0),Kj={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Gj,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Vj,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:mj,randomBytes:px,adjustScalarBytes:qj,uvRatio:Zj},kx=Hj(Kj),Yj="EdDSA",Xj="JWT",Eg=".",Ag="base64url",Rx="utf8",Bx="utf8",Jj=":",Qj="did",ez="key",Mx="base58btc",tz="z",nz="K36",rz=32;function Vb(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function Dx(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Vb(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function Ux(e,t){t||(t=e.reduce((i,s)=>i+s.length,0));const n=Dx(t);let r=0;for(const i of e)n.set(i,r),r+=i.length;return Vb(n)}function iz(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,A=0,_=p.length;A!==_&&p[A]===0;)A++,g++;for(var v=(_-A)*u+1>>>0,w=new Uint8Array(v);A!==_;){for(var T=p[A],O=0,D=v-1;(T!==0||O<y)&&D!==-1;D--,O++)T+=256*w[D]>>>0,w[D]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");y=O,A++}for(var F=v-y;F!==v&&w[F]===0;)F++;for(var U=c.repeat(g);F<v;++F)U+=e.charAt(w[F]);return U}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,A=0;p[g]===c;)y++,g++;for(var _=(p.length-g)*l+1>>>0,v=new Uint8Array(_);p[g];){var w=n[p.charCodeAt(g)];if(w===255)return;for(var T=0,O=_-1;(w!==0||T<A)&&O!==-1;O--,T++)w+=a*v[O]>>>0,v[O]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");A=T,g++}if(p[g]!==" "){for(var D=_-A;D!==_&&v[D]===0;)D++;for(var F=new Uint8Array(y+(_-D)),U=y;D!==_;)F[U++]=v[D++];return F}}}function f(p){var g=h(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var sz=iz,oz=sz;const Lx=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},az=e=>new TextEncoder().encode(e),cz=e=>new TextDecoder().decode(e);class lz{constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class uz{constructor(t,n,r){if(this.name=t,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Fx(this,t)}}class dz{constructor(t){this.decoders=t}or(t){return Fx(this,t)}decode(t){const n=t[0],r=this.decoders[n];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Fx=(e,t)=>new dz({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class fz{constructor(t,n,r,i){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new lz(t,n,r),this.decoder=new uz(t,n,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const Cg=({name:e,prefix:t,encode:n,decode:r})=>new fz(e,t,n,r),Jf=({prefix:e,name:t,alphabet:n})=>{const{encode:r,decode:i}=oz(n,t);return Cg({prefix:e,name:t,encode:r,decode:s=>Lx(i(s))})},hz=(e,t,n,r)=>{const i={};for(let u=0;u<t.length;++u)i[t[u]]=u;let s=e.length;for(;e[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[e[u]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|d,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},pz=(e,t,n)=>{const r=t[t.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>n;)o-=n,s+=t[i&a>>o];if(o&&(s+=t[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Vn=({name:e,prefix:t,bitsPerChar:n,alphabet:r})=>Cg({prefix:t,name:e,encode(i){return pz(i,r,n)},decode(i){return hz(i,r,n,e)}}),gz=Cg({prefix:"\0",name:"identity",encode:e=>cz(e),decode:e=>az(e)});var mz=Object.freeze({__proto__:null,identity:gz});const yz=Vn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wz=Object.freeze({__proto__:null,base2:yz});const bz=Vn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vz=Object.freeze({__proto__:null,base8:bz});const Ez=Jf({prefix:"9",name:"base10",alphabet:"0123456789"});var Az=Object.freeze({__proto__:null,base10:Ez});const Cz=Vn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),xz=Vn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var _z=Object.freeze({__proto__:null,base16:Cz,base16upper:xz});const Sz=Vn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Iz=Vn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$z=Vn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Tz=Vn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Nz=Vn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pz=Vn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Oz=Vn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kz=Vn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Rz=Vn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Bz=Object.freeze({__proto__:null,base32:Sz,base32upper:Iz,base32pad:$z,base32padupper:Tz,base32hex:Nz,base32hexupper:Pz,base32hexpad:Oz,base32hexpadupper:kz,base32z:Rz});const Mz=Jf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Dz=Jf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Uz=Object.freeze({__proto__:null,base36:Mz,base36upper:Dz});const Lz=Jf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Fz=Jf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Hz=Object.freeze({__proto__:null,base58btc:Lz,base58flickr:Fz});const jz=Vn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),zz=Vn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Vz=Vn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Wz=Vn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var qz=Object.freeze({__proto__:null,base64:jz,base64pad:zz,base64url:Vz,base64urlpad:Wz});const Hx=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}"),Zz=Hx.reduce((e,t,n)=>(e[n]=t,e),[]),Gz=Hx.reduce((e,t,n)=>(e[t.codePointAt(0)]=n,e),[]);function Kz(e){return e.reduce((t,n)=>(t+=Zz[n],t),"")}function Yz(e){const t=[];for(const n of e){const r=Gz[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}const Xz=Cg({prefix:"\u{1F680}",name:"base256emoji",encode:Kz,decode:Yz});var Jz=Object.freeze({__proto__:null,base256emoji:Xz}),Qz=zx,jx=128,eV=127,tV=~eV,nV=Math.pow(2,31);function zx(e,t,n){t=t||[],n=n||0;for(var r=n;e>=nV;)t[n++]=e&255|jx,e/=128;for(;e&tV;)t[n++]=e&255|jx,e>>>=7;return t[n]=e|0,zx.bytes=n-r+1,t}var rV=Wb,iV=128,Vx=127;function Wb(e,r){var n=0,r=r||0,i=0,s=r,o,a=e.length;do{if(s>=a)throw Wb.bytes=0,new RangeError("Could not decode varint");o=e[s++],n+=i<28?(o&Vx)<<i:(o&Vx)*Math.pow(2,i),i+=7}while(o>=iV);return Wb.bytes=s-r,n}var sV=Math.pow(2,7),oV=Math.pow(2,14),aV=Math.pow(2,21),cV=Math.pow(2,28),lV=Math.pow(2,35),uV=Math.pow(2,42),dV=Math.pow(2,49),fV=Math.pow(2,56),hV=Math.pow(2,63),pV=function(e){return e<sV?1:e<oV?2:e<aV?3:e<cV?4:e<lV?5:e<uV?6:e<dV?7:e<fV?8:e<hV?9:10},gV={encode:Qz,decode:rV,encodingLength:pV},Wx=gV;const qx=(e,t,n=0)=>(Wx.encode(e,t,n),t),Zx=e=>Wx.encodingLength(e),qb=(e,t)=>{const n=t.byteLength,r=Zx(e),i=r+Zx(n),s=new Uint8Array(i+n);return qx(e,s,0),qx(n,s,r),s.set(t,i),new mV(e,n,t,s)};class mV{constructor(t,n,r,i){this.code=t,this.size=n,this.digest=r,this.bytes=i}}const Gx=({name:e,code:t,encode:n})=>new yV(e,t,n);class yV{constructor(t,n,r){this.name=t,this.code=n,this.encode=r}digest(t){if(t instanceof Uint8Array){const n=this.encode(t);return n instanceof Uint8Array?qb(this.code,n):n.then(r=>qb(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Kx=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),wV=Gx({name:"sha2-256",code:18,encode:Kx("SHA-256")}),bV=Gx({name:"sha2-512",code:19,encode:Kx("SHA-512")});var vV=Object.freeze({__proto__:null,sha256:wV,sha512:bV});const Yx=0,EV="identity",Xx=Lx;var AV=Object.freeze({__proto__:null,identity:{code:Yx,name:EV,encode:Xx,digest:e=>qb(Yx,Xx(e))}});new TextEncoder,new TextDecoder;const Jx={...mz,...wz,...vz,...Az,..._z,...Bz,...Uz,...Hz,...qz,...Jz};({...vV,...AV});function Qx(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const e_=Qx("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),Zb=Qx("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{e=e.substring(1);const t=Dx(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),t_={utf8:e_,"utf-8":e_,hex:Jx.base16,latin1:Zb,ascii:Zb,binary:Zb,...Jx};function xg(e,t="utf8"){const n=t_[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):n.encoder.encode(e).substring(1)}function Zd(e,t="utf8"){const n=t_[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Vb(globalThis.Buffer.from(e,"utf-8")):n.decoder.decode(`${n.prefix}${e}`)}function n_(e){return su(xg(Zd(e,Ag),Rx))}function _g(e){return xg(Zd(ou(e),Rx),Ag)}function r_(e){const t=Zd(nz,Mx),n=tz+xg(Ux([t,e]),Mx);return[Qj,ez,n].join(Jj)}function CV(e){return xg(e,Ag)}function xV(e){return Zd(e,Ag)}function _V(e){return Zd([_g(e.header),_g(e.payload)].join(Eg),Bx)}function SV(e){return[_g(e.header),_g(e.payload),CV(e.signature)].join(Eg)}function Gb(e){const t=e.split(Eg),n=n_(t[0]),r=n_(t[1]),i=xV(t[2]),s=Zd(t.slice(0,2).join(Eg),Bx);return{header:n,payload:r,signature:i,data:s}}function i_(e=px(rz)){const t=kx.getPublicKey(e);return{secretKey:Ux([e,t]),publicKey:t}}async function IV(e,t,n,r,i=ve.fromMiliseconds(Date.now())){const s={alg:Yj,typ:Xj},o=r_(r.publicKey),a=i+n,c={iss:o,sub:e,aud:t,iat:i,exp:a},l=_V({header:s,payload:c}),u=kx.sign(l,r.secretKey.slice(0,32));return SV({header:s,payload:c,signature:u})}function Kb(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function s_(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Kb(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function Qf(e,t){t||(t=e.reduce((i,s)=>i+s.length,0));const n=s_(t);let r=0;for(const i of e)n.set(i,r),r+=i.length;return Kb(n)}function $V(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,A=0,_=p.length;A!==_&&p[A]===0;)A++,g++;for(var v=(_-A)*u+1>>>0,w=new Uint8Array(v);A!==_;){for(var T=p[A],O=0,D=v-1;(T!==0||O<y)&&D!==-1;D--,O++)T+=256*w[D]>>>0,w[D]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");y=O,A++}for(var F=v-y;F!==v&&w[F]===0;)F++;for(var U=c.repeat(g);F<v;++F)U+=e.charAt(w[F]);return U}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,A=0;p[g]===c;)y++,g++;for(var _=(p.length-g)*l+1>>>0,v=new Uint8Array(_);p[g];){var w=n[p.charCodeAt(g)];if(w===255)return;for(var T=0,O=_-1;(w!==0||T<A)&&O!==-1;O--,T++)w+=a*v[O]>>>0,v[O]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");A=T,g++}if(p[g]!==" "){for(var D=_-A;D!==_&&v[D]===0;)D++;for(var F=new Uint8Array(y+(_-D)),U=y;D!==_;)F[U++]=v[D++];return F}}}function f(p){var g=h(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var TV=$V,NV=TV;const o_=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},PV=e=>new TextEncoder().encode(e),OV=e=>new TextDecoder().decode(e);class kV{constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class RV{constructor(t,n,r){if(this.name=t,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return a_(this,t)}}class BV{constructor(t){this.decoders=t}or(t){return a_(this,t)}decode(t){const n=t[0],r=this.decoders[n];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const a_=(e,t)=>new BV({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class MV{constructor(t,n,r,i){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new kV(t,n,r),this.decoder=new RV(t,n,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const Sg=({name:e,prefix:t,encode:n,decode:r})=>new MV(e,t,n,r),eh=({prefix:e,name:t,alphabet:n})=>{const{encode:r,decode:i}=NV(n,t);return Sg({prefix:e,name:t,encode:r,decode:s=>o_(i(s))})},DV=(e,t,n,r)=>{const i={};for(let u=0;u<t.length;++u)i[t[u]]=u;let s=e.length;for(;e[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[e[u]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|d,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},UV=(e,t,n)=>{const r=t[t.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>n;)o-=n,s+=t[i&a>>o];if(o&&(s+=t[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Wn=({name:e,prefix:t,bitsPerChar:n,alphabet:r})=>Sg({prefix:t,name:e,encode(i){return UV(i,r,n)},decode(i){return DV(i,r,n,e)}}),LV=Sg({prefix:"\0",name:"identity",encode:e=>OV(e),decode:e=>PV(e)});var FV=Object.freeze({__proto__:null,identity:LV});const HV=Wn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var jV=Object.freeze({__proto__:null,base2:HV});const zV=Wn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var VV=Object.freeze({__proto__:null,base8:zV});const WV=eh({prefix:"9",name:"base10",alphabet:"0123456789"});var qV=Object.freeze({__proto__:null,base10:WV});const ZV=Wn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),GV=Wn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var KV=Object.freeze({__proto__:null,base16:ZV,base16upper:GV});const YV=Wn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),XV=Wn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),JV=Wn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),QV=Wn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),eW=Wn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),tW=Wn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),nW=Wn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rW=Wn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),iW=Wn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var sW=Object.freeze({__proto__:null,base32:YV,base32upper:XV,base32pad:JV,base32padupper:QV,base32hex:eW,base32hexupper:tW,base32hexpad:nW,base32hexpadupper:rW,base32z:iW});const oW=eh({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),aW=eh({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var cW=Object.freeze({__proto__:null,base36:oW,base36upper:aW});const lW=eh({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),uW=eh({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var dW=Object.freeze({__proto__:null,base58btc:lW,base58flickr:uW});const fW=Wn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),hW=Wn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),pW=Wn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gW=Wn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mW=Object.freeze({__proto__:null,base64:fW,base64pad:hW,base64url:pW,base64urlpad:gW});const c_=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}"),yW=c_.reduce((e,t,n)=>(e[n]=t,e),[]),wW=c_.reduce((e,t,n)=>(e[t.codePointAt(0)]=n,e),[]);function bW(e){return e.reduce((t,n)=>(t+=yW[n],t),"")}function vW(e){const t=[];for(const n of e){const r=wW[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}const EW=Sg({prefix:"\u{1F680}",name:"base256emoji",encode:bW,decode:vW});var AW=Object.freeze({__proto__:null,base256emoji:EW}),CW=u_,l_=128,xW=127,_W=~xW,SW=Math.pow(2,31);function u_(e,t,n){t=t||[],n=n||0;for(var r=n;e>=SW;)t[n++]=e&255|l_,e/=128;for(;e&_W;)t[n++]=e&255|l_,e>>>=7;return t[n]=e|0,u_.bytes=n-r+1,t}var IW=Yb,$W=128,d_=127;function Yb(e,r){var n=0,r=r||0,i=0,s=r,o,a=e.length;do{if(s>=a)throw Yb.bytes=0,new RangeError("Could not decode varint");o=e[s++],n+=i<28?(o&d_)<<i:(o&d_)*Math.pow(2,i),i+=7}while(o>=$W);return Yb.bytes=s-r,n}var TW=Math.pow(2,7),NW=Math.pow(2,14),PW=Math.pow(2,21),OW=Math.pow(2,28),kW=Math.pow(2,35),RW=Math.pow(2,42),BW=Math.pow(2,49),MW=Math.pow(2,56),DW=Math.pow(2,63),UW=function(e){return e<TW?1:e<NW?2:e<PW?3:e<OW?4:e<kW?5:e<RW?6:e<BW?7:e<MW?8:e<DW?9:10},LW={encode:CW,decode:IW,encodingLength:UW},f_=LW;const h_=(e,t,n=0)=>(f_.encode(e,t,n),t),p_=e=>f_.encodingLength(e),Xb=(e,t)=>{const n=t.byteLength,r=p_(e),i=r+p_(n),s=new Uint8Array(i+n);return h_(e,s,0),h_(n,s,r),s.set(t,i),new FW(e,n,t,s)};class FW{constructor(t,n,r,i){this.code=t,this.size=n,this.digest=r,this.bytes=i}}const g_=({name:e,code:t,encode:n})=>new HW(e,t,n);class HW{constructor(t,n,r){this.name=t,this.code=n,this.encode=r}digest(t){if(t instanceof Uint8Array){const n=this.encode(t);return n instanceof Uint8Array?Xb(this.code,n):n.then(r=>Xb(this.code,r))}else throw Error("Unknown type, must be binary type")}}const m_=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),jW=g_({name:"sha2-256",code:18,encode:m_("SHA-256")}),zW=g_({name:"sha2-512",code:19,encode:m_("SHA-512")});var VW=Object.freeze({__proto__:null,sha256:jW,sha512:zW});const y_=0,WW="identity",w_=o_;var qW=Object.freeze({__proto__:null,identity:{code:y_,name:WW,encode:w_,digest:e=>Xb(y_,w_(e))}});new TextEncoder,new TextDecoder;const b_={...FV,...jV,...VV,...qV,...KV,...sW,...cW,...dW,...mW,...AW};({...VW,...qW});function v_(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const E_=v_("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),Jb=v_("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{e=e.substring(1);const t=s_(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),A_={utf8:E_,"utf-8":E_,hex:b_.base16,latin1:Jb,ascii:Jb,binary:Jb,...b_};function Ui(e,t="utf8"){const n=A_[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Kb(globalThis.Buffer.from(e,"utf-8")):n.decoder.decode(`${n.prefix}${e}`)}function Zr(e,t="utf8"){const n=A_[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):n.encoder.encode(e).substring(1)}const ZW={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}},GW="Input must be an string, Buffer or Uint8Array";function KW(e){let t;if(e instanceof Uint8Array)t=e;else if(typeof e=="string")t=new TextEncoder().encode(e);else throw new Error(GW);return t}function YW(e){return Array.prototype.map.call(e,function(t){return(t<16?"0":"")+t.toString(16)}).join("")}function Ig(e){return(4294967296+e).toString(16).substring(1)}function XW(e,t,n){let r=`
|
|
18
18
|
`+e+" = ";for(let i=0;i<t.length;i+=2){if(n===32)r+=Ig(t[i]).toUpperCase(),r+=" ",r+=Ig(t[i+1]).toUpperCase();else if(n===64)r+=Ig(t[i+1]).toUpperCase(),r+=Ig(t[i]).toUpperCase();else throw new Error("Invalid size "+n);i%6===4?r+=`
|
|
19
|
-
`+new Array(e.length+4).join(" "):i<t.length-2&&(r+=" ")}console.log(r)}function JW(e,t,n){let r=new Date().getTime();const i=new Uint8Array(t);for(let o=0;o<t;o++)i[o]=o%256;const s=new Date().getTime();console.log("Generated random input in "+(s-r)+"ms"),r=s;for(let o=0;o<n;o++){const a=e(i),c=new Date().getTime(),l=c-r;r=c,console.log("Hashed in "+l+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(t/(1<<20)/(l/1e3)*100)/100+" MB PER SECOND")}}var C_={normalizeInput:KW,toHex:YW,debugPrint:XW,testSpeed:JW};const $g=C_;function Tg(e,t,n){const r=e[t]+e[n];let i=e[t+1]+e[n+1];r>=4294967296&&i++,e[t]=r,e[t+1]=i}function x_(e,t,n,r){let i=e[t]+n;n<0&&(i+=4294967296);let s=e[t+1]+r;i>=4294967296&&s++,e[t]=i,e[t+1]=s}function __(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function Bc(e,t,n,r,i,s){const o=th[i],a=th[i+1],c=th[s],l=th[s+1];Tg(st,e,t),x_(st,e,o,a);let u=st[r]^st[e],d=st[r+1]^st[e+1];st[r]=d,st[r+1]=u,Tg(st,n,r),u=st[t]^st[n],d=st[t+1]^st[n+1],st[t]=u>>>24^d<<8,st[t+1]=d>>>24^u<<8,Tg(st,e,t),x_(st,e,c,l),u=st[r]^st[e],d=st[r+1]^st[e+1],st[r]=u>>>16^d<<16,st[r+1]=d>>>16^u<<16,Tg(st,n,r),u=st[t]^st[n],d=st[t+1]^st[n+1],st[t]=d>>>31^u<<1,st[t+1]=u>>>31^d<<1}const S_=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),QW=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],ar=new Uint8Array(QW.map(function(e){return e*2})),st=new Uint32Array(32),th=new Uint32Array(32);function I_(e,t){let n=0;for(n=0;n<16;n++)st[n]=e.h[n],st[n+16]=S_[n];for(st[24]=st[24]^e.t,st[25]=st[25]^e.t/4294967296,t&&(st[28]=~st[28],st[29]=~st[29]),n=0;n<32;n++)th[n]=__(e.b,4*n);for(n=0;n<12;n++)Bc(0,8,16,24,ar[n*16+0],ar[n*16+1]),Bc(2,10,18,26,ar[n*16+2],ar[n*16+3]),Bc(4,12,20,28,ar[n*16+4],ar[n*16+5]),Bc(6,14,22,30,ar[n*16+6],ar[n*16+7]),Bc(0,10,20,30,ar[n*16+8],ar[n*16+9]),Bc(2,12,22,24,ar[n*16+10],ar[n*16+11]),Bc(4,14,16,26,ar[n*16+12],ar[n*16+13]),Bc(6,8,18,28,ar[n*16+14],ar[n*16+15]);for(n=0;n<16;n++)e.h[n]=e.h[n]^st[n]^st[n+16]}const Mc=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function $_(e,t,n,r){if(e===0||e>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(t&&t.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(n&&n.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:e};Mc.fill(0),Mc[0]=e,t&&(Mc[1]=t.length),Mc[2]=1,Mc[3]=1,n&&Mc.set(n,32),r&&Mc.set(r,48);for(let s=0;s<16;s++)i.h[s]=S_[s]^__(Mc,s*4);return t&&(Qb(i,t),i.c=128),i}function Qb(e,t){for(let n=0;n<t.length;n++)e.c===128&&(e.t+=e.c,I_(e,!1),e.c=0),e.b[e.c++]=t[n]}function T_(e){for(e.t+=e.c;e.c<128;)e.b[e.c++]=0;I_(e,!0);const t=new Uint8Array(e.outlen);for(let n=0;n<e.outlen;n++)t[n]=e.h[n>>2]>>8*(n&3);return t}function N_(e,t,n,r,i){n=n||64,e=$g.normalizeInput(e),r&&(r=$g.normalizeInput(r)),i&&(i=$g.normalizeInput(i));const s=$_(n,t,r,i);return Qb(s,e),T_(s)}function eq(e,t,n,r,i){const s=N_(e,t,n,r,i);return $g.toHex(s)}var tq={blake2b:N_,blake2bHex:eq,blake2bInit:$_,blake2bUpdate:Qb,blake2bFinal:T_};const P_=C_;function nq(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function Dc(e,t,n,r,i,s){$t[e]=$t[e]+$t[t]+i,$t[r]=Ng($t[r]^$t[e],16),$t[n]=$t[n]+$t[r],$t[t]=Ng($t[t]^$t[n],12),$t[e]=$t[e]+$t[t]+s,$t[r]=Ng($t[r]^$t[e],8),$t[n]=$t[n]+$t[r],$t[t]=Ng($t[t]^$t[n],7)}function Ng(e,t){return e>>>t^e<<32-t}const O_=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cr=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),$t=new Uint32Array(16),qn=new Uint32Array(16);function k_(e,t){let n=0;for(n=0;n<8;n++)$t[n]=e.h[n],$t[n+8]=O_[n];for($t[12]^=e.t,$t[13]^=e.t/4294967296,t&&($t[14]=~$t[14]),n=0;n<16;n++)qn[n]=nq(e.b,4*n);for(n=0;n<10;n++)Dc(0,4,8,12,qn[cr[n*16+0]],qn[cr[n*16+1]]),Dc(1,5,9,13,qn[cr[n*16+2]],qn[cr[n*16+3]]),Dc(2,6,10,14,qn[cr[n*16+4]],qn[cr[n*16+5]]),Dc(3,7,11,15,qn[cr[n*16+6]],qn[cr[n*16+7]]),Dc(0,5,10,15,qn[cr[n*16+8]],qn[cr[n*16+9]]),Dc(1,6,11,12,qn[cr[n*16+10]],qn[cr[n*16+11]]),Dc(2,7,8,13,qn[cr[n*16+12]],qn[cr[n*16+13]]),Dc(3,4,9,14,qn[cr[n*16+14]],qn[cr[n*16+15]]);for(n=0;n<8;n++)e.h[n]^=$t[n]^$t[n+8]}function R_(e,t){if(!(e>0&&e<=32))throw new Error("Incorrect output length, should be in [1, 32]");const n=t?t.length:0;if(t&&!(n>0&&n<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(O_),b:new Uint8Array(64),c:0,t:0,outlen:e};return r.h[0]^=16842752^n<<8^e,n>0&&(e8(r,t),r.c=64),r}function e8(e,t){for(let n=0;n<t.length;n++)e.c===64&&(e.t+=e.c,k_(e,!1),e.c=0),e.b[e.c++]=t[n]}function B_(e){for(e.t+=e.c;e.c<64;)e.b[e.c++]=0;k_(e,!0);const t=new Uint8Array(e.outlen);for(let n=0;n<e.outlen;n++)t[n]=e.h[n>>2]>>8*(n&3)&255;return t}function M_(e,t,n){n=n||32,e=P_.normalizeInput(e);const r=R_(n,t);return e8(r,e),B_(r)}function rq(e,t,n){const r=M_(e,t,n);return P_.toHex(r)}var iq={blake2s:M_,blake2sHex:rq,blake2sInit:R_,blake2sUpdate:e8,blake2sFinal:B_};const nh=tq,rh=iq;var sq={blake2b:nh.blake2b,blake2bHex:nh.blake2bHex,blake2bInit:nh.blake2bInit,blake2bUpdate:nh.blake2bUpdate,blake2bFinal:nh.blake2bFinal,blake2s:rh.blake2s,blake2sHex:rh.blake2sHex,blake2sInit:rh.blake2sInit,blake2sUpdate:rh.blake2sUpdate,blake2sFinal:rh.blake2sFinal},Xs={exports:{}};function oq(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}var aq=cq;function cq(e,t,n){var r=n&&n.stringify||oq,i=1;if(typeof e=="object"&&e!==null){var s=t.length+i;if(s===1)return e;var o=new Array(s);o[0]=r(e);for(var a=1;a<s;a++)o[a]=r(t[a]);return o.join(" ")}if(typeof e!="string")return e;var c=t.length;if(c===0)return e;for(var l="",u=1-i,d=-1,h=e&&e.length||0,f=0;f<h;){if(e.charCodeAt(f)===37&&f+1<h){switch(d=d>-1?d:0,e.charCodeAt(f+1)){case 100:case 102:if(u>=c||t[u]==null)break;d<f&&(l+=e.slice(d,f)),l+=Number(t[u]),d=f+2,f++;break;case 105:if(u>=c||t[u]==null)break;d<f&&(l+=e.slice(d,f)),l+=Math.floor(Number(t[u])),d=f+2,f++;break;case 79:case 111:case 106:if(u>=c||t[u]===void 0)break;d<f&&(l+=e.slice(d,f));var p=typeof t[u];if(p==="string"){l+="'"+t[u]+"'",d=f+2,f++;break}if(p==="function"){l+=t[u].name||"<anonymous>",d=f+2,f++;break}l+=r(t[u]),d=f+2,f++;break;case 115:if(u>=c)break;d<f&&(l+=e.slice(d,f)),l+=String(t[u]),d=f+2,f++;break;case 37:d<f&&(l+=e.slice(d,f)),l+="%",d=f+2,f++,u--;break}++u}++f}return d===-1?e:(d<h&&(l+=e.slice(d)),l)}const D_=aq;Xs.exports=Za;const ih=Cq().console||{},lq={mapHttpRequest:Pg,mapHttpResponse:Pg,wrapRequestSerializer:s8,wrapResponseSerializer:s8,wrapErrorSerializer:s8,req:Pg,res:Pg,err:L_,errWithCause:L_};function Uc(e,t){return e==="silent"?1/0:t.levels.values[e]}const t8=Symbol("pino.logFuncs"),n8=Symbol("pino.hierarchy"),uq={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function U_(e,t){const n={logger:t,parent:e[n8]};t[n8]=n}function dq(e,t,n){const r={};t.forEach(i=>{r[i]=n[i]?n[i]:ih[i]||ih[uq[i]||"log"]||Gd}),e[t8]=r}function fq(e,t){return Array.isArray(e)?e.filter(function(n){return n!=="!stdSerializers.err"}):e===!0?Object.keys(t):!1}function Za(e){e=e||{},e.browser=e.browser||{};const t=e.browser.transmit;if(t&&typeof t.send!="function")throw Error("pino: transmit option must have a send function");const n=e.browser.write||ih;e.browser.write&&(e.browser.asObject=!0);const r=e.serializers||{},i=fq(e.browser.serialize,r);let s=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof n=="function"&&a.forEach(function(g){n[g]=n}),(e.enabled===!1||e.browser.disabled)&&(e.level="silent");const c=e.level||"info",l=Object.create(n);l.log||(l.log=Gd),dq(l,a,n),U_({},l),Object.defineProperty(l,"levelVal",{get:d}),Object.defineProperty(l,"level",{get:h,set:f});const u={transmit:t,serialize:i,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:vq(e),messageKey:e.messageKey||"msg",onChild:e.onChild||Gd};l.levels=hq(e),l.level=c,l.isLevelEnabled=function(g){return this.levels.values[g]?this.levels.values[g]>=this.levels.values[this.level]:!1},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=Gd,l.serializers=r,l._serialize=i,l._stdErrSerialize=s,l.child=function(...g){return p.call(this,u,...g)},t&&(l._logEvent=i8());function d(){return Uc(this.level,this)}function h(){return this._level}function f(g){if(g!=="silent"&&!this.levels.values[g])throw Error("unknown level "+g);this._level=g,cu(this,u,l,"error"),cu(this,u,l,"fatal"),cu(this,u,l,"warn"),cu(this,u,l,"info"),cu(this,u,l,"debug"),cu(this,u,l,"trace"),o.forEach(y=>{cu(this,u,l,y)})}function p(g,y,A){if(!y)throw new Error("missing bindings for child Pino");A=A||{},i&&y.serializers&&(A.serializers=y.serializers);const _=A.serializers;if(i&&_){var v=Object.assign({},r,_),w=e.browser.serialize===!0?Object.keys(v):i;delete y.serializers,r8([y],w,v,this._stdErrSerialize)}function T(D){this._childLevel=(D._childLevel|0)+1,this.bindings=y,v&&(this.serializers=v,this._serialize=w),t&&(this._logEvent=i8([].concat(D._logEvent.bindings,y)))}T.prototype=this;const O=new T(this);return U_(this,O),O.child=function(...D){return p.call(this,g,...D)},O.level=A.level||this.level,g.onChild(O),O}return l}function hq(e){const t=e.customLevels||{},n=Object.assign({},Za.levels.values,t),r=Object.assign({},Za.levels.labels,pq(t));return{values:n,labels:r}}function pq(e){const t={};return Object.keys(e).forEach(function(n){t[e[n]]=n}),t}Za.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"}},Za.stdSerializers=lq,Za.stdTimeFunctions=Object.assign({},{nullTime:F_,epochTime:H_,unixTime:Eq,isoTime:Aq});function gq(e){const t=[];e.bindings&&t.push(e.bindings);let n=e[n8];for(;n.parent;)n=n.parent,n.logger.bindings&&t.push(n.logger.bindings);return t.reverse()}function cu(e,t,n,r){if(Object.defineProperty(e,r,{value:Uc(e.level,n)>Uc(r,n)?Gd:n[t8][r],writable:!0,enumerable:!0,configurable:!0}),e[r]===Gd){if(!t.transmit)return;const s=t.transmit.level||e.level,o=Uc(s,n);if(Uc(r,n)<o)return}e[r]=yq(e,t,n,r);const i=gq(e);i.length!==0&&(e[r]=mq(i,e[r]))}function mq(e,t){return function(){return t.apply(this,[...e,...arguments])}}function yq(e,t,n,r){return function(i){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ih?ih:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(t.serialize&&(r8(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),t.asObject||t.formatters?i.call(a,...wq(this,r,o,s,t)):i.apply(a,o),t.transmit){const u=t.transmit.level||e._level,d=Uc(u,n),h=Uc(r,n);if(h<d)return;bq(this,{ts:s,methodLevel:r,methodValue:h,transmitLevel:u,transmitValue:n.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:Uc(e._level,n)},o,l)}}}(e[t8][r])}function wq(e,t,n,r,i){const{level:s,log:o=d=>d}=i.formatters||{},a=n.slice();let c=a[0];const l={};let u=(e._childLevel|0)+1;if(u<1&&(u=1),r&&(l.time=r),s){const d=s(t,e.levels.values[t]);Object.assign(l,d)}else l.level=e.levels.values[t];if(i.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());return[o(l),...a]}else{if(c!==null&&typeof c=="object"){for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());c=a.length?D_(a.shift(),a):void 0}else typeof c=="string"&&(c=D_(a.shift(),a));return c!==void 0&&(l[i.messageKey]=c),[o(l)]}}function r8(e,t,n,r){for(const i in e)if(r&&e[i]instanceof Error)e[i]=Za.stdSerializers.err(e[i]);else if(typeof e[i]=="object"&&!Array.isArray(e[i])&&t)for(const s in e[i])t.indexOf(s)>-1&&s in n&&(e[i][s]=n[s](e[i][s]))}function bq(e,t,n,r=!1){const i=t.send,s=t.ts,o=t.methodLevel,a=t.methodValue,c=t.val,l=e._logEvent.bindings;r||r8(n,e._serialize||Object.keys(e.serializers),e.serializers,e._stdErrSerialize===void 0?!0:e._stdErrSerialize),e._logEvent.ts=s,e._logEvent.messages=n.filter(function(u){return l.indexOf(u)===-1}),e._logEvent.level.label=o,e._logEvent.level.value=a,i(o,e._logEvent,c),e._logEvent=i8(l)}function i8(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function L_(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const n in e)t[n]===void 0&&(t[n]=e[n]);return t}function vq(e){return typeof e.timestamp=="function"?e.timestamp:e.timestamp===!1?F_:H_}function Pg(){return{}}function s8(e){return e}function Gd(){}function F_(){return!1}function H_(){return Date.now()}function Eq(){return Math.round(Date.now()/1e3)}function Aq(){return new Date(Date.now()).toISOString()}function Cq(){function e(t){return typeof t<"u"&&t}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 e(self)||e(window)||e(this)||{}}}Xs.exports.default=Za,Xs.exports.pino=Za;const xq={level:"info"},Og="custom_context",o8=1e3*1024;var _q=Object.defineProperty,Sq=(e,t,n)=>t in e?_q(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Lc=(e,t,n)=>Sq(e,typeof t!="symbol"?t+"":t,n);class Iq{constructor(t){Lc(this,"nodeValue"),Lc(this,"sizeInBytes"),Lc(this,"next"),this.nodeValue=t,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class j_{constructor(t){Lc(this,"lengthInNodes"),Lc(this,"sizeInBytes"),Lc(this,"head"),Lc(this,"tail"),Lc(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=t,this.sizeInBytes=0}append(t){const n=new Iq(t);if(n.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${t} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.size}shift(){if(!this.head)return;const t=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=t.size}toArray(){const t=[];let n=this.head;for(;n!==null;)t.push(n.value),n=n.next;return t}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let t=this.head;return{next:()=>{if(!t)return{done:!0,value:null};const n=t.value;return t=t.next,{done:!1,value:n}}}}}const $q=e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString()+"n":n);function z_(e){return typeof e=="string"?e:$q(e)||""}var Tq=Object.defineProperty,Nq=(e,t,n)=>t in e?Tq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kg=(e,t,n)=>Nq(e,typeof t!="symbol"?t+"":t,n);class V_{constructor(t,n=o8){kg(this,"logs"),kg(this,"level"),kg(this,"levelValue"),kg(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=t??"error",this.levelValue=Xs.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new j_(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(t,n){n===Xs.exports.levels.values.error?console.error(t):n===Xs.exports.levels.values.warn?console.warn(t):n===Xs.exports.levels.values.debug?console.debug(t):n===Xs.exports.levels.values.trace?console.trace(t):console.log(t)}appendToLogs(t){this.logs.append(z_({timestamp:new Date().toISOString(),log:t}));const n=typeof t=="string"?JSON.parse(t).level:t.level;n>=this.levelValue&&this.forwardToConsole(t,n)}getLogs(){return this.logs}clearLogs(){this.logs=new j_(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(t){const n=this.getLogArray();return n.push(z_({extraMetadata:t})),new Blob(n,{type:"application/json"})}}var Pq=Object.defineProperty,Oq=(e,t,n)=>t in e?Pq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kq=(e,t,n)=>Oq(e,typeof t!="symbol"?t+"":t,n);class Rq{constructor(t,n=o8){kq(this,"baseChunkLogger"),this.baseChunkLogger=new V_(t,n)}write(t){this.baseChunkLogger.appendToLogs(t)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(t){return this.baseChunkLogger.logsToBlob(t)}downloadLogsBlobInBrowser(t){const n=URL.createObjectURL(this.logsToBlob(t)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}}var Bq=Object.defineProperty,Mq=(e,t,n)=>t in e?Bq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Dq=(e,t,n)=>Mq(e,typeof t!="symbol"?t+"":t,n);class Uq{constructor(t,n=o8){Dq(this,"baseChunkLogger"),this.baseChunkLogger=new V_(t,n)}write(t){this.baseChunkLogger.appendToLogs(t)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(t){return this.baseChunkLogger.logsToBlob(t)}}var Lq=Object.defineProperty,Fq=Object.defineProperties,Hq=Object.getOwnPropertyDescriptors,W_=Object.getOwnPropertySymbols,jq=Object.prototype.hasOwnProperty,zq=Object.prototype.propertyIsEnumerable,q_=(e,t,n)=>t in e?Lq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Fc=(e,t)=>{for(var n in t||(t={}))jq.call(t,n)&&q_(e,n,t[n]);if(W_)for(var n of W_(t))zq.call(t,n)&&q_(e,n,t[n]);return e},Hc=(e,t)=>Fq(e,Hq(t));function Z_(e){return Hc(Fc({},e),{level:e?.level||xq.level})}function Vq(e,t,n=Og){return e[n]=t,e}function Gr(e,t=Og){return e[t]||""}function Wq(e,t,n=Og){const r=Gr(e,n);return r.trim()?`${r}/${t}`:t}function vi(e,t,n=Og){const r=Wq(e,t,n),i=e.child({context:r});return Vq(i,r,n)}function qq(e){var t,n;const r=new Rq((t=e.opts)==null?void 0:t.level,e.maxSizeInBytes);return{logger:Xs.exports(Hc(Fc({},e.opts),{level:"trace",browser:Hc(Fc({},(n=e.opts)==null?void 0:n.browser),{write:i=>r.write(i)})})),chunkLoggerController:r}}function Zq(e){var t,n;const r=new Uq((t=e.opts)==null?void 0:t.level,e.maxSizeInBytes);return{logger:Xs.exports(Hc(Fc({},e.opts),{level:"trace",browser:Hc(Fc({},(n=e.opts)==null?void 0:n.browser),{write:i=>r.write(i)})}),r),chunkLoggerController:r}}function a8(e){var t;if(typeof e.loggerOverride<"u"&&typeof e.loggerOverride!="string")return{logger:e.loggerOverride,chunkLoggerController:null};const n=Hc(Fc({},e.opts),{level:typeof e.loggerOverride=="string"?e.loggerOverride:(t=e.opts)==null?void 0:t.level});return typeof window<"u"?qq(Hc(Fc({},e),{opts:n})):Zq(Hc(Fc({},e),{opts:n}))}var Gq=Object.defineProperty,Kq=Object.defineProperties,Yq=Object.getOwnPropertyDescriptors,G_=Object.getOwnPropertySymbols,Xq=Object.prototype.hasOwnProperty,Jq=Object.prototype.propertyIsEnumerable,K_=(e,t,n)=>t in e?Gq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Kd=(e,t)=>{for(var n in t||(t={}))Xq.call(t,n)&&K_(e,n,t[n]);if(G_)for(var n of G_(t))Jq.call(t,n)&&K_(e,n,t[n]);return e},sh=(e,t)=>Kq(e,Yq(t));const Qq=":";function Ga(e){const[t,n]=e.split(Qq);return{namespace:t,reference:n}}function Y_(e,t=[]){const n=[];return Object.keys(e).forEach(r=>{if(t.length&&!t.includes(r))return;const i=e[r];n.push(...i.accounts)}),n}function X_(e,t){return e.includes(":")?[e]:t.chains||[]}var eZ=Object.defineProperty,tZ=Object.defineProperties,nZ=Object.getOwnPropertyDescriptors,J_=Object.getOwnPropertySymbols,rZ=Object.prototype.hasOwnProperty,iZ=Object.prototype.propertyIsEnumerable,c8=(e,t,n)=>t in e?eZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Q_=(e,t)=>{for(var n in t||(t={}))rZ.call(t,n)&&c8(e,n,t[n]);if(J_)for(var n of J_(t))iZ.call(t,n)&&c8(e,n,t[n]);return e},sZ=(e,t)=>tZ(e,nZ(t)),e7=(e,t,n)=>c8(e,typeof t!="symbol"?t+"":t,n);const oZ="ReactNative",Ei={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},aZ="js";function Rg(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function jc(){return!Kl()&&!!l6()&&navigator.product===oZ}function cZ(){return jc()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function lZ(){return jc()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Yd(){return!Rg()&&!!l6()&&!!Kl()}function oh(){return jc()?Ei.reactNative:Rg()?Ei.node:Yd()?Ei.browser:Ei.unknown}function t7(){var e;try{return jc()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(e=global.Application)==null?void 0:e.applicationId:void 0}catch{return}}function uZ(e,t){const n=new URLSearchParams(e);return Object.entries(t).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!=null&&n.set(r,String(i))}),n.toString()}function dZ(e){var t,n;const r=n7();try{return e!=null&&e.url&&r.url&&new URL(e.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),e.url=r.url),(t=e?.icons)!=null&&t.length&&e.icons.length>0&&(e.icons=e.icons.filter(i=>i!=="")),sZ(Q_(Q_({},r),e),{url:e?.url||r.url,name:e?.name||r.name,description:e?.description||r.description,icons:(n=e?.icons)!=null&&n.length&&e.icons.length>0?e.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),e||r}}function n7(){return xA()||{name:"",description:"",url:"",icons:[""]}}function fZ(){if(oh()===Ei.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:n,Version:r}=global.Platform;return[n,r].join("-")}const e=hM();if(e===null)return"unknown";const t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return e.type==="browser"?[t,e.name,e.version].join("-"):[t,e.version].join("-")}function hZ(){var e;const t=oh();return t===Ei.browser?[t,((e=CA())==null?void 0:e.host)||"unknown"].join(":"):t}function r7(e,t,n){const r=fZ(),i=hZ();return[[e,t].join("-"),[aZ,n].join("-"),r,i].join("/")}function pZ({protocol:e,version:t,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=n.split("?"),u=r7(e,t,r),d={auth:i,ua:u,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=uZ(l[1]||"",d);return l[0]+"?"+h}function lu(e,t){return e.filter(n=>t.includes(n)).length===e.length}function l8(e){return Object.fromEntries(e.entries())}function u8(e){return new Map(Object.entries(e))}function uu(e=ve.FIVE_MINUTES,t){const n=ve.toMiliseconds(e||ve.FIVE_MINUTES);let r,i,s,o;return{resolve:a=>{s&&r&&(clearTimeout(s),r(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const l=new Error(t);o=Promise.reject(l),c(l)},n),r=a,i=c})}}function Js(e,t,n){return new Promise(async(r,i)=>{const s=setTimeout(()=>i(new Error(n)),t);try{const o=await e;r(o)}catch(o){i(o)}clearTimeout(s)})}function i7(e,t){if(typeof t=="string"&&t.startsWith(`${e}:`))return t;if(e.toLowerCase()==="topic"){if(typeof t!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}else if(e.toLowerCase()==="id"){if(typeof t!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function gZ(e){return i7("topic",e)}function mZ(e){return i7("id",e)}function s7(e){const[t,n]=e.split(":"),r={id:void 0,topic:void 0};if(t==="topic"&&typeof n=="string")r.topic=n;else if(t==="id"&&Number.isInteger(Number(n)))r.id=Number(n);else throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${n}`);return r}function mn(e,t){return ve.fromMiliseconds((t||Date.now())+ve.toMiliseconds(e))}function Qs(e){return Date.now()>=ve.toMiliseconds(e)}function Rt(e,t){return`${e}${t?`:${t}`:""}`}function eo(e=[],t=[]){return[...new Set([...e,...t])]}async function yZ({id:e,topic:t,wcDeepLink:n}){var r;try{if(!n)return;const i=typeof n=="string"?JSON.parse(n):n,s=i?.href;if(typeof s!="string")return;const o=wZ(s,e,t),a=oh();if(a===Ei.browser){if(!((r=Kl())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}bZ(o)}else a===Ei.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function wZ(e,t,n){const r=`requestId=${t}&sessionTopic=${n}`;e.endsWith("/")&&(e=e.slice(0,-1));let i=`${e}`;if(e.startsWith("https://t.me")){const s=e.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${CZ(r,!0)}`}else i=`${i}/wc?${r}`;return i}function bZ(e){let t="_self";AZ()?t="_top":(EZ()||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"),window.open(e,t,"noreferrer noopener")}async function vZ(e,t){let n="";try{if(Yd()&&(n=localStorage.getItem(t),n))return n;n=await e.getItem(t)}catch(r){console.error(r)}return n}function o7(e,t){if(!e.includes(t))return null;const n=e.split(/([&,?,=])/),r=n.indexOf(t);return n[r+2]}function a7(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function d8(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function EZ(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function AZ(){try{return window.self!==window.top}catch{return!1}}function CZ(e,t=!1){const n=Buffer.from(e).toString("base64");return t?n.replace(/[=]/g,""):n}function c7(e){return Buffer.from(e,"base64").toString("utf-8")}function xZ(e){return new Promise(t=>setTimeout(t,e))}class _Z{constructor({limit:t}){e7(this,"limit"),e7(this,"set"),this.limit=t,this.set=new Set}add(t){if(!this.set.has(t)){if(this.set.size>=this.limit){const n=this.set.values().next().value;n&&this.set.delete(n)}this.set.add(t)}}has(t){return this.set.has(t)}}const Bg=BigInt(2**32-1),l7=BigInt(32);function u7(e,t=!1){return t?{h:Number(e&Bg),l:Number(e>>l7&Bg)}:{h:Number(e>>l7&Bg)|0,l:Number(e&Bg)|0}}function d7(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=u7(e[s],t);[r[s],i[s]]=[o,a]}return[r,i]}const f7=(e,t,n)=>e>>>n,h7=(e,t,n)=>e<<32-n|t>>>n,zc=(e,t,n)=>e>>>n|t<<32-n,Vc=(e,t,n)=>e<<32-n|t>>>n,ah=(e,t,n)=>e<<64-n|t>>>n-32,ch=(e,t,n)=>e>>>n-32|t<<64-n,SZ=(e,t)=>t,IZ=(e,t)=>e,$Z=(e,t,n)=>e<<n|t>>>32-n,TZ=(e,t,n)=>t<<n|e>>>32-n,NZ=(e,t,n)=>t<<n-32|e>>>64-n,PZ=(e,t,n)=>e<<n-32|t>>>64-n;function ps(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}const f8=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),h8=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,OZ=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),kZ=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,RZ=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),BZ=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,Xd=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Mg(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ka(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function gs(e,...t){if(!Mg(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Dg(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ka(e.outputLen),Ka(e.blockLen)}function Wc(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function p8(e,t){gs(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function lh(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Li(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function g8(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function to(e,t){return e<<32-t|e>>>t}const p7=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function g7(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Ya=p7?e=>e:e=>g7(e);function MZ(e){for(let t=0;t<e.length;t++)e[t]=g7(e[t]);return e}const qc=p7?e=>e:MZ,m7=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",DZ=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Jd(e){if(gs(e),m7)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=DZ[e[n]];return t}const Xa={_0:48,_9:57,A:65,F:70,a:97,f:102};function y7(e){if(e>=Xa._0&&e<=Xa._9)return e-Xa._0;if(e>=Xa.A&&e<=Xa.F)return e-(Xa.A-10);if(e>=Xa.a&&e<=Xa.f)return e-(Xa.a-10)}function Ug(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(m7)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=y7(e.charCodeAt(s)),a=y7(e.charCodeAt(s+1));if(o===void 0||a===void 0){const c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function w7(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ms(e){return typeof e=="string"&&(e=w7(e)),gs(e),e}function Zc(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];gs(i),t+=i.length}const n=new Uint8Array(t);for(let r=0,i=0;r<e.length;r++){const s=e[r];n.set(s,i),i+=s.length}return n}class Lg{}function uh(e){const t=r=>e().update(ms(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function UZ(e){const t=(r,i)=>e(i).update(ms(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}function du(e=32){if(Xd&&typeof Xd.getRandomValues=="function")return Xd.getRandomValues(new Uint8Array(e));if(Xd&&typeof Xd.randomBytes=="function")return Uint8Array.from(Xd.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const LZ=BigInt(0),dh=BigInt(1),FZ=BigInt(2),HZ=BigInt(7),jZ=BigInt(256),zZ=BigInt(113),b7=[],v7=[],E7=[];for(let e=0,t=dh,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],b7.push(2*(5*r+n)),v7.push((e+1)*(e+2)/2%64);let i=LZ;for(let s=0;s<7;s++)t=(t<<dh^(t>>HZ)*zZ)%jZ,t&FZ&&(i^=dh<<(dh<<BigInt(s))-dh);E7.push(i)}const A7=d7(E7,!0),VZ=A7[0],WZ=A7[1],C7=(e,t,n)=>n>32?NZ(e,t,n):$Z(e,t,n),x7=(e,t,n)=>n>32?PZ(e,t,n):TZ(e,t,n);function qZ(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let o=0;o<10;o++)n[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=n[c],u=n[c+1],d=C7(l,u,1)^n[a],h=x7(l,u,1)^n[a+1];for(let f=0;f<50;f+=10)e[o+f]^=d,e[o+f+1]^=h}let i=e[2],s=e[3];for(let o=0;o<24;o++){const a=v7[o],c=C7(i,s,a),l=x7(i,s,a),u=b7[o];i=e[u],s=e[u+1],e[u]=c,e[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=e[o+a];for(let a=0;a<10;a++)e[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}e[0]^=VZ[r],e[1]^=WZ[r]}Li(n)}class m8 extends Lg{constructor(t,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,Ka(r),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=lh(this.state)}clone(){return this._cloneInto()}keccak(){qc(this.state32),qZ(this.state32,this.rounds),qc(this.state32),this.posOut=0,this.pos=0}update(t){Wc(this),t=ms(t),gs(t);const{blockLen:n,state:r}=this,i=t.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=t[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:n,pos:r,blockLen:i}=this;t[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){Wc(this,!1),gs(t),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=t.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);t.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Ka(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(p8(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Li(this.state)}_cloneInto(t){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return t||(t=new m8(n,r,i,o,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=r,t.outputLen=i,t.enableXOF=o,t.destroyed=this.destroyed,t}}const ZZ=(e,t,n)=>uh(()=>new m8(t,e,n)),GZ=ZZ(1,136,256/8);function KZ(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}function YZ(e,t,n){return e&t^~e&n}function XZ(e,t,n){return e&t^e&n^t&n}class _7 extends Lg{constructor(t,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=g8(this.buffer)}update(t){Wc(this),t=ms(t),gs(t);const{view:n,buffer:r,blockLen:i}=this,s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=g8(t);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Wc(this),p8(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Li(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let d=o;d<i;d++)n[d]=0;KZ(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=g8(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=a,i%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}}const Gc=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lr=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),ur=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),JZ=Uint32Array.from([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]),Kc=new Uint32Array(64);class QZ extends _7{constructor(t=32){super(64,t,8,!1),this.A=Gc[0]|0,this.B=Gc[1]|0,this.C=Gc[2]|0,this.D=Gc[3]|0,this.E=Gc[4]|0,this.F=Gc[5]|0,this.G=Gc[6]|0,this.H=Gc[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[t,n,r,i,s,o,a,c]}set(t,n,r,i,s,o,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,n){for(let d=0;d<16;d++,n+=4)Kc[d]=t.getUint32(n,!1);for(let d=16;d<64;d++){const h=Kc[d-15],f=Kc[d-2],p=to(h,7)^to(h,18)^h>>>3,g=to(f,17)^to(f,19)^f>>>10;Kc[d]=g+Kc[d-7]+p+Kc[d-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const h=to(a,6)^to(a,11)^to(a,25),f=u+h+YZ(a,c,l)+JZ[d]+Kc[d]|0,p=(to(r,2)^to(r,13)^to(r,22))+XZ(r,i,s)|0;u=l,l=c,c=a,a=o+f|0,o=s,s=i,i=r,r=f+p|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,i,s,o,a,c,l,u)}roundClean(){Li(Kc)}destroy(){this.set(0,0,0,0,0,0,0,0),Li(this.buffer)}}const S7=d7(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),eG=S7[0],tG=S7[1],Yc=new Uint32Array(80),Xc=new Uint32Array(80);class y8 extends _7{constructor(t=64){super(128,t,16,!1),this.Ah=ur[0]|0,this.Al=ur[1]|0,this.Bh=ur[2]|0,this.Bl=ur[3]|0,this.Ch=ur[4]|0,this.Cl=ur[5]|0,this.Dh=ur[6]|0,this.Dl=ur[7]|0,this.Eh=ur[8]|0,this.El=ur[9]|0,this.Fh=ur[10]|0,this.Fl=ur[11]|0,this.Gh=ur[12]|0,this.Gl=ur[13]|0,this.Hh=ur[14]|0,this.Hl=ur[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:h,Gh:f,Gl:p,Hh:g,Hl:y}=this;return[t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y]}set(t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=h|0,this.Gh=f|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}process(t,n){for(let v=0;v<16;v++,n+=4)Yc[v]=t.getUint32(n),Xc[v]=t.getUint32(n+=4);for(let v=16;v<80;v++){const w=Yc[v-15]|0,T=Xc[v-15]|0,O=zc(w,T,1)^zc(w,T,8)^f7(w,T,7),D=Vc(w,T,1)^Vc(w,T,8)^h7(w,T,7),F=Yc[v-2]|0,U=Xc[v-2]|0,j=zc(F,U,19)^ah(F,U,61)^f7(F,U,6),W=Vc(F,U,19)^ch(F,U,61)^h7(F,U,6),S=OZ(D,W,Xc[v-7],Xc[v-16]),x=kZ(S,O,j,Yc[v-7],Yc[v-16]);Yc[v]=x|0,Xc[v]=S|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:h,Fh:f,Fl:p,Gh:g,Gl:y,Hh:A,Hl:_}=this;for(let v=0;v<80;v++){const w=zc(d,h,14)^zc(d,h,18)^ah(d,h,41),T=Vc(d,h,14)^Vc(d,h,18)^ch(d,h,41),O=d&f^~d&g,D=h&p^~h&y,F=RZ(_,T,D,tG[v],Xc[v]),U=BZ(F,A,w,O,eG[v],Yc[v]),j=F|0,W=zc(r,i,28)^ah(r,i,34)^ah(r,i,39),S=Vc(r,i,28)^ch(r,i,34)^ch(r,i,39),x=r&s^r&a^s&a,I=i&o^i&c^o&c;A=g|0,_=y|0,g=f|0,y=p|0,f=d|0,p=h|0,{h:d,l:h}=ps(l|0,u|0,U|0,j|0),l=a|0,u=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const m=f8(j,S,I);r=h8(m,U,W,x),i=m|0}({h:r,l:i}=ps(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=ps(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=ps(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ps(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:h}=ps(this.Eh|0,this.El|0,d|0,h|0),{h:f,l:p}=ps(this.Fh|0,this.Fl|0,f|0,p|0),{h:g,l:y}=ps(this.Gh|0,this.Gl|0,g|0,y|0),{h:A,l:_}=ps(this.Hh|0,this.Hl|0,A|0,_|0),this.set(r,i,s,o,a,c,l,u,d,h,f,p,g,y,A,_)}roundClean(){Li(Yc,Xc)}destroy(){Li(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class nG extends y8{constructor(){super(48),this.Ah=lr[0]|0,this.Al=lr[1]|0,this.Bh=lr[2]|0,this.Bl=lr[3]|0,this.Ch=lr[4]|0,this.Cl=lr[5]|0,this.Dh=lr[6]|0,this.Dl=lr[7]|0,this.Eh=lr[8]|0,this.El=lr[9]|0,this.Fh=lr[10]|0,this.Fl=lr[11]|0,this.Gh=lr[12]|0,this.Gl=lr[13]|0,this.Hh=lr[14]|0,this.Hl=lr[15]|0}}const dr=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class rG extends y8{constructor(){super(32),this.Ah=dr[0]|0,this.Al=dr[1]|0,this.Bh=dr[2]|0,this.Bl=dr[3]|0,this.Ch=dr[4]|0,this.Cl=dr[5]|0,this.Dh=dr[6]|0,this.Dl=dr[7]|0,this.Eh=dr[8]|0,this.El=dr[9]|0,this.Fh=dr[10]|0,this.Fl=dr[11]|0,this.Gh=dr[12]|0,this.Gl=dr[13]|0,this.Hh=dr[14]|0,this.Hl=dr[15]|0}}const Fg=uh(()=>new QZ),iG=uh(()=>new y8),sG=uh(()=>new nG),oG=uh(()=>new rG),aG=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),In=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Se=new Uint32Array(32);function Jc(e,t,n,r,i,s){const o=i[s],a=i[s+1];let c=Se[2*e],l=Se[2*e+1],u=Se[2*t],d=Se[2*t+1],h=Se[2*n],f=Se[2*n+1],p=Se[2*r],g=Se[2*r+1],y=f8(c,u,o);l=h8(y,l,d,a),c=y|0,{Dh:g,Dl:p}={Dh:g^l,Dl:p^c},{Dh:g,Dl:p}={Dh:SZ(g,p),Dl:IZ(g)},{h:f,l:h}=ps(f,h,g,p),{Bh:d,Bl:u}={Bh:d^f,Bl:u^h},{Bh:d,Bl:u}={Bh:zc(d,u,24),Bl:Vc(d,u,24)},Se[2*e]=c,Se[2*e+1]=l,Se[2*t]=u,Se[2*t+1]=d,Se[2*n]=h,Se[2*n+1]=f,Se[2*r]=p,Se[2*r+1]=g}function Qc(e,t,n,r,i,s){const o=i[s],a=i[s+1];let c=Se[2*e],l=Se[2*e+1],u=Se[2*t],d=Se[2*t+1],h=Se[2*n],f=Se[2*n+1],p=Se[2*r],g=Se[2*r+1],y=f8(c,u,o);l=h8(y,l,d,a),c=y|0,{Dh:g,Dl:p}={Dh:g^l,Dl:p^c},{Dh:g,Dl:p}={Dh:zc(g,p,16),Dl:Vc(g,p,16)},{h:f,l:h}=ps(f,h,g,p),{Bh:d,Bl:u}={Bh:d^f,Bl:u^h},{Bh:d,Bl:u}={Bh:ah(d,u,63),Bl:ch(d,u,63)},Se[2*e]=c,Se[2*e+1]=l,Se[2*t]=u,Se[2*t+1]=d,Se[2*n]=h,Se[2*n+1]=f,Se[2*r]=p,Se[2*r+1]=g}function cG(e,t={},n,r,i){if(Ka(n),e<0||e>n)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=t;if(s!==void 0&&(s.length<1||s.length>n))throw new Error("key length must be undefined or 1.."+n);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==i)throw new Error("personalization must be undefined or "+i)}class lG extends Lg{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Ka(t),Ka(n),this.blockLen=t,this.outputLen=n,this.buffer=new Uint8Array(t),this.buffer32=lh(this.buffer)}update(t){Wc(this),t=ms(t),gs(t);const{blockLen:n,buffer:r,buffer32:i}=this,s=t.length,o=t.byteOffset,a=t.buffer;for(let c=0;c<s;){this.pos===n&&(qc(i),this.compress(i,0,!1),qc(i),this.pos=0);const l=Math.min(n-this.pos,s-c),u=o+c;if(l===n&&!(u%4)&&c+l<s){const d=new Uint32Array(a,u,Math.floor((s-c)/4));qc(d);for(let h=0;c+n<s;h+=i.length,c+=n)this.length+=n,this.compress(d,h,!1);qc(d);continue}r.set(t.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(t){Wc(this),p8(t,this);const{pos:n,buffer32:r}=this;this.finished=!0,Li(this.buffer.subarray(n)),qc(r),this.compress(r,0,!0),qc(r);const i=lh(t);this.get().forEach((s,o)=>i[o]=Ya(s))}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){const{buffer:n,length:r,finished:i,destroyed:s,outputLen:o,pos:a}=this;return t||(t=new this.constructor({dkLen:o})),t.set(...this.get()),t.buffer.set(n),t.destroyed=s,t.finished=i,t.length=r,t.pos=a,t.outputLen=o,t}clone(){return this._cloneInto()}}class uG extends lG{constructor(t={}){const n=t.dkLen===void 0?64:t.dkLen;super(128,n),this.v0l=In[0]|0,this.v0h=In[1]|0,this.v1l=In[2]|0,this.v1h=In[3]|0,this.v2l=In[4]|0,this.v2h=In[5]|0,this.v3l=In[6]|0,this.v3h=In[7]|0,this.v4l=In[8]|0,this.v4h=In[9]|0,this.v5l=In[10]|0,this.v5h=In[11]|0,this.v6l=In[12]|0,this.v6h=In[13]|0,this.v7l=In[14]|0,this.v7h=In[15]|0,cG(n,t,64,16,16);let{key:r,personalization:i,salt:s}=t,o=0;if(r!==void 0&&(r=ms(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=ms(s);const a=lh(s);this.v4l^=Ya(a[0]),this.v4h^=Ya(a[1]),this.v5l^=Ya(a[2]),this.v5h^=Ya(a[3])}if(i!==void 0){i=ms(i);const a=lh(i);this.v6l^=Ya(a[0]),this.v6h^=Ya(a[1]),this.v7l^=Ya(a[2]),this.v7h^=Ya(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:t,v0h:n,v1l:r,v1h:i,v2l:s,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:d,v5h:h,v6l:f,v6h:p,v7l:g,v7h:y}=this;return[t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y]}set(t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y){this.v0l=t|0,this.v0h=n|0,this.v1l=r|0,this.v1h=i|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|0,this.v5l=d|0,this.v5h=h|0,this.v6l=f|0,this.v6h=p|0,this.v7l=g|0,this.v7h=y|0}compress(t,n,r){this.get().forEach((c,l)=>Se[l]=c),Se.set(In,16);let{h:i,l:s}=u7(BigInt(this.length));Se[24]=In[8]^s,Se[25]=In[9]^i,r&&(Se[28]=~Se[28],Se[29]=~Se[29]);let o=0;const a=aG;for(let c=0;c<12;c++)Jc(0,4,8,12,t,n+2*a[o++]),Qc(0,4,8,12,t,n+2*a[o++]),Jc(1,5,9,13,t,n+2*a[o++]),Qc(1,5,9,13,t,n+2*a[o++]),Jc(2,6,10,14,t,n+2*a[o++]),Qc(2,6,10,14,t,n+2*a[o++]),Jc(3,7,11,15,t,n+2*a[o++]),Qc(3,7,11,15,t,n+2*a[o++]),Jc(0,5,10,15,t,n+2*a[o++]),Qc(0,5,10,15,t,n+2*a[o++]),Jc(1,6,11,12,t,n+2*a[o++]),Qc(1,6,11,12,t,n+2*a[o++]),Jc(2,7,8,13,t,n+2*a[o++]),Qc(2,7,8,13,t,n+2*a[o++]),Jc(3,4,9,14,t,n+2*a[o++]),Qc(3,4,9,14,t,n+2*a[o++]);this.v0l^=Se[0]^Se[16],this.v0h^=Se[1]^Se[17],this.v1l^=Se[2]^Se[18],this.v1h^=Se[3]^Se[19],this.v2l^=Se[4]^Se[20],this.v2h^=Se[5]^Se[21],this.v3l^=Se[6]^Se[22],this.v3h^=Se[7]^Se[23],this.v4l^=Se[8]^Se[24],this.v4h^=Se[9]^Se[25],this.v5l^=Se[10]^Se[26],this.v5h^=Se[11]^Se[27],this.v6l^=Se[12]^Se[28],this.v6h^=Se[13]^Se[29],this.v7l^=Se[14]^Se[30],this.v7h^=Se[15]^Se[31],Li(Se)}destroy(){this.destroyed=!0,Li(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const dG=UZ(e=>new uG(e)),fG="https://rpc.walletconnect.org/v1";function I7(e){const t=`Ethereum Signed Message:
|
|
20
|
-
${e.length}`,n=new TextEncoder().encode(t+e);return"0x"+Buffer.from(
|
|
21
|
-
- ${y}`).join("")}`:void 0,g=zg(e.resources);if(g){const y=fh(g);s=
|
|
22
|
-
`)};function kG(e){return Buffer.from(JSON.stringify(e)).toString("base64")}function RG(e){return JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}function fu(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");const t=Object.keys(e.att);if(!(t!=null&&t.length))throw new Error("No resources found in `att` property");t.forEach(n=>{const r=e.att[n];if(Array.isArray(r))throw new Error(`Resource must be an object: ${n}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${n}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${n}`);Object.keys(r).forEach(i=>{const s=r[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function BG(e,t,n,r={}){return n?.sort((i,s)=>i.localeCompare(s)),{att:{[e]:MG(t,n,r)}}}function MG(e,t,n={}){t=t?.sort((i,s)=>i.localeCompare(s));const r=t.map(i=>({[`${e}/${i}`]:[n]}));return Object.assign({},...r)}function B7(e){return fu(e),`urn:recap:${kG(e).replace(/=/g,"")}`}function fh(e){const t=RG(e.replace("urn:recap:",""));return fu(t),t}function DG(e,t,n){const r=BG(e,t,n);return B7(r)}function UG(e){return e&&e.includes("urn:recap:")}function LG(e,t){const n=fh(e),r=fh(t),i=FG(n,r);return B7(i)}function FG(e,t){fu(e),fu(t);const n=Object.keys(e.att).concat(Object.keys(t.att)).sort((i,s)=>i.localeCompare(s)),r={att:{}};return n.forEach(i=>{var s,o;Object.keys(((s=e.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=t.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;r.att[i]=$G(IG({},r.att[i]),{[a]:((c=e.att[i])==null?void 0:c[a])||((l=t.att[i])==null?void 0:l[a])})})}),r}function HG(e="",t){fu(t);const n="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(n))return e;const r=[];let i=0;Object.keys(t.att).forEach(a=>{const c=Object.keys(t.att[a]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));c.sort((d,h)=>d.action.localeCompare(h.action));const l={};c.forEach(d=>{l[d.ability]||(l[d.ability]=[]),l[d.ability].push(d.action)});const u=Object.keys(l).map(d=>(i++,`(${i}) '${d}': '${l[d].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const s=r.join(" "),o=`${n}${s}`;return`${e?e+" ":""}${o}`}function M7(e){var t;const n=fh(e);fu(n);const r=(t=n.att)==null?void 0:t.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function D7(e){const t=fh(e);fu(t);const n=[];return Object.values(t.att).forEach(r=>{Object.values(r).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&n.push(i[0].chains)})}),[...new Set(n.flat())]}function zg(e){if(!e)return;const t=e?.[e.length-1];return UG(t)?t:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function U7(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function v8(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function E8(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Kr(e,...t){if(!U7(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function L7(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function jG(e,t){Kr(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function el(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Qd(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function zG(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const VG=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function WG(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function A8(e){if(typeof e=="string")e=WG(e);else if(U7(e))e=C8(e);else throw new Error("Uint8Array expected, got "+typeof e);return e}function qG(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function ZG(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}const GG=(e,t)=>{function n(r,...i){if(Kr(r),!VG)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){const l=i[0];if(!l)throw new Error("nonce / iv required");e.varSizeNonce?Kr(l):Kr(l,e.nonceLength)}const s=e.tagLength;s&&i[1]!==void 0&&Kr(i[1]);const o=t(r,...i),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");Kr(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Kr(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(Kr(l),s&&l.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(n,e),n};function F7(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(n&&!YG(t))throw new Error("invalid output, must be aligned");return t}function H7(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}function KG(e,t,n){v8(n);const r=new Uint8Array(16),i=zG(r);return H7(i,0,BigInt(t),n),H7(i,8,BigInt(e),n),r}function YG(e){return e.byteOffset%4===0}function C8(e){return Uint8Array.from(e)}const j7=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),XG=j7("expand 16-byte k"),JG=j7("expand 32-byte k"),QG=el(XG),eK=el(JG);function Tt(e,t){return e<<t|e>>>32-t}function x8(e){return e.byteOffset%4===0}const Vg=64,tK=16,z7=2**32-1,V7=new Uint32Array;function nK(e,t,n,r,i,s,o,a){const c=i.length,l=new Uint8Array(Vg),u=el(l),d=x8(i)&&x8(s),h=d?el(i):V7,f=d?el(s):V7;for(let p=0;p<c;o++){if(e(t,n,r,u,o,a),o>=z7)throw new Error("arx: counter overflow");const g=Math.min(Vg,c-p);if(d&&g===Vg){const y=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let A=0,_;A<tK;A++)_=y+A,f[_]=h[_]^u[A];p+=Vg;continue}for(let y=0,A;y<g;y++)A=p+y,s[A]=i[A]^l[y];p+=g}}function rK(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=qG({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return E8(i),E8(o),v8(s),v8(n),(a,c,l,u,d=0)=>{Kr(a),Kr(c),Kr(l);const h=l.length;if(u===void 0&&(u=new Uint8Array(h)),Kr(u),E8(d),d<0||d>=z7)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);const f=[];let p=a.length,g,y;if(p===32)f.push(g=C8(a)),y=eK;else if(p===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),y=QG,f.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);x8(c)||f.push(c=C8(c));const A=el(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,A,el(c.subarray(0,16)),A),c=c.subarray(16)}const _=16-i;if(_!==c.length)throw new Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){const w=new Uint8Array(12);w.set(c,s?0:12-c.length),c=w,f.push(c)}const v=el(c);return nK(e,y,A,v,l,u,d,o),Qd(...f),u}}const Zn=(e,t)=>e[t++]&255|(e[t++]&255)<<8;class iK{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=A8(t),Kr(t,32);const n=Zn(t,0),r=Zn(t,2),i=Zn(t,4),s=Zn(t,6),o=Zn(t,8),a=Zn(t,10),c=Zn(t,12),l=Zn(t,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Zn(t,16+2*u)}process(t,n,r=!1){const i=r?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],h=o[5],f=o[6],p=o[7],g=o[8],y=o[9],A=Zn(t,n+0),_=Zn(t,n+2),v=Zn(t,n+4),w=Zn(t,n+6),T=Zn(t,n+8),O=Zn(t,n+10),D=Zn(t,n+12),F=Zn(t,n+14);let U=s[0]+(A&8191),j=s[1]+((A>>>13|_<<3)&8191),W=s[2]+((_>>>10|v<<6)&8191),S=s[3]+((v>>>7|w<<9)&8191),x=s[4]+((w>>>4|T<<12)&8191),I=s[5]+(T>>>1&8191),m=s[6]+((T>>>14|O<<2)&8191),b=s[7]+((O>>>11|D<<5)&8191),$=s[8]+((D>>>8|F<<8)&8191),N=s[9]+(F>>>5|i),P=0,B=P+U*a+j*(5*y)+W*(5*g)+S*(5*p)+x*(5*f);P=B>>>13,B&=8191,B+=I*(5*h)+m*(5*d)+b*(5*u)+$*(5*l)+N*(5*c),P+=B>>>13,B&=8191;let V=P+U*c+j*a+W*(5*y)+S*(5*g)+x*(5*p);P=V>>>13,V&=8191,V+=I*(5*f)+m*(5*h)+b*(5*d)+$*(5*u)+N*(5*l),P+=V>>>13,V&=8191;let Z=P+U*l+j*c+W*a+S*(5*y)+x*(5*g);P=Z>>>13,Z&=8191,Z+=I*(5*p)+m*(5*f)+b*(5*h)+$*(5*d)+N*(5*u),P+=Z>>>13,Z&=8191;let Y=P+U*u+j*l+W*c+S*a+x*(5*y);P=Y>>>13,Y&=8191,Y+=I*(5*g)+m*(5*p)+b*(5*f)+$*(5*h)+N*(5*d),P+=Y>>>13,Y&=8191;let X=P+U*d+j*u+W*l+S*c+x*a;P=X>>>13,X&=8191,X+=I*(5*y)+m*(5*g)+b*(5*p)+$*(5*f)+N*(5*h),P+=X>>>13,X&=8191;let G=P+U*h+j*d+W*u+S*l+x*c;P=G>>>13,G&=8191,G+=I*a+m*(5*y)+b*(5*g)+$*(5*p)+N*(5*f),P+=G>>>13,G&=8191;let ne=P+U*f+j*h+W*d+S*u+x*l;P=ne>>>13,ne&=8191,ne+=I*c+m*a+b*(5*y)+$*(5*g)+N*(5*p),P+=ne>>>13,ne&=8191;let se=P+U*p+j*f+W*h+S*d+x*u;P=se>>>13,se&=8191,se+=I*l+m*c+b*a+$*(5*y)+N*(5*g),P+=se>>>13,se&=8191;let we=P+U*g+j*p+W*f+S*h+x*d;P=we>>>13,we&=8191,we+=I*u+m*l+b*c+$*a+N*(5*y),P+=we>>>13,we&=8191;let ue=P+U*y+j*g+W*p+S*f+x*h;P=ue>>>13,ue&=8191,ue+=I*d+m*u+b*l+$*c+N*a,P+=ue>>>13,ue&=8191,P=(P<<2)+P|0,P=P+B|0,B=P&8191,P=P>>>13,V+=P,s[0]=B,s[1]=V,s[2]=Z,s[3]=Y,s[4]=X,s[5]=G,s[6]=ne,s[7]=se,s[8]=we,s[9]=ue}finalize(){const{h:t,pad:n}=this,r=new Uint16Array(10);let i=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=i,i=t[a]>>>13,t[a]&=8191;t[0]+=i*5,i=t[0]>>>13,t[0]&=8191,t[1]+=i,i=t[1]>>>13,t[1]&=8191,t[2]+=i,r[0]=t[0]+5,i=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=t[a]+i,i=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|r[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let o=t[0]+n[0];t[0]=o&65535;for(let a=1;a<8;a++)o=(t[a]+n[a]|0)+(o>>>16)|0,t[a]=o&65535;Qd(r)}update(t){L7(this),t=A8(t),Kr(t);const{buffer:n,blockLen:r}=this,i=t.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){for(;r<=i-s;s+=r)this.process(t,s);continue}n.set(t.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Qd(this.h,this.r,this.buffer,this.pad)}digestInto(t){L7(this),jG(t,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:i}=this;if(i){for(n[i++]=1;i<16;i++)n[i]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)t[s++]=r[o]>>>0,t[s++]=r[o]>>>8;return t}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}}function sK(e){const t=(r,i)=>e(i).update(A8(r)).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}const oK=sK(e=>new iK(e));function aK(e,t,n,r,i,s=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],d=t[1],h=t[2],f=t[3],p=t[4],g=t[5],y=t[6],A=t[7],_=i,v=n[0],w=n[1],T=n[2],O=o,D=a,F=c,U=l,j=u,W=d,S=h,x=f,I=p,m=g,b=y,$=A,N=_,P=v,B=w,V=T;for(let Y=0;Y<s;Y+=2)O=O+j|0,N=Tt(N^O,16),I=I+N|0,j=Tt(j^I,12),O=O+j|0,N=Tt(N^O,8),I=I+N|0,j=Tt(j^I,7),D=D+W|0,P=Tt(P^D,16),m=m+P|0,W=Tt(W^m,12),D=D+W|0,P=Tt(P^D,8),m=m+P|0,W=Tt(W^m,7),F=F+S|0,B=Tt(B^F,16),b=b+B|0,S=Tt(S^b,12),F=F+S|0,B=Tt(B^F,8),b=b+B|0,S=Tt(S^b,7),U=U+x|0,V=Tt(V^U,16),$=$+V|0,x=Tt(x^$,12),U=U+x|0,V=Tt(V^U,8),$=$+V|0,x=Tt(x^$,7),O=O+W|0,V=Tt(V^O,16),b=b+V|0,W=Tt(W^b,12),O=O+W|0,V=Tt(V^O,8),b=b+V|0,W=Tt(W^b,7),D=D+S|0,N=Tt(N^D,16),$=$+N|0,S=Tt(S^$,12),D=D+S|0,N=Tt(N^D,8),$=$+N|0,S=Tt(S^$,7),F=F+x|0,P=Tt(P^F,16),I=I+P|0,x=Tt(x^I,12),F=F+x|0,P=Tt(P^F,8),I=I+P|0,x=Tt(x^I,7),U=U+j|0,B=Tt(B^U,16),m=m+B|0,j=Tt(j^m,12),U=U+j|0,B=Tt(B^U,8),m=m+B|0,j=Tt(j^m,7);let Z=0;r[Z++]=o+O|0,r[Z++]=a+D|0,r[Z++]=c+F|0,r[Z++]=l+U|0,r[Z++]=u+j|0,r[Z++]=d+W|0,r[Z++]=h+S|0,r[Z++]=f+x|0,r[Z++]=p+I|0,r[Z++]=g+m|0,r[Z++]=y+b|0,r[Z++]=A+$|0,r[Z++]=_+N|0,r[Z++]=v+P|0,r[Z++]=w+B|0,r[Z++]=T+V|0}const cK=rK(aK,{counterRight:!1,counterLength:4,allowShortKeys:!1}),lK=new Uint8Array(16),W7=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(lK.subarray(n))},uK=new Uint8Array(32);function q7(e,t,n,r,i){const s=e(t,n,uK),o=oK.create(s);i&&W7(o,i),W7(o,r);const a=KG(r.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Qd(s,a),c}const dK=e=>(t,n,r)=>({encrypt(i,s){const o=i.length;s=F7(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);e(t,n,a,a,1);const c=q7(e,t,n,a,r);return s.set(c,o),Qd(c),s},decrypt(i,s){s=F7(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=q7(e,t,n,o,r);if(!ZG(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,n,s,s,1),Qd(c),s}}),Z7=GG({blockSize:64,nonceLength:12,tagLength:16},dK(cK));class G7 extends Lg{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Dg(t);const r=ms(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Li(s)}update(t){return Wc(this),this.iHash.update(t),this}digestInto(t){Wc(this),gs(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Wg=(e,t,n)=>new G7(e,t).update(n).digest();Wg.create=(e,t)=>new G7(e,t);function fK(e,t,n){return Dg(e),n===void 0&&(n=new Uint8Array(e.outputLen)),Wg(e,ms(n),ms(t))}const _8=Uint8Array.from([0]),K7=Uint8Array.of();function hK(e,t,n,r=32){Dg(e),Ka(r);const i=e.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/i);n===void 0&&(n=K7);const o=new Uint8Array(s*i),a=Wg.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)_8[0]=u+1,c.update(u===0?K7:l).update(n).update(_8).digestInto(l),o.set(l,i*u),a._cloneInto(c);return a.destroy(),c.destroy(),Li(l,_8),o.slice(0,r)}const pK=(e,t,n,r,i)=>hK(e,fK(e,t,n),r,i),qg=Fg,S8=BigInt(0),I8=BigInt(1);function Zg(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function hu(e,t,n=""){const r=Mg(e),i=e?.length,s=t!==void 0;if(!r||s&&i!==t){const o=n&&`"${n}" `,a=s?` of length ${t}`:"",c=r?`length=${i}`:`type=${typeof e}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return e}function Gg(e){const t=e.toString(16);return t.length&1?"0"+t:t}function Y7(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?S8:BigInt("0x"+e)}function Kg(e){return Y7(Jd(e))}function Yg(e){return gs(e),Y7(Jd(Uint8Array.from(e).reverse()))}function $8(e,t){return Ug(e.toString(16).padStart(t*2,"0"))}function T8(e,t){return $8(e,t).reverse()}function fr(e,t,n){let r;if(typeof t=="string")try{r=Ug(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(Mg(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}const N8=e=>typeof e=="bigint"&&S8<=e;function gK(e,t,n){return N8(e)&&N8(t)&&N8(n)&&t<=e&&e<n}function P8(e,t,n,r){if(!gK(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function X7(e){let t;for(t=0;e>S8;e>>=I8,t+=1);return t}const hh=e=>(I8<<BigInt(e))-I8;function mK(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),i=h=>Uint8Array.of(h);let s=r(e),o=r(e),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},l=(...h)=>n(o,s,...h),u=(h=r(0))=>{o=l(i(0),h),s=l(),h.length!==0&&(o=l(i(1),h),s=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<t;){s=l();const p=s.slice();f.push(p),h+=s.length}return Zc(...f)};return(h,f)=>{c(),u(h);let p;for(;!(p=f(d()));)u();return c(),p}}function Xg(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(i,s,o){const a=e[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function J7(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(i!==void 0)return i;const s=e(n,...r);return t.set(n,s),s}}const Yr=BigInt(0),$r=BigInt(1),pu=BigInt(2),Q7=BigInt(3),eS=BigInt(4),tS=BigInt(5),yK=BigInt(7),nS=BigInt(8),wK=BigInt(9),rS=BigInt(16);function Ai(e,t){const n=e%t;return n>=Yr?n:t+n}function ys(e,t,n){let r=e;for(;t-- >Yr;)r*=r,r%=n;return r}function iS(e,t){if(e===Yr)throw new Error("invert: expected non-zero number");if(t<=Yr)throw new Error("invert: expected positive modulus, got "+t);let n=Ai(e,t),r=t,i=Yr,s=$r;for(;n!==Yr;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==$r)throw new Error("invert: does not exist");return Ai(i,t)}function O8(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function sS(e,t){const n=(e.ORDER+$r)/eS,r=e.pow(t,n);return O8(e,r,t),r}function bK(e,t){const n=(e.ORDER-tS)/nS,r=e.mul(t,pu),i=e.pow(r,n),s=e.mul(t,i),o=e.mul(e.mul(s,pu),i),a=e.mul(s,e.sub(o,e.ONE));return O8(e,a,t),a}function vK(e){const t=tl(e),n=oS(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+yK)/rS;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,r);const d=a.mul(l,i),h=a.mul(l,s),f=a.eql(a.sqr(u),c),p=a.eql(a.sqr(d),c);l=a.cmov(l,u,f),u=a.cmov(h,d,p);const g=a.eql(a.sqr(u),c),y=a.cmov(l,u,g);return O8(a,y,c),y}}function oS(e){if(e<Q7)throw new Error("sqrt is not defined for small field");let t=e-$r,n=0;for(;t%pu===Yr;)t/=pu,n++;let r=pu;const i=tl(e);for(;cS(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return sS;let s=i.pow(r,t);const o=(t+$r)/pu;return function(a,c){if(a.is0(c))return c;if(cS(a,c)!==1)throw new Error("Cannot find square root");let l=n,u=a.mul(a.ONE,s),d=a.pow(c,t),h=a.pow(c,o);for(;!a.eql(d,a.ONE);){if(a.is0(d))return a.ZERO;let f=1,p=a.sqr(d);for(;!a.eql(p,a.ONE);)if(f++,p=a.sqr(p),f===l)throw new Error("Cannot find square root");const g=$r<<BigInt(l-f-1),y=a.pow(u,g);l=f,u=a.sqr(y),d=a.mul(d,u),h=a.mul(h,y)}return h}}function EK(e){return e%eS===Q7?sS:e%nS===tS?bK:e%rS===wK?vK(e):oS(e)}const AK=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function CK(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=AK.reduce((r,i)=>(r[i]="function",r),t);return Xg(e,n),e}function xK(e,t,n){if(n<Yr)throw new Error("invalid exponent, negatives unsupported");if(n===Yr)return e.ONE;if(n===$r)return t;let r=e.ONE,i=t;for(;n>Yr;)n&$r&&(r=e.mul(r,i)),i=e.sqr(i),n>>=$r;return r}function aS(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((o,a,c)=>e.is0(a)?o:(r[c]=o,e.mul(o,a)),e.ONE),s=e.inv(i);return t.reduceRight((o,a,c)=>e.is0(a)?o:(r[c]=e.mul(o,r[c]),e.mul(o,a)),s),r}function cS(e,t){const n=(e.ORDER-$r)/pu,r=e.pow(t,n),i=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function lS(e,t){t!==void 0&&Ka(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function tl(e,t,n=!1,r={}){if(e<=Yr)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s,o=!1,a;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const h=t;h.BITS&&(i=h.BITS),h.sqrt&&(s=h.sqrt),typeof h.isLE=="boolean"&&(n=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof t=="number"&&(i=t),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=lS(e,i);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:hh(c),ZERO:Yr,ONE:$r,allowedLengths:a,create:h=>Ai(h,e),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Yr<=h&&h<e},is0:h=>h===Yr,isValidNot0:h=>!d.is0(h)&&d.isValid(h),isOdd:h=>(h&$r)===$r,neg:h=>Ai(-h,e),eql:(h,f)=>h===f,sqr:h=>Ai(h*h,e),add:(h,f)=>Ai(h+f,e),sub:(h,f)=>Ai(h-f,e),mul:(h,f)=>Ai(h*f,e),pow:(h,f)=>xK(d,h,f),div:(h,f)=>Ai(h*iS(f,e),e),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>iS(h,e),sqrt:s||(h=>(u||(u=EK(e)),u(d,h))),toBytes:h=>n?T8(h,l):$8(h,l),fromBytes:(h,f=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(l);g.set(h,n?0:g.length-h.length),h=g}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let p=n?Yg(h):Kg(h);if(o&&(p=Ai(p,e)),!f&&!d.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>aS(d,h),cmov:(h,f,p)=>p?f:h});return Object.freeze(d)}function uS(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function dS(e){const t=uS(e);return t+Math.ceil(t/2)}function _K(e,t,n=!1){const r=e.length,i=uS(t),s=dS(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Yg(e):Kg(e),a=Ai(o,t-$r)+$r;return n?T8(a,i):$8(a,i)}const e0=BigInt(0),gu=BigInt(1);function Jg(e,t){const n=t.negate();return e?n:t}function k8(e,t){const n=aS(e.Fp,t.map(r=>r.Z));return t.map((r,i)=>e.fromAffine(r.toAffine(n[i])))}function fS(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function R8(e,t){fS(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e,s=hh(e),o=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function hS(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(e&i),c=e>>o;a>r&&(a-=s,c+=gu);const l=t*r,u=l+Math.abs(a)-1,d=a===0,h=a<0,f=t%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:l}}function SK(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function IK(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const B8=new WeakMap,pS=new WeakMap;function M8(e){return pS.get(e)||1}function gS(e){if(e!==e0)throw new Error("invalid wNAF")}class $K{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let i=t;for(;n>e0;)n&gu&&(r=r.add(i)),i=i.double(),n>>=gu;return r}precomputeWindow(t,n){const{windows:r,windowSize:i}=R8(n,this.bits),s=[];let o=t,a=o;for(let c=0;c<r;c++){a=o,s.push(a);for(let l=1;l<i;l++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=R8(t,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:h,offsetF:f}=hS(r,a,o);r=c,u?s=s.add(Jg(h,n[f])):i=i.add(Jg(d,n[l]))}return gS(r),{p:i,f:s}}wNAFUnsafe(t,n,r,i=this.ZERO){const s=R8(t,this.bits);for(let o=0;o<s.windows&&r!==e0;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=hS(r,o,s);if(r=a,!l){const d=n[c];i=i.add(u?d.negate():d)}}return gS(r),i}getPrecomputes(t,n,r){let i=B8.get(n);return i||(i=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(i=r(i)),B8.set(n,i))),i}cached(t,n,r){const i=M8(t);return this.wNAF(i,this.getPrecomputes(i,t,r),n)}unsafe(t,n,r,i){const s=M8(t);return s===1?this._unsafeLadder(t,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,i)}createCache(t,n){fS(n,this.bits),pS.set(t,n),B8.delete(t)}hasCache(t){return M8(t)!==1}}function TK(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>e0||r>e0;)n&gu&&(s=s.add(i)),r&gu&&(o=o.add(i)),i=i.double(),n>>=gu,r>>=gu;return{p1:s,p2:o}}function NK(e,t,n,r){SK(n,e),IK(r,t);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=X7(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=hh(c),u=new Array(Number(l)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c;let h=o;for(let f=d;f>=0;f-=c){u.fill(o);for(let g=0;g<s;g++){const y=r[g],A=Number(y>>BigInt(f)&l);u[A]=u[A].add(n[g])}let p=o;for(let g=u.length-1,y=o;g>0;g--)y=y.add(u[g]),p=p.add(y);if(h=h.add(p),f!==0)for(let g=0;g<c;g++)h=h.double()}return h}function mS(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return CK(t),t}else return tl(e,{isLE:n})}function PK(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const c=t[a];if(!(typeof c=="bigint"&&c>e0))throw new Error(`CURVE.${a} must be positive bigint`)}const i=mS(t.p,n.Fp,r),s=mS(t.n,n.Fn,r),o=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(const a of o)if(!i.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:s}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),w7("HashToScalar-");const ph=BigInt(0),t0=BigInt(1),Qg=BigInt(2);function OK(e){return Xg(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze(Kd({},e))}function kK(e){const t=OK(e),{P:n,type:r,adjustScalarBytes:i,powPminus2:s,randomBytes:o}=t,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||du,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),h=BigInt(a?121665:39081),f=a?Qg**BigInt(254):Qg**BigInt(447),p=a?BigInt(8)*Qg**BigInt(251)-t0:BigInt(4)*Qg**BigInt(445)-t0,g=f+p+t0,y=S=>Ai(S,n),A=_(d);function _(S){return T8(y(S),u)}function v(S){const x=fr("u coordinate",S,u);return a&&(x[31]&=127),y(Yg(x))}function w(S){return Yg(i(fr("scalar",S,u)))}function T(S,x){const I=F(v(x),w(S));if(I===ph)throw new Error("invalid private or public key received");return _(I)}function O(S){return T(S,A)}function D(S,x,I){const m=y(S*(x-I));return x=y(x-m),I=y(I+m),{x_2:x,x_3:I}}function F(S,x){P8("u",S,ph,n),P8("scalar",x,f,g);const I=x,m=S;let b=t0,$=ph,N=S,P=t0,B=ph;for(let Z=BigInt(l-1);Z>=ph;Z--){const Y=I>>Z&t0;B^=Y,{x_2:b,x_3:N}=D(B,b,N),{x_2:$,x_3:P}=D(B,$,P),B=Y;const X=b+$,G=y(X*X),ne=b-$,se=y(ne*ne),we=G-se,ue=N+P,ge=N-P,Be=y(ge*X),Fe=y(ue*ne),qe=Be+Fe,ct=Be-Fe;N=y(qe*qe),P=y(m*y(ct*ct)),b=y(G*se),$=y(we*(G+y(h*we)))}({x_2:b,x_3:N}=D(B,b,N)),{x_2:$,x_3:P}=D(B,$,P);const V=s($);return y(b*V)}const U={secretKey:u,publicKey:u,seed:u},j=(S=c(u))=>(gs(S,U.seed),S);function W(S){const x=j(S);return{secretKey:x,publicKey:O(x)}}return{keygen:W,getSharedSecret:(S,x)=>T(S,x),getPublicKey:S=>O(S),scalarMult:T,scalarMultBase:O,utils:{randomSecretKey:j,randomPrivateKey:j},GuBytes:A.slice(),lengths:U}}const RK=BigInt(1),yS=BigInt(2),BK=BigInt(3),MK=BigInt(5),DK=BigInt(8),wS=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),UK={p:wS,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:DK,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function LK(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=wS,o=e*e%s*e%s,a=ys(o,yS,s)*o%s,c=ys(a,RK,s)*e%s,l=ys(c,MK,s)*c%s,u=ys(l,t,s)*l%s,d=ys(u,n,s)*u%s,h=ys(d,r,s)*d%s,f=ys(h,i,s)*h%s,p=ys(f,i,s)*h%s,g=ys(p,t,s)*l%s;return{pow_p_5_8:ys(g,yS,s)*e%s,b2:o}}function FK(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const HK=tl(UK.p,{isLE:!0}),D8=(()=>{const e=HK.ORDER;return kK({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:n,b2:r}=LK(t);return Ai(ys(n,BK,e)*r,e)},adjustScalarBytes:FK})})(),bS=(e,t)=>(e+(e>=0?t:-t)/vS)/t;function jK(e,t,n){const[[r,i],[s,o]]=t,a=bS(o*e,n),c=bS(-i*e,n);let l=e-a*r-c*s,u=-a*i-c*o;const d=l<Qa,h=u<Qa;d&&(l=-l),h&&(u=-u);const f=hh(Math.ceil(X7(n)/2))+n0;if(l<Qa||l>=f||u<Qa||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}function U8(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function L8(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return Zg(n.lowS,"lowS"),Zg(n.prehash,"prehash"),n.format!==void 0&&U8(n.format),n}class zK extends Error{constructor(t=""){super(t)}}const Ja={Err:zK,_tlv:{encode:(e,t)=>{const{Err:n}=Ja;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const r=t.length/2,i=Gg(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Gg(i.length/2|128):"";return Gg(e)+s+i+t},decode(e,t){const{Err:n}=Ja;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const i=t[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=t.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+o)}}},_int:{encode(e){const{Err:t}=Ja;if(e<Qa)throw new t("integer: negative integers are not allowed");let n=Gg(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Ja;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Kg(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Ja,i=fr("signature",e),{v:s,l:o}=r.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=Ja,r=t.encode(2,n.encode(e.r)),i=t.encode(2,n.encode(e.s)),s=r+i;return t.encode(48,s)}},Qa=BigInt(0),n0=BigInt(1),vS=BigInt(2),em=BigInt(3),VK=BigInt(4);function r0(e,t){const{BYTES:n}=e;let r;if(typeof t=="bigint")r=t;else{let i=fr("private key",t);try{r=e.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function WK(e,t={}){const n=PK("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;Xg(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=AS(r,i);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(S,x,I){const{x:m,y:b}=x.toAffine(),$=r.toBytes(m);if(Zg(I,"isCompressed"),I){u();const N=!r.isOdd(b);return Zc(ES(N),$)}else return Zc(Uint8Array.of(4),$,r.toBytes(b))}function h(S){hu(S,void 0,"Point");const{publicKey:x,publicKeyUncompressed:I}=l,m=S.length,b=S[0],$=S.subarray(1);if(m===x&&(b===2||b===3)){const N=r.fromBytes($);if(!r.isValid(N))throw new Error("bad point: is not on curve, wrong x");const P=g(N);let B;try{B=r.sqrt(P)}catch(Z){const Y=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}u();const V=r.isOdd(B);return(b&1)===1!==V&&(B=r.neg(B)),{x:N,y:B}}else if(m===I&&b===4){const N=r.BYTES,P=r.fromBytes($.subarray(0,N)),B=r.fromBytes($.subarray(N,N*2));if(!y(P,B))throw new Error("bad point: is not on curve");return{x:P,y:B}}else throw new Error(`bad point: got length ${m}, expected compressed=${x} or uncompressed=${I}`)}const f=t.toBytes||d,p=t.fromBytes||h;function g(S){const x=r.sqr(S),I=r.mul(x,S);return r.add(r.add(I,r.mul(S,s.a)),s.b)}function y(S,x){const I=r.sqr(x),m=g(S);return r.eql(I,m)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const A=r.mul(r.pow(s.a,em),VK),_=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(A,_)))throw new Error("bad curve params: a or b");function v(S,x,I=!1){if(!r.isValid(x)||I&&r.is0(x))throw new Error(`bad point coordinate ${S}`);return x}function w(S){if(!(S instanceof U))throw new Error("ProjectivePoint expected")}function T(S){if(!c||!c.basises)throw new Error("no endo");return jK(S,c.basises,i.ORDER)}const O=J7((S,x)=>{const{X:I,Y:m,Z:b}=S;if(r.eql(b,r.ONE))return{x:I,y:m};const $=S.is0();x==null&&(x=$?r.ONE:r.inv(b));const N=r.mul(I,x),P=r.mul(m,x),B=r.mul(b,x);if($)return{x:r.ZERO,y:r.ZERO};if(!r.eql(B,r.ONE))throw new Error("invZ was invalid");return{x:N,y:P}}),D=J7(S=>{if(S.is0()){if(t.allowInfinityPoint&&!r.is0(S.Y))return;throw new Error("bad point: ZERO")}const{x,y:I}=S.toAffine();if(!r.isValid(x)||!r.isValid(I))throw new Error("bad point: x or y not field elements");if(!y(x,I))throw new Error("bad point: equation left != right");if(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function F(S,x,I,m,b){return I=new U(r.mul(I.X,S),I.Y,I.Z),x=Jg(m,x),I=Jg(b,I),x.add(I)}class U{constructor(x,I,m){this.X=v("x",x),this.Y=v("y",I,!0),this.Z=v("z",m),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){const{x:I,y:m}=x||{};if(!x||!r.isValid(I)||!r.isValid(m))throw new Error("invalid affine point");if(x instanceof U)throw new Error("projective point not allowed");return r.is0(I)&&r.is0(m)?U.ZERO:new U(I,m,r.ONE)}static fromBytes(x){const I=U.fromAffine(p(hu(x,void 0,"point")));return I.assertValidity(),I}static fromHex(x){return U.fromBytes(fr("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,I=!0){return W.createCache(this,x),I||this.multiply(em),this}assertValidity(){D(this)}hasEvenY(){const{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){w(x);const{X:I,Y:m,Z:b}=this,{X:$,Y:N,Z:P}=x,B=r.eql(r.mul(I,P),r.mul($,b)),V=r.eql(r.mul(m,P),r.mul(N,b));return B&&V}negate(){return new U(this.X,r.neg(this.Y),this.Z)}double(){const{a:x,b:I}=s,m=r.mul(I,em),{X:b,Y:$,Z:N}=this;let P=r.ZERO,B=r.ZERO,V=r.ZERO,Z=r.mul(b,b),Y=r.mul($,$),X=r.mul(N,N),G=r.mul(b,$);return G=r.add(G,G),V=r.mul(b,N),V=r.add(V,V),P=r.mul(x,V),B=r.mul(m,X),B=r.add(P,B),P=r.sub(Y,B),B=r.add(Y,B),B=r.mul(P,B),P=r.mul(G,P),V=r.mul(m,V),X=r.mul(x,X),G=r.sub(Z,X),G=r.mul(x,G),G=r.add(G,V),V=r.add(Z,Z),Z=r.add(V,Z),Z=r.add(Z,X),Z=r.mul(Z,G),B=r.add(B,Z),X=r.mul($,N),X=r.add(X,X),Z=r.mul(X,G),P=r.sub(P,Z),V=r.mul(X,Y),V=r.add(V,V),V=r.add(V,V),new U(P,B,V)}add(x){w(x);const{X:I,Y:m,Z:b}=this,{X:$,Y:N,Z:P}=x;let B=r.ZERO,V=r.ZERO,Z=r.ZERO;const Y=s.a,X=r.mul(s.b,em);let G=r.mul(I,$),ne=r.mul(m,N),se=r.mul(b,P),we=r.add(I,m),ue=r.add($,N);we=r.mul(we,ue),ue=r.add(G,ne),we=r.sub(we,ue),ue=r.add(I,b);let ge=r.add($,P);return ue=r.mul(ue,ge),ge=r.add(G,se),ue=r.sub(ue,ge),ge=r.add(m,b),B=r.add(N,P),ge=r.mul(ge,B),B=r.add(ne,se),ge=r.sub(ge,B),Z=r.mul(Y,ue),B=r.mul(X,se),Z=r.add(B,Z),B=r.sub(ne,Z),Z=r.add(ne,Z),V=r.mul(B,Z),ne=r.add(G,G),ne=r.add(ne,G),se=r.mul(Y,se),ue=r.mul(X,ue),ne=r.add(ne,se),se=r.sub(G,se),se=r.mul(Y,se),ue=r.add(ue,se),G=r.mul(ne,ue),V=r.add(V,G),G=r.mul(ge,ue),B=r.mul(we,B),B=r.sub(B,G),G=r.mul(we,ne),Z=r.mul(ge,Z),Z=r.add(Z,G),new U(B,V,Z)}subtract(x){return this.add(x.negate())}is0(){return this.equals(U.ZERO)}multiply(x){const{endo:I}=t;if(!i.isValidNot0(x))throw new Error("invalid scalar: out of range");let m,b;const $=N=>W.cached(this,N,P=>k8(U,P));if(I){const{k1neg:N,k1:P,k2neg:B,k2:V}=T(x),{p:Z,f:Y}=$(P),{p:X,f:G}=$(V);b=Y.add(G),m=F(I.beta,Z,X,N,B)}else{const{p:N,f:P}=$(x);m=N,b=P}return k8(U,[m,b])[0]}multiplyUnsafe(x){const{endo:I}=t,m=this;if(!i.isValid(x))throw new Error("invalid scalar: out of range");if(x===Qa||m.is0())return U.ZERO;if(x===n0)return m;if(W.hasCache(this))return this.multiply(x);if(I){const{k1neg:b,k1:$,k2neg:N,k2:P}=T(x),{p1:B,p2:V}=TK(U,m,$,P);return F(I.beta,B,V,b,N)}else return W.unsafe(m,x)}multiplyAndAddUnsafe(x,I,m){const b=this.multiplyUnsafe(I).add(x.multiplyUnsafe(m));return b.is0()?void 0:b}toAffine(x){return O(this,x)}isTorsionFree(){const{isTorsionFree:x}=t;return o===n0?!0:x?x(U,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:x}=t;return o===n0?this:x?x(U,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(x=!0){return Zg(x,"isCompressed"),this.assertValidity(),f(U,this,x)}toHex(x=!0){return Jd(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return k8(U,x)}static msm(x,I){return NK(U,i,x,I)}static fromPrivateKey(x){return U.BASE.multiply(r0(i,x))}}U.BASE=new U(s.Gx,s.Gy,r.ONE),U.ZERO=new U(r.ZERO,r.ONE,r.ZERO),U.Fp=r,U.Fn=i;const j=i.BITS,W=new $K(U,t.endo?Math.ceil(j/2):j);return U.BASE.precompute(8),U}function ES(e){return Uint8Array.of(e?2:3)}function AS(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function qK(e,t={}){const{Fn:n}=e,r=t.randomBytes||du,i=Object.assign(AS(e.Fp,n),{seed:dS(n.ORDER)});function s(h){try{return!!r0(n,h)}catch{return!1}}function o(h,f){const{publicKey:p,publicKeyUncompressed:g}=i;try{const y=h.length;return f===!0&&y!==p||f===!1&&y!==g?!1:!!e.fromBytes(h)}catch{return!1}}function a(h=r(i.seed)){return _K(hu(h,i.seed,"seed"),n.ORDER)}function c(h,f=!0){return e.BASE.multiply(r0(n,h)).toBytes(f)}function l(h){const f=a(h);return{secretKey:f,publicKey:c(f)}}function u(h){if(typeof h=="bigint")return!1;if(h instanceof e)return!0;const{secretKey:f,publicKey:p,publicKeyUncompressed:g}=i;if(n.allowedLengths||f===p)return;const y=fr("key",h).length;return y===p||y===g}function d(h,f,p=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(f)===!1)throw new Error("second arg must be public key");const g=r0(n,h);return e.fromHex(f).multiply(g).toBytes(p)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:l,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>r0(n,h),precompute(h=8,f=e.BASE){return f.precompute(h,!1)}},lengths:i})}function ZK(e,t,n={}){Dg(t),Xg(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||du,i=n.hmac||((I,...m)=>Wg(t,I,Zc(...m))),{Fp:s,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:f}=qK(e,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function y(I){const m=a>>n0;return I>m}function A(I,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return m}function _(I,m){U8(m);const b=f.signature,$=m==="compact"?b:m==="recovered"?b+1:void 0;return hu(I,$,`${m} signature`)}class v{constructor(m,b,$){this.r=A("r",m),this.s=A("s",b),$!=null&&(this.recovery=$),Object.freeze(this)}static fromBytes(m,b=g){_(m,b);let $;if(b==="der"){const{r:V,s:Z}=Ja.toSig(hu(m));return new v(V,Z)}b==="recovered"&&($=m[0],b="compact",m=m.subarray(1));const N=o.BYTES,P=m.subarray(0,N),B=m.subarray(N,N*2);return new v(o.fromBytes(P),o.fromBytes(B),$)}static fromHex(m,b){return this.fromBytes(Ug(m),b)}addRecoveryBit(m){return new v(this.r,this.s,m)}recoverPublicKey(m){const b=s.ORDER,{r:$,s:N,recovery:P}=this;if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");if(a*vS<b&&P>1)throw new Error("recovery id is ambiguous for h>1 curve");const B=P===2||P===3?$+a:$;if(!s.isValid(B))throw new Error("recovery id 2 or 3 invalid");const V=s.toBytes(B),Z=e.fromBytes(Zc(ES((P&1)===0),V)),Y=o.inv(B),X=T(fr("msgHash",m)),G=o.create(-X*Y),ne=o.create(N*Y),se=e.BASE.multiplyUnsafe(G).add(Z.multiplyUnsafe(ne));if(se.is0())throw new Error("point at infinify");return se.assertValidity(),se}hasHighS(){return y(this.s)}toBytes(m=g){if(U8(m),m==="der")return Ug(Ja.hexFromSig(this));const b=o.toBytes(this.r),$=o.toBytes(this.s);if(m==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Zc(Uint8Array.of(this.recovery),b,$)}return Zc(b,$)}toHex(m){return Jd(this.toBytes(m))}assertValidity(){}static fromCompact(m){return v.fromBytes(fr("sig",m),"compact")}static fromDER(m){return v.fromBytes(fr("sig",m),"der")}normalizeS(){return this.hasHighS()?new v(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Jd(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Jd(this.toBytes("compact"))}}const w=n.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const m=Kg(I),b=I.length*8-c;return b>0?m>>BigInt(b):m},T=n.bits2int_modN||function(I){return o.create(w(I))},O=hh(c);function D(I){return P8("num < 2^"+c,I,Qa,O),o.toBytes(I)}function F(I,m){return hu(I,void 0,"message"),m?hu(t(I),void 0,"prehashed message"):I}function U(I,m,b){if(["recovered","canonical"].some(ne=>ne in b))throw new Error("sign() legacy options not supported");const{lowS:$,prehash:N,extraEntropy:P}=L8(b,p);I=F(I,N);const B=T(I),V=r0(o,m),Z=[D(V),D(B)];if(P!=null&&P!==!1){const ne=P===!0?r(f.secretKey):P;Z.push(fr("extraEntropy",ne))}const Y=Zc(...Z),X=B;function G(ne){const se=w(ne);if(!o.isValidNot0(se))return;const we=o.inv(se),ue=e.BASE.multiply(se).toAffine(),ge=o.create(ue.x);if(ge===Qa)return;const Be=o.create(we*o.create(X+ge*V));if(Be===Qa)return;let Fe=(ue.x===ge?0:2)|Number(ue.y&n0),qe=Be;return $&&y(Be)&&(qe=o.neg(Be),Fe^=1),new v(ge,qe,Fe)}return{seed:Y,k2sig:G}}function j(I,m,b={}){I=fr("message",I);const{seed:$,k2sig:N}=U(I,m,b);return mK(t.outputLen,o.BYTES,i)($,N)}function W(I){let m;const b=typeof I=="string"||Mg(I),$=!b&&I!==null&&typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint";if(!b&&!$)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if($)m=new v(I.r,I.s);else if(b){try{m=v.fromBytes(fr("sig",I),"der")}catch(N){if(!(N instanceof Ja.Err))throw N}if(!m)try{m=v.fromBytes(fr("sig",I),"compact")}catch{return!1}}return m||!1}function S(I,m,b,$={}){const{lowS:N,prehash:P,format:B}=L8($,p);if(b=fr("publicKey",b),m=F(fr("message",m),P),"strict"in $)throw new Error("options.strict was renamed to lowS");const V=B===void 0?W(I):v.fromBytes(fr("sig",I),B);if(V===!1)return!1;try{const Z=e.fromBytes(b);if(N&&V.hasHighS())return!1;const{r:Y,s:X}=V,G=T(m),ne=o.inv(X),se=o.create(G*ne),we=o.create(Y*ne),ue=e.BASE.multiplyUnsafe(se).add(Z.multiplyUnsafe(we));return ue.is0()?!1:o.create(ue.x)===Y}catch{return!1}}function x(I,m,b={}){const{prehash:$}=L8(b,p);return m=F(m,$),v.fromBytes(I,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:f,Point:e,sign:j,verify:S,recoverPublicKey:x,Signature:v,hash:t})}function GK(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=tl(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function KK(e){const{CURVE:t,curveOpts:n}=GK(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function YK(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,lS(n.Fn.ORDER,n.Fn.BITS))})}function XK(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=KK(e),s=WK(t,n),o=ZK(s,r,i);return YK(e,o)}function F8(e,t){const n=r=>XK(sh(Kd({},e),{hash:r}));return sh(Kd({},n(t)),{create:n})}const CS={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},xS={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},_S={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},JK=tl(CS.p),QK=tl(xS.p),eY=tl(_S.p),tY=F8(sh(Kd({},CS),{Fp:JK,lowS:!1}),Fg);F8(sh(Kd({},xS),{Fp:QK,lowS:!1}),sG),F8(sh(Kd({},_S),{Fp:eY,lowS:!1,allowedPrivateKeyLengths:[130,131,132]}),iG);const nY=tY,SS="base10",Tr="base16",Xr="base64pad",nl="base64url",gh="utf8",IS=0,ec=1,mh=2,rY=0,$S=1,yh=12,H8=32;function iY(){const e=D8.utils.randomPrivateKey(),t=D8.getPublicKey(e);return{privateKey:Zr(e,Tr),publicKey:Zr(t,Tr)}}function j8(){const e=du(H8);return Zr(e,Tr)}function sY(e,t){const n=D8.getSharedSecret(Ui(e,Tr),Ui(t,Tr)),r=pK(qg,n,void 0,void 0,H8);return Zr(r,Tr)}function tm(e){const t=qg(Ui(e,Tr));return Zr(t,Tr)}function Fi(e){const t=qg(Ui(e,gh));return Zr(t,Tr)}function TS(e){return Ui(`${e}`,SS)}function mu(e){return Number(Zr(e,SS))}function NS(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function PS(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4;return t+"=".repeat(n)}function oY(e){const t=TS(typeof e.type<"u"?e.type:IS);if(mu(t)===ec&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof e.senderPublicKey<"u"?Ui(e.senderPublicKey,Tr):void 0,r=typeof e.iv<"u"?Ui(e.iv,Tr):du(yh),i=Ui(e.symKey,Tr),s=Z7(i,r).encrypt(Ui(e.message,gh)),o=OS({type:t,sealed:s,iv:r,senderPublicKey:n});return e.encoding===nl?NS(o):o}function aY(e){const t=Ui(e.symKey,Tr),{sealed:n,iv:r}=wh({encoded:e.encoded,encoding:e.encoding}),i=Z7(t,r).decrypt(n);if(i===null)throw new Error("Failed to decrypt");return Zr(i,gh)}function cY(e,t){const n=TS(mh),r=du(yh),i=Ui(e,gh),s=OS({type:n,sealed:i,iv:r});return t===nl?NS(s):s}function lY(e,t){const{sealed:n}=wh({encoded:e,encoding:t});return Zr(n,gh)}function OS(e){if(mu(e.type)===mh)return Zr(Qf([e.type,e.sealed]),Xr);if(mu(e.type)===ec){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Zr(Qf([e.type,e.senderPublicKey,e.iv,e.sealed]),Xr)}return Zr(Qf([e.type,e.iv,e.sealed]),Xr)}function wh(e){const t=(e.encoding||Xr)===nl?PS(e.encoded):e.encoded,n=Ui(t,Xr),r=n.slice(rY,$S),i=$S;if(mu(r)===ec){const c=i+H8,l=c+yh,u=n.slice(i,c),d=n.slice(c,l),h=n.slice(l);return{type:r,sealed:h,iv:d,senderPublicKey:u}}if(mu(r)===mh){const c=n.slice(i),l=du(yh);return{type:r,sealed:c,iv:l}}const s=i+yh,o=n.slice(i,s),a=n.slice(s);return{type:r,sealed:a,iv:o}}function uY(e,t){const n=wh({encoded:e,encoding:t?.encoding});return kS({type:mu(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?Zr(n.senderPublicKey,Tr):void 0,receiverPublicKey:t?.receiverPublicKey})}function kS(e){const t=e?.type||IS;if(t===ec){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function RS(e){return e.type===ec&&typeof e.senderPublicKey=="string"&&typeof e.receiverPublicKey=="string"}function BS(e){return e.type===mh}function dY(e){const t=Buffer.from(e.x,"base64"),n=Buffer.from(e.y,"base64");return Qf([new Uint8Array([4]),t,n])}function fY(e,t){const[n,r,i]=e.split("."),s=Buffer.from(PS(i),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${n}.${r}`,l=qg(c),u=dY(t);if(!nY.verify(Qf([o,a]),l,u))throw new Error("Invalid signature");return Gb(e).payload}const hY="irn";function nm(e){return e?.relay||{protocol:hY}}function i0(e){const t=ZW[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}var pY=Object.defineProperty,gY=Object.defineProperties,mY=Object.getOwnPropertyDescriptors,MS=Object.getOwnPropertySymbols,yY=Object.prototype.hasOwnProperty,wY=Object.prototype.propertyIsEnumerable,DS=(e,t,n)=>t in e?pY(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,z8=(e,t)=>{for(var n in t||(t={}))yY.call(t,n)&&DS(e,n,t[n]);if(MS)for(var n of MS(t))wY.call(t,n)&&DS(e,n,t[n]);return e},bY=(e,t)=>gY(e,mY(t));function vY(e,t="-"){const n={},r="relay"+t;return Object.keys(e).forEach(i=>{if(i.startsWith(r)){const s=i.replace(r,""),o=e[i];n[s]=o}}),n}function US(e){if(!e.includes("wc:")){const l=c7(e);l!=null&&l.includes("wc:")&&(e=l)}e=e.includes("wc://")?e.replace("wc://",""):e,e=e.includes("wc:")?e.replace("wc:",""):e;const t=e.indexOf(":"),n=e.indexOf("?")!==-1?e.indexOf("?"):void 0,r=e.substring(0,t),i=e.substring(t+1,n).split("@"),s=typeof n<"u"?e.substring(n):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:EY(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:vY(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function EY(e){return e.startsWith("//")?e.substring(2):e}function AY(e,t="-"){const n="relay",r={};return Object.keys(e).forEach(i=>{const s=i,o=n+t+s;e[s]&&(r[o]=e[s])}),r}function LS(e){const t=new URLSearchParams,n=z8(z8(bY(z8({},AY(e.relay)),{symKey:e.symKey}),e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()}),e.methods&&{methods:e.methods.join(",")});return Object.entries(n).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!==void 0&&t.append(r,String(i))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function rm(e,t,n){return`${e}?wc_ev=${n}&topic=${t}`}var CY=Object.defineProperty,xY=Object.defineProperties,_Y=Object.getOwnPropertyDescriptors,FS=Object.getOwnPropertySymbols,SY=Object.prototype.hasOwnProperty,IY=Object.prototype.propertyIsEnumerable,HS=(e,t,n)=>t in e?CY(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$Y=(e,t)=>{for(var n in t||(t={}))SY.call(t,n)&&HS(e,n,t[n]);if(FS)for(var n of FS(t))IY.call(t,n)&&HS(e,n,t[n]);return e},TY=(e,t)=>xY(e,_Y(t));function s0(e){const t=[];return e.forEach(n=>{const[r,i]=n.split(":");t.push(`${r}:${i}`)}),t}function jS(e){const t=[];return Object.values(e).forEach(n=>{t.push(...s0(n.accounts))}),[...new Set(t)]}function NY(e){const t=[];return Object.values(e).forEach(n=>{t.push(...n.methods)}),[...new Set(t)]}function PY(e){const t=[];return Object.values(e).forEach(n=>{t.push(...n.events)}),[...new Set(t)]}function OY(e,t){const n=[];return Object.values(e).forEach(r=>{s0(r.accounts).includes(t)&&n.push(...r.methods)}),n}function kY(e,t){const n=[];return Object.values(e).forEach(r=>{s0(r.accounts).includes(t)&&n.push(...r.events)}),n}function im(e){return e.includes(":")}function o0(e){return im(e)?e.split(":")[0]:e}function zS(e){var t,n,r;const i={};if(!no(e))return i;for(const[s,o]of Object.entries(e)){const a=im(s)?[s]:o.chains,c=o.methods||[],l=o.events||[],u=o0(s);i[u]=TY($Y({},i[u]),{chains:eo(a,(t=i[u])==null?void 0:t.chains),methods:eo(c,(n=i[u])==null?void 0:n.methods),events:eo(l,(r=i[u])==null?void 0:r.events)})}return i}function RY(e){const t={};return e?.forEach(n=>{var r;const[i,s]=n.split(":");t[i]||(t[i]={accounts:[],chains:[],events:[],methods:[]}),t[i].accounts.push(n),(r=t[i].chains)==null||r.push(`${i}:${s}`)}),t}function VS(e,t){t=t.map(r=>r.replace("did:pkh:",""));const n=RY(t);for(const[r,i]of Object.entries(n))i.methods?i.methods=eo(i.methods,e):i.methods=e,i.events=["chainChanged","accountsChanged"];return n}function BY(e,t){var n,r,i,s,o,a;const c=zS(e),l=zS(t),u={},d=Object.keys(c).concat(Object.keys(l));for(const h of d)u[h]={chains:eo((n=c[h])==null?void 0:n.chains,(r=l[h])==null?void 0:r.chains),methods:eo((i=c[h])==null?void 0:i.methods,(s=l[h])==null?void 0:s.methods),events:eo((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return u}const MY={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}},DY={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 Ae(e,t){const{message:n,code:r}=DY[e];return{message:t?`${n} ${t}`:n,code:r}}function Gt(e,t){const{message:n,code:r}=MY[e];return{message:t?`${n} ${t}`:n,code:r}}function Hi(e,t){return Array.isArray(e)?typeof t<"u"&&e.length?e.every(t):!0:!1}function no(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function $n(e){return typeof e>"u"}function yn(e,t){return t&&$n(e)?!0:typeof e=="string"&&!!e.trim().length}function V8(e,t){return t&&$n(e)?!0:typeof e=="number"&&!isNaN(e)}function UY(e,t){const{requiredNamespaces:n}=t,r=Object.keys(e.namespaces),i=Object.keys(n);let s=!0;return lu(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:l}=e.namespaces[o],u=s0(a),d=n[o];(!lu(X_(o,d),u)||!lu(d.methods,c)||!lu(d.events,l))&&(s=!1)}),s):!1}function sm(e){return yn(e,!1)&&e.includes(":")?e.split(":").length===2:!1}function LY(e){if(yn(e,!1)&&e.includes(":")){const t=e.split(":");if(t.length===3){const n=t[0]+":"+t[1];return!!t[2]&&sm(n)}}return!1}function FY(e){function t(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(yn(e,!1)){if(t(e))return!0;const n=c7(e);return t(n)}}catch{}return!1}function HY(e){var t;return(t=e?.proposer)==null?void 0:t.publicKey}function jY(e){return e?.topic}function zY(e,t){let n=null;return yn(e?.publicKey,!1)||(n=Ae("MISSING_OR_INVALID",`${t} controller public key should be a string`)),n}function WS(e){let t=!0;return Hi(e)?e.length&&(t=e.every(n=>yn(n,!1))):t=!1,t}function VY(e,t,n){let r=null;return Hi(t)&&t.length?t.forEach(i=>{r||sm(i)||(r=Gt("UNSUPPORTED_CHAINS",`${n}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):sm(e)||(r=Gt("UNSUPPORTED_CHAINS",`${n}, 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"] }`)),r}function WY(e,t,n){let r=null;return Object.entries(e).forEach(([i,s])=>{if(r)return;const o=VY(i,X_(i,s),`${t} ${n}`);o&&(r=o)}),r}function qY(e,t){let n=null;return Hi(e)?e.forEach(r=>{n||LY(r)||(n=Gt("UNSUPPORTED_ACCOUNTS",`${t}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=Gt("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function ZY(e,t){let n=null;return Object.values(e).forEach(r=>{if(n)return;const i=qY(r?.accounts,`${t} namespace`);i&&(n=i)}),n}function GY(e,t){let n=null;return WS(e?.methods)?WS(e?.events)||(n=Gt("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):n=Gt("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),n}function qS(e,t){let n=null;return Object.values(e).forEach(r=>{if(n)return;const i=GY(r,`${t}, namespace`);i&&(n=i)}),n}function KY(e,t,n){let r=null;if(e&&no(e)){const i=qS(e,t);i&&(r=i);const s=WY(e,t,n);s&&(r=s)}else r=Ae("MISSING_OR_INVALID",`${t}, ${n} should be an object with data`);return r}function W8(e,t){let n=null;if(e&&no(e)){const r=qS(e,t);r&&(n=r);const i=ZY(e,t);i&&(n=i)}else n=Ae("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return n}function ZS(e){return yn(e.protocol,!0)}function YY(e,t){let n=!1;return t&&!e?n=!0:e&&Hi(e)&&e.length&&e.forEach(r=>{n=ZS(r)}),n}function XY(e){return typeof e=="number"}function Jr(e){return typeof e<"u"&&typeof e!==null}function JY(e){return!(!e||typeof e!="object"||!e.code||!V8(e.code,!1)||!e.message||!yn(e.message,!1))}function QY(e){return!($n(e)||!yn(e.method,!1))}function eX(e){return!($n(e)||$n(e.result)&&$n(e.error)||!V8(e.id,!1)||!yn(e.jsonrpc,!1))}function tX(e){return!($n(e)||!yn(e.name,!1))}function GS(e,t){return!(!sm(t)||!jS(e).includes(t))}function nX(e,t,n){return yn(n,!1)?OY(e,t).includes(n):!1}function rX(e,t,n){return yn(n,!1)?kY(e,t).includes(n):!1}function KS(e,t,n){let r=null;const i=iX(e),s=sX(t),o=Object.keys(i),a=Object.keys(s),c=YS(Object.keys(e)),l=YS(Object.keys(t)),u=c.filter(d=>!l.includes(d));return u.length&&(r=Ae("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
|
|
19
|
+
`+new Array(e.length+4).join(" "):i<t.length-2&&(r+=" ")}console.log(r)}function JW(e,t,n){let r=new Date().getTime();const i=new Uint8Array(t);for(let o=0;o<t;o++)i[o]=o%256;const s=new Date().getTime();console.log("Generated random input in "+(s-r)+"ms"),r=s;for(let o=0;o<n;o++){const a=e(i),c=new Date().getTime(),l=c-r;r=c,console.log("Hashed in "+l+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(t/(1<<20)/(l/1e3)*100)/100+" MB PER SECOND")}}var C_={normalizeInput:KW,toHex:YW,debugPrint:XW,testSpeed:JW};const $g=C_;function Tg(e,t,n){const r=e[t]+e[n];let i=e[t+1]+e[n+1];r>=4294967296&&i++,e[t]=r,e[t+1]=i}function x_(e,t,n,r){let i=e[t]+n;n<0&&(i+=4294967296);let s=e[t+1]+r;i>=4294967296&&s++,e[t]=i,e[t+1]=s}function __(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function Bc(e,t,n,r,i,s){const o=th[i],a=th[i+1],c=th[s],l=th[s+1];Tg(st,e,t),x_(st,e,o,a);let u=st[r]^st[e],d=st[r+1]^st[e+1];st[r]=d,st[r+1]=u,Tg(st,n,r),u=st[t]^st[n],d=st[t+1]^st[n+1],st[t]=u>>>24^d<<8,st[t+1]=d>>>24^u<<8,Tg(st,e,t),x_(st,e,c,l),u=st[r]^st[e],d=st[r+1]^st[e+1],st[r]=u>>>16^d<<16,st[r+1]=d>>>16^u<<16,Tg(st,n,r),u=st[t]^st[n],d=st[t+1]^st[n+1],st[t]=d>>>31^u<<1,st[t+1]=u>>>31^d<<1}const S_=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),QW=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],ar=new Uint8Array(QW.map(function(e){return e*2})),st=new Uint32Array(32),th=new Uint32Array(32);function I_(e,t){let n=0;for(n=0;n<16;n++)st[n]=e.h[n],st[n+16]=S_[n];for(st[24]=st[24]^e.t,st[25]=st[25]^e.t/4294967296,t&&(st[28]=~st[28],st[29]=~st[29]),n=0;n<32;n++)th[n]=__(e.b,4*n);for(n=0;n<12;n++)Bc(0,8,16,24,ar[n*16+0],ar[n*16+1]),Bc(2,10,18,26,ar[n*16+2],ar[n*16+3]),Bc(4,12,20,28,ar[n*16+4],ar[n*16+5]),Bc(6,14,22,30,ar[n*16+6],ar[n*16+7]),Bc(0,10,20,30,ar[n*16+8],ar[n*16+9]),Bc(2,12,22,24,ar[n*16+10],ar[n*16+11]),Bc(4,14,16,26,ar[n*16+12],ar[n*16+13]),Bc(6,8,18,28,ar[n*16+14],ar[n*16+15]);for(n=0;n<16;n++)e.h[n]=e.h[n]^st[n]^st[n+16]}const Mc=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function $_(e,t,n,r){if(e===0||e>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(t&&t.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(n&&n.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:e};Mc.fill(0),Mc[0]=e,t&&(Mc[1]=t.length),Mc[2]=1,Mc[3]=1,n&&Mc.set(n,32),r&&Mc.set(r,48);for(let s=0;s<16;s++)i.h[s]=S_[s]^__(Mc,s*4);return t&&(Qb(i,t),i.c=128),i}function Qb(e,t){for(let n=0;n<t.length;n++)e.c===128&&(e.t+=e.c,I_(e,!1),e.c=0),e.b[e.c++]=t[n]}function T_(e){for(e.t+=e.c;e.c<128;)e.b[e.c++]=0;I_(e,!0);const t=new Uint8Array(e.outlen);for(let n=0;n<e.outlen;n++)t[n]=e.h[n>>2]>>8*(n&3);return t}function N_(e,t,n,r,i){n=n||64,e=$g.normalizeInput(e),r&&(r=$g.normalizeInput(r)),i&&(i=$g.normalizeInput(i));const s=$_(n,t,r,i);return Qb(s,e),T_(s)}function eq(e,t,n,r,i){const s=N_(e,t,n,r,i);return $g.toHex(s)}var tq={blake2b:N_,blake2bHex:eq,blake2bInit:$_,blake2bUpdate:Qb,blake2bFinal:T_};const P_=C_;function nq(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function Dc(e,t,n,r,i,s){$t[e]=$t[e]+$t[t]+i,$t[r]=Ng($t[r]^$t[e],16),$t[n]=$t[n]+$t[r],$t[t]=Ng($t[t]^$t[n],12),$t[e]=$t[e]+$t[t]+s,$t[r]=Ng($t[r]^$t[e],8),$t[n]=$t[n]+$t[r],$t[t]=Ng($t[t]^$t[n],7)}function Ng(e,t){return e>>>t^e<<32-t}const O_=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cr=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),$t=new Uint32Array(16),qn=new Uint32Array(16);function k_(e,t){let n=0;for(n=0;n<8;n++)$t[n]=e.h[n],$t[n+8]=O_[n];for($t[12]^=e.t,$t[13]^=e.t/4294967296,t&&($t[14]=~$t[14]),n=0;n<16;n++)qn[n]=nq(e.b,4*n);for(n=0;n<10;n++)Dc(0,4,8,12,qn[cr[n*16+0]],qn[cr[n*16+1]]),Dc(1,5,9,13,qn[cr[n*16+2]],qn[cr[n*16+3]]),Dc(2,6,10,14,qn[cr[n*16+4]],qn[cr[n*16+5]]),Dc(3,7,11,15,qn[cr[n*16+6]],qn[cr[n*16+7]]),Dc(0,5,10,15,qn[cr[n*16+8]],qn[cr[n*16+9]]),Dc(1,6,11,12,qn[cr[n*16+10]],qn[cr[n*16+11]]),Dc(2,7,8,13,qn[cr[n*16+12]],qn[cr[n*16+13]]),Dc(3,4,9,14,qn[cr[n*16+14]],qn[cr[n*16+15]]);for(n=0;n<8;n++)e.h[n]^=$t[n]^$t[n+8]}function R_(e,t){if(!(e>0&&e<=32))throw new Error("Incorrect output length, should be in [1, 32]");const n=t?t.length:0;if(t&&!(n>0&&n<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(O_),b:new Uint8Array(64),c:0,t:0,outlen:e};return r.h[0]^=16842752^n<<8^e,n>0&&(e8(r,t),r.c=64),r}function e8(e,t){for(let n=0;n<t.length;n++)e.c===64&&(e.t+=e.c,k_(e,!1),e.c=0),e.b[e.c++]=t[n]}function B_(e){for(e.t+=e.c;e.c<64;)e.b[e.c++]=0;k_(e,!0);const t=new Uint8Array(e.outlen);for(let n=0;n<e.outlen;n++)t[n]=e.h[n>>2]>>8*(n&3)&255;return t}function M_(e,t,n){n=n||32,e=P_.normalizeInput(e);const r=R_(n,t);return e8(r,e),B_(r)}function rq(e,t,n){const r=M_(e,t,n);return P_.toHex(r)}var iq={blake2s:M_,blake2sHex:rq,blake2sInit:R_,blake2sUpdate:e8,blake2sFinal:B_};const nh=tq,rh=iq;var sq={blake2b:nh.blake2b,blake2bHex:nh.blake2bHex,blake2bInit:nh.blake2bInit,blake2bUpdate:nh.blake2bUpdate,blake2bFinal:nh.blake2bFinal,blake2s:rh.blake2s,blake2sHex:rh.blake2sHex,blake2sInit:rh.blake2sInit,blake2sUpdate:rh.blake2sUpdate,blake2sFinal:rh.blake2sFinal},Xs={exports:{}};function oq(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}var aq=cq;function cq(e,t,n){var r=n&&n.stringify||oq,i=1;if(typeof e=="object"&&e!==null){var s=t.length+i;if(s===1)return e;var o=new Array(s);o[0]=r(e);for(var a=1;a<s;a++)o[a]=r(t[a]);return o.join(" ")}if(typeof e!="string")return e;var c=t.length;if(c===0)return e;for(var l="",u=1-i,d=-1,h=e&&e.length||0,f=0;f<h;){if(e.charCodeAt(f)===37&&f+1<h){switch(d=d>-1?d:0,e.charCodeAt(f+1)){case 100:case 102:if(u>=c||t[u]==null)break;d<f&&(l+=e.slice(d,f)),l+=Number(t[u]),d=f+2,f++;break;case 105:if(u>=c||t[u]==null)break;d<f&&(l+=e.slice(d,f)),l+=Math.floor(Number(t[u])),d=f+2,f++;break;case 79:case 111:case 106:if(u>=c||t[u]===void 0)break;d<f&&(l+=e.slice(d,f));var p=typeof t[u];if(p==="string"){l+="'"+t[u]+"'",d=f+2,f++;break}if(p==="function"){l+=t[u].name||"<anonymous>",d=f+2,f++;break}l+=r(t[u]),d=f+2,f++;break;case 115:if(u>=c)break;d<f&&(l+=e.slice(d,f)),l+=String(t[u]),d=f+2,f++;break;case 37:d<f&&(l+=e.slice(d,f)),l+="%",d=f+2,f++,u--;break}++u}++f}return d===-1?e:(d<h&&(l+=e.slice(d)),l)}const D_=aq;Xs.exports=Za;const ih=Cq().console||{},lq={mapHttpRequest:Pg,mapHttpResponse:Pg,wrapRequestSerializer:s8,wrapResponseSerializer:s8,wrapErrorSerializer:s8,req:Pg,res:Pg,err:L_,errWithCause:L_};function Uc(e,t){return e==="silent"?1/0:t.levels.values[e]}const t8=Symbol("pino.logFuncs"),n8=Symbol("pino.hierarchy"),uq={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function U_(e,t){const n={logger:t,parent:e[n8]};t[n8]=n}function dq(e,t,n){const r={};t.forEach(i=>{r[i]=n[i]?n[i]:ih[i]||ih[uq[i]||"log"]||Gd}),e[t8]=r}function fq(e,t){return Array.isArray(e)?e.filter(function(n){return n!=="!stdSerializers.err"}):e===!0?Object.keys(t):!1}function Za(e){e=e||{},e.browser=e.browser||{};const t=e.browser.transmit;if(t&&typeof t.send!="function")throw Error("pino: transmit option must have a send function");const n=e.browser.write||ih;e.browser.write&&(e.browser.asObject=!0);const r=e.serializers||{},i=fq(e.browser.serialize,r);let s=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof n=="function"&&a.forEach(function(g){n[g]=n}),(e.enabled===!1||e.browser.disabled)&&(e.level="silent");const c=e.level||"info",l=Object.create(n);l.log||(l.log=Gd),dq(l,a,n),U_({},l),Object.defineProperty(l,"levelVal",{get:d}),Object.defineProperty(l,"level",{get:h,set:f});const u={transmit:t,serialize:i,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:vq(e),messageKey:e.messageKey||"msg",onChild:e.onChild||Gd};l.levels=hq(e),l.level=c,l.isLevelEnabled=function(g){return this.levels.values[g]?this.levels.values[g]>=this.levels.values[this.level]:!1},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=Gd,l.serializers=r,l._serialize=i,l._stdErrSerialize=s,l.child=function(...g){return p.call(this,u,...g)},t&&(l._logEvent=i8());function d(){return Uc(this.level,this)}function h(){return this._level}function f(g){if(g!=="silent"&&!this.levels.values[g])throw Error("unknown level "+g);this._level=g,cu(this,u,l,"error"),cu(this,u,l,"fatal"),cu(this,u,l,"warn"),cu(this,u,l,"info"),cu(this,u,l,"debug"),cu(this,u,l,"trace"),o.forEach(y=>{cu(this,u,l,y)})}function p(g,y,A){if(!y)throw new Error("missing bindings for child Pino");A=A||{},i&&y.serializers&&(A.serializers=y.serializers);const _=A.serializers;if(i&&_){var v=Object.assign({},r,_),w=e.browser.serialize===!0?Object.keys(v):i;delete y.serializers,r8([y],w,v,this._stdErrSerialize)}function T(D){this._childLevel=(D._childLevel|0)+1,this.bindings=y,v&&(this.serializers=v,this._serialize=w),t&&(this._logEvent=i8([].concat(D._logEvent.bindings,y)))}T.prototype=this;const O=new T(this);return U_(this,O),O.child=function(...D){return p.call(this,g,...D)},O.level=A.level||this.level,g.onChild(O),O}return l}function hq(e){const t=e.customLevels||{},n=Object.assign({},Za.levels.values,t),r=Object.assign({},Za.levels.labels,pq(t));return{values:n,labels:r}}function pq(e){const t={};return Object.keys(e).forEach(function(n){t[e[n]]=n}),t}Za.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"}},Za.stdSerializers=lq,Za.stdTimeFunctions=Object.assign({},{nullTime:F_,epochTime:H_,unixTime:Eq,isoTime:Aq});function gq(e){const t=[];e.bindings&&t.push(e.bindings);let n=e[n8];for(;n.parent;)n=n.parent,n.logger.bindings&&t.push(n.logger.bindings);return t.reverse()}function cu(e,t,n,r){if(Object.defineProperty(e,r,{value:Uc(e.level,n)>Uc(r,n)?Gd:n[t8][r],writable:!0,enumerable:!0,configurable:!0}),e[r]===Gd){if(!t.transmit)return;const s=t.transmit.level||e.level,o=Uc(s,n);if(Uc(r,n)<o)return}e[r]=yq(e,t,n,r);const i=gq(e);i.length!==0&&(e[r]=mq(i,e[r]))}function mq(e,t){return function(){return t.apply(this,[...e,...arguments])}}function yq(e,t,n,r){return function(i){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ih?ih:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(t.serialize&&(r8(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),t.asObject||t.formatters?i.call(a,...wq(this,r,o,s,t)):i.apply(a,o),t.transmit){const u=t.transmit.level||e._level,d=Uc(u,n),h=Uc(r,n);if(h<d)return;bq(this,{ts:s,methodLevel:r,methodValue:h,transmitLevel:u,transmitValue:n.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:Uc(e._level,n)},o,l)}}}(e[t8][r])}function wq(e,t,n,r,i){const{level:s,log:o=d=>d}=i.formatters||{},a=n.slice();let c=a[0];const l={};let u=(e._childLevel|0)+1;if(u<1&&(u=1),r&&(l.time=r),s){const d=s(t,e.levels.values[t]);Object.assign(l,d)}else l.level=e.levels.values[t];if(i.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());return[o(l),...a]}else{if(c!==null&&typeof c=="object"){for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());c=a.length?D_(a.shift(),a):void 0}else typeof c=="string"&&(c=D_(a.shift(),a));return c!==void 0&&(l[i.messageKey]=c),[o(l)]}}function r8(e,t,n,r){for(const i in e)if(r&&e[i]instanceof Error)e[i]=Za.stdSerializers.err(e[i]);else if(typeof e[i]=="object"&&!Array.isArray(e[i])&&t)for(const s in e[i])t.indexOf(s)>-1&&s in n&&(e[i][s]=n[s](e[i][s]))}function bq(e,t,n,r=!1){const i=t.send,s=t.ts,o=t.methodLevel,a=t.methodValue,c=t.val,l=e._logEvent.bindings;r||r8(n,e._serialize||Object.keys(e.serializers),e.serializers,e._stdErrSerialize===void 0?!0:e._stdErrSerialize),e._logEvent.ts=s,e._logEvent.messages=n.filter(function(u){return l.indexOf(u)===-1}),e._logEvent.level.label=o,e._logEvent.level.value=a,i(o,e._logEvent,c),e._logEvent=i8(l)}function i8(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function L_(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const n in e)t[n]===void 0&&(t[n]=e[n]);return t}function vq(e){return typeof e.timestamp=="function"?e.timestamp:e.timestamp===!1?F_:H_}function Pg(){return{}}function s8(e){return e}function Gd(){}function F_(){return!1}function H_(){return Date.now()}function Eq(){return Math.round(Date.now()/1e3)}function Aq(){return new Date(Date.now()).toISOString()}function Cq(){function e(t){return typeof t<"u"&&t}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 e(self)||e(window)||e(this)||{}}}Xs.exports.default=Za,Xs.exports.pino=Za;const xq={level:"info"},Og="custom_context",o8=1e3*1024;var _q=Object.defineProperty,Sq=(e,t,n)=>t in e?_q(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Lc=(e,t,n)=>Sq(e,typeof t!="symbol"?t+"":t,n);class Iq{constructor(t){Lc(this,"nodeValue"),Lc(this,"sizeInBytes"),Lc(this,"next"),this.nodeValue=t,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class j_{constructor(t){Lc(this,"lengthInNodes"),Lc(this,"sizeInBytes"),Lc(this,"head"),Lc(this,"tail"),Lc(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=t,this.sizeInBytes=0}append(t){const n=new Iq(t);if(n.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${t} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.size}shift(){if(!this.head)return;const t=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=t.size}toArray(){const t=[];let n=this.head;for(;n!==null;)t.push(n.value),n=n.next;return t}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let t=this.head;return{next:()=>{if(!t)return{done:!0,value:null};const n=t.value;return t=t.next,{done:!1,value:n}}}}}const $q=e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString()+"n":n);function z_(e){return typeof e=="string"?e:$q(e)||""}var Tq=Object.defineProperty,Nq=(e,t,n)=>t in e?Tq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kg=(e,t,n)=>Nq(e,typeof t!="symbol"?t+"":t,n);class V_{constructor(t,n=o8){kg(this,"logs"),kg(this,"level"),kg(this,"levelValue"),kg(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=t??"error",this.levelValue=Xs.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new j_(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(t,n){n===Xs.exports.levels.values.error?console.error(t):n===Xs.exports.levels.values.warn?console.warn(t):n===Xs.exports.levels.values.debug?console.debug(t):n===Xs.exports.levels.values.trace?console.trace(t):console.log(t)}appendToLogs(t){this.logs.append(z_({timestamp:new Date().toISOString(),log:t}));const n=typeof t=="string"?JSON.parse(t).level:t.level;n>=this.levelValue&&this.forwardToConsole(t,n)}getLogs(){return this.logs}clearLogs(){this.logs=new j_(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(t){const n=this.getLogArray();return n.push(z_({extraMetadata:t})),new Blob(n,{type:"application/json"})}}var Pq=Object.defineProperty,Oq=(e,t,n)=>t in e?Pq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kq=(e,t,n)=>Oq(e,typeof t!="symbol"?t+"":t,n);class Rq{constructor(t,n=o8){kq(this,"baseChunkLogger"),this.baseChunkLogger=new V_(t,n)}write(t){this.baseChunkLogger.appendToLogs(t)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(t){return this.baseChunkLogger.logsToBlob(t)}downloadLogsBlobInBrowser(t){const n=URL.createObjectURL(this.logsToBlob(t)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}}var Bq=Object.defineProperty,Mq=(e,t,n)=>t in e?Bq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Dq=(e,t,n)=>Mq(e,typeof t!="symbol"?t+"":t,n);class Uq{constructor(t,n=o8){Dq(this,"baseChunkLogger"),this.baseChunkLogger=new V_(t,n)}write(t){this.baseChunkLogger.appendToLogs(t)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(t){return this.baseChunkLogger.logsToBlob(t)}}var Lq=Object.defineProperty,Fq=Object.defineProperties,Hq=Object.getOwnPropertyDescriptors,W_=Object.getOwnPropertySymbols,jq=Object.prototype.hasOwnProperty,zq=Object.prototype.propertyIsEnumerable,q_=(e,t,n)=>t in e?Lq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Fc=(e,t)=>{for(var n in t||(t={}))jq.call(t,n)&&q_(e,n,t[n]);if(W_)for(var n of W_(t))zq.call(t,n)&&q_(e,n,t[n]);return e},Hc=(e,t)=>Fq(e,Hq(t));function Z_(e){return Hc(Fc({},e),{level:e?.level||xq.level})}function Vq(e,t,n=Og){return e[n]=t,e}function Gr(e,t=Og){return e[t]||""}function Wq(e,t,n=Og){const r=Gr(e,n);return r.trim()?`${r}/${t}`:t}function vi(e,t,n=Og){const r=Wq(e,t,n),i=e.child({context:r});return Vq(i,r,n)}function qq(e){var t,n;const r=new Rq((t=e.opts)==null?void 0:t.level,e.maxSizeInBytes);return{logger:Xs.exports(Hc(Fc({},e.opts),{level:"trace",browser:Hc(Fc({},(n=e.opts)==null?void 0:n.browser),{write:i=>r.write(i)})})),chunkLoggerController:r}}function Zq(e){var t,n;const r=new Uq((t=e.opts)==null?void 0:t.level,e.maxSizeInBytes);return{logger:Xs.exports(Hc(Fc({},e.opts),{level:"trace",browser:Hc(Fc({},(n=e.opts)==null?void 0:n.browser),{write:i=>r.write(i)})}),r),chunkLoggerController:r}}function a8(e){var t;if(typeof e.loggerOverride<"u"&&typeof e.loggerOverride!="string")return{logger:e.loggerOverride,chunkLoggerController:null};const n=Hc(Fc({},e.opts),{level:typeof e.loggerOverride=="string"?e.loggerOverride:(t=e.opts)==null?void 0:t.level});return typeof window<"u"?qq(Hc(Fc({},e),{opts:n})):Zq(Hc(Fc({},e),{opts:n}))}var Gq=Object.defineProperty,Kq=Object.defineProperties,Yq=Object.getOwnPropertyDescriptors,G_=Object.getOwnPropertySymbols,Xq=Object.prototype.hasOwnProperty,Jq=Object.prototype.propertyIsEnumerable,K_=(e,t,n)=>t in e?Gq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Kd=(e,t)=>{for(var n in t||(t={}))Xq.call(t,n)&&K_(e,n,t[n]);if(G_)for(var n of G_(t))Jq.call(t,n)&&K_(e,n,t[n]);return e},sh=(e,t)=>Kq(e,Yq(t));const Qq=":";function Ga(e){const[t,n]=e.split(Qq);return{namespace:t,reference:n}}function Y_(e,t=[]){const n=[];return Object.keys(e).forEach(r=>{if(t.length&&!t.includes(r))return;const i=e[r];n.push(...i.accounts)}),n}function X_(e,t){return e.includes(":")?[e]:t.chains||[]}const eZ={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}},tZ={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 Ae(e,t){const{message:n,code:r}=tZ[e];return{message:t?`${n} ${t}`:n,code:r}}function Gt(e,t){const{message:n,code:r}=eZ[e];return{message:t?`${n} ${t}`:n,code:r}}var nZ=Object.defineProperty,rZ=Object.defineProperties,iZ=Object.getOwnPropertyDescriptors,J_=Object.getOwnPropertySymbols,sZ=Object.prototype.hasOwnProperty,oZ=Object.prototype.propertyIsEnumerable,c8=(e,t,n)=>t in e?nZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Q_=(e,t)=>{for(var n in t||(t={}))sZ.call(t,n)&&c8(e,n,t[n]);if(J_)for(var n of J_(t))oZ.call(t,n)&&c8(e,n,t[n]);return e},aZ=(e,t)=>rZ(e,iZ(t)),e7=(e,t,n)=>c8(e,typeof t!="symbol"?t+"":t,n);const cZ="ReactNative",Ei={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},lZ="js";function Rg(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function jc(){return!Kl()&&!!l6()&&navigator.product===cZ}function uZ(){return jc()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function dZ(){return jc()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Yd(){return!Rg()&&!!l6()&&!!Kl()}function oh(){return jc()?Ei.reactNative:Rg()?Ei.node:Yd()?Ei.browser:Ei.unknown}function t7(){var e;try{return jc()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(e=global.Application)==null?void 0:e.applicationId:void 0}catch{return}}function fZ(e,t){const n=new URLSearchParams(e);return Object.entries(t).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!=null&&n.set(r,String(i))}),n.toString()}function hZ(e){var t,n;const r=n7();try{return e!=null&&e.url&&r.url&&new URL(e.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),e.url=r.url),(t=e?.icons)!=null&&t.length&&e.icons.length>0&&(e.icons=e.icons.filter(i=>i!=="")),aZ(Q_(Q_({},r),e),{url:e?.url||r.url,name:e?.name||r.name,description:e?.description||r.description,icons:(n=e?.icons)!=null&&n.length&&e.icons.length>0?e.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),e||r}}function n7(){return xA()||{name:"",description:"",url:"",icons:[""]}}function pZ(){if(oh()===Ei.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:n,Version:r}=global.Platform;return[n,r].join("-")}const e=hM();if(e===null)return"unknown";const t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return e.type==="browser"?[t,e.name,e.version].join("-"):[t,e.version].join("-")}function gZ(){var e;const t=oh();return t===Ei.browser?[t,((e=CA())==null?void 0:e.host)||"unknown"].join(":"):t}function r7(e,t,n){const r=pZ(),i=gZ();return[[e,t].join("-"),[lZ,n].join("-"),r,i].join("/")}function mZ({protocol:e,version:t,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=n.split("?"),u=r7(e,t,r),d={auth:i,ua:u,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=fZ(l[1]||"",d);return l[0]+"?"+h}function lu(e,t){return e.filter(n=>t.includes(n)).length===e.length}function l8(e){return Object.fromEntries(e.entries())}function u8(e){return new Map(Object.entries(e))}function uu(e=ve.FIVE_MINUTES,t){const n=ve.toMiliseconds(e||ve.FIVE_MINUTES);let r,i,s,o;return{resolve:a=>{s&&r&&(clearTimeout(s),r(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const l=Ae("EXPIRED"),u=new Error(t||l.message);u.code=l.code,c(u)},n),r=a,i=c})}}function Js(e,t,n){return new Promise(async(r,i)=>{const s=setTimeout(()=>i(new Error(n)),t);try{const o=await e;r(o)}catch(o){i(o)}clearTimeout(s)})}function i7(e,t){if(typeof t=="string"&&t.startsWith(`${e}:`))return t;if(e.toLowerCase()==="topic"){if(typeof t!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}else if(e.toLowerCase()==="id"){if(typeof t!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function yZ(e){return i7("topic",e)}function wZ(e){return i7("id",e)}function s7(e){const[t,n]=e.split(":"),r={id:void 0,topic:void 0};if(t==="topic"&&typeof n=="string")r.topic=n;else if(t==="id"&&Number.isInteger(Number(n)))r.id=Number(n);else throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${n}`);return r}function mn(e,t){return ve.fromMiliseconds((t||Date.now())+ve.toMiliseconds(e))}function Qs(e){return Date.now()>=ve.toMiliseconds(e)}function Rt(e,t){return`${e}${t?`:${t}`:""}`}function eo(e=[],t=[]){return[...new Set([...e,...t])]}async function bZ({id:e,topic:t,wcDeepLink:n}){var r;try{if(!n)return;const i=typeof n=="string"?JSON.parse(n):n,s=i?.href;if(typeof s!="string")return;const o=vZ(s,e,t),a=oh();if(a===Ei.browser){if(!((r=Kl())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}EZ(o)}else a===Ei.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function vZ(e,t,n){const r=`requestId=${t}&sessionTopic=${n}`;e.endsWith("/")&&(e=e.slice(0,-1));let i=`${e}`;if(e.startsWith("https://t.me")){const s=e.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${_Z(r,!0)}`}else i=`${i}/wc?${r}`;return i}function EZ(e){let t="_self";xZ()?t="_top":(CZ()||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"),window.open(e,t,"noreferrer noopener")}async function AZ(e,t){let n="";try{if(Yd()&&(n=localStorage.getItem(t),n))return n;n=await e.getItem(t)}catch(r){console.error(r)}return n}function o7(e,t){if(!e.includes(t))return null;const n=e.split(/([&,?,=])/),r=n.indexOf(t);return n[r+2]}function a7(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function d8(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function CZ(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function xZ(){try{return window.self!==window.top}catch{return!1}}function _Z(e,t=!1){const n=Buffer.from(e).toString("base64");return t?n.replace(/[=]/g,""):n}function c7(e){return Buffer.from(e,"base64").toString("utf-8")}function SZ(e){return new Promise(t=>setTimeout(t,e))}class IZ{constructor({limit:t}){e7(this,"limit"),e7(this,"set"),this.limit=t,this.set=new Set}add(t){if(!this.set.has(t)){if(this.set.size>=this.limit){const n=this.set.values().next().value;n&&this.set.delete(n)}this.set.add(t)}}has(t){return this.set.has(t)}}const Bg=BigInt(2**32-1),l7=BigInt(32);function u7(e,t=!1){return t?{h:Number(e&Bg),l:Number(e>>l7&Bg)}:{h:Number(e>>l7&Bg)|0,l:Number(e&Bg)|0}}function d7(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=u7(e[s],t);[r[s],i[s]]=[o,a]}return[r,i]}const f7=(e,t,n)=>e>>>n,h7=(e,t,n)=>e<<32-n|t>>>n,zc=(e,t,n)=>e>>>n|t<<32-n,Vc=(e,t,n)=>e<<32-n|t>>>n,ah=(e,t,n)=>e<<64-n|t>>>n-32,ch=(e,t,n)=>e>>>n-32|t<<64-n,$Z=(e,t)=>t,TZ=(e,t)=>e,NZ=(e,t,n)=>e<<n|t>>>32-n,PZ=(e,t,n)=>t<<n|e>>>32-n,OZ=(e,t,n)=>t<<n-32|e>>>64-n,kZ=(e,t,n)=>e<<n-32|t>>>64-n;function ps(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}const f8=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),h8=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,RZ=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),BZ=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,MZ=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),DZ=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,Xd=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Mg(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ka(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function gs(e,...t){if(!Mg(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Dg(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ka(e.outputLen),Ka(e.blockLen)}function Wc(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function p8(e,t){gs(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function lh(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Li(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function g8(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function to(e,t){return e<<32-t|e>>>t}const p7=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function g7(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Ya=p7?e=>e:e=>g7(e);function UZ(e){for(let t=0;t<e.length;t++)e[t]=g7(e[t]);return e}const qc=p7?e=>e:UZ,m7=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",LZ=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Jd(e){if(gs(e),m7)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=LZ[e[n]];return t}const Xa={_0:48,_9:57,A:65,F:70,a:97,f:102};function y7(e){if(e>=Xa._0&&e<=Xa._9)return e-Xa._0;if(e>=Xa.A&&e<=Xa.F)return e-(Xa.A-10);if(e>=Xa.a&&e<=Xa.f)return e-(Xa.a-10)}function Ug(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(m7)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=y7(e.charCodeAt(s)),a=y7(e.charCodeAt(s+1));if(o===void 0||a===void 0){const c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function w7(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ms(e){return typeof e=="string"&&(e=w7(e)),gs(e),e}function Zc(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];gs(i),t+=i.length}const n=new Uint8Array(t);for(let r=0,i=0;r<e.length;r++){const s=e[r];n.set(s,i),i+=s.length}return n}class Lg{}function uh(e){const t=r=>e().update(ms(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function FZ(e){const t=(r,i)=>e(i).update(ms(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}function du(e=32){if(Xd&&typeof Xd.getRandomValues=="function")return Xd.getRandomValues(new Uint8Array(e));if(Xd&&typeof Xd.randomBytes=="function")return Uint8Array.from(Xd.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const HZ=BigInt(0),dh=BigInt(1),jZ=BigInt(2),zZ=BigInt(7),VZ=BigInt(256),WZ=BigInt(113),b7=[],v7=[],E7=[];for(let e=0,t=dh,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],b7.push(2*(5*r+n)),v7.push((e+1)*(e+2)/2%64);let i=HZ;for(let s=0;s<7;s++)t=(t<<dh^(t>>zZ)*WZ)%VZ,t&jZ&&(i^=dh<<(dh<<BigInt(s))-dh);E7.push(i)}const A7=d7(E7,!0),qZ=A7[0],ZZ=A7[1],C7=(e,t,n)=>n>32?OZ(e,t,n):NZ(e,t,n),x7=(e,t,n)=>n>32?kZ(e,t,n):PZ(e,t,n);function GZ(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let o=0;o<10;o++)n[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=n[c],u=n[c+1],d=C7(l,u,1)^n[a],h=x7(l,u,1)^n[a+1];for(let f=0;f<50;f+=10)e[o+f]^=d,e[o+f+1]^=h}let i=e[2],s=e[3];for(let o=0;o<24;o++){const a=v7[o],c=C7(i,s,a),l=x7(i,s,a),u=b7[o];i=e[u],s=e[u+1],e[u]=c,e[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=e[o+a];for(let a=0;a<10;a++)e[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}e[0]^=qZ[r],e[1]^=ZZ[r]}Li(n)}class m8 extends Lg{constructor(t,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,Ka(r),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=lh(this.state)}clone(){return this._cloneInto()}keccak(){qc(this.state32),GZ(this.state32,this.rounds),qc(this.state32),this.posOut=0,this.pos=0}update(t){Wc(this),t=ms(t),gs(t);const{blockLen:n,state:r}=this,i=t.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=t[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:n,pos:r,blockLen:i}=this;t[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){Wc(this,!1),gs(t),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=t.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);t.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Ka(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(p8(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Li(this.state)}_cloneInto(t){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return t||(t=new m8(n,r,i,o,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=r,t.outputLen=i,t.enableXOF=o,t.destroyed=this.destroyed,t}}const KZ=(e,t,n)=>uh(()=>new m8(t,e,n)),YZ=KZ(1,136,256/8);function XZ(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}function JZ(e,t,n){return e&t^~e&n}function QZ(e,t,n){return e&t^e&n^t&n}class _7 extends Lg{constructor(t,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=g8(this.buffer)}update(t){Wc(this),t=ms(t),gs(t);const{view:n,buffer:r,blockLen:i}=this,s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=g8(t);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Wc(this),p8(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Li(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let d=o;d<i;d++)n[d]=0;XZ(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=g8(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=a,i%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}}const Gc=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lr=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),ur=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),eG=Uint32Array.from([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]),Kc=new Uint32Array(64);class tG extends _7{constructor(t=32){super(64,t,8,!1),this.A=Gc[0]|0,this.B=Gc[1]|0,this.C=Gc[2]|0,this.D=Gc[3]|0,this.E=Gc[4]|0,this.F=Gc[5]|0,this.G=Gc[6]|0,this.H=Gc[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[t,n,r,i,s,o,a,c]}set(t,n,r,i,s,o,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,n){for(let d=0;d<16;d++,n+=4)Kc[d]=t.getUint32(n,!1);for(let d=16;d<64;d++){const h=Kc[d-15],f=Kc[d-2],p=to(h,7)^to(h,18)^h>>>3,g=to(f,17)^to(f,19)^f>>>10;Kc[d]=g+Kc[d-7]+p+Kc[d-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const h=to(a,6)^to(a,11)^to(a,25),f=u+h+JZ(a,c,l)+eG[d]+Kc[d]|0,p=(to(r,2)^to(r,13)^to(r,22))+QZ(r,i,s)|0;u=l,l=c,c=a,a=o+f|0,o=s,s=i,i=r,r=f+p|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,i,s,o,a,c,l,u)}roundClean(){Li(Kc)}destroy(){this.set(0,0,0,0,0,0,0,0),Li(this.buffer)}}const S7=d7(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),nG=S7[0],rG=S7[1],Yc=new Uint32Array(80),Xc=new Uint32Array(80);class y8 extends _7{constructor(t=64){super(128,t,16,!1),this.Ah=ur[0]|0,this.Al=ur[1]|0,this.Bh=ur[2]|0,this.Bl=ur[3]|0,this.Ch=ur[4]|0,this.Cl=ur[5]|0,this.Dh=ur[6]|0,this.Dl=ur[7]|0,this.Eh=ur[8]|0,this.El=ur[9]|0,this.Fh=ur[10]|0,this.Fl=ur[11]|0,this.Gh=ur[12]|0,this.Gl=ur[13]|0,this.Hh=ur[14]|0,this.Hl=ur[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:h,Gh:f,Gl:p,Hh:g,Hl:y}=this;return[t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y]}set(t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=h|0,this.Gh=f|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}process(t,n){for(let v=0;v<16;v++,n+=4)Yc[v]=t.getUint32(n),Xc[v]=t.getUint32(n+=4);for(let v=16;v<80;v++){const w=Yc[v-15]|0,T=Xc[v-15]|0,O=zc(w,T,1)^zc(w,T,8)^f7(w,T,7),D=Vc(w,T,1)^Vc(w,T,8)^h7(w,T,7),F=Yc[v-2]|0,U=Xc[v-2]|0,j=zc(F,U,19)^ah(F,U,61)^f7(F,U,6),W=Vc(F,U,19)^ch(F,U,61)^h7(F,U,6),S=RZ(D,W,Xc[v-7],Xc[v-16]),x=BZ(S,O,j,Yc[v-7],Yc[v-16]);Yc[v]=x|0,Xc[v]=S|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:h,Fh:f,Fl:p,Gh:g,Gl:y,Hh:A,Hl:_}=this;for(let v=0;v<80;v++){const w=zc(d,h,14)^zc(d,h,18)^ah(d,h,41),T=Vc(d,h,14)^Vc(d,h,18)^ch(d,h,41),O=d&f^~d&g,D=h&p^~h&y,F=MZ(_,T,D,rG[v],Xc[v]),U=DZ(F,A,w,O,nG[v],Yc[v]),j=F|0,W=zc(r,i,28)^ah(r,i,34)^ah(r,i,39),S=Vc(r,i,28)^ch(r,i,34)^ch(r,i,39),x=r&s^r&a^s&a,I=i&o^i&c^o&c;A=g|0,_=y|0,g=f|0,y=p|0,f=d|0,p=h|0,{h:d,l:h}=ps(l|0,u|0,U|0,j|0),l=a|0,u=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const m=f8(j,S,I);r=h8(m,U,W,x),i=m|0}({h:r,l:i}=ps(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=ps(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=ps(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ps(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:h}=ps(this.Eh|0,this.El|0,d|0,h|0),{h:f,l:p}=ps(this.Fh|0,this.Fl|0,f|0,p|0),{h:g,l:y}=ps(this.Gh|0,this.Gl|0,g|0,y|0),{h:A,l:_}=ps(this.Hh|0,this.Hl|0,A|0,_|0),this.set(r,i,s,o,a,c,l,u,d,h,f,p,g,y,A,_)}roundClean(){Li(Yc,Xc)}destroy(){Li(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class iG extends y8{constructor(){super(48),this.Ah=lr[0]|0,this.Al=lr[1]|0,this.Bh=lr[2]|0,this.Bl=lr[3]|0,this.Ch=lr[4]|0,this.Cl=lr[5]|0,this.Dh=lr[6]|0,this.Dl=lr[7]|0,this.Eh=lr[8]|0,this.El=lr[9]|0,this.Fh=lr[10]|0,this.Fl=lr[11]|0,this.Gh=lr[12]|0,this.Gl=lr[13]|0,this.Hh=lr[14]|0,this.Hl=lr[15]|0}}const dr=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class sG extends y8{constructor(){super(32),this.Ah=dr[0]|0,this.Al=dr[1]|0,this.Bh=dr[2]|0,this.Bl=dr[3]|0,this.Ch=dr[4]|0,this.Cl=dr[5]|0,this.Dh=dr[6]|0,this.Dl=dr[7]|0,this.Eh=dr[8]|0,this.El=dr[9]|0,this.Fh=dr[10]|0,this.Fl=dr[11]|0,this.Gh=dr[12]|0,this.Gl=dr[13]|0,this.Hh=dr[14]|0,this.Hl=dr[15]|0}}const Fg=uh(()=>new tG),oG=uh(()=>new y8),aG=uh(()=>new iG),cG=uh(()=>new sG),lG=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),In=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Se=new Uint32Array(32);function Jc(e,t,n,r,i,s){const o=i[s],a=i[s+1];let c=Se[2*e],l=Se[2*e+1],u=Se[2*t],d=Se[2*t+1],h=Se[2*n],f=Se[2*n+1],p=Se[2*r],g=Se[2*r+1],y=f8(c,u,o);l=h8(y,l,d,a),c=y|0,{Dh:g,Dl:p}={Dh:g^l,Dl:p^c},{Dh:g,Dl:p}={Dh:$Z(g,p),Dl:TZ(g)},{h:f,l:h}=ps(f,h,g,p),{Bh:d,Bl:u}={Bh:d^f,Bl:u^h},{Bh:d,Bl:u}={Bh:zc(d,u,24),Bl:Vc(d,u,24)},Se[2*e]=c,Se[2*e+1]=l,Se[2*t]=u,Se[2*t+1]=d,Se[2*n]=h,Se[2*n+1]=f,Se[2*r]=p,Se[2*r+1]=g}function Qc(e,t,n,r,i,s){const o=i[s],a=i[s+1];let c=Se[2*e],l=Se[2*e+1],u=Se[2*t],d=Se[2*t+1],h=Se[2*n],f=Se[2*n+1],p=Se[2*r],g=Se[2*r+1],y=f8(c,u,o);l=h8(y,l,d,a),c=y|0,{Dh:g,Dl:p}={Dh:g^l,Dl:p^c},{Dh:g,Dl:p}={Dh:zc(g,p,16),Dl:Vc(g,p,16)},{h:f,l:h}=ps(f,h,g,p),{Bh:d,Bl:u}={Bh:d^f,Bl:u^h},{Bh:d,Bl:u}={Bh:ah(d,u,63),Bl:ch(d,u,63)},Se[2*e]=c,Se[2*e+1]=l,Se[2*t]=u,Se[2*t+1]=d,Se[2*n]=h,Se[2*n+1]=f,Se[2*r]=p,Se[2*r+1]=g}function uG(e,t={},n,r,i){if(Ka(n),e<0||e>n)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=t;if(s!==void 0&&(s.length<1||s.length>n))throw new Error("key length must be undefined or 1.."+n);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==i)throw new Error("personalization must be undefined or "+i)}class dG extends Lg{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Ka(t),Ka(n),this.blockLen=t,this.outputLen=n,this.buffer=new Uint8Array(t),this.buffer32=lh(this.buffer)}update(t){Wc(this),t=ms(t),gs(t);const{blockLen:n,buffer:r,buffer32:i}=this,s=t.length,o=t.byteOffset,a=t.buffer;for(let c=0;c<s;){this.pos===n&&(qc(i),this.compress(i,0,!1),qc(i),this.pos=0);const l=Math.min(n-this.pos,s-c),u=o+c;if(l===n&&!(u%4)&&c+l<s){const d=new Uint32Array(a,u,Math.floor((s-c)/4));qc(d);for(let h=0;c+n<s;h+=i.length,c+=n)this.length+=n,this.compress(d,h,!1);qc(d);continue}r.set(t.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(t){Wc(this),p8(t,this);const{pos:n,buffer32:r}=this;this.finished=!0,Li(this.buffer.subarray(n)),qc(r),this.compress(r,0,!0),qc(r);const i=lh(t);this.get().forEach((s,o)=>i[o]=Ya(s))}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){const{buffer:n,length:r,finished:i,destroyed:s,outputLen:o,pos:a}=this;return t||(t=new this.constructor({dkLen:o})),t.set(...this.get()),t.buffer.set(n),t.destroyed=s,t.finished=i,t.length=r,t.pos=a,t.outputLen=o,t}clone(){return this._cloneInto()}}class fG extends dG{constructor(t={}){const n=t.dkLen===void 0?64:t.dkLen;super(128,n),this.v0l=In[0]|0,this.v0h=In[1]|0,this.v1l=In[2]|0,this.v1h=In[3]|0,this.v2l=In[4]|0,this.v2h=In[5]|0,this.v3l=In[6]|0,this.v3h=In[7]|0,this.v4l=In[8]|0,this.v4h=In[9]|0,this.v5l=In[10]|0,this.v5h=In[11]|0,this.v6l=In[12]|0,this.v6h=In[13]|0,this.v7l=In[14]|0,this.v7h=In[15]|0,uG(n,t,64,16,16);let{key:r,personalization:i,salt:s}=t,o=0;if(r!==void 0&&(r=ms(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=ms(s);const a=lh(s);this.v4l^=Ya(a[0]),this.v4h^=Ya(a[1]),this.v5l^=Ya(a[2]),this.v5h^=Ya(a[3])}if(i!==void 0){i=ms(i);const a=lh(i);this.v6l^=Ya(a[0]),this.v6h^=Ya(a[1]),this.v7l^=Ya(a[2]),this.v7h^=Ya(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:t,v0h:n,v1l:r,v1h:i,v2l:s,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:d,v5h:h,v6l:f,v6h:p,v7l:g,v7h:y}=this;return[t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y]}set(t,n,r,i,s,o,a,c,l,u,d,h,f,p,g,y){this.v0l=t|0,this.v0h=n|0,this.v1l=r|0,this.v1h=i|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|0,this.v5l=d|0,this.v5h=h|0,this.v6l=f|0,this.v6h=p|0,this.v7l=g|0,this.v7h=y|0}compress(t,n,r){this.get().forEach((c,l)=>Se[l]=c),Se.set(In,16);let{h:i,l:s}=u7(BigInt(this.length));Se[24]=In[8]^s,Se[25]=In[9]^i,r&&(Se[28]=~Se[28],Se[29]=~Se[29]);let o=0;const a=lG;for(let c=0;c<12;c++)Jc(0,4,8,12,t,n+2*a[o++]),Qc(0,4,8,12,t,n+2*a[o++]),Jc(1,5,9,13,t,n+2*a[o++]),Qc(1,5,9,13,t,n+2*a[o++]),Jc(2,6,10,14,t,n+2*a[o++]),Qc(2,6,10,14,t,n+2*a[o++]),Jc(3,7,11,15,t,n+2*a[o++]),Qc(3,7,11,15,t,n+2*a[o++]),Jc(0,5,10,15,t,n+2*a[o++]),Qc(0,5,10,15,t,n+2*a[o++]),Jc(1,6,11,12,t,n+2*a[o++]),Qc(1,6,11,12,t,n+2*a[o++]),Jc(2,7,8,13,t,n+2*a[o++]),Qc(2,7,8,13,t,n+2*a[o++]),Jc(3,4,9,14,t,n+2*a[o++]),Qc(3,4,9,14,t,n+2*a[o++]);this.v0l^=Se[0]^Se[16],this.v0h^=Se[1]^Se[17],this.v1l^=Se[2]^Se[18],this.v1h^=Se[3]^Se[19],this.v2l^=Se[4]^Se[20],this.v2h^=Se[5]^Se[21],this.v3l^=Se[6]^Se[22],this.v3h^=Se[7]^Se[23],this.v4l^=Se[8]^Se[24],this.v4h^=Se[9]^Se[25],this.v5l^=Se[10]^Se[26],this.v5h^=Se[11]^Se[27],this.v6l^=Se[12]^Se[28],this.v6h^=Se[13]^Se[29],this.v7l^=Se[14]^Se[30],this.v7h^=Se[15]^Se[31],Li(Se)}destroy(){this.destroyed=!0,Li(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const hG=FZ(e=>new fG(e)),pG="https://rpc.walletconnect.org/v1";function I7(e){const t=`Ethereum Signed Message:
|
|
20
|
+
${e.length}`,n=new TextEncoder().encode(t+e);return"0x"+Buffer.from(YZ(n)).toString("hex")}async function gG(e,t,n,r,i,s){switch(n.t){case"eip191":return await mG(e,t,n.s);case"eip1271":return await yG(e,t,n.s,r,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}function mG(e,t,n){const r=HL(n);return HF({payload:I7(t),signature:r}).toLowerCase()===e.toLowerCase()}async function yG(e,t,n,r,i,s){const o=Ga(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l=n.substring(2),u=(l.length/2).toString(16).padStart(64,"0"),d=(t.startsWith("0x")?t:I7(t)).substring(2),h=a+d+c+u+l,f=await fetch(`${s||pG}/?chainId=${r}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:wG(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:h},"latest"]})}),{result:p}=await f.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function wG(){return Date.now()+Math.floor(Math.random()*1e3)}function bG(e){const t=atob(e),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);const r=n[0];if(r===0)throw new Error("No signatures found");const i=1+r*64;if(n.length<i)throw new Error("Transaction data too short for claimed signature count");if(n.length<100)throw new Error("Transaction too short");const s=Buffer.from(e,"base64").slice(1,65);return Wd.encode(s)}function vG(e){const t=new Uint8Array(Buffer.from(e,"base64")),n=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),r=new Uint8Array(n.length+t.length);r.set(n),r.set(t,n.length);const i=hG(r,{dkLen:32});return Wd.encode(i)}function $7(e){const t=new Uint8Array(Fg(EG(e)));return Wd.encode(t)}function EG(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if(typeof e=="object"&&e!=null&&e.data)return new Uint8Array(Object.values(e.data));if(typeof e=="object"&&e)return new Uint8Array(Object.values(e));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function T7(e){const t=Buffer.from(e,"base64"),n=MH(t).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=$H(n),i=Buffer.from("TX"),s=Buffer.concat([i,Buffer.from(r)]),o=cG(s);return DF.encode(o).replace(/=+$/,"")}function w8(e){const t=[];let n=BigInt(e);for(;n>=BigInt(128);)t.push(Number(n&BigInt(127)|BigInt(128))),n>>=BigInt(7);return t.push(Number(n)),Buffer.from(t)}function AG(e){const t=Buffer.from(e.signed.bodyBytes,"base64"),n=Buffer.from(e.signed.authInfoBytes,"base64"),r=Buffer.from(e.signature.signature,"base64"),i=[];i.push(Buffer.from([10])),i.push(w8(t.length)),i.push(t),i.push(Buffer.from([18])),i.push(w8(n.length)),i.push(n),i.push(Buffer.from([26])),i.push(w8(r.length)),i.push(r);const s=Buffer.concat(i),o=Fg(s);return Buffer.from(o).toString("hex").toUpperCase()}function CG(e){var t,n;const r=[];try{if(typeof e=="string")return r.push(e),r;if(typeof e!="object")return r;e!=null&&e.id&&r.push(e.id);const i=(n=(t=e?.capabilities)==null?void 0:t.caip345)==null?void 0:n.transactionHashes;i&&r.push(...i)}catch(i){console.warn("getWalletSendCallsHashes failed: ",i)}return r}var xG=Object.defineProperty,_G=Object.defineProperties,SG=Object.getOwnPropertyDescriptors,N7=Object.getOwnPropertySymbols,IG=Object.prototype.hasOwnProperty,$G=Object.prototype.propertyIsEnumerable,P7=(e,t,n)=>t in e?xG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,TG=(e,t)=>{for(var n in t||(t={}))IG.call(t,n)&&P7(e,n,t[n]);if(N7)for(var n of N7(t))$G.call(t,n)&&P7(e,n,t[n]);return e},NG=(e,t)=>_G(e,SG(t));const O7="did:pkh:",PG={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},OG=e=>e?PG[e]||e:"",Hg=e=>e?.split(":"),kG=e=>{const t=e&&Hg(e);if(t)return e.includes(O7)?t[3]:t[1]},RG=e=>{const t=e&&Hg(e);if(t)return e.includes(O7)?t[2]:t[0]},b8=e=>{const t=e&&Hg(e);if(t)return t[2]+":"+t[3]},jg=e=>{const t=e&&Hg(e);if(t)return t.pop()};async function k7(e){const{cacao:t,projectId:n}=e,{s:r,p:i}=t,s=R7(i,i.iss),o=jg(i.iss);return await gG(o,s,r,b8(i.iss),n)}const R7=(e,t)=>{const n=RG(t);if(!n)throw new Error("Invalid issuer: "+t);const r=`${e.domain} wants you to sign in with your ${OG(n)} account:`,i=jg(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=e.statement||void 0;const o=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${kG(t)}`,l=`Nonce: ${e.nonce}`,u=`Issued At: ${e.iat}`,d=e.exp?`Expiration Time: ${e.exp}`:void 0,h=e.nbf?`Not Before: ${e.nbf}`:void 0,f=e.requestId?`Request ID: ${e.requestId}`:void 0,p=e.resources?`Resources:${e.resources.map(y=>`
|
|
21
|
+
- ${y}`).join("")}`:void 0,g=zg(e.resources);if(g){const y=fh(g);s=zG(s,y)}return[r,i,"",s,"",o,a,c,l,u,d,h,f,p].filter(y=>y!=null).join(`
|
|
22
|
+
`)};function BG(e){return Buffer.from(JSON.stringify(e)).toString("base64")}function MG(e){return JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}function fu(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");const t=Object.keys(e.att);if(!(t!=null&&t.length))throw new Error("No resources found in `att` property");t.forEach(n=>{const r=e.att[n];if(Array.isArray(r))throw new Error(`Resource must be an object: ${n}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${n}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${n}`);Object.keys(r).forEach(i=>{const s=r[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function DG(e,t,n,r={}){return n?.sort((i,s)=>i.localeCompare(s)),{att:{[e]:UG(t,n,r)}}}function UG(e,t,n={}){t=t?.sort((i,s)=>i.localeCompare(s));const r=t.map(i=>({[`${e}/${i}`]:[n]}));return Object.assign({},...r)}function B7(e){return fu(e),`urn:recap:${BG(e).replace(/=/g,"")}`}function fh(e){const t=MG(e.replace("urn:recap:",""));return fu(t),t}function LG(e,t,n){const r=DG(e,t,n);return B7(r)}function FG(e){return e&&e.includes("urn:recap:")}function HG(e,t){const n=fh(e),r=fh(t),i=jG(n,r);return B7(i)}function jG(e,t){fu(e),fu(t);const n=Object.keys(e.att).concat(Object.keys(t.att)).sort((i,s)=>i.localeCompare(s)),r={att:{}};return n.forEach(i=>{var s,o;Object.keys(((s=e.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=t.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;r.att[i]=NG(TG({},r.att[i]),{[a]:((c=e.att[i])==null?void 0:c[a])||((l=t.att[i])==null?void 0:l[a])})})}),r}function zG(e="",t){fu(t);const n="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(n))return e;const r=[];let i=0;Object.keys(t.att).forEach(a=>{const c=Object.keys(t.att[a]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));c.sort((d,h)=>d.action.localeCompare(h.action));const l={};c.forEach(d=>{l[d.ability]||(l[d.ability]=[]),l[d.ability].push(d.action)});const u=Object.keys(l).map(d=>(i++,`(${i}) '${d}': '${l[d].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const s=r.join(" "),o=`${n}${s}`;return`${e?e+" ":""}${o}`}function M7(e){var t;const n=fh(e);fu(n);const r=(t=n.att)==null?void 0:t.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function D7(e){const t=fh(e);fu(t);const n=[];return Object.values(t.att).forEach(r=>{Object.values(r).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&n.push(i[0].chains)})}),[...new Set(n.flat())]}function zg(e){if(!e)return;const t=e?.[e.length-1];return FG(t)?t:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function U7(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function v8(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function E8(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Kr(e,...t){if(!U7(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function L7(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function VG(e,t){Kr(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function el(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Qd(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function WG(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const qG=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ZG(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function A8(e){if(typeof e=="string")e=ZG(e);else if(U7(e))e=C8(e);else throw new Error("Uint8Array expected, got "+typeof e);return e}function GG(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function KG(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}const YG=(e,t)=>{function n(r,...i){if(Kr(r),!qG)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){const l=i[0];if(!l)throw new Error("nonce / iv required");e.varSizeNonce?Kr(l):Kr(l,e.nonceLength)}const s=e.tagLength;s&&i[1]!==void 0&&Kr(i[1]);const o=t(r,...i),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");Kr(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Kr(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(Kr(l),s&&l.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(n,e),n};function F7(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(n&&!JG(t))throw new Error("invalid output, must be aligned");return t}function H7(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}function XG(e,t,n){v8(n);const r=new Uint8Array(16),i=WG(r);return H7(i,0,BigInt(t),n),H7(i,8,BigInt(e),n),r}function JG(e){return e.byteOffset%4===0}function C8(e){return Uint8Array.from(e)}const j7=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),QG=j7("expand 16-byte k"),eK=j7("expand 32-byte k"),tK=el(QG),nK=el(eK);function Tt(e,t){return e<<t|e>>>32-t}function x8(e){return e.byteOffset%4===0}const Vg=64,rK=16,z7=2**32-1,V7=new Uint32Array;function iK(e,t,n,r,i,s,o,a){const c=i.length,l=new Uint8Array(Vg),u=el(l),d=x8(i)&&x8(s),h=d?el(i):V7,f=d?el(s):V7;for(let p=0;p<c;o++){if(e(t,n,r,u,o,a),o>=z7)throw new Error("arx: counter overflow");const g=Math.min(Vg,c-p);if(d&&g===Vg){const y=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let A=0,_;A<rK;A++)_=y+A,f[_]=h[_]^u[A];p+=Vg;continue}for(let y=0,A;y<g;y++)A=p+y,s[A]=i[A]^l[y];p+=g}}function sK(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=GG({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return E8(i),E8(o),v8(s),v8(n),(a,c,l,u,d=0)=>{Kr(a),Kr(c),Kr(l);const h=l.length;if(u===void 0&&(u=new Uint8Array(h)),Kr(u),E8(d),d<0||d>=z7)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);const f=[];let p=a.length,g,y;if(p===32)f.push(g=C8(a)),y=nK;else if(p===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),y=tK,f.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);x8(c)||f.push(c=C8(c));const A=el(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,A,el(c.subarray(0,16)),A),c=c.subarray(16)}const _=16-i;if(_!==c.length)throw new Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){const w=new Uint8Array(12);w.set(c,s?0:12-c.length),c=w,f.push(c)}const v=el(c);return iK(e,y,A,v,l,u,d,o),Qd(...f),u}}const Zn=(e,t)=>e[t++]&255|(e[t++]&255)<<8;class oK{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=A8(t),Kr(t,32);const n=Zn(t,0),r=Zn(t,2),i=Zn(t,4),s=Zn(t,6),o=Zn(t,8),a=Zn(t,10),c=Zn(t,12),l=Zn(t,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Zn(t,16+2*u)}process(t,n,r=!1){const i=r?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],h=o[5],f=o[6],p=o[7],g=o[8],y=o[9],A=Zn(t,n+0),_=Zn(t,n+2),v=Zn(t,n+4),w=Zn(t,n+6),T=Zn(t,n+8),O=Zn(t,n+10),D=Zn(t,n+12),F=Zn(t,n+14);let U=s[0]+(A&8191),j=s[1]+((A>>>13|_<<3)&8191),W=s[2]+((_>>>10|v<<6)&8191),S=s[3]+((v>>>7|w<<9)&8191),x=s[4]+((w>>>4|T<<12)&8191),I=s[5]+(T>>>1&8191),m=s[6]+((T>>>14|O<<2)&8191),b=s[7]+((O>>>11|D<<5)&8191),$=s[8]+((D>>>8|F<<8)&8191),N=s[9]+(F>>>5|i),P=0,B=P+U*a+j*(5*y)+W*(5*g)+S*(5*p)+x*(5*f);P=B>>>13,B&=8191,B+=I*(5*h)+m*(5*d)+b*(5*u)+$*(5*l)+N*(5*c),P+=B>>>13,B&=8191;let V=P+U*c+j*a+W*(5*y)+S*(5*g)+x*(5*p);P=V>>>13,V&=8191,V+=I*(5*f)+m*(5*h)+b*(5*d)+$*(5*u)+N*(5*l),P+=V>>>13,V&=8191;let Z=P+U*l+j*c+W*a+S*(5*y)+x*(5*g);P=Z>>>13,Z&=8191,Z+=I*(5*p)+m*(5*f)+b*(5*h)+$*(5*d)+N*(5*u),P+=Z>>>13,Z&=8191;let Y=P+U*u+j*l+W*c+S*a+x*(5*y);P=Y>>>13,Y&=8191,Y+=I*(5*g)+m*(5*p)+b*(5*f)+$*(5*h)+N*(5*d),P+=Y>>>13,Y&=8191;let X=P+U*d+j*u+W*l+S*c+x*a;P=X>>>13,X&=8191,X+=I*(5*y)+m*(5*g)+b*(5*p)+$*(5*f)+N*(5*h),P+=X>>>13,X&=8191;let G=P+U*h+j*d+W*u+S*l+x*c;P=G>>>13,G&=8191,G+=I*a+m*(5*y)+b*(5*g)+$*(5*p)+N*(5*f),P+=G>>>13,G&=8191;let ne=P+U*f+j*h+W*d+S*u+x*l;P=ne>>>13,ne&=8191,ne+=I*c+m*a+b*(5*y)+$*(5*g)+N*(5*p),P+=ne>>>13,ne&=8191;let se=P+U*p+j*f+W*h+S*d+x*u;P=se>>>13,se&=8191,se+=I*l+m*c+b*a+$*(5*y)+N*(5*g),P+=se>>>13,se&=8191;let we=P+U*g+j*p+W*f+S*h+x*d;P=we>>>13,we&=8191,we+=I*u+m*l+b*c+$*a+N*(5*y),P+=we>>>13,we&=8191;let ue=P+U*y+j*g+W*p+S*f+x*h;P=ue>>>13,ue&=8191,ue+=I*d+m*u+b*l+$*c+N*a,P+=ue>>>13,ue&=8191,P=(P<<2)+P|0,P=P+B|0,B=P&8191,P=P>>>13,V+=P,s[0]=B,s[1]=V,s[2]=Z,s[3]=Y,s[4]=X,s[5]=G,s[6]=ne,s[7]=se,s[8]=we,s[9]=ue}finalize(){const{h:t,pad:n}=this,r=new Uint16Array(10);let i=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=i,i=t[a]>>>13,t[a]&=8191;t[0]+=i*5,i=t[0]>>>13,t[0]&=8191,t[1]+=i,i=t[1]>>>13,t[1]&=8191,t[2]+=i,r[0]=t[0]+5,i=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=t[a]+i,i=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|r[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let o=t[0]+n[0];t[0]=o&65535;for(let a=1;a<8;a++)o=(t[a]+n[a]|0)+(o>>>16)|0,t[a]=o&65535;Qd(r)}update(t){L7(this),t=A8(t),Kr(t);const{buffer:n,blockLen:r}=this,i=t.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){for(;r<=i-s;s+=r)this.process(t,s);continue}n.set(t.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Qd(this.h,this.r,this.buffer,this.pad)}digestInto(t){L7(this),VG(t,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:i}=this;if(i){for(n[i++]=1;i<16;i++)n[i]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)t[s++]=r[o]>>>0,t[s++]=r[o]>>>8;return t}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}}function aK(e){const t=(r,i)=>e(i).update(A8(r)).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}const cK=aK(e=>new oK(e));function lK(e,t,n,r,i,s=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],d=t[1],h=t[2],f=t[3],p=t[4],g=t[5],y=t[6],A=t[7],_=i,v=n[0],w=n[1],T=n[2],O=o,D=a,F=c,U=l,j=u,W=d,S=h,x=f,I=p,m=g,b=y,$=A,N=_,P=v,B=w,V=T;for(let Y=0;Y<s;Y+=2)O=O+j|0,N=Tt(N^O,16),I=I+N|0,j=Tt(j^I,12),O=O+j|0,N=Tt(N^O,8),I=I+N|0,j=Tt(j^I,7),D=D+W|0,P=Tt(P^D,16),m=m+P|0,W=Tt(W^m,12),D=D+W|0,P=Tt(P^D,8),m=m+P|0,W=Tt(W^m,7),F=F+S|0,B=Tt(B^F,16),b=b+B|0,S=Tt(S^b,12),F=F+S|0,B=Tt(B^F,8),b=b+B|0,S=Tt(S^b,7),U=U+x|0,V=Tt(V^U,16),$=$+V|0,x=Tt(x^$,12),U=U+x|0,V=Tt(V^U,8),$=$+V|0,x=Tt(x^$,7),O=O+W|0,V=Tt(V^O,16),b=b+V|0,W=Tt(W^b,12),O=O+W|0,V=Tt(V^O,8),b=b+V|0,W=Tt(W^b,7),D=D+S|0,N=Tt(N^D,16),$=$+N|0,S=Tt(S^$,12),D=D+S|0,N=Tt(N^D,8),$=$+N|0,S=Tt(S^$,7),F=F+x|0,P=Tt(P^F,16),I=I+P|0,x=Tt(x^I,12),F=F+x|0,P=Tt(P^F,8),I=I+P|0,x=Tt(x^I,7),U=U+j|0,B=Tt(B^U,16),m=m+B|0,j=Tt(j^m,12),U=U+j|0,B=Tt(B^U,8),m=m+B|0,j=Tt(j^m,7);let Z=0;r[Z++]=o+O|0,r[Z++]=a+D|0,r[Z++]=c+F|0,r[Z++]=l+U|0,r[Z++]=u+j|0,r[Z++]=d+W|0,r[Z++]=h+S|0,r[Z++]=f+x|0,r[Z++]=p+I|0,r[Z++]=g+m|0,r[Z++]=y+b|0,r[Z++]=A+$|0,r[Z++]=_+N|0,r[Z++]=v+P|0,r[Z++]=w+B|0,r[Z++]=T+V|0}const uK=sK(lK,{counterRight:!1,counterLength:4,allowShortKeys:!1}),dK=new Uint8Array(16),W7=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(dK.subarray(n))},fK=new Uint8Array(32);function q7(e,t,n,r,i){const s=e(t,n,fK),o=cK.create(s);i&&W7(o,i),W7(o,r);const a=XG(r.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Qd(s,a),c}const hK=e=>(t,n,r)=>({encrypt(i,s){const o=i.length;s=F7(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);e(t,n,a,a,1);const c=q7(e,t,n,a,r);return s.set(c,o),Qd(c),s},decrypt(i,s){s=F7(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=q7(e,t,n,o,r);if(!KG(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,n,s,s,1),Qd(c),s}}),Z7=YG({blockSize:64,nonceLength:12,tagLength:16},hK(uK));class G7 extends Lg{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,Dg(t);const r=ms(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Li(s)}update(t){return Wc(this),this.iHash.update(t),this}digestInto(t){Wc(this),gs(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Wg=(e,t,n)=>new G7(e,t).update(n).digest();Wg.create=(e,t)=>new G7(e,t);function pK(e,t,n){return Dg(e),n===void 0&&(n=new Uint8Array(e.outputLen)),Wg(e,ms(n),ms(t))}const _8=Uint8Array.from([0]),K7=Uint8Array.of();function gK(e,t,n,r=32){Dg(e),Ka(r);const i=e.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/i);n===void 0&&(n=K7);const o=new Uint8Array(s*i),a=Wg.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)_8[0]=u+1,c.update(u===0?K7:l).update(n).update(_8).digestInto(l),o.set(l,i*u),a._cloneInto(c);return a.destroy(),c.destroy(),Li(l,_8),o.slice(0,r)}const mK=(e,t,n,r,i)=>gK(e,pK(e,t,n),r,i),qg=Fg,S8=BigInt(0),I8=BigInt(1);function Zg(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function hu(e,t,n=""){const r=Mg(e),i=e?.length,s=t!==void 0;if(!r||s&&i!==t){const o=n&&`"${n}" `,a=s?` of length ${t}`:"",c=r?`length=${i}`:`type=${typeof e}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return e}function Gg(e){const t=e.toString(16);return t.length&1?"0"+t:t}function Y7(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?S8:BigInt("0x"+e)}function Kg(e){return Y7(Jd(e))}function Yg(e){return gs(e),Y7(Jd(Uint8Array.from(e).reverse()))}function $8(e,t){return Ug(e.toString(16).padStart(t*2,"0"))}function T8(e,t){return $8(e,t).reverse()}function fr(e,t,n){let r;if(typeof t=="string")try{r=Ug(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(Mg(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}const N8=e=>typeof e=="bigint"&&S8<=e;function yK(e,t,n){return N8(e)&&N8(t)&&N8(n)&&t<=e&&e<n}function P8(e,t,n,r){if(!yK(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function X7(e){let t;for(t=0;e>S8;e>>=I8,t+=1);return t}const hh=e=>(I8<<BigInt(e))-I8;function wK(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),i=h=>Uint8Array.of(h);let s=r(e),o=r(e),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},l=(...h)=>n(o,s,...h),u=(h=r(0))=>{o=l(i(0),h),s=l(),h.length!==0&&(o=l(i(1),h),s=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<t;){s=l();const p=s.slice();f.push(p),h+=s.length}return Zc(...f)};return(h,f)=>{c(),u(h);let p;for(;!(p=f(d()));)u();return c(),p}}function Xg(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(i,s,o){const a=e[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function J7(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(i!==void 0)return i;const s=e(n,...r);return t.set(n,s),s}}const Yr=BigInt(0),$r=BigInt(1),pu=BigInt(2),Q7=BigInt(3),eS=BigInt(4),tS=BigInt(5),bK=BigInt(7),nS=BigInt(8),vK=BigInt(9),rS=BigInt(16);function Ai(e,t){const n=e%t;return n>=Yr?n:t+n}function ys(e,t,n){let r=e;for(;t-- >Yr;)r*=r,r%=n;return r}function iS(e,t){if(e===Yr)throw new Error("invert: expected non-zero number");if(t<=Yr)throw new Error("invert: expected positive modulus, got "+t);let n=Ai(e,t),r=t,i=Yr,s=$r;for(;n!==Yr;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==$r)throw new Error("invert: does not exist");return Ai(i,t)}function O8(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function sS(e,t){const n=(e.ORDER+$r)/eS,r=e.pow(t,n);return O8(e,r,t),r}function EK(e,t){const n=(e.ORDER-tS)/nS,r=e.mul(t,pu),i=e.pow(r,n),s=e.mul(t,i),o=e.mul(e.mul(s,pu),i),a=e.mul(s,e.sub(o,e.ONE));return O8(e,a,t),a}function AK(e){const t=tl(e),n=oS(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+bK)/rS;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,r);const d=a.mul(l,i),h=a.mul(l,s),f=a.eql(a.sqr(u),c),p=a.eql(a.sqr(d),c);l=a.cmov(l,u,f),u=a.cmov(h,d,p);const g=a.eql(a.sqr(u),c),y=a.cmov(l,u,g);return O8(a,y,c),y}}function oS(e){if(e<Q7)throw new Error("sqrt is not defined for small field");let t=e-$r,n=0;for(;t%pu===Yr;)t/=pu,n++;let r=pu;const i=tl(e);for(;cS(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return sS;let s=i.pow(r,t);const o=(t+$r)/pu;return function(a,c){if(a.is0(c))return c;if(cS(a,c)!==1)throw new Error("Cannot find square root");let l=n,u=a.mul(a.ONE,s),d=a.pow(c,t),h=a.pow(c,o);for(;!a.eql(d,a.ONE);){if(a.is0(d))return a.ZERO;let f=1,p=a.sqr(d);for(;!a.eql(p,a.ONE);)if(f++,p=a.sqr(p),f===l)throw new Error("Cannot find square root");const g=$r<<BigInt(l-f-1),y=a.pow(u,g);l=f,u=a.sqr(y),d=a.mul(d,u),h=a.mul(h,y)}return h}}function CK(e){return e%eS===Q7?sS:e%nS===tS?EK:e%rS===vK?AK(e):oS(e)}const xK=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function _K(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=xK.reduce((r,i)=>(r[i]="function",r),t);return Xg(e,n),e}function SK(e,t,n){if(n<Yr)throw new Error("invalid exponent, negatives unsupported");if(n===Yr)return e.ONE;if(n===$r)return t;let r=e.ONE,i=t;for(;n>Yr;)n&$r&&(r=e.mul(r,i)),i=e.sqr(i),n>>=$r;return r}function aS(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((o,a,c)=>e.is0(a)?o:(r[c]=o,e.mul(o,a)),e.ONE),s=e.inv(i);return t.reduceRight((o,a,c)=>e.is0(a)?o:(r[c]=e.mul(o,r[c]),e.mul(o,a)),s),r}function cS(e,t){const n=(e.ORDER-$r)/pu,r=e.pow(t,n),i=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function lS(e,t){t!==void 0&&Ka(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function tl(e,t,n=!1,r={}){if(e<=Yr)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s,o=!1,a;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const h=t;h.BITS&&(i=h.BITS),h.sqrt&&(s=h.sqrt),typeof h.isLE=="boolean"&&(n=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof t=="number"&&(i=t),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=lS(e,i);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:hh(c),ZERO:Yr,ONE:$r,allowedLengths:a,create:h=>Ai(h,e),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Yr<=h&&h<e},is0:h=>h===Yr,isValidNot0:h=>!d.is0(h)&&d.isValid(h),isOdd:h=>(h&$r)===$r,neg:h=>Ai(-h,e),eql:(h,f)=>h===f,sqr:h=>Ai(h*h,e),add:(h,f)=>Ai(h+f,e),sub:(h,f)=>Ai(h-f,e),mul:(h,f)=>Ai(h*f,e),pow:(h,f)=>SK(d,h,f),div:(h,f)=>Ai(h*iS(f,e),e),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>iS(h,e),sqrt:s||(h=>(u||(u=CK(e)),u(d,h))),toBytes:h=>n?T8(h,l):$8(h,l),fromBytes:(h,f=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(l);g.set(h,n?0:g.length-h.length),h=g}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let p=n?Yg(h):Kg(h);if(o&&(p=Ai(p,e)),!f&&!d.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>aS(d,h),cmov:(h,f,p)=>p?f:h});return Object.freeze(d)}function uS(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function dS(e){const t=uS(e);return t+Math.ceil(t/2)}function IK(e,t,n=!1){const r=e.length,i=uS(t),s=dS(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Yg(e):Kg(e),a=Ai(o,t-$r)+$r;return n?T8(a,i):$8(a,i)}const e0=BigInt(0),gu=BigInt(1);function Jg(e,t){const n=t.negate();return e?n:t}function k8(e,t){const n=aS(e.Fp,t.map(r=>r.Z));return t.map((r,i)=>e.fromAffine(r.toAffine(n[i])))}function fS(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function R8(e,t){fS(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e,s=hh(e),o=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function hS(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(e&i),c=e>>o;a>r&&(a-=s,c+=gu);const l=t*r,u=l+Math.abs(a)-1,d=a===0,h=a<0,f=t%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:l}}function $K(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function TK(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const B8=new WeakMap,pS=new WeakMap;function M8(e){return pS.get(e)||1}function gS(e){if(e!==e0)throw new Error("invalid wNAF")}class NK{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let i=t;for(;n>e0;)n&gu&&(r=r.add(i)),i=i.double(),n>>=gu;return r}precomputeWindow(t,n){const{windows:r,windowSize:i}=R8(n,this.bits),s=[];let o=t,a=o;for(let c=0;c<r;c++){a=o,s.push(a);for(let l=1;l<i;l++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=R8(t,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:h,offsetF:f}=hS(r,a,o);r=c,u?s=s.add(Jg(h,n[f])):i=i.add(Jg(d,n[l]))}return gS(r),{p:i,f:s}}wNAFUnsafe(t,n,r,i=this.ZERO){const s=R8(t,this.bits);for(let o=0;o<s.windows&&r!==e0;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=hS(r,o,s);if(r=a,!l){const d=n[c];i=i.add(u?d.negate():d)}}return gS(r),i}getPrecomputes(t,n,r){let i=B8.get(n);return i||(i=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(i=r(i)),B8.set(n,i))),i}cached(t,n,r){const i=M8(t);return this.wNAF(i,this.getPrecomputes(i,t,r),n)}unsafe(t,n,r,i){const s=M8(t);return s===1?this._unsafeLadder(t,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,i)}createCache(t,n){fS(n,this.bits),pS.set(t,n),B8.delete(t)}hasCache(t){return M8(t)!==1}}function PK(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>e0||r>e0;)n&gu&&(s=s.add(i)),r&gu&&(o=o.add(i)),i=i.double(),n>>=gu,r>>=gu;return{p1:s,p2:o}}function OK(e,t,n,r){$K(n,e),TK(r,t);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=X7(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=hh(c),u=new Array(Number(l)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c;let h=o;for(let f=d;f>=0;f-=c){u.fill(o);for(let g=0;g<s;g++){const y=r[g],A=Number(y>>BigInt(f)&l);u[A]=u[A].add(n[g])}let p=o;for(let g=u.length-1,y=o;g>0;g--)y=y.add(u[g]),p=p.add(y);if(h=h.add(p),f!==0)for(let g=0;g<c;g++)h=h.double()}return h}function mS(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return _K(t),t}else return tl(e,{isLE:n})}function kK(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const c=t[a];if(!(typeof c=="bigint"&&c>e0))throw new Error(`CURVE.${a} must be positive bigint`)}const i=mS(t.p,n.Fp,r),s=mS(t.n,n.Fn,r),o=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(const a of o)if(!i.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:s}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),w7("HashToScalar-");const ph=BigInt(0),t0=BigInt(1),Qg=BigInt(2);function RK(e){return Xg(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze(Kd({},e))}function BK(e){const t=RK(e),{P:n,type:r,adjustScalarBytes:i,powPminus2:s,randomBytes:o}=t,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||du,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),h=BigInt(a?121665:39081),f=a?Qg**BigInt(254):Qg**BigInt(447),p=a?BigInt(8)*Qg**BigInt(251)-t0:BigInt(4)*Qg**BigInt(445)-t0,g=f+p+t0,y=S=>Ai(S,n),A=_(d);function _(S){return T8(y(S),u)}function v(S){const x=fr("u coordinate",S,u);return a&&(x[31]&=127),y(Yg(x))}function w(S){return Yg(i(fr("scalar",S,u)))}function T(S,x){const I=F(v(x),w(S));if(I===ph)throw new Error("invalid private or public key received");return _(I)}function O(S){return T(S,A)}function D(S,x,I){const m=y(S*(x-I));return x=y(x-m),I=y(I+m),{x_2:x,x_3:I}}function F(S,x){P8("u",S,ph,n),P8("scalar",x,f,g);const I=x,m=S;let b=t0,$=ph,N=S,P=t0,B=ph;for(let Z=BigInt(l-1);Z>=ph;Z--){const Y=I>>Z&t0;B^=Y,{x_2:b,x_3:N}=D(B,b,N),{x_2:$,x_3:P}=D(B,$,P),B=Y;const X=b+$,G=y(X*X),ne=b-$,se=y(ne*ne),we=G-se,ue=N+P,ge=N-P,Be=y(ge*X),Fe=y(ue*ne),qe=Be+Fe,ct=Be-Fe;N=y(qe*qe),P=y(m*y(ct*ct)),b=y(G*se),$=y(we*(G+y(h*we)))}({x_2:b,x_3:N}=D(B,b,N)),{x_2:$,x_3:P}=D(B,$,P);const V=s($);return y(b*V)}const U={secretKey:u,publicKey:u,seed:u},j=(S=c(u))=>(gs(S,U.seed),S);function W(S){const x=j(S);return{secretKey:x,publicKey:O(x)}}return{keygen:W,getSharedSecret:(S,x)=>T(S,x),getPublicKey:S=>O(S),scalarMult:T,scalarMultBase:O,utils:{randomSecretKey:j,randomPrivateKey:j},GuBytes:A.slice(),lengths:U}}const MK=BigInt(1),yS=BigInt(2),DK=BigInt(3),UK=BigInt(5),LK=BigInt(8),wS=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),FK={p:wS,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:LK,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function HK(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=wS,o=e*e%s*e%s,a=ys(o,yS,s)*o%s,c=ys(a,MK,s)*e%s,l=ys(c,UK,s)*c%s,u=ys(l,t,s)*l%s,d=ys(u,n,s)*u%s,h=ys(d,r,s)*d%s,f=ys(h,i,s)*h%s,p=ys(f,i,s)*h%s,g=ys(p,t,s)*l%s;return{pow_p_5_8:ys(g,yS,s)*e%s,b2:o}}function jK(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const zK=tl(FK.p,{isLE:!0}),D8=(()=>{const e=zK.ORDER;return BK({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:n,b2:r}=HK(t);return Ai(ys(n,DK,e)*r,e)},adjustScalarBytes:jK})})(),bS=(e,t)=>(e+(e>=0?t:-t)/vS)/t;function VK(e,t,n){const[[r,i],[s,o]]=t,a=bS(o*e,n),c=bS(-i*e,n);let l=e-a*r-c*s,u=-a*i-c*o;const d=l<Qa,h=u<Qa;d&&(l=-l),h&&(u=-u);const f=hh(Math.ceil(X7(n)/2))+n0;if(l<Qa||l>=f||u<Qa||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}function U8(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function L8(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return Zg(n.lowS,"lowS"),Zg(n.prehash,"prehash"),n.format!==void 0&&U8(n.format),n}class WK extends Error{constructor(t=""){super(t)}}const Ja={Err:WK,_tlv:{encode:(e,t)=>{const{Err:n}=Ja;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const r=t.length/2,i=Gg(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Gg(i.length/2|128):"";return Gg(e)+s+i+t},decode(e,t){const{Err:n}=Ja;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const i=t[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=t.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+o)}}},_int:{encode(e){const{Err:t}=Ja;if(e<Qa)throw new t("integer: negative integers are not allowed");let n=Gg(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Ja;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Kg(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Ja,i=fr("signature",e),{v:s,l:o}=r.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=Ja,r=t.encode(2,n.encode(e.r)),i=t.encode(2,n.encode(e.s)),s=r+i;return t.encode(48,s)}},Qa=BigInt(0),n0=BigInt(1),vS=BigInt(2),em=BigInt(3),qK=BigInt(4);function r0(e,t){const{BYTES:n}=e;let r;if(typeof t=="bigint")r=t;else{let i=fr("private key",t);try{r=e.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function ZK(e,t={}){const n=kK("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;Xg(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=AS(r,i);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(S,x,I){const{x:m,y:b}=x.toAffine(),$=r.toBytes(m);if(Zg(I,"isCompressed"),I){u();const N=!r.isOdd(b);return Zc(ES(N),$)}else return Zc(Uint8Array.of(4),$,r.toBytes(b))}function h(S){hu(S,void 0,"Point");const{publicKey:x,publicKeyUncompressed:I}=l,m=S.length,b=S[0],$=S.subarray(1);if(m===x&&(b===2||b===3)){const N=r.fromBytes($);if(!r.isValid(N))throw new Error("bad point: is not on curve, wrong x");const P=g(N);let B;try{B=r.sqrt(P)}catch(Z){const Y=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}u();const V=r.isOdd(B);return(b&1)===1!==V&&(B=r.neg(B)),{x:N,y:B}}else if(m===I&&b===4){const N=r.BYTES,P=r.fromBytes($.subarray(0,N)),B=r.fromBytes($.subarray(N,N*2));if(!y(P,B))throw new Error("bad point: is not on curve");return{x:P,y:B}}else throw new Error(`bad point: got length ${m}, expected compressed=${x} or uncompressed=${I}`)}const f=t.toBytes||d,p=t.fromBytes||h;function g(S){const x=r.sqr(S),I=r.mul(x,S);return r.add(r.add(I,r.mul(S,s.a)),s.b)}function y(S,x){const I=r.sqr(x),m=g(S);return r.eql(I,m)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const A=r.mul(r.pow(s.a,em),qK),_=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(A,_)))throw new Error("bad curve params: a or b");function v(S,x,I=!1){if(!r.isValid(x)||I&&r.is0(x))throw new Error(`bad point coordinate ${S}`);return x}function w(S){if(!(S instanceof U))throw new Error("ProjectivePoint expected")}function T(S){if(!c||!c.basises)throw new Error("no endo");return VK(S,c.basises,i.ORDER)}const O=J7((S,x)=>{const{X:I,Y:m,Z:b}=S;if(r.eql(b,r.ONE))return{x:I,y:m};const $=S.is0();x==null&&(x=$?r.ONE:r.inv(b));const N=r.mul(I,x),P=r.mul(m,x),B=r.mul(b,x);if($)return{x:r.ZERO,y:r.ZERO};if(!r.eql(B,r.ONE))throw new Error("invZ was invalid");return{x:N,y:P}}),D=J7(S=>{if(S.is0()){if(t.allowInfinityPoint&&!r.is0(S.Y))return;throw new Error("bad point: ZERO")}const{x,y:I}=S.toAffine();if(!r.isValid(x)||!r.isValid(I))throw new Error("bad point: x or y not field elements");if(!y(x,I))throw new Error("bad point: equation left != right");if(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function F(S,x,I,m,b){return I=new U(r.mul(I.X,S),I.Y,I.Z),x=Jg(m,x),I=Jg(b,I),x.add(I)}class U{constructor(x,I,m){this.X=v("x",x),this.Y=v("y",I,!0),this.Z=v("z",m),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){const{x:I,y:m}=x||{};if(!x||!r.isValid(I)||!r.isValid(m))throw new Error("invalid affine point");if(x instanceof U)throw new Error("projective point not allowed");return r.is0(I)&&r.is0(m)?U.ZERO:new U(I,m,r.ONE)}static fromBytes(x){const I=U.fromAffine(p(hu(x,void 0,"point")));return I.assertValidity(),I}static fromHex(x){return U.fromBytes(fr("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,I=!0){return W.createCache(this,x),I||this.multiply(em),this}assertValidity(){D(this)}hasEvenY(){const{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){w(x);const{X:I,Y:m,Z:b}=this,{X:$,Y:N,Z:P}=x,B=r.eql(r.mul(I,P),r.mul($,b)),V=r.eql(r.mul(m,P),r.mul(N,b));return B&&V}negate(){return new U(this.X,r.neg(this.Y),this.Z)}double(){const{a:x,b:I}=s,m=r.mul(I,em),{X:b,Y:$,Z:N}=this;let P=r.ZERO,B=r.ZERO,V=r.ZERO,Z=r.mul(b,b),Y=r.mul($,$),X=r.mul(N,N),G=r.mul(b,$);return G=r.add(G,G),V=r.mul(b,N),V=r.add(V,V),P=r.mul(x,V),B=r.mul(m,X),B=r.add(P,B),P=r.sub(Y,B),B=r.add(Y,B),B=r.mul(P,B),P=r.mul(G,P),V=r.mul(m,V),X=r.mul(x,X),G=r.sub(Z,X),G=r.mul(x,G),G=r.add(G,V),V=r.add(Z,Z),Z=r.add(V,Z),Z=r.add(Z,X),Z=r.mul(Z,G),B=r.add(B,Z),X=r.mul($,N),X=r.add(X,X),Z=r.mul(X,G),P=r.sub(P,Z),V=r.mul(X,Y),V=r.add(V,V),V=r.add(V,V),new U(P,B,V)}add(x){w(x);const{X:I,Y:m,Z:b}=this,{X:$,Y:N,Z:P}=x;let B=r.ZERO,V=r.ZERO,Z=r.ZERO;const Y=s.a,X=r.mul(s.b,em);let G=r.mul(I,$),ne=r.mul(m,N),se=r.mul(b,P),we=r.add(I,m),ue=r.add($,N);we=r.mul(we,ue),ue=r.add(G,ne),we=r.sub(we,ue),ue=r.add(I,b);let ge=r.add($,P);return ue=r.mul(ue,ge),ge=r.add(G,se),ue=r.sub(ue,ge),ge=r.add(m,b),B=r.add(N,P),ge=r.mul(ge,B),B=r.add(ne,se),ge=r.sub(ge,B),Z=r.mul(Y,ue),B=r.mul(X,se),Z=r.add(B,Z),B=r.sub(ne,Z),Z=r.add(ne,Z),V=r.mul(B,Z),ne=r.add(G,G),ne=r.add(ne,G),se=r.mul(Y,se),ue=r.mul(X,ue),ne=r.add(ne,se),se=r.sub(G,se),se=r.mul(Y,se),ue=r.add(ue,se),G=r.mul(ne,ue),V=r.add(V,G),G=r.mul(ge,ue),B=r.mul(we,B),B=r.sub(B,G),G=r.mul(we,ne),Z=r.mul(ge,Z),Z=r.add(Z,G),new U(B,V,Z)}subtract(x){return this.add(x.negate())}is0(){return this.equals(U.ZERO)}multiply(x){const{endo:I}=t;if(!i.isValidNot0(x))throw new Error("invalid scalar: out of range");let m,b;const $=N=>W.cached(this,N,P=>k8(U,P));if(I){const{k1neg:N,k1:P,k2neg:B,k2:V}=T(x),{p:Z,f:Y}=$(P),{p:X,f:G}=$(V);b=Y.add(G),m=F(I.beta,Z,X,N,B)}else{const{p:N,f:P}=$(x);m=N,b=P}return k8(U,[m,b])[0]}multiplyUnsafe(x){const{endo:I}=t,m=this;if(!i.isValid(x))throw new Error("invalid scalar: out of range");if(x===Qa||m.is0())return U.ZERO;if(x===n0)return m;if(W.hasCache(this))return this.multiply(x);if(I){const{k1neg:b,k1:$,k2neg:N,k2:P}=T(x),{p1:B,p2:V}=PK(U,m,$,P);return F(I.beta,B,V,b,N)}else return W.unsafe(m,x)}multiplyAndAddUnsafe(x,I,m){const b=this.multiplyUnsafe(I).add(x.multiplyUnsafe(m));return b.is0()?void 0:b}toAffine(x){return O(this,x)}isTorsionFree(){const{isTorsionFree:x}=t;return o===n0?!0:x?x(U,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:x}=t;return o===n0?this:x?x(U,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(x=!0){return Zg(x,"isCompressed"),this.assertValidity(),f(U,this,x)}toHex(x=!0){return Jd(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return k8(U,x)}static msm(x,I){return OK(U,i,x,I)}static fromPrivateKey(x){return U.BASE.multiply(r0(i,x))}}U.BASE=new U(s.Gx,s.Gy,r.ONE),U.ZERO=new U(r.ZERO,r.ONE,r.ZERO),U.Fp=r,U.Fn=i;const j=i.BITS,W=new NK(U,t.endo?Math.ceil(j/2):j);return U.BASE.precompute(8),U}function ES(e){return Uint8Array.of(e?2:3)}function AS(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function GK(e,t={}){const{Fn:n}=e,r=t.randomBytes||du,i=Object.assign(AS(e.Fp,n),{seed:dS(n.ORDER)});function s(h){try{return!!r0(n,h)}catch{return!1}}function o(h,f){const{publicKey:p,publicKeyUncompressed:g}=i;try{const y=h.length;return f===!0&&y!==p||f===!1&&y!==g?!1:!!e.fromBytes(h)}catch{return!1}}function a(h=r(i.seed)){return IK(hu(h,i.seed,"seed"),n.ORDER)}function c(h,f=!0){return e.BASE.multiply(r0(n,h)).toBytes(f)}function l(h){const f=a(h);return{secretKey:f,publicKey:c(f)}}function u(h){if(typeof h=="bigint")return!1;if(h instanceof e)return!0;const{secretKey:f,publicKey:p,publicKeyUncompressed:g}=i;if(n.allowedLengths||f===p)return;const y=fr("key",h).length;return y===p||y===g}function d(h,f,p=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(f)===!1)throw new Error("second arg must be public key");const g=r0(n,h);return e.fromHex(f).multiply(g).toBytes(p)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:l,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>r0(n,h),precompute(h=8,f=e.BASE){return f.precompute(h,!1)}},lengths:i})}function KK(e,t,n={}){Dg(t),Xg(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||du,i=n.hmac||((I,...m)=>Wg(t,I,Zc(...m))),{Fp:s,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:f}=GK(e,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function y(I){const m=a>>n0;return I>m}function A(I,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return m}function _(I,m){U8(m);const b=f.signature,$=m==="compact"?b:m==="recovered"?b+1:void 0;return hu(I,$,`${m} signature`)}class v{constructor(m,b,$){this.r=A("r",m),this.s=A("s",b),$!=null&&(this.recovery=$),Object.freeze(this)}static fromBytes(m,b=g){_(m,b);let $;if(b==="der"){const{r:V,s:Z}=Ja.toSig(hu(m));return new v(V,Z)}b==="recovered"&&($=m[0],b="compact",m=m.subarray(1));const N=o.BYTES,P=m.subarray(0,N),B=m.subarray(N,N*2);return new v(o.fromBytes(P),o.fromBytes(B),$)}static fromHex(m,b){return this.fromBytes(Ug(m),b)}addRecoveryBit(m){return new v(this.r,this.s,m)}recoverPublicKey(m){const b=s.ORDER,{r:$,s:N,recovery:P}=this;if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");if(a*vS<b&&P>1)throw new Error("recovery id is ambiguous for h>1 curve");const B=P===2||P===3?$+a:$;if(!s.isValid(B))throw new Error("recovery id 2 or 3 invalid");const V=s.toBytes(B),Z=e.fromBytes(Zc(ES((P&1)===0),V)),Y=o.inv(B),X=T(fr("msgHash",m)),G=o.create(-X*Y),ne=o.create(N*Y),se=e.BASE.multiplyUnsafe(G).add(Z.multiplyUnsafe(ne));if(se.is0())throw new Error("point at infinify");return se.assertValidity(),se}hasHighS(){return y(this.s)}toBytes(m=g){if(U8(m),m==="der")return Ug(Ja.hexFromSig(this));const b=o.toBytes(this.r),$=o.toBytes(this.s);if(m==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Zc(Uint8Array.of(this.recovery),b,$)}return Zc(b,$)}toHex(m){return Jd(this.toBytes(m))}assertValidity(){}static fromCompact(m){return v.fromBytes(fr("sig",m),"compact")}static fromDER(m){return v.fromBytes(fr("sig",m),"der")}normalizeS(){return this.hasHighS()?new v(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Jd(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Jd(this.toBytes("compact"))}}const w=n.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const m=Kg(I),b=I.length*8-c;return b>0?m>>BigInt(b):m},T=n.bits2int_modN||function(I){return o.create(w(I))},O=hh(c);function D(I){return P8("num < 2^"+c,I,Qa,O),o.toBytes(I)}function F(I,m){return hu(I,void 0,"message"),m?hu(t(I),void 0,"prehashed message"):I}function U(I,m,b){if(["recovered","canonical"].some(ne=>ne in b))throw new Error("sign() legacy options not supported");const{lowS:$,prehash:N,extraEntropy:P}=L8(b,p);I=F(I,N);const B=T(I),V=r0(o,m),Z=[D(V),D(B)];if(P!=null&&P!==!1){const ne=P===!0?r(f.secretKey):P;Z.push(fr("extraEntropy",ne))}const Y=Zc(...Z),X=B;function G(ne){const se=w(ne);if(!o.isValidNot0(se))return;const we=o.inv(se),ue=e.BASE.multiply(se).toAffine(),ge=o.create(ue.x);if(ge===Qa)return;const Be=o.create(we*o.create(X+ge*V));if(Be===Qa)return;let Fe=(ue.x===ge?0:2)|Number(ue.y&n0),qe=Be;return $&&y(Be)&&(qe=o.neg(Be),Fe^=1),new v(ge,qe,Fe)}return{seed:Y,k2sig:G}}function j(I,m,b={}){I=fr("message",I);const{seed:$,k2sig:N}=U(I,m,b);return wK(t.outputLen,o.BYTES,i)($,N)}function W(I){let m;const b=typeof I=="string"||Mg(I),$=!b&&I!==null&&typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint";if(!b&&!$)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if($)m=new v(I.r,I.s);else if(b){try{m=v.fromBytes(fr("sig",I),"der")}catch(N){if(!(N instanceof Ja.Err))throw N}if(!m)try{m=v.fromBytes(fr("sig",I),"compact")}catch{return!1}}return m||!1}function S(I,m,b,$={}){const{lowS:N,prehash:P,format:B}=L8($,p);if(b=fr("publicKey",b),m=F(fr("message",m),P),"strict"in $)throw new Error("options.strict was renamed to lowS");const V=B===void 0?W(I):v.fromBytes(fr("sig",I),B);if(V===!1)return!1;try{const Z=e.fromBytes(b);if(N&&V.hasHighS())return!1;const{r:Y,s:X}=V,G=T(m),ne=o.inv(X),se=o.create(G*ne),we=o.create(Y*ne),ue=e.BASE.multiplyUnsafe(se).add(Z.multiplyUnsafe(we));return ue.is0()?!1:o.create(ue.x)===Y}catch{return!1}}function x(I,m,b={}){const{prehash:$}=L8(b,p);return m=F(m,$),v.fromBytes(I,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:f,Point:e,sign:j,verify:S,recoverPublicKey:x,Signature:v,hash:t})}function YK(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=tl(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function XK(e){const{CURVE:t,curveOpts:n}=YK(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function JK(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,lS(n.Fn.ORDER,n.Fn.BITS))})}function QK(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=XK(e),s=ZK(t,n),o=KK(s,r,i);return JK(e,o)}function F8(e,t){const n=r=>QK(sh(Kd({},e),{hash:r}));return sh(Kd({},n(t)),{create:n})}const CS={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},xS={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},_S={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},eY=tl(CS.p),tY=tl(xS.p),nY=tl(_S.p),rY=F8(sh(Kd({},CS),{Fp:eY,lowS:!1}),Fg);F8(sh(Kd({},xS),{Fp:tY,lowS:!1}),aG),F8(sh(Kd({},_S),{Fp:nY,lowS:!1,allowedPrivateKeyLengths:[130,131,132]}),oG);const iY=rY,SS="base10",Tr="base16",Xr="base64pad",nl="base64url",gh="utf8",IS=0,ec=1,mh=2,sY=0,$S=1,yh=12,H8=32;function oY(){const e=D8.utils.randomPrivateKey(),t=D8.getPublicKey(e);return{privateKey:Zr(e,Tr),publicKey:Zr(t,Tr)}}function j8(){const e=du(H8);return Zr(e,Tr)}function aY(e,t){const n=D8.getSharedSecret(Ui(e,Tr),Ui(t,Tr)),r=mK(qg,n,void 0,void 0,H8);return Zr(r,Tr)}function tm(e){const t=qg(Ui(e,Tr));return Zr(t,Tr)}function Fi(e){const t=qg(Ui(e,gh));return Zr(t,Tr)}function TS(e){return Ui(`${e}`,SS)}function mu(e){return Number(Zr(e,SS))}function NS(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function PS(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4;return t+"=".repeat(n)}function cY(e){const t=TS(typeof e.type<"u"?e.type:IS);if(mu(t)===ec&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof e.senderPublicKey<"u"?Ui(e.senderPublicKey,Tr):void 0,r=typeof e.iv<"u"?Ui(e.iv,Tr):du(yh),i=Ui(e.symKey,Tr),s=Z7(i,r).encrypt(Ui(e.message,gh)),o=OS({type:t,sealed:s,iv:r,senderPublicKey:n});return e.encoding===nl?NS(o):o}function lY(e){const t=Ui(e.symKey,Tr),{sealed:n,iv:r}=wh({encoded:e.encoded,encoding:e.encoding}),i=Z7(t,r).decrypt(n);if(i===null)throw new Error("Failed to decrypt");return Zr(i,gh)}function uY(e,t){const n=TS(mh),r=du(yh),i=Ui(e,gh),s=OS({type:n,sealed:i,iv:r});return t===nl?NS(s):s}function dY(e,t){const{sealed:n}=wh({encoded:e,encoding:t});return Zr(n,gh)}function OS(e){if(mu(e.type)===mh)return Zr(Qf([e.type,e.sealed]),Xr);if(mu(e.type)===ec){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Zr(Qf([e.type,e.senderPublicKey,e.iv,e.sealed]),Xr)}return Zr(Qf([e.type,e.iv,e.sealed]),Xr)}function wh(e){const t=(e.encoding||Xr)===nl?PS(e.encoded):e.encoded,n=Ui(t,Xr),r=n.slice(sY,$S),i=$S;if(mu(r)===ec){const c=i+H8,l=c+yh,u=n.slice(i,c),d=n.slice(c,l),h=n.slice(l);return{type:r,sealed:h,iv:d,senderPublicKey:u}}if(mu(r)===mh){const c=n.slice(i),l=du(yh);return{type:r,sealed:c,iv:l}}const s=i+yh,o=n.slice(i,s),a=n.slice(s);return{type:r,sealed:a,iv:o}}function fY(e,t){const n=wh({encoded:e,encoding:t?.encoding});return kS({type:mu(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?Zr(n.senderPublicKey,Tr):void 0,receiverPublicKey:t?.receiverPublicKey})}function kS(e){const t=e?.type||IS;if(t===ec){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function RS(e){return e.type===ec&&typeof e.senderPublicKey=="string"&&typeof e.receiverPublicKey=="string"}function BS(e){return e.type===mh}function hY(e){const t=Buffer.from(e.x,"base64"),n=Buffer.from(e.y,"base64");return Qf([new Uint8Array([4]),t,n])}function pY(e,t){const[n,r,i]=e.split("."),s=Buffer.from(PS(i),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${n}.${r}`,l=qg(c),u=hY(t);if(!iY.verify(Qf([o,a]),l,u))throw new Error("Invalid signature");return Gb(e).payload}const gY="irn";function nm(e){return e?.relay||{protocol:gY}}function i0(e){const t=ZW[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}var mY=Object.defineProperty,yY=Object.defineProperties,wY=Object.getOwnPropertyDescriptors,MS=Object.getOwnPropertySymbols,bY=Object.prototype.hasOwnProperty,vY=Object.prototype.propertyIsEnumerable,DS=(e,t,n)=>t in e?mY(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,z8=(e,t)=>{for(var n in t||(t={}))bY.call(t,n)&&DS(e,n,t[n]);if(MS)for(var n of MS(t))vY.call(t,n)&&DS(e,n,t[n]);return e},EY=(e,t)=>yY(e,wY(t));function AY(e,t="-"){const n={},r="relay"+t;return Object.keys(e).forEach(i=>{if(i.startsWith(r)){const s=i.replace(r,""),o=e[i];n[s]=o}}),n}function US(e){if(!e.includes("wc:")){const l=c7(e);l!=null&&l.includes("wc:")&&(e=l)}e=e.includes("wc://")?e.replace("wc://",""):e,e=e.includes("wc:")?e.replace("wc:",""):e;const t=e.indexOf(":"),n=e.indexOf("?")!==-1?e.indexOf("?"):void 0,r=e.substring(0,t),i=e.substring(t+1,n).split("@"),s=typeof n<"u"?e.substring(n):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:CY(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:AY(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function CY(e){return e.startsWith("//")?e.substring(2):e}function xY(e,t="-"){const n="relay",r={};return Object.keys(e).forEach(i=>{const s=i,o=n+t+s;e[s]&&(r[o]=e[s])}),r}function LS(e){const t=new URLSearchParams,n=z8(z8(EY(z8({},xY(e.relay)),{symKey:e.symKey}),e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()}),e.methods&&{methods:e.methods.join(",")});return Object.entries(n).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!==void 0&&t.append(r,String(i))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function rm(e,t,n){return`${e}?wc_ev=${n}&topic=${t}`}var _Y=Object.defineProperty,SY=Object.defineProperties,IY=Object.getOwnPropertyDescriptors,FS=Object.getOwnPropertySymbols,$Y=Object.prototype.hasOwnProperty,TY=Object.prototype.propertyIsEnumerable,HS=(e,t,n)=>t in e?_Y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,NY=(e,t)=>{for(var n in t||(t={}))$Y.call(t,n)&&HS(e,n,t[n]);if(FS)for(var n of FS(t))TY.call(t,n)&&HS(e,n,t[n]);return e},PY=(e,t)=>SY(e,IY(t));function s0(e){const t=[];return e.forEach(n=>{const[r,i]=n.split(":");t.push(`${r}:${i}`)}),t}function jS(e){const t=[];return Object.values(e).forEach(n=>{t.push(...s0(n.accounts))}),[...new Set(t)]}function OY(e){const t=[];return Object.values(e).forEach(n=>{t.push(...n.methods)}),[...new Set(t)]}function kY(e){const t=[];return Object.values(e).forEach(n=>{t.push(...n.events)}),[...new Set(t)]}function RY(e,t){const n=[];return Object.values(e).forEach(r=>{s0(r.accounts).includes(t)&&n.push(...r.methods)}),n}function BY(e,t){const n=[];return Object.values(e).forEach(r=>{s0(r.accounts).includes(t)&&n.push(...r.events)}),n}function im(e){return e.includes(":")}function o0(e){return im(e)?e.split(":")[0]:e}function zS(e){var t,n,r;const i={};if(!no(e))return i;for(const[s,o]of Object.entries(e)){const a=im(s)?[s]:o.chains,c=o.methods||[],l=o.events||[],u=o0(s);i[u]=PY(NY({},i[u]),{chains:eo(a,(t=i[u])==null?void 0:t.chains),methods:eo(c,(n=i[u])==null?void 0:n.methods),events:eo(l,(r=i[u])==null?void 0:r.events)})}return i}function MY(e){const t={};return e?.forEach(n=>{var r;const[i,s]=n.split(":");t[i]||(t[i]={accounts:[],chains:[],events:[],methods:[]}),t[i].accounts.push(n),(r=t[i].chains)==null||r.push(`${i}:${s}`)}),t}function VS(e,t){t=t.map(r=>r.replace("did:pkh:",""));const n=MY(t);for(const[r,i]of Object.entries(n))i.methods?i.methods=eo(i.methods,e):i.methods=e,i.events=["chainChanged","accountsChanged"];return n}function DY(e,t){var n,r,i,s,o,a;const c=zS(e),l=zS(t),u={},d=Object.keys(c).concat(Object.keys(l));for(const h of d)u[h]={chains:eo((n=c[h])==null?void 0:n.chains,(r=l[h])==null?void 0:r.chains),methods:eo((i=c[h])==null?void 0:i.methods,(s=l[h])==null?void 0:s.methods),events:eo((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return u}function Hi(e,t){return Array.isArray(e)?typeof t<"u"&&e.length?e.every(t):!0:!1}function no(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function $n(e){return typeof e>"u"}function yn(e,t){return t&&$n(e)?!0:typeof e=="string"&&!!e.trim().length}function V8(e,t){return t&&$n(e)?!0:typeof e=="number"&&!isNaN(e)}function UY(e,t){const{requiredNamespaces:n}=t,r=Object.keys(e.namespaces),i=Object.keys(n);let s=!0;return lu(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:l}=e.namespaces[o],u=s0(a),d=n[o];(!lu(X_(o,d),u)||!lu(d.methods,c)||!lu(d.events,l))&&(s=!1)}),s):!1}function sm(e){return yn(e,!1)&&e.includes(":")?e.split(":").length===2:!1}function LY(e){if(yn(e,!1)&&e.includes(":")){const t=e.split(":");if(t.length===3){const n=t[0]+":"+t[1];return!!t[2]&&sm(n)}}return!1}function FY(e){function t(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(yn(e,!1)){if(t(e))return!0;const n=c7(e);return t(n)}}catch{}return!1}function HY(e){var t;return(t=e?.proposer)==null?void 0:t.publicKey}function jY(e){return e?.topic}function zY(e,t){let n=null;return yn(e?.publicKey,!1)||(n=Ae("MISSING_OR_INVALID",`${t} controller public key should be a string`)),n}function WS(e){let t=!0;return Hi(e)?e.length&&(t=e.every(n=>yn(n,!1))):t=!1,t}function VY(e,t,n){let r=null;return Hi(t)&&t.length?t.forEach(i=>{r||sm(i)||(r=Gt("UNSUPPORTED_CHAINS",`${n}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):sm(e)||(r=Gt("UNSUPPORTED_CHAINS",`${n}, 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"] }`)),r}function WY(e,t,n){let r=null;return Object.entries(e).forEach(([i,s])=>{if(r)return;const o=VY(i,X_(i,s),`${t} ${n}`);o&&(r=o)}),r}function qY(e,t){let n=null;return Hi(e)?e.forEach(r=>{n||LY(r)||(n=Gt("UNSUPPORTED_ACCOUNTS",`${t}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=Gt("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function ZY(e,t){let n=null;return Object.values(e).forEach(r=>{if(n)return;const i=qY(r?.accounts,`${t} namespace`);i&&(n=i)}),n}function GY(e,t){let n=null;return WS(e?.methods)?WS(e?.events)||(n=Gt("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):n=Gt("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),n}function qS(e,t){let n=null;return Object.values(e).forEach(r=>{if(n)return;const i=GY(r,`${t}, namespace`);i&&(n=i)}),n}function KY(e,t,n){let r=null;if(e&&no(e)){const i=qS(e,t);i&&(r=i);const s=WY(e,t,n);s&&(r=s)}else r=Ae("MISSING_OR_INVALID",`${t}, ${n} should be an object with data`);return r}function W8(e,t){let n=null;if(e&&no(e)){const r=qS(e,t);r&&(n=r);const i=ZY(e,t);i&&(n=i)}else n=Ae("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return n}function ZS(e){return yn(e.protocol,!0)}function YY(e,t){let n=!1;return t&&!e?n=!0:e&&Hi(e)&&e.length&&e.forEach(r=>{n=ZS(r)}),n}function XY(e){return typeof e=="number"}function Jr(e){return typeof e<"u"&&typeof e!==null}function JY(e){return!(!e||typeof e!="object"||!e.code||!V8(e.code,!1)||!e.message||!yn(e.message,!1))}function QY(e){return!($n(e)||!yn(e.method,!1))}function eX(e){return!($n(e)||$n(e.result)&&$n(e.error)||!V8(e.id,!1)||!yn(e.jsonrpc,!1))}function tX(e){return!($n(e)||!yn(e.name,!1))}function GS(e,t){return!(!sm(t)||!jS(e).includes(t))}function nX(e,t,n){return yn(n,!1)?RY(e,t).includes(n):!1}function rX(e,t,n){return yn(n,!1)?BY(e,t).includes(n):!1}function KS(e,t,n){let r=null;const i=iX(e),s=sX(t),o=Object.keys(i),a=Object.keys(s),c=YS(Object.keys(e)),l=YS(Object.keys(t)),u=c.filter(d=>!l.includes(d));return u.length&&(r=Ae("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
|
|
23
23
|
Required: ${u.toString()}
|
|
24
24
|
Received: ${Object.keys(t).toString()}`)),lu(o,a)||(r=Ae("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces.
|
|
25
25
|
Required: ${o.toString()}
|
|
@@ -38,7 +38,7 @@ ${e.length}`,n=new TextEncoder().encode(t+e);return"0x"+Buffer.from(GZ(n)).toStr
|
|
|
38
38
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
39
39
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
40
40
|
PERFORMANCE OF THIS SOFTWARE.
|
|
41
|
-
***************************************************************************** */var e4=function(e,t){return e4=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},e4(e,t)};function NJ(e,t){e4(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var t4=function(){return t4=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},t4.apply(this,arguments)};function PJ(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function OJ(e,t,n,r){var i=arguments.length,s=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s}function kJ(e,t){return function(n,r){t(n,r,e)}}function RJ(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function BJ(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((r=r.apply(e,t||[])).next())})}function MJ(e,t){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,i=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){n.label=l[1];break}if(l[0]===6&&n.label<s[1]){n.label=s[1],s=l;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(l);break}s[2]&&n.ops.pop(),n.trys.pop();continue}l=t.call(e,n)}catch(u){l=[6,u],i=0}finally{r=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function DJ(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}function UJ(e,t){for(var n in e)n!=="default"&&!t.hasOwnProperty(n)&&(t[n]=e[n])}function n4(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function dI(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,s=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function LJ(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(dI(arguments[t]));return e}function FJ(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Ah(e){return this instanceof Ah?(this.v=e,this):new Ah(e)}function HJ(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(e,t||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){r[h]&&(i[h]=function(f){return new Promise(function(p,g){s.push([h,f,p,g])>1||a(h,f)})})}function a(h,f){try{c(r[h](f))}catch(p){d(s[0][3],p)}}function c(h){h.value instanceof Ah?Promise.resolve(h.value.v).then(l,u):d(s[0][2],h)}function l(h){a("next",h)}function u(h){a("throw",h)}function d(h,f){h(f),s.shift(),s.length&&a(s[0][0],s[0][1])}}function jJ(e){var t,n;return t={},r("next"),r("throw",function(i){throw i}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(i,s){t[i]=e[i]?function(o){return(n=!n)?{value:Ah(e[i](o)),done:i==="return"}:s?s(o):o}:s}}function zJ(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof n4=="function"?n4(e):e[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=e[s]&&function(o){return new Promise(function(a,c){o=e[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function VJ(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function WJ(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function qJ(e){return e&&e.__esModule?e:{default:e}}function ZJ(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function GJ(e,t,n){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,n),n}var KJ=Object.freeze({__proto__:null,__extends:NJ,get __assign(){return t4},__rest:PJ,__decorate:OJ,__param:kJ,__metadata:RJ,__awaiter:BJ,__generator:MJ,__createBinding:DJ,__exportStar:UJ,__values:n4,__read:dI,__spread:LJ,__spreadArrays:FJ,__await:Ah,__asyncGenerator:HJ,__asyncDelegator:jJ,__asyncValues:zJ,__makeTemplateObject:VJ,__importStar:WJ,__importDefault:qJ,__classPrivateFieldGet:ZJ,__classPrivateFieldSet:GJ}),YJ=XE(KJ),tc={},fI;function XJ(){if(fI)return tc;fI=1,Object.defineProperty(tc,"__esModule",{value:!0}),tc.isBrowserCryptoAvailable=tc.getSubtleCrypto=tc.getBrowerCrypto=void 0;function e(){return Pn?.crypto||Pn?.msCrypto||{}}tc.getBrowerCrypto=e;function t(){const r=e();return r.subtle||r.webkitSubtle}tc.getSubtleCrypto=t;function n(){return!!e()&&!!t()}return tc.isBrowserCryptoAvailable=n,tc}var nc={},hI;function JJ(){if(hI)return nc;hI=1,Object.defineProperty(nc,"__esModule",{value:!0}),nc.isBrowser=nc.isNode=nc.isReactNative=void 0;function e(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}nc.isReactNative=e;function t(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}nc.isNode=t;function n(){return!e()&&!t()}return nc.isBrowser=n,nc}(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=YJ;t.__exportStar(XJ(),e),t.__exportStar(JJ(),e)})(uI);function ro(e=3){const t=Date.now()*Math.pow(10,e),n=Math.floor(Math.random()*Math.pow(10,e));return t+n}function rl(e=6){return BigInt(ro(e))}function ws(e,t,n){return{id:n||ro(),jsonrpc:"2.0",method:e,params:t}}function Ch(e,t){return{id:e,jsonrpc:"2.0",result:t}}function um(e,t,n){return{id:e,jsonrpc:"2.0",error:QJ(t,n)}}function QJ(e,t){return typeof e>"u"?cI(oI):(typeof e=="string"&&(e=Object.assign(Object.assign({},cI(Q8)),{message:e})),typeof t<"u"&&(e.data=t),$J(e.code)&&(e=TJ(e.code)),e)}class eQ{}class tQ extends eQ{constructor(){super()}}class nQ extends tQ{constructor(t){super()}}const rQ="^https?:",iQ="^wss?:";function sQ(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(!(!t||!t.length))return t[0]}function pI(e,t){const n=sQ(e);return typeof n>"u"?!1:new RegExp(t).test(n)}function gI(e){return pI(e,rQ)}function mI(e){return pI(e,iQ)}function oQ(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function yI(e){return typeof e=="object"&&"id"in e&&"jsonrpc"in e&&e.jsonrpc==="2.0"}function r4(e){return yI(e)&&"method"in e}function dm(e){return yI(e)&&(io(e)||ji(e))}function io(e){return"result"in e}function ji(e){return"error"in e}class i4 extends nQ{constructor(t){super(t),this.events=new zn.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),this.connection.connected&&this.registerEventListeners()}async connect(t=this.connection){await this.open(t)}async disconnect(){await this.close()}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async request(t,n){return this.requestStrict(ws(t.method,t.params||[],t.id||rl().toString()),n)}async requestStrict(t,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${t.id}`,s=>{ji(s)?i(s.error):r(s.result)});try{await this.connection.send(t,n)}catch(s){i(s)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit("payload",t),dm(t)?this.events.emit(`${t.id}`,t):this.events.emit("message",{type:t.method,data:t.params})}onClose(t){t&&t.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${t.code} ${t.reason?`(${t.reason})`:""}`)),this.events.emit("disconnect")}async open(t=this.connection){this.connection===t&&this.connection.connected||(this.connection.connected&&this.close(),typeof t=="string"&&(await this.connection.open(t),t=this.connection),this.connection=this.setConnection(t),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",t=>this.onPayload(t)),this.connection.on("close",t=>this.onClose(t)),this.connection.on("error",t=>this.events.emit("error",t)),this.connection.on("register_error",t=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const aQ=()=>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"),cQ=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",wI=e=>e.split("?")[0],bI=10,lQ=aQ();class uQ{constructor(t){if(this.url=t,this.events=new zn.exports.EventEmitter,this.registering=!1,!mI(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);this.url=t}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async open(t=this.url){await this.register(t)}async close(){return new Promise((t,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),t()},this.socket.close()})}async send(t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ou(t))}catch(n){this.onError(t.id,n)}}register(t=this.url){if(!mI(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=t,this.registering=!0,new Promise((n,r)=>{const i=uI.isReactNative()?void 0:{rejectUnauthorized:!oQ(t)},s=new lQ(t,[],i);cQ()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),n(s)}})}onOpen(t){t.onmessage=n=>this.onPayload(n),t.onclose=n=>this.onClose(n),this.socket=t,this.registering=!1,this.events.emit("open")}onClose(t){this.socket=void 0,this.registering=!1,this.events.emit("close",t)}onPayload(t){if(typeof t.data>"u")return;const n=typeof t.data=="string"?su(t.data):t.data;this.events.emit("payload",n)}onError(t,n){const r=this.parseError(n),i=r.message||r.toString(),s=um(t,i);this.events.emit("payload",s)}parseError(t,n=this.url){return lI(t,wI(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>bI&&this.events.setMaxListeners(bI)}emitError(t){const n=this.parseError(new Error(t?.message||`WebSocket connection failed for host: ${wI(this.url)}`));return this.events.emit("register_error",n),n}}var dQ=Object.defineProperty,vI=Object.getOwnPropertySymbols,fQ=Object.prototype.hasOwnProperty,hQ=Object.prototype.propertyIsEnumerable,EI=(e,t,n)=>t in e?dQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Nr=(e,t)=>{for(var n in t||(t={}))fQ.call(t,n)&&EI(e,n,t[n]);if(vI)for(var n of vI(t))hQ.call(t,n)&&EI(e,n,t[n]);return e};const AI="wc",CI=2,fm="core",so=`${AI}@2:${fm}:`,pQ={name:fm,logger:"error"},gQ={database:":memory:"},mQ="crypto",xI="client_ed25519_seed",yQ=ve.ONE_DAY,wQ="keychain",bQ="0.3",vQ="messages",EQ="0.3",AQ=ve.SIX_HOURS,CQ="publisher",_I="irn",xQ="error",SI="wss://relay.walletconnect.org",_Q="relayer",hn={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"},SQ="_subscription",zi={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},IQ=.1,s4="2.23.6",Kt={link_mode:"link_mode",relay:"relay"},hm={inbound:"inbound",outbound:"outbound"},$Q="0.3",TQ="WALLETCONNECT_CLIENT_ID",II="WALLETCONNECT_LINK_MODE_APPS",Ci={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},NQ="subscription",PQ="0.3",OQ="pairing",kQ="0.3",xh={wc_pairingDelete:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ve.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ve.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:0},res:{ttl:ve.ONE_DAY,prompt:!1,tag:0}}},vu={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},bs={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},RQ="history",BQ="0.3",MQ="expirer",Vi={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},DQ="0.3",UQ="verify-api",LQ="https://verify.walletconnect.com",$I="https://verify.walletconnect.org",_h=$I,FQ=`${_h}/v3`,HQ=[LQ,$I],jQ="echo",zQ="https://echo.walletconnect.com",oo={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"},rc={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"},vs={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Eu={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Au={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"},Sh={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"},VQ=.1,WQ="event-client",qQ=86400,ZQ="https://pulse.walletconnect.org/batch";function GQ(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,A=0,_=p.length;A!==_&&p[A]===0;)A++,g++;for(var v=(_-A)*u+1>>>0,w=new Uint8Array(v);A!==_;){for(var T=p[A],O=0,D=v-1;(T!==0||O<y)&&D!==-1;D--,O++)T+=256*w[D]>>>0,w[D]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");y=O,A++}for(var F=v-y;F!==v&&w[F]===0;)F++;for(var U=c.repeat(g);F<v;++F)U+=e.charAt(w[F]);return U}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,A=0;p[g]===c;)y++,g++;for(var _=(p.length-g)*l+1>>>0,v=new Uint8Array(_);p[g];){var w=n[p.charCodeAt(g)];if(w===255)return;for(var T=0,O=_-1;(w!==0||T<A)&&O!==-1;O--,T++)w+=a*v[O]>>>0,v[O]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");A=T,g++}if(p[g]!==" "){for(var D=_-A;D!==_&&v[D]===0;)D++;for(var F=new Uint8Array(y+(_-D)),U=y;D!==_;)F[U++]=v[D++];return F}}}function f(p){var g=h(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var KQ=GQ,YQ=KQ;const TI=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},XQ=e=>new TextEncoder().encode(e),JQ=e=>new TextDecoder().decode(e);class QQ{constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class eee{constructor(t,n,r){if(this.name=t,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return NI(this,t)}}class tee{constructor(t){this.decoders=t}or(t){return NI(this,t)}decode(t){const n=t[0],r=this.decoders[n];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const NI=(e,t)=>new tee(Nr(Nr({},e.decoders||{[e.prefix]:e}),t.decoders||{[t.prefix]:t}));class nee{constructor(t,n,r,i){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new QQ(t,n,r),this.decoder=new eee(t,n,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const pm=({name:e,prefix:t,encode:n,decode:r})=>new nee(e,t,n,r),Ih=({prefix:e,name:t,alphabet:n})=>{const{encode:r,decode:i}=YQ(n,t);return pm({prefix:e,name:t,encode:r,decode:s=>TI(i(s))})},ree=(e,t,n,r)=>{const i={};for(let u=0;u<t.length;++u)i[t[u]]=u;let s=e.length;for(;e[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[e[u]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|d,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},iee=(e,t,n)=>{const r=t[t.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>n;)o-=n,s+=t[i&a>>o];if(o&&(s+=t[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Gn=({name:e,prefix:t,bitsPerChar:n,alphabet:r})=>pm({prefix:t,name:e,encode(i){return iee(i,r,n)},decode(i){return ree(i,r,n,e)}}),see=pm({prefix:"\0",name:"identity",encode:e=>JQ(e),decode:e=>XQ(e)});var oee=Object.freeze({__proto__:null,identity:see});const aee=Gn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cee=Object.freeze({__proto__:null,base2:aee});const lee=Gn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var uee=Object.freeze({__proto__:null,base8:lee});const dee=Ih({prefix:"9",name:"base10",alphabet:"0123456789"});var fee=Object.freeze({__proto__:null,base10:dee});const hee=Gn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),pee=Gn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gee=Object.freeze({__proto__:null,base16:hee,base16upper:pee});const mee=Gn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yee=Gn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wee=Gn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bee=Gn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vee=Gn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Eee=Gn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Aee=Gn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Cee=Gn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xee=Gn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _ee=Object.freeze({__proto__:null,base32:mee,base32upper:yee,base32pad:wee,base32padupper:bee,base32hex:vee,base32hexupper:Eee,base32hexpad:Aee,base32hexpadupper:Cee,base32z:xee});const See=Ih({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Iee=Ih({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $ee=Object.freeze({__proto__:null,base36:See,base36upper:Iee});const Tee=Ih({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nee=Ih({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Pee=Object.freeze({__proto__:null,base58btc:Tee,base58flickr:Nee});const Oee=Gn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kee=Gn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ree=Gn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bee=Gn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Mee=Object.freeze({__proto__:null,base64:Oee,base64pad:kee,base64url:Ree,base64urlpad:Bee});const PI=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}"),Dee=PI.reduce((e,t,n)=>(e[n]=t,e),[]),Uee=PI.reduce((e,t,n)=>(e[t.codePointAt(0)]=n,e),[]);function Lee(e){return e.reduce((t,n)=>(t+=Dee[n],t),"")}function Fee(e){const t=[];for(const n of e){const r=Uee[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}const Hee=pm({prefix:"\u{1F680}",name:"base256emoji",encode:Lee,decode:Fee});var jee=Object.freeze({__proto__:null,base256emoji:Hee}),zee=kI,OI=128,Vee=127,Wee=~Vee,qee=Math.pow(2,31);function kI(e,t,n){t=t||[],n=n||0;for(var r=n;e>=qee;)t[n++]=e&255|OI,e/=128;for(;e&Wee;)t[n++]=e&255|OI,e>>>=7;return t[n]=e|0,kI.bytes=n-r+1,t}var Zee=o4,Gee=128,RI=127;function o4(e,r){var n=0,r=r||0,i=0,s=r,o,a=e.length;do{if(s>=a)throw o4.bytes=0,new RangeError("Could not decode varint");o=e[s++],n+=i<28?(o&RI)<<i:(o&RI)*Math.pow(2,i),i+=7}while(o>=Gee);return o4.bytes=s-r,n}var Kee=Math.pow(2,7),Yee=Math.pow(2,14),Xee=Math.pow(2,21),Jee=Math.pow(2,28),Qee=Math.pow(2,35),ete=Math.pow(2,42),tte=Math.pow(2,49),nte=Math.pow(2,56),rte=Math.pow(2,63),ite=function(e){return e<Kee?1:e<Yee?2:e<Xee?3:e<Jee?4:e<Qee?5:e<ete?6:e<tte?7:e<nte?8:e<rte?9:10},ste={encode:zee,decode:Zee,encodingLength:ite},BI=ste;const MI=(e,t,n=0)=>(BI.encode(e,t,n),t),DI=e=>BI.encodingLength(e),a4=(e,t)=>{const n=t.byteLength,r=DI(e),i=r+DI(n),s=new Uint8Array(i+n);return MI(e,s,0),MI(n,s,r),s.set(t,i),new ote(e,n,t,s)};class ote{constructor(t,n,r,i){this.code=t,this.size=n,this.digest=r,this.bytes=i}}const UI=({name:e,code:t,encode:n})=>new ate(e,t,n);class ate{constructor(t,n,r){this.name=t,this.code=n,this.encode=r}digest(t){if(t instanceof Uint8Array){const n=this.encode(t);return n instanceof Uint8Array?a4(this.code,n):n.then(r=>a4(this.code,r))}else throw Error("Unknown type, must be binary type")}}const LI=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),cte=UI({name:"sha2-256",code:18,encode:LI("SHA-256")}),lte=UI({name:"sha2-512",code:19,encode:LI("SHA-512")});var ute=Object.freeze({__proto__:null,sha256:cte,sha512:lte});const FI=0,dte="identity",HI=TI;var fte=Object.freeze({__proto__:null,identity:{code:FI,name:dte,encode:HI,digest:e=>a4(FI,HI(e))}});new TextEncoder,new TextDecoder;const jI=Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr({},oee),cee),uee),fee),gee),_ee),$ee),Pee),Mee),jee);Nr(Nr({},ute),fte);function zI(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function hte(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?zI(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function VI(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const WI=VI("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),c4=VI("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{e=e.substring(1);const t=hte(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),pte=Nr({utf8:WI,"utf-8":WI,hex:jI.base16,latin1:c4,ascii:c4,binary:c4},jI);function gte(e,t="utf8"){const n=pte[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?zI(globalThis.Buffer.from(e,"utf-8")):n.decoder.decode(`${n.prefix}${e}`)}var mte=Object.defineProperty,yte=(e,t,n)=>t in e?mte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ao=(e,t,n)=>yte(e,typeof t!="symbol"?t+"":t,n);class wte{constructor(t,n){this.core=t,this.logger=n,ao(this,"keychain",new Map),ao(this,"name",wQ),ao(this,"version",bQ),ao(this,"initialized",!1),ao(this,"storagePrefix",so),ao(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),ao(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),ao(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),ao(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=Ae("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),ao(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=t,this.logger=vi(n,this.name)}get context(){return Gr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,l8(t))}async getKeyChain(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?u8(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var bte=Object.defineProperty,vte=(e,t,n)=>t in e?bte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mn=(e,t,n)=>vte(e,typeof t!="symbol"?t+"":t,n);class Ete{constructor(t,n,r){this.core=t,this.logger=n,Mn(this,"name",mQ),Mn(this,"keychain"),Mn(this,"randomSessionIdentifier",j8()),Mn(this,"initialized",!1),Mn(this,"clientId"),Mn(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Mn(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Mn(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const i=await this.getClientSeed(),s=i_(i),o=r_(s.publicKey);return this.clientId=o,o}),Mn(this,"generateKeyPair",()=>{this.isInitialized();const i=iY();return this.setPrivateKey(i.publicKey,i.privateKey)}),Mn(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=i_(s),a=this.randomSessionIdentifier;return await IV(a,i,yQ,o)}),Mn(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=sY(a,s);return this.setSymKey(c,o)}),Mn(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||tm(i);return await this.keychain.set(o,i),o}),Mn(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Mn(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Mn(this,"encode",async(i,s,o)=>{this.isInitialized();const a=kS(o),c=ou(s);if(BS(a))return cY(c,o?.encoding);if(RS(a)){const h=a.senderPublicKey,f=a.receiverPublicKey;i=await this.generateSharedKey(h,f)}const l=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return oY({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),Mn(this,"decode",async(i,s,o)=>{this.isInitialized();const a=uY(s,o);if(BS(a)){const c=lY(s,o?.encoding);return su(c)}if(RS(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=aY({symKey:c,encoded:s,encoding:o?.encoding});return su(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Mn(this,"getPayloadType",(i,s=Xr)=>{const o=wh({encoded:i,encoding:s});return mu(o.type)}),Mn(this,"getPayloadSenderPublicKey",(i,s=Xr)=>{const o=wh({encoded:i,encoding:s});return o.senderPublicKey?Zr(o.senderPublicKey,Tr):void 0}),this.core=t,this.logger=vi(n,this.name),this.keychain=r||new wte(this.core,this.logger)}get context(){return Gr(this.logger)}async setPrivateKey(t,n){return await this.keychain.set(t,n),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(xI)}catch{t=j8(),await this.keychain.set(xI,t)}return gte(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Ate=Object.defineProperty,Cte=Object.defineProperties,xte=Object.getOwnPropertyDescriptors,qI=Object.getOwnPropertySymbols,_te=Object.prototype.hasOwnProperty,Ste=Object.prototype.propertyIsEnumerable,l4=(e,t,n)=>t in e?Ate(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ite=(e,t)=>{for(var n in t||(t={}))_te.call(t,n)&&l4(e,n,t[n]);if(qI)for(var n of qI(t))Ste.call(t,n)&&l4(e,n,t[n]);return e},$te=(e,t)=>Cte(e,xte(t)),xi=(e,t,n)=>l4(e,typeof t!="symbol"?t+"":t,n);class Tte extends uJ{constructor(t,n){super(t,n),this.logger=t,this.core=n,xi(this,"messages",new Map),xi(this,"messagesWithoutClientAck",new Map),xi(this,"name",vQ),xi(this,"version",EQ),xi(this,"initialized",!1),xi(this,"storagePrefix",so),xi(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),xi(this,"set",async(r,i,s)=>{this.isInitialized();const o=Fi(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),s===hm.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,$te(Ite({},c),{[o]:i}))}return await this.persist(),o}),xi(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),xi(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),xi(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=Fi(i);return typeof s[o]<"u"}),xi(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=Fi(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),xi(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=vi(t,this.name),this.core=n}get context(){return Gr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(t){await this.core.storage.setItem(this.storageKey,l8(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,l8(t))}async getRelayerMessages(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?u8(t):void 0}async getRelayerMessagesWithoutClientAck(){const t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?u8(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Nte=Object.defineProperty,Pte=Object.defineProperties,Ote=Object.getOwnPropertyDescriptors,ZI=Object.getOwnPropertySymbols,kte=Object.prototype.hasOwnProperty,Rte=Object.prototype.propertyIsEnumerable,u4=(e,t,n)=>t in e?Nte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,a0=(e,t)=>{for(var n in t||(t={}))kte.call(t,n)&&u4(e,n,t[n]);if(ZI)for(var n of ZI(t))Rte.call(t,n)&&u4(e,n,t[n]);return e},GI=(e,t)=>Pte(e,Ote(t)),Wi=(e,t,n)=>u4(e,typeof t!="symbol"?t+"":t,n);class Bte extends dJ{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,Wi(this,"events",new zn.exports.EventEmitter),Wi(this,"name",CQ),Wi(this,"queue",new Map),Wi(this,"publishTimeout",ve.toMiliseconds(ve.ONE_MINUTE)),Wi(this,"initialPublishTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),Wi(this,"needsTransportRestart",!1),Wi(this,"publish",async(r,i,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const d=s?.ttl||AQ,h=s?.prompt||!1,f=s?.tag||0,p=s?.id||rl().toString(),g=i0(nm().protocol),y={id:p,method:s?.publishMethod||g.publish,params:a0({topic:r,message:i,ttl:d,prompt:h,tag:f,attestation:s?.attestation},s?.tvf)},A=`Failed to publish payload, please try again. id:${p} tag:${f}`;try{$n((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),$n((c=y.params)==null?void 0:c.tag)&&((l=y.params)==null||delete l.tag);const _=new Promise(async v=>{const w=({id:O})=>{var D;((D=y.id)==null?void 0:D.toString())===O.toString()&&(this.removeRequestFromQueue(O),this.relayer.events.removeListener(hn.publish,w),v())};this.relayer.events.on(hn.publish,w);const T=Js(new Promise((O,D)=>{this.rpcPublish(y,s).then(O).catch(F=>{this.logger.warn(F,F?.message),D(F)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${f}`);try{await T,this.events.removeListener(hn.publish,w)}catch(O){this.queue.set(p,{request:y,opts:s,attempt:1}),this.logger.warn(O,O?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await Js(_,this.publishTimeout,A)}catch(_){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(_),(u=s?.internal)!=null&&u.throwOnFailedPublish)throw _}finally{this.queue.delete(p)}}),Wi(this,"publishCustom",async r=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:l,opts:u={}}=r,{attestation:d,tvf:h,publishMethod:f,prompt:p,tag:g,ttl:y=ve.FIVE_MINUTES}=u,A=u.id||rl().toString(),_=i0(nm().protocol),v=f||_.publish,w={id:A,method:v,params:a0(GI(a0({},l),{ttl:y,prompt:p,tag:g,attestation:d}),h)},T=`Failed to publish custom payload, please try again. id:${A} tag:${g}`;try{$n((i=w.params)==null?void 0:i.prompt)&&((s=w.params)==null||delete s.prompt),$n((o=w.params)==null?void 0:o.tag)&&((a=w.params)==null||delete a.tag);const O=new Promise(async D=>{const F=({id:j})=>{var W;((W=w.id)==null?void 0:W.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(hn.publish,F),D())};this.relayer.events.on(hn.publish,F);const U=Js(new Promise((j,W)=>{this.rpcPublish(w,u).then(j).catch(S=>{this.logger.warn(S,S?.message),W(S)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${v} id:${A} tag:${g}`);try{await U,this.events.removeListener(hn.publish,F)}catch(j){this.queue.set(A,{request:w,opts:u,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:A,payload:l,opts:u}}),await Js(O,this.publishTimeout,T)}catch(O){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(O),(c=u?.internal)!=null&&c.throwOnFailedPublish)throw O}finally{this.queue.delete(A)}}),Wi(this,"on",(r,i)=>{this.events.on(r,i)}),Wi(this,"once",(r,i)=>{this.events.once(r,i)}),Wi(this,"off",(r,i)=>{this.events.off(r,i)}),Wi(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=t,this.logger=vi(n,this.name),this.registerEventListeners()}get context(){return Gr(this.logger)}async rpcPublish(t,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:t});const r=await this.relayer.request(t);return this.relayer.events.emit(hn.publish,a0(a0({},t),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async(t,n)=>{var r;const i=t.attempt+1;this.queue.set(n,GI(a0({},t),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${(r=t.request.params)==null?void 0:r.tag}, attempt: ${i}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(wu.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(hn.connection_stalled);return}this.checkQueue()}),this.relayer.on(hn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}}var Mte=Object.defineProperty,Dte=(e,t,n)=>t in e?Mte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,c0=(e,t,n)=>Dte(e,typeof t!="symbol"?t+"":t,n);class Ute{constructor(){c0(this,"map",new Map),c0(this,"set",(t,n)=>{const r=this.get(t);this.exists(t,n)||this.map.set(t,[...r,n])}),c0(this,"get",t=>this.map.get(t)||[]),c0(this,"exists",(t,n)=>this.get(t).includes(n)),c0(this,"delete",(t,n)=>{if(typeof n>"u"){this.map.delete(t);return}if(!this.map.has(t))return;const r=this.get(t);if(!this.exists(t,n))return;const i=r.filter(s=>s!==n);if(!i.length){this.map.delete(t);return}this.map.set(t,i)}),c0(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Lte=Object.defineProperty,Fte=Object.defineProperties,Hte=Object.getOwnPropertyDescriptors,KI=Object.getOwnPropertySymbols,jte=Object.prototype.hasOwnProperty,zte=Object.prototype.propertyIsEnumerable,d4=(e,t,n)=>t in e?Lte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$h=(e,t)=>{for(var n in t||(t={}))jte.call(t,n)&&d4(e,n,t[n]);if(KI)for(var n of KI(t))zte.call(t,n)&&d4(e,n,t[n]);return e},f4=(e,t)=>Fte(e,Hte(t)),jt=(e,t,n)=>d4(e,typeof t!="symbol"?t+"":t,n);class Vte extends pJ{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,jt(this,"subscriptions",new Map),jt(this,"topicMap",new Ute),jt(this,"events",new zn.exports.EventEmitter),jt(this,"name",NQ),jt(this,"version",PQ),jt(this,"pending",new Map),jt(this,"cached",[]),jt(this,"initialized",!1),jt(this,"storagePrefix",so),jt(this,"subscribeTimeout",ve.toMiliseconds(ve.ONE_MINUTE)),jt(this,"initialSubscribeTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),jt(this,"clientId"),jt(this,"batchSubscribeTopicsLimit",500),jt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),jt(this,"subscribe",async(r,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=nm(i),a={topic:r,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),jt(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),jt(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),jt(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),jt(this,"on",(r,i)=>{this.events.on(r,i)}),jt(this,"once",(r,i)=>{this.events.once(r,i)}),jt(this,"off",(r,i)=>{this.events.off(r,i)}),jt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),jt(this,"start",async()=>{await this.onConnect()}),jt(this,"stop",async()=>{await this.onDisconnect()}),jt(this,"restart",async()=>{await this.restore(),await this.onRestart()}),jt(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),jt(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(wu.pulse,async()=>{await this.checkPending()}),this.events.on(Ci.created,async r=>{const i=Ci.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(Ci.deleted,async r=>{const i=Ci.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=t,this.logger=vi(n,this.name),this.clientId=""}get context(){return Gr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(t,n){let r=!1;try{r=this.getSubscription(t).topic===n}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,n){const r=this.topicMap.get(t);await Promise.all(r.map(async i=>await this.unsubscribeById(t,i,n)))}async unsubscribeById(t,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:n,opts:r}});try{const i=nm(r);await this.restartToComplete({topic:t,id:n,relay:i}),await this.rpcUnsubscribe(t,n,i);const s=Gt("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(t,n,r){var i,s;const o=await this.getSubscriptionId(t);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===Kt.relay)&&await this.restartToComplete({topic:t,id:t,relay:n});const a={method:i0(n.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{if(r?.transportType===Kt.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(d=>this.logger.warn(d))},ve.toMiliseconds(ve.ONE_SECOND)),o;const l=new Promise(async d=>{const h=f=>{f.topic===t&&(this.events.removeListener(Ci.created,h),d(f.id))};this.events.on(Ci.created,h);try{const f=await Js(new Promise((p,g)=>{this.relayer.request(a).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${t} failed, please try again`);this.events.removeListener(Ci.created,h),d(f)}catch{}}),u=await Js(l,this.subscribeTimeout,`Subscribing to ${t} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${t} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(hn.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(t){if(!t.length)return!0;const n=t[0].relay,r={method:i0(n.protocol).batchSubscribe,params:{topics:t.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{return await Js(new Promise((i,s)=>{this.relayer.request(r).then(i).catch(o=>{this.logger.warn(o),s(o)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(hn.connection_stalled),!1}}async rpcBatchFetchMessages(t){if(!t.length)return;const n=t[0].relay,r={method:i0(n.protocol).batchFetchMessages,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await Js(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(hn.connection_stalled)}return i}rpcUnsubscribe(t,n,r){const i={method:i0(r.protocol).unsubscribe,params:{topic:t,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(t,n){this.setSubscription(t,f4($h({},n),{id:t})),this.pending.delete(n.topic)}onBatchSubscribe(t){t.length&&t.forEach(n=>{this.setSubscription(n.id,$h({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(t,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,t)&&this.deleteSubscription(n,r),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:n}),this.addSubscription(t,n)}addSubscription(t,n){this.subscriptions.set(t,$h({},n)),this.topicMap.set(n.topic,t),this.events.emit(Ci.created,n)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});const n=this.subscriptions.get(t);if(!n){const{message:r}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(r)}return n}deleteSubscription(t,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:n});const r=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(r.topic,t),this.events.emit(Ci.deleted,f4($h({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ci.sync)}async onRestart(){if(this.cached.length){const t=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const i=t.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(Ci.resubscribed)}async restore(){try{const t=await this.getRelayerSubscriptions();if(typeof t>"u"||!t.length)return;if(this.subscriptions.size&&!t.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){if(t.length){if(!await this.rpcBatchSubscribe(t)){this.logger.warn(`Batch subscribe failed for ${t.length} topics, adding to pending for retry`),t.forEach(n=>{this.pending.set(n.topic,n)});return}this.onBatchSubscribe(await Promise.all(t.map(async n=>f4($h({},n),{id:await this.getSubscriptionId(n.topic)}))))}}async batchFetchMessages(t){if(!t.length)return;this.logger.trace(`Fetching batch messages for ${t.length} subscriptions`);const n=await this.rpcBatchFetchMessages(t);n&&n.messages&&(await xZ(ve.toMiliseconds(ve.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(t){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(t),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(t){return Fi(t+await this.getClientId())}}var Wte=Object.defineProperty,YI=Object.getOwnPropertySymbols,qte=Object.prototype.hasOwnProperty,Zte=Object.prototype.propertyIsEnumerable,h4=(e,t,n)=>t in e?Wte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,XI=(e,t)=>{for(var n in t||(t={}))qte.call(t,n)&&h4(e,n,t[n]);if(YI)for(var n of YI(t))Zte.call(t,n)&&h4(e,n,t[n]);return e},pt=(e,t,n)=>h4(e,typeof t!="symbol"?t+"":t,n);class Gte extends fJ{constructor(t){var n;super(t),pt(this,"protocol","wc"),pt(this,"version",2),pt(this,"core"),pt(this,"logger"),pt(this,"events",new zn.exports.EventEmitter),pt(this,"provider"),pt(this,"messages"),pt(this,"subscriber"),pt(this,"publisher"),pt(this,"name",_Q),pt(this,"transportExplicitlyClosed",!1),pt(this,"initialized",!1),pt(this,"connectionAttemptInProgress",!1),pt(this,"relayUrl"),pt(this,"projectId"),pt(this,"packageName"),pt(this,"bundleId"),pt(this,"hasExperiencedNetworkDisruption",!1),pt(this,"pingTimeout"),pt(this,"heartBeatTimeout",ve.toMiliseconds(ve.THIRTY_SECONDS+ve.FIVE_SECONDS)),pt(this,"reconnectTimeout"),pt(this,"connectPromise"),pt(this,"reconnectInProgress",!1),pt(this,"requestsInFlight",[]),pt(this,"connectTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),pt(this,"stalledRestartInProgress",!1),pt(this,"stalledRestartTimeout"),pt(this,"stalledRestartBackoff",0),pt(this,"stalledRestartBaseInterval",ve.toMiliseconds(ve.ONE_SECOND*2)),pt(this,"stalledRestartMaxInterval",ve.toMiliseconds(ve.THIRTY_SECONDS)),pt(this,"request",async r=>{var i,s;this.logger.debug("Publishing Request Payload");const o=r.id||rl().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const a=`${o}:${((s=r.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),pt(this,"resetPingTimeout",()=>{Rg()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),pt(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),pt(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(hn.connect)}),pt(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),pt(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(hn.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(i=>this.logger.warn(i))}),pt(this,"registerProviderListeners",()=>{this.provider.on(zi.payload,this.onPayloadHandler),this.provider.on(zi.connect,this.onConnectHandler),this.provider.on(zi.disconnect,this.onDisconnectHandler),this.provider.on(zi.error,this.onProviderErrorHandler)}),this.core=t.core,this.logger=G8({logger:(n=t.logger)!=null?n:xQ,name:this.name}),this.messages=new Tte(this.logger,t.core),this.subscriber=new Vte(this,this.logger),this.publisher=new Bte(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||SI,cZ()?this.packageName=t7():lZ()&&(this.bundleId=t7()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(t=>this.logger.warn(t,t?.message))}get context(){return Gr(this.logger)}get connected(){var t,n,r;return((r=(n=(t=this.provider)==null?void 0:t.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var t,n,r;return((r=(n=(t=this.provider)==null?void 0:t.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(t,n,r){this.isInitialized(),await this.publisher.publish(t,n,r),await this.recordMessageEvent({topic:t,message:n,publishedAt:Date.now(),transportType:Kt.relay},hm.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,n){var r,i,s;this.isInitialized(),(!(n!=null&&n.transportType)||n?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=n?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=n?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(t))==null?void 0:s[0])||"",c;const l=u=>{u.topic===t&&(this.subscriber.off(Ci.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(Ci.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(t,XI({internal:{throwOnFailedPublish:o}},n)).catch(h=>{o&&d(h)})||a,u()})]),a}async unsubscribe(t,n){this.isInitialized(),await this.subscriber.unsubscribe(t,n)}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Js(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(t){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(n,r)=>{await this.connect(t).then(n).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(t){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await XS())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(t){if(t?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const n=t.sort((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(t,n){const{topic:r}=t;if(!n.sessionExists){const i=mn(ve.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(hn.message,t),await this.recordMessageEvent(t,hm.inbound)}async connect(t){await this.confirmOnlineStateOrThrow(),t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let n=1;for(;n<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise(async(r,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(zi.disconnect,s),await Js(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(zi.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(zi.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(zi.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,ve.toMiliseconds(n*1))),n++}}startPingTimeout(){var t,n,r,i,s;if(Rg())try{(n=(t=this.provider)==null?void 0:t.connection)!=null&&n.socket&&((s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new i4(new uQ(pZ({sdkVersion:s4,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(t,n){const{topic:r,message:i}=t;await this.messages.set(r,i,n)}async shouldIgnoreMessageEvent(t){const{topic:n,message:r}=t;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(n))return this.logger.warn(`Ignoring message for unknown topic ${n}`),!0;const i=this.messages.has(n,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),r4(t)){if(!t.method.endsWith(SQ))return;const n=t.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:Kt.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(XI({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else dm(t)&&this.events.emit(hn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,hm.inbound),this.events.emit(hn.message,t))}async acknowledgePayload(t){const n=Ch(t.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(zi.payload,this.onPayloadHandler),this.provider.off(zi.connect,this.onConnectHandler),this.provider.off(zi.disconnect,this.onDisconnectHandler),this.provider.off(zi.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await XS();uX(async n=>{t!==n&&(t=n,n?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(wu.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&hX())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}}),this.events.on(hn.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const n=this.stalledRestartBackoff===0?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${n?` in ${n}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(r){this.logger.error(r,r?.message)}finally{this.stalledRestartInProgress=!1}},n)})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(hn.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(t=>this.logger.error(t,t?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},ve.toMiliseconds(IQ)))))}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function Kte(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function JI(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function QI(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Yte="[object RegExp]",Xte="[object String]",Jte="[object Number]",Qte="[object Boolean]",e$="[object Arguments]",ene="[object Symbol]",tne="[object Date]",nne="[object Map]",rne="[object Set]",ine="[object Array]",sne="[object Function]",one="[object ArrayBuffer]",p4="[object Object]",ane="[object Error]",cne="[object DataView]",lne="[object Uint8Array]",une="[object Uint8ClampedArray]",dne="[object Uint16Array]",fne="[object Uint32Array]",hne="[object BigUint64Array]",pne="[object Int8Array]",gne="[object Int16Array]",mne="[object Int32Array]",yne="[object BigInt64Array]",wne="[object Float32Array]",bne="[object Float64Array]";function t$(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(e)==="[object Object]":!1}function vne(e,t,n){return Th(e,t,void 0,void 0,void 0,void 0,n)}function Th(e,t,n,r,i,s,o){const a=o(e,t,n,r,i,s);if(a!==void 0)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return e===t;case"number":return e===t||Object.is(e,t);case"function":return e===t;case"object":return Nh(e,t,s,o)}return Nh(e,t,s,o)}function Nh(e,t,n,r){if(Object.is(e,t))return!0;let i=QI(e),s=QI(t);if(i===e$&&(i=p4),s===e$&&(s=p4),i!==s)return!1;switch(i){case Xte:return e.toString()===t.toString();case Jte:{const c=e.valueOf(),l=t.valueOf();return Kte(c,l)}case Qte:case tne:case ene:return Object.is(e.valueOf(),t.valueOf());case Yte:return e.source===t.source&&e.flags===t.flags;case sne:return e===t}n=n??new Map;const o=n.get(e),a=n.get(t);if(o!=null&&a!=null)return o===t;n.set(e,t),n.set(t,e);try{switch(i){case nne:{if(e.size!==t.size)return!1;for(const[c,l]of e.entries())if(!t.has(c)||!Th(l,t.get(c),c,e,t,n,r))return!1;return!0}case rne:{if(e.size!==t.size)return!1;const c=Array.from(e.values()),l=Array.from(t.values());for(let u=0;u<c.length;u++){const d=c[u],h=l.findIndex(f=>Th(d,f,void 0,e,t,n,r));if(h===-1)return!1;l.splice(h,1)}return!0}case ine:case lne:case une:case dne:case fne:case hne:case pne:case gne:case mne:case yne:case wne:case bne:{if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let c=0;c<e.length;c++)if(!Th(e[c],t[c],c,e,t,n,r))return!1;return!0}case one:return e.byteLength!==t.byteLength?!1:Nh(new Uint8Array(e),new Uint8Array(t),n,r);case cne:return e.byteLength!==t.byteLength||e.byteOffset!==t.byteOffset?!1:Nh(new Uint8Array(e),new Uint8Array(t),n,r);case ane:return e.name===t.name&&e.message===t.message;case p4:{if(!(Nh(e.constructor,t.constructor,n,r)||t$(e)&&t$(t)))return!1;const c=[...Object.keys(e),...JI(e)],l=[...Object.keys(t),...JI(t)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],h=e[d];if(!Object.hasOwn(t,d))return!1;const f=t[d];if(!Th(h,f,d,e,t,n,r))return!1}return!0}default:return!1}}finally{n.delete(e),n.delete(t)}}function Ene(){}function Ane(e,t){return vne(e,t,Ene)}var Cne=Object.defineProperty,n$=Object.getOwnPropertySymbols,xne=Object.prototype.hasOwnProperty,_ne=Object.prototype.propertyIsEnumerable,g4=(e,t,n)=>t in e?Cne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,r$=(e,t)=>{for(var n in t||(t={}))xne.call(t,n)&&g4(e,n,t[n]);if(n$)for(var n of n$(t))_ne.call(t,n)&&g4(e,n,t[n]);return e},ei=(e,t,n)=>g4(e,typeof t!="symbol"?t+"":t,n);class Cu extends hJ{constructor(t,n,r,i=so,s=void 0){super(t,n,r,i),this.core=t,this.logger=n,this.name=r,ei(this,"map",new Map),ei(this,"version",$Q),ei(this,"cached",[]),ei(this,"initialized",!1),ei(this,"getKey"),ei(this,"storagePrefix",so),ei(this,"recentlyDeleted",[]),ei(this,"recentlyDeletedLimit",200),ei(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!$n(o)?this.map.set(this.getKey(o),o):HY(o)?this.map.set(o.id,o):jY(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ei(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),ei(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ei(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Ane(a[c],o[c]))):this.values)),ei(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=r$(r$({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ei(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=vi(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Gr(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(t){this.recentlyDeleted.push(t),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){const n=this.map.get(t);if(!n){if(this.recentlyDeleted.includes(t)){const{message:i}=Ae("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(i),new Error(i)}const{message:r}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(r),new Error(r)}return n}async persist(){await this.setDataStore(this.values)}async restore(){try{const t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){const{message:n}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Sne=Object.defineProperty,Ine=(e,t,n)=>t in e?Sne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,bt=(e,t,n)=>Ine(e,typeof t!="symbol"?t+"":t,n);class $ne{constructor(t,n){this.core=t,this.logger=n,bt(this,"name",OQ),bt(this,"version",kQ),bt(this,"events",new zn.exports),bt(this,"pairings"),bt(this,"initialized",!1),bt(this,"storagePrefix",so),bt(this,"ignoredPayloadTypes",[ec]),bt(this,"registeredMethods",[]),bt(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),bt(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),bt(this,"create",async r=>{this.isInitialized();const i=j8(),s=await this.core.crypto.setSymKey(i),o=mn(ve.FIVE_MINUTES),a={protocol:_I},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},l=LS({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(vu.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r?.transportType,internal:r?.internal}),{topic:s,uri:l}}),bt(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[oo.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=US(r.uri);i.props.properties.topic=s,i.addTrace(oo.pairing_uri_validation_success),i.addTrace(oo.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),i.addTrace(oo.existing_pairing),u.active)throw i.setError(rc.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(oo.pairing_not_expired)}const d=c||mn(ve.FIVE_MINUTES),h={topic:s,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(s,d),await this.pairings.set(s,h),i.addTrace(oo.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(vu.create,h),i.addTrace(oo.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(oo.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(rc.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(f){throw i.setError(rc.subscribe_pairing_topic_failure),f}return i.addTrace(oo.subscribe_pairing_topic_success),h}),bt(this,"activate",async({topic:r})=>{this.isInitialized();const i=mn(ve.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),bt(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=uu();this.events.once(Rt("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),bt(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),bt(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),bt(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),bt(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Gt("USER_DISCONNECTED")),await this.deletePairing(i))}),bt(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return LS({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),bt(this,"sendRequest",async(r,i,s)=>{const o=ws(i,s),a=await this.core.crypto.encode(r,o),c=xh[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),bt(this,"sendResult",async(r,i,s)=>{const o=Ch(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=xh[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),bt(this,"sendError",async(r,i,s)=>{const o=um(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=xh[c]?xh[c].res:xh.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),bt(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,Gt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),bt(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>Qs(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),bt(this,"onRelayEventRequest",async r=>{const{topic:i,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),bt(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s}=r,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),bt(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(vu.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),bt(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{io(i)?this.events.emit(Rt("pairing_ping",s),{}):ji(i)&&this.events.emit(Rt("pairing_ping",s),{error:i.error})},500)}),bt(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(vu.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),bt(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=Gt("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),bt(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(Gt("WC_METHOD_UNSUPPORTED",r))}),bt(this,"isValidPair",(r,i)=>{var s;if(!Jr(r)){const{message:a}=Ae("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(!FY(r.uri)){const{message:a}=Ae("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(rc.malformed_pairing_uri),new Error(a)}const o=US(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=Ae("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=Ae("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&ve.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(rc.pairing_expired);const{message:a}=Ae("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),bt(this,"isValidPing",async r=>{if(!Jr(r)){const{message:s}=Ae("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),bt(this,"isValidDisconnect",async r=>{if(!Jr(r)){const{message:s}=Ae("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),bt(this,"isValidPairingTopic",async r=>{if(!yn(r,!1)){const{message:i}=Ae("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=Ae("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(Qs(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=Ae("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=t,this.logger=vi(n,this.name),this.pairings=new Cu(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Gr(this.logger)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(hn.message,async t=>{const{topic:n,message:r,transportType:i}=t;if(this.pairings.keys.includes(n)&&i!==Kt.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);r4(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):dm(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:n,payload:s}),this.core.history.delete(n,s.id)),await this.core.relayer.messages.ack(n,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Vi.expired,async t=>{const{topic:n}=s7(t.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(vu.expire,{topic:n}))})}}var Tne=Object.defineProperty,Nne=(e,t,n)=>t in e?Tne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Kn=(e,t,n)=>Nne(e,typeof t!="symbol"?t+"":t,n);class Pne extends lJ{constructor(t,n){super(t,n),this.core=t,this.logger=n,Kn(this,"records",new Map),Kn(this,"events",new zn.exports.EventEmitter),Kn(this,"name",RQ),Kn(this,"version",BQ),Kn(this,"cached",[]),Kn(this,"initialized",!1),Kn(this,"storagePrefix",so),Kn(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Kn(this,"set",(r,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:s,expiry:mn(ve.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(bs.created,o)}),Kn(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=ji(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(bs.updated,i))}),Kn(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Kn(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===r){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(bs.deleted,s)}}),this.persist()}),Kn(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Kn(this,"on",(r,i)=>{this.events.on(r,i)}),Kn(this,"once",(r,i)=>{this.events.once(r,i)}),Kn(this,"off",(r,i)=>{this.events.off(r,i)}),Kn(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=vi(n,this.name)}get context(){return Gr(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 t=[];return this.values.forEach(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:ws(n.request.method,n.request.params,n.id),chainId:n.chainId};return t.push(r)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();const n=this.records.get(t);if(!n){const{message:r}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(bs.sync)}async restore(){try{const t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){const{message:n}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(bs.created,t=>{const n=bs.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(bs.updated,t=>{const n=bs.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(bs.deleted,t=>{const n=bs.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.core.heartbeat.on(wu.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(n=>{ve.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(bs.deleted,n,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var One=Object.defineProperty,kne=(e,t,n)=>t in e?One(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hr=(e,t,n)=>kne(e,typeof t!="symbol"?t+"":t,n);class Rne extends gJ{constructor(t,n){super(t,n),this.core=t,this.logger=n,hr(this,"expirations",new Map),hr(this,"events",new zn.exports.EventEmitter),hr(this,"name",MQ),hr(this,"version",DQ),hr(this,"cached",[]),hr(this,"initialized",!1),hr(this,"storagePrefix",so),hr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),hr(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),hr(this,"set",(r,i)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Vi.created,{target:s,expiration:o})}),hr(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),hr(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Vi.deleted,{target:i,expiration:s})}}),hr(this,"on",(r,i)=>{this.events.on(r,i)}),hr(this,"once",(r,i)=>{this.events.once(r,i)}),hr(this,"off",(r,i)=>{this.events.off(r,i)}),hr(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=vi(n,this.name)}get context(){return Gr(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(t){if(typeof t=="string")return gZ(t);if(typeof t=="number")return mZ(t);const{message:n}=Ae("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(n)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Vi.sync)}async restore(){try{const t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){const{message:n}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){const n=this.expirations.get(t);if(!n){const{message:r}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(t,n){const{expiry:r}=n;ve.toMiliseconds(r)-Date.now()<=0&&this.expire(t,n)}expire(t,n){this.expirations.delete(t),this.events.emit(Vi.expired,{target:t,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,n)=>this.checkExpiry(n,t))}registerEventListeners(){this.core.heartbeat.on(wu.pulse,()=>this.checkExpirations()),this.events.on(Vi.created,t=>{const n=Vi.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Vi.expired,t=>{const n=Vi.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Vi.deleted,t=>{const n=Vi.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()})}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Bne=Object.defineProperty,Mne=(e,t,n)=>t in e?Bne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wn=(e,t,n)=>Mne(e,typeof t!="symbol"?t+"":t,n);class Dne extends mJ{constructor(t,n,r){super(t,n,r),this.core=t,this.logger=n,this.store=r,wn(this,"name",UQ),wn(this,"abortController"),wn(this,"isDevEnv"),wn(this,"verifyUrlV3",FQ),wn(this,"storagePrefix",so),wn(this,"version",CI),wn(this,"publicKey"),wn(this,"fetchPromise"),wn(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&ve.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),wn(this,"register",async i=>{if(!Yd()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=Kl(),u=this.startAbortTimer(ve.ONE_SECOND*5),d=await new Promise((h,f)=>{const p=()=>{window.removeEventListener("message",y),l.body.removeChild(g),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const y=A=>{if(A.data&&typeof A.data=="string")try{const _=JSON.parse(A.data);if(_.type==="verify_attestation"){if(Gb(_.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",y),h(_.attestation===null?"":_.attestation)}}catch(_){this.logger.warn(_)}};l.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug(d,"jwt attestation"),d}catch(l){this.logger.warn(l)}return""}),wn(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Gb(s).payload.id!==a)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(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),wn(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(ve.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),wn(this,"getVerifyUrl",i=>{let s=i||_h;return HQ.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${_h}`),s=_h),s}),wn(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(ve.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),wn(this,"persistPublicKey",async i=>{this.logger.debug(i,"persisting public key to local storage"),await this.store.setItem(this.storeKey,i),this.publicKey=i}),wn(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),wn(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),wn(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),wn(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),wn(this,"validateAttestation",(i,s)=>{const o=fY(i,s.publicKey),a={hasExpired:ve.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=vi(n,this.name),this.abortController=new AbortController,this.isDevEnv=d8(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Gr(this.logger)}startAbortTimer(t){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ve.toMiliseconds(t))}}var Une=Object.defineProperty,Lne=(e,t,n)=>t in e?Une(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,i$=(e,t,n)=>Lne(e,typeof t!="symbol"?t+"":t,n);class Fne extends yJ{constructor(t,n){super(t,n),this.projectId=t,this.logger=n,i$(this,"context",jQ),i$(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${zQ}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=vi(n,this.context)}}var Hne=Object.defineProperty,s$=Object.getOwnPropertySymbols,jne=Object.prototype.hasOwnProperty,zne=Object.prototype.propertyIsEnumerable,m4=(e,t,n)=>t in e?Hne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ph=(e,t)=>{for(var n in t||(t={}))jne.call(t,n)&&m4(e,n,t[n]);if(s$)for(var n of s$(t))zne.call(t,n)&&m4(e,n,t[n]);return e},Dn=(e,t,n)=>m4(e,typeof t!="symbol"?t+"":t,n);class Vne extends wJ{constructor(t,n,r=!0){super(t,n,r),this.core=t,this.logger=n,Dn(this,"context",WQ),Dn(this,"storagePrefix",so),Dn(this,"storageVersion",VQ),Dn(this,"events",new Map),Dn(this,"shouldPersist",!1),Dn(this,"init",async()=>{if(!d8())try{const i={eventId:a7(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:r7(this.core.relayer.protocol,this.core.relayer.version,s4)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Dn(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=a7(),u=this.core.projectId||"",d=Date.now(),h=Ph({eventId:l,timestamp:d,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),Dn(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Ph(Ph({},a),this.setMethods(a.eventId))}),Dn(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Dn(this,"setEventListeners",()=>{this.core.heartbeat.on(wu.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{ve.fromMiliseconds(Date.now())-ve.fromMiliseconds(i.timestamp)>qQ&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Dn(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Dn(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Dn(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Dn(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Dn(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Ph(Ph({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Dn(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Dn(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${ZQ}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${s4}${s}`,{method:"POST",body:JSON.stringify(i)})}),Dn(this,"getAppDomain",()=>n7().url),this.logger=vi(n,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var Wne=Object.defineProperty,o$=Object.getOwnPropertySymbols,qne=Object.prototype.hasOwnProperty,Zne=Object.prototype.propertyIsEnumerable,y4=(e,t,n)=>t in e?Wne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,a$=(e,t)=>{for(var n in t||(t={}))qne.call(t,n)&&y4(e,n,t[n]);if(o$)for(var n of o$(t))Zne.call(t,n)&&y4(e,n,t[n]);return e},qt=(e,t,n)=>y4(e,typeof t!="symbol"?t+"":t,n);class w4 extends sJ{constructor(t){var n;super(t),qt(this,"protocol",AI),qt(this,"version",CI),qt(this,"name",fm),qt(this,"relayUrl"),qt(this,"projectId"),qt(this,"customStoragePrefix"),qt(this,"events",new zn.exports.EventEmitter),qt(this,"logger"),qt(this,"heartbeat"),qt(this,"relayer"),qt(this,"crypto"),qt(this,"storage"),qt(this,"history"),qt(this,"expirer"),qt(this,"pairing"),qt(this,"verify"),qt(this,"echoClient"),qt(this,"linkModeSupportedApps"),qt(this,"eventClient"),qt(this,"initialized",!1),qt(this,"logChunkController"),qt(this,"on",(a,c)=>this.events.on(a,c)),qt(this,"once",(a,c)=>this.events.once(a,c)),qt(this,"off",(a,c)=>this.events.off(a,c)),qt(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),qt(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Kt.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(t?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||SI,this.customStoragePrefix=t!=null&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";const i=Z_({level:typeof t?.logger=="string"&&t.logger?t.logger:pQ.logger,name:fm}),{logger:s,chunkLoggerController:o}=a8({opts:i,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=o,(n=this.logChunkController)!=null&&n.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=vi(s,this.name),this.heartbeat=new K8,this.crypto=new Ete(this,this.logger,t?.keychain),this.history=new Pne(this,this.logger),this.expirer=new Rne(this,this.logger),this.storage=t!=null&&t.storage?t.storage:new nJ(a$(a$({},gQ),t?.storageOptions)),this.relayer=new Gte({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new $ne(this,this.logger),this.verify=new Dne(this,this.logger,this.storage),this.echoClient=new Fne(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Vne(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){const n=new w4(t);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(TQ,r),n}get context(){return Gr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var t;return(t=this.logChunkController)==null?void 0:t.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(t){this.linkModeSupportedApps.includes(t)||(this.linkModeSupportedApps.push(t),await this.storage.setItem(II,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.linkModeSupportedApps=await this.storage.getItem(II)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(t,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(t.message),t}}getGlobalCore(t=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${t}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(t){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=t.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=t}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const Gne=w4,c$="wc",l$=2,u$="client",b4=`${c$}@${l$}:${u$}:`,v4={name:u$,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},d$="WALLETCONNECT_DEEPLINK_CHOICE",Kne="proposal",f$="Proposal expired",Yne="session",l0=ve.SEVEN_DAYS,Xne="engine",Yn={wc_sessionPropose:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1114},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:ve.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:ve.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1119}}},E4={min:ve.FIVE_MINUTES,max:ve.SEVEN_DAYS},co={idle:"IDLE",active:"ACTIVE"},Jne={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},Qne="request",ere=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],tre="wc",nre="auth",rre="authKeys",ire="pairingTopics",sre="requests",gm=`${tre}@${1.5}:${nre}:`,mm=`${gm}:PUB_KEY`;var ore=Object.defineProperty,are=Object.defineProperties,cre=Object.getOwnPropertyDescriptors,h$=Object.getOwnPropertySymbols,lre=Object.prototype.hasOwnProperty,ure=Object.prototype.propertyIsEnumerable,A4=(e,t,n)=>t in e?ore(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pt=(e,t)=>{for(var n in t||(t={}))lre.call(t,n)&&A4(e,n,t[n]);if(h$)for(var n of h$(t))ure.call(t,n)&&A4(e,n,t[n]);return e},Xn=(e,t)=>are(e,cre(t)),ye=(e,t,n)=>A4(e,typeof t!="symbol"?t+"":t,n);class dre extends AJ{constructor(t){super(t),ye(this,"name",Xne),ye(this,"events",new zn.exports),ye(this,"initialized",!1),ye(this,"requestQueue",{state:co.idle,queue:[]}),ye(this,"sessionRequestQueue",{state:co.idle,queue:[]}),ye(this,"emittedSessionRequests",new _Z({limit:500})),ye(this,"requestQueueDelay",ve.ONE_SECOND),ye(this,"expectedPairingMethodMap",new Map),ye(this,"recentlyDeletedMap",new Map),ye(this,"recentlyDeletedLimit",200),ye(this,"relayMessageCache",[]),ye(this,"pendingSessions",new Map),ye(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(Yn)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ve.toMiliseconds(this.requestQueueDelay)))}),ye(this,"connect",async n=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Xn(Pt({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=BY(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:u,authentication:d,walletPay:h}=i,f=((r=d?.[0])==null?void 0:r.ttl)||Yn.wc_sessionPropose.req.ttl||ve.FIVE_MINUTES;this.validateRequestExpiry(f);let p=s,g,y=!1;try{if(p){const U=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),y=U.active}}catch(U){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),U}if(!p||!y){const{topic:U,uri:j}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=U,g=j}if(!p){const{message:U}=Ae("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(U)}const A=await this.client.core.crypto.generateKeyPair(),_=mn(f),v=Pt(Xn(Pt(Pt({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:_I}],proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:_,pairingTopic:p},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:ro()}),(d||h)&&{requests:{authentication:d?.map(U=>{const{domain:j,chains:W,nonce:S,uri:x,exp:I,nbf:m,type:b,statement:$,requestId:N,resources:P,signatureTypes:B}=U;return{domain:j,chains:W,nonce:S,type:b??"caip122",aud:x,version:"1",iat:new Date().toISOString(),exp:I,nbf:m,statement:$,requestId:N,resources:P,signatureTypes:B}}),walletPay:h}}),w=Rt("session_connect",v.id),{reject:T,resolve:O,done:D}=uu(f,f$),F=({id:U})=>{U===v.id&&(this.client.events.off("proposal_expire",F),this.pendingSessions.delete(v.id),this.events.emit(w,{error:{message:f$,code:0}}))};return this.client.events.on("proposal_expire",F),this.events.once(w,({error:U,session:j})=>{this.client.events.off("proposal_expire",F),U?T(U):j&&O(j)}),await this.setProposal(v.id,v),await this.sendProposeSession({proposal:v,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:v.id}}}).catch(U=>{throw this.deleteProposal(v.id),U}),{uri:g,approval:D}}),ye(this,"pair",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(n)}catch(r){throw this.client.logger.error("pair() failed"),r}}),ye(this,"approve",async n=>{var r,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[vs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(j){throw o.setError(Eu.no_internet_connection),j}try{await this.isValidProposalId(n?.id)}catch(j){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(Eu.proposal_not_found),j}try{await this.isValidApprove(n)}catch(j){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Eu.session_approve_namespace_validation_failure),j}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h,proposalRequestsResponses:f}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:y,requiredNamespaces:A,optionalNamespaces:_}=p;let v=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:g});v||(v=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:vs.session_approve_started,properties:{topic:g,trace:[vs.session_approve_started,vs.session_namespaces_validation_success]}}));const w=await this.client.core.crypto.generateKeyPair(),T=y.publicKey,O=await this.client.core.crypto.generateSharedKey(w,T),D=Xn(Pt(Pt(Pt({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:w,metadata:this.client.metadata},expiry:mn(l0)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{proposalRequestsResponses:f}),F=Kt.relay;v.addTrace(vs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:F,internal:{skipSubscribe:!0}})}catch(j){throw v.setError(Eu.subscribe_session_topic_failure),j}v.addTrace(vs.subscribe_session_topic_success);const U=Xn(Pt({},D),{topic:O,requiredNamespaces:A,optionalNamespaces:_,pairingTopic:g,acknowledged:!1,self:D.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:w,transportType:Kt.relay,authentication:f?.authentication,walletPayResult:f?.walletPay});await this.client.session.set(O,U),v.addTrace(vs.store_session);try{await this.sendApproveSession({sessionTopic:O,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:w},sessionSettleRequest:D,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:Pt({correlationId:a},this.getTVFApproveParams(U))}}),v.addTrace(vs.session_approve_publish_success)}catch(j){throw this.client.logger.error(j),this.client.session.delete(O,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(O),j}return this.client.core.eventClient.deleteEvent({eventId:v.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:y.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(O,mn(l0)),{topic:O,acknowledged:()=>Promise.resolve(this.client.session.get(O))}}),ye(this,"reject",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(n)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:i}=n;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:i,rpcOpts:Yn.wc_sessionPropose.reject}),await this.deleteProposal(r)}),ye(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=uu(ve.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=ro(),l=rl().toString(),u=this.client.session.get(r).namespaces;return this.events.once(Rt("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(r,{namespaces:u}),a(d)}),{acknowledged:s}}),ye(this,"extend",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(n)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=n,i=ro(),{done:s,resolve:o,reject:a}=uu(ve.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(Rt("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,mn(l0)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),ye(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:i,topic:s,expiry:o=Yn.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const c=ro(),l=rl().toString(),{done:u,resolve:d,reject:h}=uu(o,"Request expired. Please try again.");this.events.once(Rt("session_request",c),({error:y,result:A})=>{y?h(y):d(A)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:{request:Xn(Pt({},i),{expiryTimestamp:mn(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(y=>h(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await u();const g={request:Xn(Pt({},i),{expiryTimestamp:mn(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(A=>h(A)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var A;if(!((A=a.sessionConfig)!=null&&A.disableDeepLink)){const _=await vZ(this.client.core.storage,d$);await yZ({id:c,topic:s,wcDeepLink:_})}y()}),u()]).then(y=>y[2])}),ye(this,"respond",async n=>{var r,i;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:n?.topic||((i=(r=n?.response)==null?void 0:r.id)==null?void 0:i.toString()),trace:[vs.session_request_response_started]}});try{await this.isValidRespond(n)}catch(d){throw s.addTrace(d?.message),s.setError(Eu.session_request_response_validation_failure),d}s.addTrace(vs.session_request_response_validation_success);const{topic:o,response:a}=n,{id:c}=a,l=this.client.session.get(o);l.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{s.addTrace(vs.session_request_response_publish_started),io(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):ji(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(n)}catch(d){throw s.addTrace(d?.message),s.setError(Eu.session_request_response_publish_failure),d}}),ye(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=ro(),s=rl().toString(),{done:o,resolve:a,reject:c}=uu(ve.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(Rt("session_ping",i),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),ye(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=rl().toString(),a=ro();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),ye(this,"disconnect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(n);const{topic:r}=n;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:Gt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=Ae("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),ye(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>UY(r,n)))),ye(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),ye(this,"authenticate",async(n,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?Kt.link_mode:Kt.relay;o===Kt.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:f,nbf:p,methods:g=[],expiry:y}=n,A=[...n.resources||[]],{topic:_,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:_,uri:v}});const w=await this.client.core.crypto.generateKeyPair(),T=tm(w);if(await Promise.all([this.client.auth.authKeys.set(mm,{responseTopic:T,publicKey:w}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:_})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${_}`),g.length>0){const{namespace:P}=Ga(a[0]);let B=DG(P,"request",g);zg(A)&&(B=LG(B,A.pop())),A.push(B)}const O=y&&y>Yn.wc_sessionAuthenticate.req.ttl?y:Yn.wc_sessionAuthenticate.req.ttl,D={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:p,resources:A},requester:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:mn(O)},F={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},U={requiredNamespaces:{},optionalNamespaces:F,relays:[{protocol:"irn"}],pairingTopic:_,proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:mn(Yn.wc_sessionPropose.req.ttl),id:ro()},{done:j,resolve:W,reject:S}=uu(O,"Request expired"),x=ro(),I=Rt("session_connect",U.id),m=Rt("session_request",x),b=async({error:P,session:B})=>{this.events.off(m,$),P?S(P):B&&W({session:B})},$=async P=>{var B,V,Z;if(await this.deletePendingAuthRequest(x,{message:"fulfilled",code:0}),P.error){const ue=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===ue.code?void 0:(this.events.off(I,b),S(P.error.message))}await this.deleteProposal(U.id),this.events.off(I,b);const{cacaos:Y,responder:X}=P.result,G=[],ne=[];for(const ue of Y){await k7({cacao:ue,projectId:this.client.core.projectId})||(this.client.logger.error(ue,"Signature verification failed"),S(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ge}=ue,Be=zg(ge.resources),Fe=[b8(ge.iss)],qe=jg(ge.iss);if(Be){const ct=M7(Be),St=D7(Be);G.push(...ct),Fe.push(...St)}for(const ct of Fe)ne.push(`${ct}:${qe}`)}const se=await this.client.core.crypto.generateSharedKey(w,X.publicKey);let we;G.length>0&&(we={topic:se,acknowledged:!0,self:{publicKey:w,metadata:this.client.metadata},peer:X,controller:X.publicKey,expiry:mn(l0),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:_,namespaces:VS([...new Set(G)],[...new Set(ne)]),transportType:o},await this.client.core.relayer.subscribe(se,{transportType:o}),await this.client.session.set(se,we),_&&await this.client.core.pairing.updateMetadata({topic:_,metadata:X.metadata}),we=this.client.session.get(se)),(B=this.client.metadata.redirect)!=null&&B.linkMode&&(V=X.metadata.redirect)!=null&&V.linkMode&&(Z=X.metadata.redirect)!=null&&Z.universal&&r&&(this.client.core.addLinkModeSupportedApp(X.metadata.redirect.universal),this.client.session.update(se,{transportType:Kt.link_mode})),W({auths:Y,session:we})};this.events.once(I,b),this.events.once(m,$);let N;try{if(s){const P=ws("wc_sessionAuthenticate",D,x);this.client.core.history.set(_,P);const B=await this.client.core.crypto.encode("",P,{type:mh,encoding:nl});N=rm(r,_,B)}else await Promise.all([this.sendRequest({topic:_,method:"wc_sessionAuthenticate",params:D,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:x}),this.sendRequest({topic:_,method:"wc_sessionPropose",params:U,expiry:Yn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:U.id})])}catch(P){throw this.events.off(I,b),this.events.off(m,$),P}return await this.setProposal(U.id,U),await this.setAuthRequest(x,{request:Xn(Pt({},D),{verifyContext:{}}),pairingTopic:_,transportType:o}),{uri:N??v,response:j}}),ye(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Au.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw s.setError(Sh.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Sh.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||Kt.relay;a===Kt.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=tm(c),d={type:ec,receiverPublicKey:c,senderPublicKey:l},h=[],f=[];for(const y of i){if(!await k7({cacao:y,projectId:this.client.core.projectId})){s.setError(Sh.invalid_cacao);const T=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:T,encodeOpts:d}),new Error(T.message)}s.addTrace(Au.cacaos_verified);const{p:A}=y,_=zg(A.resources),v=[b8(A.iss)],w=jg(A.iss);if(_){const T=M7(_),O=D7(_);h.push(...T),v.push(...O)}for(const T of v)f.push(`${T}:${w}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Au.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:mn(l0),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:VS([...new Set(h)],[...new Set(f)]),transportType:a},s.addTrace(Au.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(y){throw s.setError(Sh.subscribe_authenticated_session_topic_failure),y}s.addTrace(Au.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Au.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Au.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw s.setError(Sh.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),ye(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:i}=n,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=tm(o),l={type:ec,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:l,rpcOpts:Yn.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),ye(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return R7(r,i)}),ye(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const n=this.relayMessageCache.shift();n&&await this.onRelayMessage(n)}catch(n){this.client.logger.error(n)}},50)}),ye(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),ye(this,"deleteSession",async n=>{var r;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,Gt("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(d$).catch(l=>this.client.logger.warn(l)),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=co.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===i).map(l=>this.deletePendingSessionRequest(l.id,Gt("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),ye(this,"deleteProposal",async(n,r)=>{if(r)try{const i=this.client.proposal.get(n),s=this.client.core.eventClient.getEvent({topic:i.pairingTopic});s?.setError(Eu.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,Gt("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),ye(this,"deletePendingSessionRequest",async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==n),i&&(this.sessionRequestQueue.state=co.idle,this.client.events.emit("session_request_expire",{id:n}))}),ye(this,"deletePendingAuthRequest",async(n,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])}),ye(this,"setExpiry",async(n,r)=>{this.client.session.keys.includes(n)&&(this.client.core.expirer.set(n,r),await this.client.session.update(n,{expiry:r}))}),ye(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,mn(Yn.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),ye(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=Kt.relay}=r;this.client.core.expirer.set(n,i.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:n,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),ye(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||mn(Yn.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:s,verifyContext:o})}),ye(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d,publishOpts:h={}}=n,f=ws(i,s,c);let p;const g=!!u;try{const _=g?nl:Xr;p=await this.client.core.crypto.encode(r,f,{encoding:_})}catch(_){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),_}let y;if(ere.includes(i)){const _=Fi(JSON.stringify(f)),v=Fi(p);y=await this.client.core.verify.register({id:v,decryptedId:_})}const A=Pt(Pt({},Yn[i].req),h);if(A.attestation=y,o&&(A.ttl=o),a&&(A.id=a),this.client.core.history.set(r,f),g){const _=rm(u,r,p);await global.Linking.openURL(_,this.client.name)}else A.tvf=Xn(Pt({},d),{correlationId:f.id}),l?(A.internal=Xn(Pt({},A.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,A)):this.client.core.relayer.publish(r,p,A).catch(_=>this.client.logger.error(_));return f.id}),ye(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=ws("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:Xr}),a=Fi(JSON.stringify(s)),c=Fi(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:Xn(Pt({},i),{publishMethod:"wc_proposeSession",attestation:l})})}),ye(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=Ch(s.id,i),l=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:Xr}),u=ws("wc_sessionSettle",o,a?.id),d=await this.client.core.crypto.encode(r,u,{encoding:Xr});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:d},opts:Xn(Pt({},a),{publishMethod:"wc_approveSession"})})}),ye(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,l=Ch(r,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=d?nl:Xr;u=await this.client.core.crypto.encode(i,l,Xn(Pt({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let h,f;try{h=await this.client.core.history.get(i,r);const p=h.request;try{f=this.getTVFParams(r,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),p}if(d){const p=rm(c,i,u);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=Yn[p].res;g.tvf=Xn(Pt({},f),{correlationId:r}),o?(g.internal=Xn(Pt({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,g)):this.client.core.relayer.publish(i,u,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(l)}),ye(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,l=um(r,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=d?nl:Xr;u=await this.client.core.crypto.encode(i,l,Xn(Pt({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),f}let h;try{h=await this.client.core.history.get(i,r)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),f}if(d){const f=rm(c,i,u);await global.Linking.openURL(f,this.client.name)}else{const f=h.request.method,p=a||Yn[f].res;this.client.core.relayer.publish(i,u,p)}await this.client.core.history.resolve(l)}),ye(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;Qs(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Qs(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),ye(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),ye(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),ye(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===co.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=co.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=co.idle}),ye(this,"processRequest",async n=>{const{topic:r,payload:i,attestation:s,transportType:o,encryptedId:a}=n,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),ye(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i,transportType:s}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),ye(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=Ae("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),ye(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:i}=n,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),ye(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(rc.proposal_listener_not_found)),this.isValidConnect(Pt({},i.params));const u=a.expiryTimestamp||mn(Yn.wc_sessionPropose.req.ttl),d=Pt({id:c,pairingTopic:r,expiryTimestamp:u,attestation:s,encryptedId:o},a);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:s,hash:Fi(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(oo.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:Yn.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),ye(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(io(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:n,proposalId:s,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:n})}else if(ji(r)){await this.deleteProposal(s);const o=Rt("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),ye(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h,proposalRequestsResponses:f}=r.params,p=[...this.pendingSessions.values()].find(A=>A.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const g=this.client.proposal.get(p.proposalId),y=Xn(Pt(Pt(Pt({topic:n,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:Kt.relay,authentication:f?.authentication,walletPayResult:f?.walletPay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:r.id,topic:n,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:y}),this.events.emit(Rt("session_connect",p.proposalId),{session:y})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;io(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(Rt("session_approve",i),{})):ji(r)&&(await this.client.session.delete(n,Gt("USER_DISCONNECTED")),this.events.emit(Rt("session_approve",i),{error:r.error}))}),ye(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=bh.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:n,error:Gt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Pt({topic:n},i));try{bh.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw bh.delete(o),c}this.client.events.emit("session_update",{id:s,topic:n,params:i})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),ye(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=Rt("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_update",i),{}):ji(r)&&this.events.emit(Rt("session_update",i),{error:r.error})}),ye(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,mn(l0)),await this.sendResult({id:i,topic:n,result:!0}),this.client.events.emit("session_extend",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),ye(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=Rt("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_extend",i),{}):ji(r)&&this.events.emit(Rt("session_extend",i),{error:r.error})}),ye(this,"onSessionPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:i,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),ye(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=Rt("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);io(r)?this.events.emit(Rt("session_ping",i),{}):ji(r)&&this.events.emit(Rt("session_ping",i),{error:r.error})},500)}),ye(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{await this.isValidDisconnect({topic:n,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:n,error:Gt("USER_DISCONNECTED")}),await this.deleteSession({topic:n,id:i})}catch(s){this.client.logger.error(s)}}),ye(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=n,{id:d,params:h}=a;try{await this.isValidRequest(Pt({topic:o},h));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Fi(JSON.stringify(ws("wc_sessionRequest",h,d))),encryptedId:l,metadata:f.peer.metadata,transportType:u}),g={id:d,topic:o,params:h,verifyContext:p};await this.setPendingSessionRequest(g),u===Kt.link_mode&&(r=f.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=f.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),ye(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=Rt("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_request",i),{result:r.result}):ji(r)&&this.events.emit(Rt("session_request",i),{error:r.error})}),ye(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=bh.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Pt({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),bh.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),io(r)?this.events.emit(Rt("session_request",i),{result:r.result}):ji(r)&&this.events.emit(Rt("session_request",i),{error:r.error})}),ye(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:l,authPayload:u,expiryTimestamp:d}=s.params,h=await this.getVerifyContext({attestationId:o,hash:Fi(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:i,id:s.id,authPayload:u,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(s.id,{request:f,pairingTopic:i,transportType:c}),c===Kt.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),f={type:ec,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:s.id,topic:i,error:l,encodeOpts:f,rpcOpts:Yn.wc_sessionAuthenticate.autoReject,appLink:h})}}),ye(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),ye(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=co.idle,this.processSessionRequestQueue()},ve.toMiliseconds(this.requestQueueDelay))}),ye(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===n&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(Rt("session_request",s.request.id),{error:r})})}),ye(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===co.active){this.client.logger.info("session request queue is already active.");return}const n=this.sessionRequestQueue.queue[0];if(!n){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(n)}catch(r){this.client.logger.error(r)}}),ye(this,"emitSessionRequest",n=>{if(this.emittedSessionRequests.has(n.id)){this.client.logger.warn({id:n.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${n.id}`);return}this.sessionRequestQueue.state=co.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),ye(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:ws("wc_sessionPropose",Xn(Pt({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),ye(this,"isValidConnect",async n=>{if(!Jr(n)){const{message:l}=Ae("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if($n(r)||await this.isValidPairingTopic(r),!YY(c,!0)){const{message:l}=Ae("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(i&&!$n(i)&&no(i)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(i,"requiredNamespaces")}if(s&&!$n(s)&&no(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!$n(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!$n(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),ye(this,"validateNamespaces",(n,r)=>{const i=KY(n,"connect()",r);if(i)throw new Error(i.message)}),ye(this,"isValidApprove",async n=>{if(!Jr(n))throw new Error(Ae("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=W8(i,"approve()");if(l)throw new Error(l.message);const u=KS(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!yn(s,!0)){const{message:d}=Ae("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(d)}if(o&&!$n(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!$n(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(i));if(!Object.keys(a).every(h=>d.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),ye(this,"isValidReject",async n=>{if(!Jr(n)){const{message:s}=Ae("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!JY(i)){const{message:s}=Ae("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),ye(this,"isValidSessionSettleRequest",n=>{if(!Jr(n)){const{message:l}=Ae("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(l)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!ZS(r)){const{message:l}=Ae("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=zY(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=W8(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Qs(o)){const{message:l}=Ae("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),ye(this,"isValidUpdate",async n=>{if(!Jr(n)){const{message:c}=Ae("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:i}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=W8(i,"update()");if(o)throw new Error(o.message);const a=KS(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),ye(this,"isValidExtend",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),ye(this,"isValidRequest",async n=>{if(!Jr(n)){const{message:c}=Ae("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:i,chainId:s,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!GS(a,s)){const{message:c}=Ae("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!QY(i)){const{message:c}=Ae("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!nX(a,s,i.method)){const{message:c}=Ae("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),ye(this,"isValidRespond",async n=>{var r;if(!Jr(n)){const{message:a}=Ae("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(a)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(a){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),a}if(!eX(s)){const{message:a}=Ae("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==i){const{message:a}=Ae("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${i}`);throw new Error(a)}}),ye(this,"isValidPing",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),ye(this,"isValidEmit",async n=>{if(!Jr(n)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:i,chainId:s}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!GS(o,s)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!tX(i)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!rX(o,s,i.name)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),ye(this,"isValidDisconnect",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),ye(this,"isValidAuthenticate",n=>{const{chains:r,uri:i,domain:s,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!yn(i,!1))throw new Error("uri is required parameter");if(!yn(s,!1))throw new Error("domain is required parameter");if(!yn(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Ga(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Ga(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),ye(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||_h,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Kt.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),ye(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=Ae("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),ye(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),ye(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),ye(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=Ae("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),ye(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,l,u,d,h;return!n||r!==Kt.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=n?.redirect)==null?void 0:u.universal)!==void 0&&((d=n?.redirect)==null?void 0:d.universal)!==""&&((h=n?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),ye(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),ye(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=o7(n,"topic")||"",i=decodeURIComponent(o7(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:Kt.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),ye(this,"registerLinkModeListeners",async()=>{var n;if(d8()||jc()&&(n=this.client.metadata.redirect)!=null&&n.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),ye(this,"getTVFApproveParams",n=>{try{const r=jS(n.namespaces),i=NY(n.namespaces),s=PY(n.namespaces),o=n.sessionProperties,a=n.scopedProperties;return{approvedChains:r,approvedMethods:i,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}}),ye(this,"getTVFParams",(n,r,i)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const l=this.extractTxHashesFromResult(r.request,i);c.txHashes=l,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),ye(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const i=n?.data||((r=n?.[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),ye(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=Jne[s];if(s==="sui_signTransaction")return[wG(r.transactionBytes)];if(s==="near_signTransaction")return[$7(r)];if(s==="near_signTransactions")return r.map(c=>$7(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[EX({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Hi(r)?r.map(c=>T7(c)):[T7(r)];if(s==="cosmos_signDirect")return[vG(r)];if(s==="wallet_sendCalls")return EG(r);if(typeof r=="string")return[r];const a=r[o.key];if(Hi(a))return s==="solana_signAllTransactions"?a.map(c=>yG(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const t=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(t);for(const[r,i]of Object.entries(n))for(const s of i)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(hn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){const{topic:n,message:r,attestation:i,transportType:s}=t,{publicKey:o}=this.client.auth.authKeys.keys.includes(mm)?this.client.auth.authKeys.get(mm):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===Kt.link_mode?nl:Xr});r4(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:Fi(r)})):dm(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:s}),this.client.core.history.delete(n,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Vi.expired,async t=>{const{topic:n,id:r}=s7(t.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,Ae("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,Ae("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession({topic:n,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(vu.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(vu.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!yn(t,!1)){const{message:n}=Ae("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:n}=Ae("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.core.pairing.pairings.get(t).expiry)){const{message:n}=Ae("EXPIRED",`pairing topic: ${t}`);throw new Error(n)}}async isValidSessionTopic(t){if(!yn(t,!1)){const{message:n}=Ae("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(n)}if(this.checkRecentlyDeleted(t),!this.client.session.keys.includes(t)){const{message:n}=Ae("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});const{message:n}=Ae("EXPIRED",`session topic: ${t}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(t)){const{message:n}=Ae("MISSING_OR_INVALID",`session topic does not exist in keychain: ${t}`);throw await this.deleteSession({topic:t}),new Error(n)}}async isValidSessionOrPairingTopic(t){if(this.checkRecentlyDeleted(t),this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(yn(t,!1)){const{message:n}=Ae("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(n)}else{const{message:n}=Ae("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(n)}}async isValidProposalId(t){if(!XY(t)){const{message:n}=Ae("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(n)}if(!this.client.proposal.keys.includes(t)){const{message:n}=Ae("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);const{message:n}=Ae("EXPIRED",`proposal id: ${t}`);throw new Error(n)}}validateRequestExpiry(t){if(t&&!oX(t,E4)){const{message:n}=Ae("MISSING_OR_INVALID",`request() expiry: ${t}. Expiry must be a number (in seconds) between ${E4.min} and ${E4.max}`);throw new Error(n)}}}class fre extends Cu{constructor(t,n){super(t,n,Kne,b4),this.core=t,this.logger=n}}class hre extends Cu{constructor(t,n){super(t,n,Yne,b4),this.core=t,this.logger=n}}class pre extends Cu{constructor(t,n){super(t,n,Qne,b4,r=>r.id),this.core=t,this.logger=n}}class gre extends Cu{constructor(t,n){super(t,n,rre,gm,()=>mm),this.core=t,this.logger=n}}class mre extends Cu{constructor(t,n){super(t,n,ire,gm),this.core=t,this.logger=n}}class yre extends Cu{constructor(t,n){super(t,n,sre,gm,r=>r.id),this.core=t,this.logger=n}}var wre=Object.defineProperty,bre=(e,t,n)=>t in e?wre(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,C4=(e,t,n)=>bre(e,typeof t!="symbol"?t+"":t,n);class vre{constructor(t,n){this.core=t,this.logger=n,C4(this,"authKeys"),C4(this,"pairingTopics"),C4(this,"requests"),this.authKeys=new gre(this.core,this.logger),this.pairingTopics=new mre(this.core,this.logger),this.requests=new yre(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var Ere=Object.defineProperty,Are=(e,t,n)=>t in e?Ere(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,vt=(e,t,n)=>Are(e,typeof t!="symbol"?t+"":t,n);class x4 extends EJ{constructor(t){super(t),vt(this,"protocol",c$),vt(this,"version",l$),vt(this,"name",v4.name),vt(this,"metadata"),vt(this,"core"),vt(this,"logger"),vt(this,"events",new zn.exports.EventEmitter),vt(this,"engine"),vt(this,"session"),vt(this,"proposal"),vt(this,"pendingRequest"),vt(this,"auth"),vt(this,"signConfig"),vt(this,"on",(r,i)=>this.events.on(r,i)),vt(this,"once",(r,i)=>this.events.once(r,i)),vt(this,"off",(r,i)=>this.events.off(r,i)),vt(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),vt(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),vt(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),vt(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),vt(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=t?.name||v4.name,this.metadata=dZ(t?.metadata),this.signConfig=t?.signConfig;const n=G8({logger:t?.logger||v4.logger,name:this.name});this.logger=n,this.core=t?.core||new Gne(t),this.session=new hre(this.core,this.logger),this.proposal=new fre(this.core,this.logger),this.pendingRequest=new pre(this.core,this.logger),this.engine=new dre(this),this.auth=new vre(this.core,this.logger)}static async init(t){const n=new x4(t);return await n.initialize(),n}get context(){return Gr(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")}catch(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}}const Cre=x4;var _4={exports:{}};(function(e,t){var n=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Pn<"u"&&Pn,r=function(){function s(){this.fetch=!1,this.DOMException=n.DOMException}return s.prototype=n,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof Pn<"u"&&Pn||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(m){return m&&DataView.prototype.isPrototypeOf(m)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(m){return m&&u.indexOf(Object.prototype.toString.call(m))>-1};function h(m){if(typeof m!="string"&&(m=String(m)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(m)||m==="")throw new TypeError('Invalid character in header field name: "'+m+'"');return m.toLowerCase()}function f(m){return typeof m!="string"&&(m=String(m)),m}function p(m){var b={next:function(){var $=m.shift();return{done:$===void 0,value:$}}};return c.iterable&&(b[Symbol.iterator]=function(){return b}),b}function g(m){this.map={},m instanceof g?m.forEach(function(b,$){this.append($,b)},this):Array.isArray(m)?m.forEach(function(b){if(b.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+b.length);this.append(b[0],b[1])},this):m&&Object.getOwnPropertyNames(m).forEach(function(b){this.append(b,m[b])},this)}g.prototype.append=function(m,b){m=h(m),b=f(b);var $=this.map[m];this.map[m]=$?$+", "+b:b},g.prototype.delete=function(m){delete this.map[h(m)]},g.prototype.get=function(m){return m=h(m),this.has(m)?this.map[m]:null},g.prototype.has=function(m){return this.map.hasOwnProperty(h(m))},g.prototype.set=function(m,b){this.map[h(m)]=f(b)},g.prototype.forEach=function(m,b){for(var $ in this.map)this.map.hasOwnProperty($)&&m.call(b,this.map[$],$,this)},g.prototype.keys=function(){var m=[];return this.forEach(function(b,$){m.push($)}),p(m)},g.prototype.values=function(){var m=[];return this.forEach(function(b){m.push(b)}),p(m)},g.prototype.entries=function(){var m=[];return this.forEach(function(b,$){m.push([$,b])}),p(m)},c.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function y(m){if(!m._noBody){if(m.bodyUsed)return Promise.reject(new TypeError("Already read"));m.bodyUsed=!0}}function A(m){return new Promise(function(b,$){m.onload=function(){b(m.result)},m.onerror=function(){$(m.error)}})}function _(m){var b=new FileReader,$=A(b);return b.readAsArrayBuffer(m),$}function v(m){var b=new FileReader,$=A(b),N=/charset=([A-Za-z0-9_-]+)/.exec(m.type),P=N?N[1]:"utf-8";return b.readAsText(m,P),$}function w(m){for(var b=new Uint8Array(m),$=new Array(b.length),N=0;N<b.length;N++)$[N]=String.fromCharCode(b[N]);return $.join("")}function T(m){if(m.slice)return m.slice(0);var b=new Uint8Array(m.byteLength);return b.set(new Uint8Array(m)),b.buffer}function O(){return this.bodyUsed=!1,this._initBody=function(m){this.bodyUsed=this.bodyUsed,this._bodyInit=m,m?typeof m=="string"?this._bodyText=m:c.blob&&Blob.prototype.isPrototypeOf(m)?this._bodyBlob=m:c.formData&&FormData.prototype.isPrototypeOf(m)?this._bodyFormData=m:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(m)?this._bodyText=m.toString():c.arrayBuffer&&c.blob&&l(m)?(this._bodyArrayBuffer=T(m.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(m)||d(m))?this._bodyArrayBuffer=T(m):this._bodyText=m=Object.prototype.toString.call(m):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof m=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(m)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var m=y(this);if(m)return m;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(){if(this._bodyArrayBuffer){var m=y(this);return m||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(_);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var m=y(this);if(m)return m;if(this._bodyBlob)return v(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)},c.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var D=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function F(m){var b=m.toUpperCase();return D.indexOf(b)>-1?b:m}function U(m,b){if(!(this instanceof U))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');b=b||{};var $=b.body;if(m instanceof U){if(m.bodyUsed)throw new TypeError("Already read");this.url=m.url,this.credentials=m.credentials,b.headers||(this.headers=new g(m.headers)),this.method=m.method,this.mode=m.mode,this.signal=m.signal,!$&&m._bodyInit!=null&&($=m._bodyInit,m.bodyUsed=!0)}else this.url=String(m);if(this.credentials=b.credentials||this.credentials||"same-origin",(b.headers||!this.headers)&&(this.headers=new g(b.headers)),this.method=F(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.signal=b.signal||this.signal||function(){if("AbortController"in a){var B=new AbortController;return B.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&$)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody($),(this.method==="GET"||this.method==="HEAD")&&(b.cache==="no-store"||b.cache==="no-cache")){var N=/([?&])_=[^&]*/;if(N.test(this.url))this.url=this.url.replace(N,"$1_="+new Date().getTime());else{var P=/\?/;this.url+=(P.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}U.prototype.clone=function(){return new U(this,{body:this._bodyInit})};function j(m){var b=new FormData;return m.trim().split("&").forEach(function($){if($){var N=$.split("="),P=N.shift().replace(/\+/g," "),B=N.join("=").replace(/\+/g," ");b.append(decodeURIComponent(P),decodeURIComponent(B))}}),b}function W(m){var b=new g,$=m.replace(/\r?\n[\t ]+/g," ");return $.split("\r").map(function(N){return N.indexOf(`
|
|
41
|
+
***************************************************************************** */var e4=function(e,t){return e4=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},e4(e,t)};function NJ(e,t){e4(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var t4=function(){return t4=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},t4.apply(this,arguments)};function PJ(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function OJ(e,t,n,r){var i=arguments.length,s=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s}function kJ(e,t){return function(n,r){t(n,r,e)}}function RJ(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function BJ(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((r=r.apply(e,t||[])).next())})}function MJ(e,t){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,i=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){n.label=l[1];break}if(l[0]===6&&n.label<s[1]){n.label=s[1],s=l;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(l);break}s[2]&&n.ops.pop(),n.trys.pop();continue}l=t.call(e,n)}catch(u){l=[6,u],i=0}finally{r=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function DJ(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}function UJ(e,t){for(var n in e)n!=="default"&&!t.hasOwnProperty(n)&&(t[n]=e[n])}function n4(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function dI(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,s=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function LJ(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(dI(arguments[t]));return e}function FJ(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Ah(e){return this instanceof Ah?(this.v=e,this):new Ah(e)}function HJ(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(e,t||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){r[h]&&(i[h]=function(f){return new Promise(function(p,g){s.push([h,f,p,g])>1||a(h,f)})})}function a(h,f){try{c(r[h](f))}catch(p){d(s[0][3],p)}}function c(h){h.value instanceof Ah?Promise.resolve(h.value.v).then(l,u):d(s[0][2],h)}function l(h){a("next",h)}function u(h){a("throw",h)}function d(h,f){h(f),s.shift(),s.length&&a(s[0][0],s[0][1])}}function jJ(e){var t,n;return t={},r("next"),r("throw",function(i){throw i}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(i,s){t[i]=e[i]?function(o){return(n=!n)?{value:Ah(e[i](o)),done:i==="return"}:s?s(o):o}:s}}function zJ(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof n4=="function"?n4(e):e[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=e[s]&&function(o){return new Promise(function(a,c){o=e[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function VJ(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function WJ(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function qJ(e){return e&&e.__esModule?e:{default:e}}function ZJ(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function GJ(e,t,n){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,n),n}var KJ=Object.freeze({__proto__:null,__extends:NJ,get __assign(){return t4},__rest:PJ,__decorate:OJ,__param:kJ,__metadata:RJ,__awaiter:BJ,__generator:MJ,__createBinding:DJ,__exportStar:UJ,__values:n4,__read:dI,__spread:LJ,__spreadArrays:FJ,__await:Ah,__asyncGenerator:HJ,__asyncDelegator:jJ,__asyncValues:zJ,__makeTemplateObject:VJ,__importStar:WJ,__importDefault:qJ,__classPrivateFieldGet:ZJ,__classPrivateFieldSet:GJ}),YJ=XE(KJ),tc={},fI;function XJ(){if(fI)return tc;fI=1,Object.defineProperty(tc,"__esModule",{value:!0}),tc.isBrowserCryptoAvailable=tc.getSubtleCrypto=tc.getBrowerCrypto=void 0;function e(){return Pn?.crypto||Pn?.msCrypto||{}}tc.getBrowerCrypto=e;function t(){const r=e();return r.subtle||r.webkitSubtle}tc.getSubtleCrypto=t;function n(){return!!e()&&!!t()}return tc.isBrowserCryptoAvailable=n,tc}var nc={},hI;function JJ(){if(hI)return nc;hI=1,Object.defineProperty(nc,"__esModule",{value:!0}),nc.isBrowser=nc.isNode=nc.isReactNative=void 0;function e(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}nc.isReactNative=e;function t(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}nc.isNode=t;function n(){return!e()&&!t()}return nc.isBrowser=n,nc}(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=YJ;t.__exportStar(XJ(),e),t.__exportStar(JJ(),e)})(uI);function ro(e=3){const t=Date.now()*Math.pow(10,e),n=Math.floor(Math.random()*Math.pow(10,e));return t+n}function rl(e=6){return BigInt(ro(e))}function ws(e,t,n){return{id:n||ro(),jsonrpc:"2.0",method:e,params:t}}function Ch(e,t){return{id:e,jsonrpc:"2.0",result:t}}function um(e,t,n){return{id:e,jsonrpc:"2.0",error:QJ(t,n)}}function QJ(e,t){return typeof e>"u"?cI(oI):(typeof e=="string"&&(e=Object.assign(Object.assign({},cI(Q8)),{message:e})),typeof t<"u"&&(e.data=t),$J(e.code)&&(e=TJ(e.code)),e)}class eQ{}class tQ extends eQ{constructor(){super()}}class nQ extends tQ{constructor(t){super()}}const rQ="^https?:",iQ="^wss?:";function sQ(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(!(!t||!t.length))return t[0]}function pI(e,t){const n=sQ(e);return typeof n>"u"?!1:new RegExp(t).test(n)}function gI(e){return pI(e,rQ)}function mI(e){return pI(e,iQ)}function oQ(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function yI(e){return typeof e=="object"&&"id"in e&&"jsonrpc"in e&&e.jsonrpc==="2.0"}function r4(e){return yI(e)&&"method"in e}function dm(e){return yI(e)&&(io(e)||ji(e))}function io(e){return"result"in e}function ji(e){return"error"in e}class i4 extends nQ{constructor(t){super(t),this.events=new zn.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),this.connection.connected&&this.registerEventListeners()}async connect(t=this.connection){await this.open(t)}async disconnect(){await this.close()}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async request(t,n){return this.requestStrict(ws(t.method,t.params||[],t.id||rl().toString()),n)}async requestStrict(t,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${t.id}`,s=>{ji(s)?i(s.error):r(s.result)});try{await this.connection.send(t,n)}catch(s){i(s)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit("payload",t),dm(t)?this.events.emit(`${t.id}`,t):this.events.emit("message",{type:t.method,data:t.params})}onClose(t){t&&t.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${t.code} ${t.reason?`(${t.reason})`:""}`)),this.events.emit("disconnect")}async open(t=this.connection){this.connection===t&&this.connection.connected||(this.connection.connected&&this.close(),typeof t=="string"&&(await this.connection.open(t),t=this.connection),this.connection=this.setConnection(t),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",t=>this.onPayload(t)),this.connection.on("close",t=>this.onClose(t)),this.connection.on("error",t=>this.events.emit("error",t)),this.connection.on("register_error",t=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const aQ=()=>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"),cQ=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",wI=e=>e.split("?")[0],bI=10,lQ=aQ();class uQ{constructor(t){if(this.url=t,this.events=new zn.exports.EventEmitter,this.registering=!1,!mI(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);this.url=t}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async open(t=this.url){await this.register(t)}async close(){return new Promise((t,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),t()},this.socket.close()})}async send(t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ou(t))}catch(n){this.onError(t.id,n)}}register(t=this.url){if(!mI(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=t,this.registering=!0,new Promise((n,r)=>{const i=uI.isReactNative()?void 0:{rejectUnauthorized:!oQ(t)},s=new lQ(t,[],i);cQ()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),n(s)}})}onOpen(t){t.onmessage=n=>this.onPayload(n),t.onclose=n=>this.onClose(n),this.socket=t,this.registering=!1,this.events.emit("open")}onClose(t){this.socket=void 0,this.registering=!1,this.events.emit("close",t)}onPayload(t){if(typeof t.data>"u")return;const n=typeof t.data=="string"?su(t.data):t.data;this.events.emit("payload",n)}onError(t,n){const r=this.parseError(n),i=r.message||r.toString(),s=um(t,i);this.events.emit("payload",s)}parseError(t,n=this.url){return lI(t,wI(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>bI&&this.events.setMaxListeners(bI)}emitError(t){const n=this.parseError(new Error(t?.message||`WebSocket connection failed for host: ${wI(this.url)}`));return this.events.emit("register_error",n),n}}var dQ=Object.defineProperty,vI=Object.getOwnPropertySymbols,fQ=Object.prototype.hasOwnProperty,hQ=Object.prototype.propertyIsEnumerable,EI=(e,t,n)=>t in e?dQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Nr=(e,t)=>{for(var n in t||(t={}))fQ.call(t,n)&&EI(e,n,t[n]);if(vI)for(var n of vI(t))hQ.call(t,n)&&EI(e,n,t[n]);return e};const AI="wc",CI=2,fm="core",so=`${AI}@2:${fm}:`,pQ={name:fm,logger:"error"},gQ={database:":memory:"},mQ="crypto",xI="client_ed25519_seed",yQ=ve.ONE_DAY,wQ="keychain",bQ="0.3",vQ="messages",EQ="0.3",AQ=ve.SIX_HOURS,CQ="publisher",_I="irn",xQ="error",SI="wss://relay.walletconnect.org",_Q="relayer",hn={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"},SQ="_subscription",zi={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},IQ=.1,s4="2.23.7",Kt={link_mode:"link_mode",relay:"relay"},hm={inbound:"inbound",outbound:"outbound"},$Q="0.3",TQ="WALLETCONNECT_CLIENT_ID",II="WALLETCONNECT_LINK_MODE_APPS",Ci={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},NQ="subscription",PQ="0.3",OQ="pairing",kQ="0.3",xh={wc_pairingDelete:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ve.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ve.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:0},res:{ttl:ve.ONE_DAY,prompt:!1,tag:0}}},vu={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},bs={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},RQ="history",BQ="0.3",MQ="expirer",Vi={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},DQ="0.3",UQ="verify-api",LQ="https://verify.walletconnect.com",$I="https://verify.walletconnect.org",_h=$I,FQ=`${_h}/v3`,HQ=[LQ,$I],jQ="echo",zQ="https://echo.walletconnect.com",oo={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"},rc={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"},vs={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Eu={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Au={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"},Sh={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"},VQ=.1,WQ="event-client",qQ=86400,ZQ="https://pulse.walletconnect.org/batch";function GQ(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,A=0,_=p.length;A!==_&&p[A]===0;)A++,g++;for(var v=(_-A)*u+1>>>0,w=new Uint8Array(v);A!==_;){for(var T=p[A],O=0,D=v-1;(T!==0||O<y)&&D!==-1;D--,O++)T+=256*w[D]>>>0,w[D]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");y=O,A++}for(var F=v-y;F!==v&&w[F]===0;)F++;for(var U=c.repeat(g);F<v;++F)U+=e.charAt(w[F]);return U}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,A=0;p[g]===c;)y++,g++;for(var _=(p.length-g)*l+1>>>0,v=new Uint8Array(_);p[g];){var w=n[p.charCodeAt(g)];if(w===255)return;for(var T=0,O=_-1;(w!==0||T<A)&&O!==-1;O--,T++)w+=a*v[O]>>>0,v[O]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");A=T,g++}if(p[g]!==" "){for(var D=_-A;D!==_&&v[D]===0;)D++;for(var F=new Uint8Array(y+(_-D)),U=y;D!==_;)F[U++]=v[D++];return F}}}function f(p){var g=h(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:h,decode:f}}var KQ=GQ,YQ=KQ;const TI=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},XQ=e=>new TextEncoder().encode(e),JQ=e=>new TextDecoder().decode(e);class QQ{constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class eee{constructor(t,n,r){if(this.name=t,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return NI(this,t)}}class tee{constructor(t){this.decoders=t}or(t){return NI(this,t)}decode(t){const n=t[0],r=this.decoders[n];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const NI=(e,t)=>new tee(Nr(Nr({},e.decoders||{[e.prefix]:e}),t.decoders||{[t.prefix]:t}));class nee{constructor(t,n,r,i){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new QQ(t,n,r),this.decoder=new eee(t,n,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const pm=({name:e,prefix:t,encode:n,decode:r})=>new nee(e,t,n,r),Ih=({prefix:e,name:t,alphabet:n})=>{const{encode:r,decode:i}=YQ(n,t);return pm({prefix:e,name:t,encode:r,decode:s=>TI(i(s))})},ree=(e,t,n,r)=>{const i={};for(let u=0;u<t.length;++u)i[t[u]]=u;let s=e.length;for(;e[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const d=i[e[u]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|d,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},iee=(e,t,n)=>{const r=t[t.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>n;)o-=n,s+=t[i&a>>o];if(o&&(s+=t[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Gn=({name:e,prefix:t,bitsPerChar:n,alphabet:r})=>pm({prefix:t,name:e,encode(i){return iee(i,r,n)},decode(i){return ree(i,r,n,e)}}),see=pm({prefix:"\0",name:"identity",encode:e=>JQ(e),decode:e=>XQ(e)});var oee=Object.freeze({__proto__:null,identity:see});const aee=Gn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cee=Object.freeze({__proto__:null,base2:aee});const lee=Gn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var uee=Object.freeze({__proto__:null,base8:lee});const dee=Ih({prefix:"9",name:"base10",alphabet:"0123456789"});var fee=Object.freeze({__proto__:null,base10:dee});const hee=Gn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),pee=Gn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gee=Object.freeze({__proto__:null,base16:hee,base16upper:pee});const mee=Gn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yee=Gn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wee=Gn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bee=Gn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vee=Gn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Eee=Gn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Aee=Gn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Cee=Gn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xee=Gn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _ee=Object.freeze({__proto__:null,base32:mee,base32upper:yee,base32pad:wee,base32padupper:bee,base32hex:vee,base32hexupper:Eee,base32hexpad:Aee,base32hexpadupper:Cee,base32z:xee});const See=Ih({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Iee=Ih({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $ee=Object.freeze({__proto__:null,base36:See,base36upper:Iee});const Tee=Ih({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nee=Ih({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Pee=Object.freeze({__proto__:null,base58btc:Tee,base58flickr:Nee});const Oee=Gn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kee=Gn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ree=Gn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bee=Gn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Mee=Object.freeze({__proto__:null,base64:Oee,base64pad:kee,base64url:Ree,base64urlpad:Bee});const PI=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}"),Dee=PI.reduce((e,t,n)=>(e[n]=t,e),[]),Uee=PI.reduce((e,t,n)=>(e[t.codePointAt(0)]=n,e),[]);function Lee(e){return e.reduce((t,n)=>(t+=Dee[n],t),"")}function Fee(e){const t=[];for(const n of e){const r=Uee[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}const Hee=pm({prefix:"\u{1F680}",name:"base256emoji",encode:Lee,decode:Fee});var jee=Object.freeze({__proto__:null,base256emoji:Hee}),zee=kI,OI=128,Vee=127,Wee=~Vee,qee=Math.pow(2,31);function kI(e,t,n){t=t||[],n=n||0;for(var r=n;e>=qee;)t[n++]=e&255|OI,e/=128;for(;e&Wee;)t[n++]=e&255|OI,e>>>=7;return t[n]=e|0,kI.bytes=n-r+1,t}var Zee=o4,Gee=128,RI=127;function o4(e,r){var n=0,r=r||0,i=0,s=r,o,a=e.length;do{if(s>=a)throw o4.bytes=0,new RangeError("Could not decode varint");o=e[s++],n+=i<28?(o&RI)<<i:(o&RI)*Math.pow(2,i),i+=7}while(o>=Gee);return o4.bytes=s-r,n}var Kee=Math.pow(2,7),Yee=Math.pow(2,14),Xee=Math.pow(2,21),Jee=Math.pow(2,28),Qee=Math.pow(2,35),ete=Math.pow(2,42),tte=Math.pow(2,49),nte=Math.pow(2,56),rte=Math.pow(2,63),ite=function(e){return e<Kee?1:e<Yee?2:e<Xee?3:e<Jee?4:e<Qee?5:e<ete?6:e<tte?7:e<nte?8:e<rte?9:10},ste={encode:zee,decode:Zee,encodingLength:ite},BI=ste;const MI=(e,t,n=0)=>(BI.encode(e,t,n),t),DI=e=>BI.encodingLength(e),a4=(e,t)=>{const n=t.byteLength,r=DI(e),i=r+DI(n),s=new Uint8Array(i+n);return MI(e,s,0),MI(n,s,r),s.set(t,i),new ote(e,n,t,s)};class ote{constructor(t,n,r,i){this.code=t,this.size=n,this.digest=r,this.bytes=i}}const UI=({name:e,code:t,encode:n})=>new ate(e,t,n);class ate{constructor(t,n,r){this.name=t,this.code=n,this.encode=r}digest(t){if(t instanceof Uint8Array){const n=this.encode(t);return n instanceof Uint8Array?a4(this.code,n):n.then(r=>a4(this.code,r))}else throw Error("Unknown type, must be binary type")}}const LI=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),cte=UI({name:"sha2-256",code:18,encode:LI("SHA-256")}),lte=UI({name:"sha2-512",code:19,encode:LI("SHA-512")});var ute=Object.freeze({__proto__:null,sha256:cte,sha512:lte});const FI=0,dte="identity",HI=TI;var fte=Object.freeze({__proto__:null,identity:{code:FI,name:dte,encode:HI,digest:e=>a4(FI,HI(e))}});new TextEncoder,new TextDecoder;const jI=Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr({},oee),cee),uee),fee),gee),_ee),$ee),Pee),Mee),jee);Nr(Nr({},ute),fte);function zI(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function hte(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?zI(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function VI(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const WI=VI("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),c4=VI("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{e=e.substring(1);const t=hte(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),pte=Nr({utf8:WI,"utf-8":WI,hex:jI.base16,latin1:c4,ascii:c4,binary:c4},jI);function gte(e,t="utf8"){const n=pte[t];if(!n)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?zI(globalThis.Buffer.from(e,"utf-8")):n.decoder.decode(`${n.prefix}${e}`)}var mte=Object.defineProperty,yte=(e,t,n)=>t in e?mte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ao=(e,t,n)=>yte(e,typeof t!="symbol"?t+"":t,n);class wte{constructor(t,n){this.core=t,this.logger=n,ao(this,"keychain",new Map),ao(this,"name",wQ),ao(this,"version",bQ),ao(this,"initialized",!1),ao(this,"storagePrefix",so),ao(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),ao(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),ao(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),ao(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=Ae("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),ao(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=t,this.logger=vi(n,this.name)}get context(){return Gr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,l8(t))}async getKeyChain(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?u8(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var bte=Object.defineProperty,vte=(e,t,n)=>t in e?bte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mn=(e,t,n)=>vte(e,typeof t!="symbol"?t+"":t,n);class Ete{constructor(t,n,r){this.core=t,this.logger=n,Mn(this,"name",mQ),Mn(this,"keychain"),Mn(this,"randomSessionIdentifier",j8()),Mn(this,"initialized",!1),Mn(this,"clientId"),Mn(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Mn(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Mn(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const i=await this.getClientSeed(),s=i_(i),o=r_(s.publicKey);return this.clientId=o,o}),Mn(this,"generateKeyPair",()=>{this.isInitialized();const i=oY();return this.setPrivateKey(i.publicKey,i.privateKey)}),Mn(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=i_(s),a=this.randomSessionIdentifier;return await IV(a,i,yQ,o)}),Mn(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=aY(a,s);return this.setSymKey(c,o)}),Mn(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||tm(i);return await this.keychain.set(o,i),o}),Mn(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Mn(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Mn(this,"encode",async(i,s,o)=>{this.isInitialized();const a=kS(o),c=ou(s);if(BS(a))return uY(c,o?.encoding);if(RS(a)){const h=a.senderPublicKey,f=a.receiverPublicKey;i=await this.generateSharedKey(h,f)}const l=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return cY({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),Mn(this,"decode",async(i,s,o)=>{this.isInitialized();const a=fY(s,o);if(BS(a)){const c=dY(s,o?.encoding);return su(c)}if(RS(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=lY({symKey:c,encoded:s,encoding:o?.encoding});return su(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Mn(this,"getPayloadType",(i,s=Xr)=>{const o=wh({encoded:i,encoding:s});return mu(o.type)}),Mn(this,"getPayloadSenderPublicKey",(i,s=Xr)=>{const o=wh({encoded:i,encoding:s});return o.senderPublicKey?Zr(o.senderPublicKey,Tr):void 0}),this.core=t,this.logger=vi(n,this.name),this.keychain=r||new wte(this.core,this.logger)}get context(){return Gr(this.logger)}async setPrivateKey(t,n){return await this.keychain.set(t,n),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(xI)}catch{t=j8(),await this.keychain.set(xI,t)}return gte(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Ate=Object.defineProperty,Cte=Object.defineProperties,xte=Object.getOwnPropertyDescriptors,qI=Object.getOwnPropertySymbols,_te=Object.prototype.hasOwnProperty,Ste=Object.prototype.propertyIsEnumerable,l4=(e,t,n)=>t in e?Ate(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ite=(e,t)=>{for(var n in t||(t={}))_te.call(t,n)&&l4(e,n,t[n]);if(qI)for(var n of qI(t))Ste.call(t,n)&&l4(e,n,t[n]);return e},$te=(e,t)=>Cte(e,xte(t)),xi=(e,t,n)=>l4(e,typeof t!="symbol"?t+"":t,n);class Tte extends uJ{constructor(t,n){super(t,n),this.logger=t,this.core=n,xi(this,"messages",new Map),xi(this,"messagesWithoutClientAck",new Map),xi(this,"name",vQ),xi(this,"version",EQ),xi(this,"initialized",!1),xi(this,"storagePrefix",so),xi(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),xi(this,"set",async(r,i,s)=>{this.isInitialized();const o=Fi(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),s===hm.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,$te(Ite({},c),{[o]:i}))}return await this.persist(),o}),xi(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),xi(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),xi(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=Fi(i);return typeof s[o]<"u"}),xi(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=Fi(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),xi(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=vi(t,this.name),this.core=n}get context(){return Gr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(t){await this.core.storage.setItem(this.storageKey,l8(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,l8(t))}async getRelayerMessages(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?u8(t):void 0}async getRelayerMessagesWithoutClientAck(){const t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?u8(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Nte=Object.defineProperty,Pte=Object.defineProperties,Ote=Object.getOwnPropertyDescriptors,ZI=Object.getOwnPropertySymbols,kte=Object.prototype.hasOwnProperty,Rte=Object.prototype.propertyIsEnumerable,u4=(e,t,n)=>t in e?Nte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,a0=(e,t)=>{for(var n in t||(t={}))kte.call(t,n)&&u4(e,n,t[n]);if(ZI)for(var n of ZI(t))Rte.call(t,n)&&u4(e,n,t[n]);return e},GI=(e,t)=>Pte(e,Ote(t)),Wi=(e,t,n)=>u4(e,typeof t!="symbol"?t+"":t,n);class Bte extends dJ{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,Wi(this,"events",new zn.exports.EventEmitter),Wi(this,"name",CQ),Wi(this,"queue",new Map),Wi(this,"publishTimeout",ve.toMiliseconds(ve.ONE_MINUTE)),Wi(this,"initialPublishTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),Wi(this,"needsTransportRestart",!1),Wi(this,"publish",async(r,i,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const d=s?.ttl||AQ,h=s?.prompt||!1,f=s?.tag||0,p=s?.id||rl().toString(),g=i0(nm().protocol),y={id:p,method:s?.publishMethod||g.publish,params:a0({topic:r,message:i,ttl:d,prompt:h,tag:f,attestation:s?.attestation},s?.tvf)},A=`Failed to publish payload, please try again. id:${p} tag:${f}`;try{$n((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),$n((c=y.params)==null?void 0:c.tag)&&((l=y.params)==null||delete l.tag);const _=new Promise(async v=>{const w=({id:O})=>{var D;((D=y.id)==null?void 0:D.toString())===O.toString()&&(this.removeRequestFromQueue(O),this.relayer.events.removeListener(hn.publish,w),v())};this.relayer.events.on(hn.publish,w);const T=Js(new Promise((O,D)=>{this.rpcPublish(y,s).then(O).catch(F=>{this.logger.warn(F,F?.message),D(F)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${f}`);try{await T,this.events.removeListener(hn.publish,w)}catch(O){this.queue.set(p,{request:y,opts:s,attempt:1}),this.logger.warn(O,O?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await Js(_,this.publishTimeout,A)}catch(_){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(_),(u=s?.internal)!=null&&u.throwOnFailedPublish)throw _}finally{this.queue.delete(p)}}),Wi(this,"publishCustom",async r=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:l,opts:u={}}=r,{attestation:d,tvf:h,publishMethod:f,prompt:p,tag:g,ttl:y=ve.FIVE_MINUTES}=u,A=u.id||rl().toString(),_=i0(nm().protocol),v=f||_.publish,w={id:A,method:v,params:a0(GI(a0({},l),{ttl:y,prompt:p,tag:g,attestation:d}),h)},T=`Failed to publish custom payload, please try again. id:${A} tag:${g}`;try{$n((i=w.params)==null?void 0:i.prompt)&&((s=w.params)==null||delete s.prompt),$n((o=w.params)==null?void 0:o.tag)&&((a=w.params)==null||delete a.tag);const O=new Promise(async D=>{const F=({id:j})=>{var W;((W=w.id)==null?void 0:W.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(hn.publish,F),D())};this.relayer.events.on(hn.publish,F);const U=Js(new Promise((j,W)=>{this.rpcPublish(w,u).then(j).catch(S=>{this.logger.warn(S,S?.message),W(S)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${v} id:${A} tag:${g}`);try{await U,this.events.removeListener(hn.publish,F)}catch(j){this.queue.set(A,{request:w,opts:u,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:A,payload:l,opts:u}}),await Js(O,this.publishTimeout,T)}catch(O){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(O),(c=u?.internal)!=null&&c.throwOnFailedPublish)throw O}finally{this.queue.delete(A)}}),Wi(this,"on",(r,i)=>{this.events.on(r,i)}),Wi(this,"once",(r,i)=>{this.events.once(r,i)}),Wi(this,"off",(r,i)=>{this.events.off(r,i)}),Wi(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=t,this.logger=vi(n,this.name),this.registerEventListeners()}get context(){return Gr(this.logger)}async rpcPublish(t,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:t});const r=await this.relayer.request(t);return this.relayer.events.emit(hn.publish,a0(a0({},t),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async(t,n)=>{var r;const i=t.attempt+1;this.queue.set(n,GI(a0({},t),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${(r=t.request.params)==null?void 0:r.tag}, attempt: ${i}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(wu.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(hn.connection_stalled);return}this.checkQueue()}),this.relayer.on(hn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}}var Mte=Object.defineProperty,Dte=(e,t,n)=>t in e?Mte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,c0=(e,t,n)=>Dte(e,typeof t!="symbol"?t+"":t,n);class Ute{constructor(){c0(this,"map",new Map),c0(this,"set",(t,n)=>{const r=this.get(t);this.exists(t,n)||this.map.set(t,[...r,n])}),c0(this,"get",t=>this.map.get(t)||[]),c0(this,"exists",(t,n)=>this.get(t).includes(n)),c0(this,"delete",(t,n)=>{if(typeof n>"u"){this.map.delete(t);return}if(!this.map.has(t))return;const r=this.get(t);if(!this.exists(t,n))return;const i=r.filter(s=>s!==n);if(!i.length){this.map.delete(t);return}this.map.set(t,i)}),c0(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Lte=Object.defineProperty,Fte=Object.defineProperties,Hte=Object.getOwnPropertyDescriptors,KI=Object.getOwnPropertySymbols,jte=Object.prototype.hasOwnProperty,zte=Object.prototype.propertyIsEnumerable,d4=(e,t,n)=>t in e?Lte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$h=(e,t)=>{for(var n in t||(t={}))jte.call(t,n)&&d4(e,n,t[n]);if(KI)for(var n of KI(t))zte.call(t,n)&&d4(e,n,t[n]);return e},f4=(e,t)=>Fte(e,Hte(t)),jt=(e,t,n)=>d4(e,typeof t!="symbol"?t+"":t,n);class Vte extends pJ{constructor(t,n){super(t,n),this.relayer=t,this.logger=n,jt(this,"subscriptions",new Map),jt(this,"topicMap",new Ute),jt(this,"events",new zn.exports.EventEmitter),jt(this,"name",NQ),jt(this,"version",PQ),jt(this,"pending",new Map),jt(this,"cached",[]),jt(this,"initialized",!1),jt(this,"storagePrefix",so),jt(this,"subscribeTimeout",ve.toMiliseconds(ve.ONE_MINUTE)),jt(this,"initialSubscribeTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),jt(this,"clientId"),jt(this,"batchSubscribeTopicsLimit",500),jt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),jt(this,"subscribe",async(r,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=nm(i),a={topic:r,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),jt(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),jt(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),jt(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),jt(this,"on",(r,i)=>{this.events.on(r,i)}),jt(this,"once",(r,i)=>{this.events.once(r,i)}),jt(this,"off",(r,i)=>{this.events.off(r,i)}),jt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),jt(this,"start",async()=>{await this.onConnect()}),jt(this,"stop",async()=>{await this.onDisconnect()}),jt(this,"restart",async()=>{await this.restore(),await this.onRestart()}),jt(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),jt(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(wu.pulse,async()=>{await this.checkPending()}),this.events.on(Ci.created,async r=>{const i=Ci.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(Ci.deleted,async r=>{const i=Ci.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=t,this.logger=vi(n,this.name),this.clientId=""}get context(){return Gr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(t,n){let r=!1;try{r=this.getSubscription(t).topic===n}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,n){const r=this.topicMap.get(t);await Promise.all(r.map(async i=>await this.unsubscribeById(t,i,n)))}async unsubscribeById(t,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:n,opts:r}});try{const i=nm(r);await this.restartToComplete({topic:t,id:n,relay:i}),await this.rpcUnsubscribe(t,n,i);const s=Gt("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(t,n,r){var i,s;const o=await this.getSubscriptionId(t);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===Kt.relay)&&await this.restartToComplete({topic:t,id:t,relay:n});const a={method:i0(n.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{if(r?.transportType===Kt.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(d=>this.logger.warn(d))},ve.toMiliseconds(ve.ONE_SECOND)),o;const l=new Promise(async d=>{const h=f=>{f.topic===t&&(this.events.removeListener(Ci.created,h),d(f.id))};this.events.on(Ci.created,h);try{const f=await Js(new Promise((p,g)=>{this.relayer.request(a).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${t} failed, please try again`);this.events.removeListener(Ci.created,h),d(f)}catch{}}),u=await Js(l,this.subscribeTimeout,`Subscribing to ${t} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${t} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(hn.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(t){if(!t.length)return!0;const n=t[0].relay,r={method:i0(n.protocol).batchSubscribe,params:{topics:t.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{return await Js(new Promise((i,s)=>{this.relayer.request(r).then(i).catch(o=>{this.logger.warn(o),s(o)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(hn.connection_stalled),!1}}async rpcBatchFetchMessages(t){if(!t.length)return;const n=t[0].relay,r={method:i0(n.protocol).batchFetchMessages,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await Js(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(hn.connection_stalled)}return i}rpcUnsubscribe(t,n,r){const i={method:i0(r.protocol).unsubscribe,params:{topic:t,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(t,n){this.setSubscription(t,f4($h({},n),{id:t})),this.pending.delete(n.topic)}onBatchSubscribe(t){t.length&&t.forEach(n=>{this.setSubscription(n.id,$h({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(t,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,t)&&this.deleteSubscription(n,r),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:n}),this.addSubscription(t,n)}addSubscription(t,n){this.subscriptions.set(t,$h({},n)),this.topicMap.set(n.topic,t),this.events.emit(Ci.created,n)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});const n=this.subscriptions.get(t);if(!n){const{message:r}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(r)}return n}deleteSubscription(t,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:n});const r=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(r.topic,t),this.events.emit(Ci.deleted,f4($h({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ci.sync)}async onRestart(){if(this.cached.length){const t=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const i=t.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(Ci.resubscribed)}async restore(){try{const t=await this.getRelayerSubscriptions();if(typeof t>"u"||!t.length)return;if(this.subscriptions.size&&!t.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){if(t.length){if(!await this.rpcBatchSubscribe(t)){this.logger.warn(`Batch subscribe failed for ${t.length} topics, adding to pending for retry`),t.forEach(n=>{this.pending.set(n.topic,n)});return}this.onBatchSubscribe(await Promise.all(t.map(async n=>f4($h({},n),{id:await this.getSubscriptionId(n.topic)}))))}}async batchFetchMessages(t){if(!t.length)return;this.logger.trace(`Fetching batch messages for ${t.length} subscriptions`);const n=await this.rpcBatchFetchMessages(t);n&&n.messages&&(await SZ(ve.toMiliseconds(ve.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(t){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(t),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(t){return Fi(t+await this.getClientId())}}var Wte=Object.defineProperty,YI=Object.getOwnPropertySymbols,qte=Object.prototype.hasOwnProperty,Zte=Object.prototype.propertyIsEnumerable,h4=(e,t,n)=>t in e?Wte(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,XI=(e,t)=>{for(var n in t||(t={}))qte.call(t,n)&&h4(e,n,t[n]);if(YI)for(var n of YI(t))Zte.call(t,n)&&h4(e,n,t[n]);return e},pt=(e,t,n)=>h4(e,typeof t!="symbol"?t+"":t,n);class Gte extends fJ{constructor(t){var n;super(t),pt(this,"protocol","wc"),pt(this,"version",2),pt(this,"core"),pt(this,"logger"),pt(this,"events",new zn.exports.EventEmitter),pt(this,"provider"),pt(this,"messages"),pt(this,"subscriber"),pt(this,"publisher"),pt(this,"name",_Q),pt(this,"transportExplicitlyClosed",!1),pt(this,"initialized",!1),pt(this,"connectionAttemptInProgress",!1),pt(this,"relayUrl"),pt(this,"projectId"),pt(this,"packageName"),pt(this,"bundleId"),pt(this,"hasExperiencedNetworkDisruption",!1),pt(this,"pingTimeout"),pt(this,"heartBeatTimeout",ve.toMiliseconds(ve.THIRTY_SECONDS+ve.FIVE_SECONDS)),pt(this,"reconnectTimeout"),pt(this,"connectPromise"),pt(this,"reconnectInProgress",!1),pt(this,"requestsInFlight",[]),pt(this,"connectTimeout",ve.toMiliseconds(ve.ONE_SECOND*15)),pt(this,"stalledRestartInProgress",!1),pt(this,"stalledRestartTimeout"),pt(this,"stalledRestartBackoff",0),pt(this,"stalledRestartBaseInterval",ve.toMiliseconds(ve.ONE_SECOND*2)),pt(this,"stalledRestartMaxInterval",ve.toMiliseconds(ve.THIRTY_SECONDS)),pt(this,"request",async r=>{var i,s;this.logger.debug("Publishing Request Payload");const o=r.id||rl().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const a=`${o}:${((s=r.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),pt(this,"resetPingTimeout",()=>{Rg()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),pt(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),pt(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(hn.connect)}),pt(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),pt(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(hn.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(i=>this.logger.warn(i))}),pt(this,"registerProviderListeners",()=>{this.provider.on(zi.payload,this.onPayloadHandler),this.provider.on(zi.connect,this.onConnectHandler),this.provider.on(zi.disconnect,this.onDisconnectHandler),this.provider.on(zi.error,this.onProviderErrorHandler)}),this.core=t.core,this.logger=G8({logger:(n=t.logger)!=null?n:xQ,name:this.name}),this.messages=new Tte(this.logger,t.core),this.subscriber=new Vte(this,this.logger),this.publisher=new Bte(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||SI,uZ()?this.packageName=t7():dZ()&&(this.bundleId=t7()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(t=>this.logger.warn(t,t?.message))}get context(){return Gr(this.logger)}get connected(){var t,n,r;return((r=(n=(t=this.provider)==null?void 0:t.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var t,n,r;return((r=(n=(t=this.provider)==null?void 0:t.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(t,n,r){this.isInitialized(),await this.publisher.publish(t,n,r),await this.recordMessageEvent({topic:t,message:n,publishedAt:Date.now(),transportType:Kt.relay},hm.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,n){var r,i,s;this.isInitialized(),(!(n!=null&&n.transportType)||n?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=n?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=n?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(t))==null?void 0:s[0])||"",c;const l=u=>{u.topic===t&&(this.subscriber.off(Ci.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(Ci.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(t,XI({internal:{throwOnFailedPublish:o}},n)).catch(h=>{o&&d(h)})||a,u()})]),a}async unsubscribe(t,n){this.isInitialized(),await this.subscriber.unsubscribe(t,n)}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Js(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(t){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(n,r)=>{await this.connect(t).then(n).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(t){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await XS())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(t){if(t?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const n=t.sort((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(t,n){const{topic:r}=t;if(!n.sessionExists){const i=mn(ve.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(hn.message,t),await this.recordMessageEvent(t,hm.inbound)}async connect(t){await this.confirmOnlineStateOrThrow(),t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let n=1;for(;n<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise(async(r,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(zi.disconnect,s),await Js(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(zi.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(zi.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(zi.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,ve.toMiliseconds(n*1))),n++}}startPingTimeout(){var t,n,r,i,s;if(Rg())try{(n=(t=this.provider)==null?void 0:t.connection)!=null&&n.socket&&((s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new i4(new uQ(mZ({sdkVersion:s4,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(t,n){const{topic:r,message:i}=t;await this.messages.set(r,i,n)}async shouldIgnoreMessageEvent(t){const{topic:n,message:r}=t;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(n))return this.logger.warn(`Ignoring message for unknown topic ${n}`),!0;const i=this.messages.has(n,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),r4(t)){if(!t.method.endsWith(SQ))return;const n=t.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:Kt.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(XI({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else dm(t)&&this.events.emit(hn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,hm.inbound),this.events.emit(hn.message,t))}async acknowledgePayload(t){const n=Ch(t.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(zi.payload,this.onPayloadHandler),this.provider.off(zi.connect,this.onConnectHandler),this.provider.off(zi.disconnect,this.onDisconnectHandler),this.provider.off(zi.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await XS();uX(async n=>{t!==n&&(t=n,n?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(wu.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&hX())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}}),this.events.on(hn.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const n=this.stalledRestartBackoff===0?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${n?` in ${n}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(r){this.logger.error(r,r?.message)}finally{this.stalledRestartInProgress=!1}},n)})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(hn.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(t=>this.logger.error(t,t?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},ve.toMiliseconds(IQ)))))}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function Kte(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function JI(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function QI(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Yte="[object RegExp]",Xte="[object String]",Jte="[object Number]",Qte="[object Boolean]",e$="[object Arguments]",ene="[object Symbol]",tne="[object Date]",nne="[object Map]",rne="[object Set]",ine="[object Array]",sne="[object Function]",one="[object ArrayBuffer]",p4="[object Object]",ane="[object Error]",cne="[object DataView]",lne="[object Uint8Array]",une="[object Uint8ClampedArray]",dne="[object Uint16Array]",fne="[object Uint32Array]",hne="[object BigUint64Array]",pne="[object Int8Array]",gne="[object Int16Array]",mne="[object Int32Array]",yne="[object BigInt64Array]",wne="[object Float32Array]",bne="[object Float64Array]";function t$(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(e)==="[object Object]":!1}function vne(e,t,n){return Th(e,t,void 0,void 0,void 0,void 0,n)}function Th(e,t,n,r,i,s,o){const a=o(e,t,n,r,i,s);if(a!==void 0)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return e===t;case"number":return e===t||Object.is(e,t);case"function":return e===t;case"object":return Nh(e,t,s,o)}return Nh(e,t,s,o)}function Nh(e,t,n,r){if(Object.is(e,t))return!0;let i=QI(e),s=QI(t);if(i===e$&&(i=p4),s===e$&&(s=p4),i!==s)return!1;switch(i){case Xte:return e.toString()===t.toString();case Jte:{const c=e.valueOf(),l=t.valueOf();return Kte(c,l)}case Qte:case tne:case ene:return Object.is(e.valueOf(),t.valueOf());case Yte:return e.source===t.source&&e.flags===t.flags;case sne:return e===t}n=n??new Map;const o=n.get(e),a=n.get(t);if(o!=null&&a!=null)return o===t;n.set(e,t),n.set(t,e);try{switch(i){case nne:{if(e.size!==t.size)return!1;for(const[c,l]of e.entries())if(!t.has(c)||!Th(l,t.get(c),c,e,t,n,r))return!1;return!0}case rne:{if(e.size!==t.size)return!1;const c=Array.from(e.values()),l=Array.from(t.values());for(let u=0;u<c.length;u++){const d=c[u],h=l.findIndex(f=>Th(d,f,void 0,e,t,n,r));if(h===-1)return!1;l.splice(h,1)}return!0}case ine:case lne:case une:case dne:case fne:case hne:case pne:case gne:case mne:case yne:case wne:case bne:{if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let c=0;c<e.length;c++)if(!Th(e[c],t[c],c,e,t,n,r))return!1;return!0}case one:return e.byteLength!==t.byteLength?!1:Nh(new Uint8Array(e),new Uint8Array(t),n,r);case cne:return e.byteLength!==t.byteLength||e.byteOffset!==t.byteOffset?!1:Nh(new Uint8Array(e),new Uint8Array(t),n,r);case ane:return e.name===t.name&&e.message===t.message;case p4:{if(!(Nh(e.constructor,t.constructor,n,r)||t$(e)&&t$(t)))return!1;const c=[...Object.keys(e),...JI(e)],l=[...Object.keys(t),...JI(t)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],h=e[d];if(!Object.hasOwn(t,d))return!1;const f=t[d];if(!Th(h,f,d,e,t,n,r))return!1}return!0}default:return!1}}finally{n.delete(e),n.delete(t)}}function Ene(){}function Ane(e,t){return vne(e,t,Ene)}var Cne=Object.defineProperty,n$=Object.getOwnPropertySymbols,xne=Object.prototype.hasOwnProperty,_ne=Object.prototype.propertyIsEnumerable,g4=(e,t,n)=>t in e?Cne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,r$=(e,t)=>{for(var n in t||(t={}))xne.call(t,n)&&g4(e,n,t[n]);if(n$)for(var n of n$(t))_ne.call(t,n)&&g4(e,n,t[n]);return e},ei=(e,t,n)=>g4(e,typeof t!="symbol"?t+"":t,n);class Cu extends hJ{constructor(t,n,r,i=so,s=void 0){super(t,n,r,i),this.core=t,this.logger=n,this.name=r,ei(this,"map",new Map),ei(this,"version",$Q),ei(this,"cached",[]),ei(this,"initialized",!1),ei(this,"getKey"),ei(this,"storagePrefix",so),ei(this,"recentlyDeleted",[]),ei(this,"recentlyDeletedLimit",200),ei(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!$n(o)?this.map.set(this.getKey(o),o):HY(o)?this.map.set(o.id,o):jY(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ei(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),ei(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ei(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Ane(a[c],o[c]))):this.values)),ei(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=r$(r$({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ei(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=vi(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Gr(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(t){this.recentlyDeleted.push(t),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){const n=this.map.get(t);if(!n){if(this.recentlyDeleted.includes(t)){const{message:i}=Ae("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(i),new Error(i)}const{message:r}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(r),new Error(r)}return n}async persist(){await this.setDataStore(this.values)}async restore(){try{const t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){const{message:n}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Sne=Object.defineProperty,Ine=(e,t,n)=>t in e?Sne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,bt=(e,t,n)=>Ine(e,typeof t!="symbol"?t+"":t,n);class $ne{constructor(t,n){this.core=t,this.logger=n,bt(this,"name",OQ),bt(this,"version",kQ),bt(this,"events",new zn.exports),bt(this,"pairings"),bt(this,"initialized",!1),bt(this,"storagePrefix",so),bt(this,"ignoredPayloadTypes",[ec]),bt(this,"registeredMethods",[]),bt(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),bt(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),bt(this,"create",async r=>{this.isInitialized();const i=j8(),s=await this.core.crypto.setSymKey(i),o=mn(ve.FIVE_MINUTES),a={protocol:_I},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},l=LS({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(vu.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r?.transportType,internal:r?.internal}),{topic:s,uri:l}}),bt(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[oo.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=US(r.uri);i.props.properties.topic=s,i.addTrace(oo.pairing_uri_validation_success),i.addTrace(oo.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),i.addTrace(oo.existing_pairing),u.active)throw i.setError(rc.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(oo.pairing_not_expired)}const d=c||mn(ve.FIVE_MINUTES),h={topic:s,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(s,d),await this.pairings.set(s,h),i.addTrace(oo.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(vu.create,h),i.addTrace(oo.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(oo.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(rc.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(f){throw i.setError(rc.subscribe_pairing_topic_failure),f}return i.addTrace(oo.subscribe_pairing_topic_success),h}),bt(this,"activate",async({topic:r})=>{this.isInitialized();const i=mn(ve.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),bt(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=uu();this.events.once(Rt("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),bt(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),bt(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),bt(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),bt(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Gt("USER_DISCONNECTED")),await this.deletePairing(i))}),bt(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return LS({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),bt(this,"sendRequest",async(r,i,s)=>{const o=ws(i,s),a=await this.core.crypto.encode(r,o),c=xh[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),bt(this,"sendResult",async(r,i,s)=>{const o=Ch(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=xh[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),bt(this,"sendError",async(r,i,s)=>{const o=um(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=xh[c]?xh[c].res:xh.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),bt(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,Gt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),bt(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>Qs(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),bt(this,"onRelayEventRequest",async r=>{const{topic:i,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),bt(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s}=r,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),bt(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(vu.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),bt(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{io(i)?this.events.emit(Rt("pairing_ping",s),{}):ji(i)&&this.events.emit(Rt("pairing_ping",s),{error:i.error})},500)}),bt(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(vu.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),bt(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=Gt("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),bt(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(Gt("WC_METHOD_UNSUPPORTED",r))}),bt(this,"isValidPair",(r,i)=>{var s;if(!Jr(r)){const{message:a}=Ae("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(!FY(r.uri)){const{message:a}=Ae("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(rc.malformed_pairing_uri),new Error(a)}const o=US(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=Ae("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=Ae("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(rc.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&ve.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(rc.pairing_expired);const{message:a}=Ae("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),bt(this,"isValidPing",async r=>{if(!Jr(r)){const{message:s}=Ae("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),bt(this,"isValidDisconnect",async r=>{if(!Jr(r)){const{message:s}=Ae("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),bt(this,"isValidPairingTopic",async r=>{if(!yn(r,!1)){const{message:i}=Ae("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=Ae("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(Qs(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=Ae("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=t,this.logger=vi(n,this.name),this.pairings=new Cu(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Gr(this.logger)}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(hn.message,async t=>{const{topic:n,message:r,transportType:i}=t;if(this.pairings.keys.includes(n)&&i!==Kt.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);r4(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):dm(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:n,payload:s}),this.core.history.delete(n,s.id)),await this.core.relayer.messages.ack(n,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Vi.expired,async t=>{const{topic:n}=s7(t.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(vu.expire,{topic:n}))})}}var Tne=Object.defineProperty,Nne=(e,t,n)=>t in e?Tne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Kn=(e,t,n)=>Nne(e,typeof t!="symbol"?t+"":t,n);class Pne extends lJ{constructor(t,n){super(t,n),this.core=t,this.logger=n,Kn(this,"records",new Map),Kn(this,"events",new zn.exports.EventEmitter),Kn(this,"name",RQ),Kn(this,"version",BQ),Kn(this,"cached",[]),Kn(this,"initialized",!1),Kn(this,"storagePrefix",so),Kn(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Kn(this,"set",(r,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:s,expiry:mn(ve.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(bs.created,o)}),Kn(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=ji(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(bs.updated,i))}),Kn(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Kn(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===r){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(bs.deleted,s)}}),this.persist()}),Kn(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Kn(this,"on",(r,i)=>{this.events.on(r,i)}),Kn(this,"once",(r,i)=>{this.events.once(r,i)}),Kn(this,"off",(r,i)=>{this.events.off(r,i)}),Kn(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=vi(n,this.name)}get context(){return Gr(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 t=[];return this.values.forEach(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:ws(n.request.method,n.request.params,n.id),chainId:n.chainId};return t.push(r)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();const n=this.records.get(t);if(!n){const{message:r}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(bs.sync)}async restore(){try{const t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){const{message:n}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(bs.created,t=>{const n=bs.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(bs.updated,t=>{const n=bs.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.events.on(bs.deleted,t=>{const n=bs.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:t})}),this.core.heartbeat.on(wu.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(n=>{ve.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(bs.deleted,n,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var One=Object.defineProperty,kne=(e,t,n)=>t in e?One(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hr=(e,t,n)=>kne(e,typeof t!="symbol"?t+"":t,n);class Rne extends gJ{constructor(t,n){super(t,n),this.core=t,this.logger=n,hr(this,"expirations",new Map),hr(this,"events",new zn.exports.EventEmitter),hr(this,"name",MQ),hr(this,"version",DQ),hr(this,"cached",[]),hr(this,"initialized",!1),hr(this,"storagePrefix",so),hr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),hr(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),hr(this,"set",(r,i)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Vi.created,{target:s,expiration:o})}),hr(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),hr(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Vi.deleted,{target:i,expiration:s})}}),hr(this,"on",(r,i)=>{this.events.on(r,i)}),hr(this,"once",(r,i)=>{this.events.once(r,i)}),hr(this,"off",(r,i)=>{this.events.off(r,i)}),hr(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=vi(n,this.name)}get context(){return Gr(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(t){if(typeof t=="string")return yZ(t);if(typeof t=="number")return wZ(t);const{message:n}=Ae("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(n)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Vi.sync)}async restore(){try{const t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){const{message:n}=Ae("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){const n=this.expirations.get(t);if(!n){const{message:r}=Ae("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(t,n){const{expiry:r}=n;ve.toMiliseconds(r)-Date.now()<=0&&this.expire(t,n)}expire(t,n){this.expirations.delete(t),this.events.emit(Vi.expired,{target:t,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,n)=>this.checkExpiry(n,t))}registerEventListeners(){this.core.heartbeat.on(wu.pulse,()=>this.checkExpirations()),this.events.on(Vi.created,t=>{const n=Vi.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Vi.expired,t=>{const n=Vi.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()}),this.events.on(Vi.deleted,t=>{const n=Vi.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:t}),this.persist()})}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}}var Bne=Object.defineProperty,Mne=(e,t,n)=>t in e?Bne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wn=(e,t,n)=>Mne(e,typeof t!="symbol"?t+"":t,n);class Dne extends mJ{constructor(t,n,r){super(t,n,r),this.core=t,this.logger=n,this.store=r,wn(this,"name",UQ),wn(this,"abortController"),wn(this,"isDevEnv"),wn(this,"verifyUrlV3",FQ),wn(this,"storagePrefix",so),wn(this,"version",CI),wn(this,"publicKey"),wn(this,"fetchPromise"),wn(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&ve.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),wn(this,"register",async i=>{if(!Yd()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=Kl(),u=this.startAbortTimer(ve.ONE_SECOND*5),d=await new Promise((h,f)=>{const p=()=>{window.removeEventListener("message",y),l.body.removeChild(g),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const y=A=>{if(A.data&&typeof A.data=="string")try{const _=JSON.parse(A.data);if(_.type==="verify_attestation"){if(Gb(_.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",y),h(_.attestation===null?"":_.attestation)}}catch(_){this.logger.warn(_)}};l.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug(d,"jwt attestation"),d}catch(l){this.logger.warn(l)}return""}),wn(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Gb(s).payload.id!==a)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(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),wn(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(ve.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),wn(this,"getVerifyUrl",i=>{let s=i||_h;return HQ.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${_h}`),s=_h),s}),wn(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(ve.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),wn(this,"persistPublicKey",async i=>{this.logger.debug(i,"persisting public key to local storage"),await this.store.setItem(this.storeKey,i),this.publicKey=i}),wn(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),wn(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),wn(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),wn(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),wn(this,"validateAttestation",(i,s)=>{const o=pY(i,s.publicKey),a={hasExpired:ve.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=vi(n,this.name),this.abortController=new AbortController,this.isDevEnv=d8(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Gr(this.logger)}startAbortTimer(t){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ve.toMiliseconds(t))}}var Une=Object.defineProperty,Lne=(e,t,n)=>t in e?Une(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,i$=(e,t,n)=>Lne(e,typeof t!="symbol"?t+"":t,n);class Fne extends yJ{constructor(t,n){super(t,n),this.projectId=t,this.logger=n,i$(this,"context",jQ),i$(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${zQ}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=vi(n,this.context)}}var Hne=Object.defineProperty,s$=Object.getOwnPropertySymbols,jne=Object.prototype.hasOwnProperty,zne=Object.prototype.propertyIsEnumerable,m4=(e,t,n)=>t in e?Hne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ph=(e,t)=>{for(var n in t||(t={}))jne.call(t,n)&&m4(e,n,t[n]);if(s$)for(var n of s$(t))zne.call(t,n)&&m4(e,n,t[n]);return e},Dn=(e,t,n)=>m4(e,typeof t!="symbol"?t+"":t,n);class Vne extends wJ{constructor(t,n,r=!0){super(t,n,r),this.core=t,this.logger=n,Dn(this,"context",WQ),Dn(this,"storagePrefix",so),Dn(this,"storageVersion",VQ),Dn(this,"events",new Map),Dn(this,"shouldPersist",!1),Dn(this,"init",async()=>{if(!d8())try{const i={eventId:a7(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:r7(this.core.relayer.protocol,this.core.relayer.version,s4)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Dn(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=a7(),u=this.core.projectId||"",d=Date.now(),h=Ph({eventId:l,timestamp:d,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),Dn(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Ph(Ph({},a),this.setMethods(a.eventId))}),Dn(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Dn(this,"setEventListeners",()=>{this.core.heartbeat.on(wu.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{ve.fromMiliseconds(Date.now())-ve.fromMiliseconds(i.timestamp)>qQ&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Dn(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Dn(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Dn(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Dn(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Dn(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Ph(Ph({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Dn(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Dn(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${ZQ}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${s4}${s}`,{method:"POST",body:JSON.stringify(i)})}),Dn(this,"getAppDomain",()=>n7().url),this.logger=vi(n,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var Wne=Object.defineProperty,o$=Object.getOwnPropertySymbols,qne=Object.prototype.hasOwnProperty,Zne=Object.prototype.propertyIsEnumerable,y4=(e,t,n)=>t in e?Wne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,a$=(e,t)=>{for(var n in t||(t={}))qne.call(t,n)&&y4(e,n,t[n]);if(o$)for(var n of o$(t))Zne.call(t,n)&&y4(e,n,t[n]);return e},qt=(e,t,n)=>y4(e,typeof t!="symbol"?t+"":t,n);class w4 extends sJ{constructor(t){var n;super(t),qt(this,"protocol",AI),qt(this,"version",CI),qt(this,"name",fm),qt(this,"relayUrl"),qt(this,"projectId"),qt(this,"customStoragePrefix"),qt(this,"events",new zn.exports.EventEmitter),qt(this,"logger"),qt(this,"heartbeat"),qt(this,"relayer"),qt(this,"crypto"),qt(this,"storage"),qt(this,"history"),qt(this,"expirer"),qt(this,"pairing"),qt(this,"verify"),qt(this,"echoClient"),qt(this,"linkModeSupportedApps"),qt(this,"eventClient"),qt(this,"initialized",!1),qt(this,"logChunkController"),qt(this,"on",(a,c)=>this.events.on(a,c)),qt(this,"once",(a,c)=>this.events.once(a,c)),qt(this,"off",(a,c)=>this.events.off(a,c)),qt(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),qt(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Kt.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(t?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||SI,this.customStoragePrefix=t!=null&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";const i=Z_({level:typeof t?.logger=="string"&&t.logger?t.logger:pQ.logger,name:fm}),{logger:s,chunkLoggerController:o}=a8({opts:i,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=o,(n=this.logChunkController)!=null&&n.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=vi(s,this.name),this.heartbeat=new K8,this.crypto=new Ete(this,this.logger,t?.keychain),this.history=new Pne(this,this.logger),this.expirer=new Rne(this,this.logger),this.storage=t!=null&&t.storage?t.storage:new nJ(a$(a$({},gQ),t?.storageOptions)),this.relayer=new Gte({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new $ne(this,this.logger),this.verify=new Dne(this,this.logger,this.storage),this.echoClient=new Fne(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Vne(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){const n=new w4(t);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(TQ,r),n}get context(){return Gr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var t;return(t=this.logChunkController)==null?void 0:t.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(t){this.linkModeSupportedApps.includes(t)||(this.linkModeSupportedApps.push(t),await this.storage.setItem(II,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.linkModeSupportedApps=await this.storage.getItem(II)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(t,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(t.message),t}}getGlobalCore(t=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${t}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(t){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=t.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=t}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const Gne=w4,c$="wc",l$=2,u$="client",b4=`${c$}@${l$}:${u$}:`,v4={name:u$,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},d$="WALLETCONNECT_DEEPLINK_CHOICE",Kne="proposal",f$="Proposal expired",Yne="session",l0=ve.SEVEN_DAYS,Xne="engine",Yn={wc_sessionPropose:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ve.FIVE_MINUTES*3,prompt:!0,tag:1108},res:{ttl:ve.FIVE_MINUTES*3,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ve.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ve.ONE_DAY,prompt:!1,tag:1114},res:{ttl:ve.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:ve.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:ve.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:ve.FIVE_MINUTES,prompt:!1,tag:1119}}},E4={min:ve.FIVE_MINUTES,max:ve.SEVEN_DAYS},co={idle:"IDLE",active:"ACTIVE"},Jne={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},Qne="request",ere=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],tre="wc",nre="auth",rre="authKeys",ire="pairingTopics",sre="requests",gm=`${tre}@${1.5}:${nre}:`,mm=`${gm}:PUB_KEY`;var ore=Object.defineProperty,are=Object.defineProperties,cre=Object.getOwnPropertyDescriptors,h$=Object.getOwnPropertySymbols,lre=Object.prototype.hasOwnProperty,ure=Object.prototype.propertyIsEnumerable,A4=(e,t,n)=>t in e?ore(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pt=(e,t)=>{for(var n in t||(t={}))lre.call(t,n)&&A4(e,n,t[n]);if(h$)for(var n of h$(t))ure.call(t,n)&&A4(e,n,t[n]);return e},Xn=(e,t)=>are(e,cre(t)),ye=(e,t,n)=>A4(e,typeof t!="symbol"?t+"":t,n);class dre extends AJ{constructor(t){super(t),ye(this,"name",Xne),ye(this,"events",new zn.exports),ye(this,"initialized",!1),ye(this,"requestQueue",{state:co.idle,queue:[]}),ye(this,"sessionRequestQueue",{state:co.idle,queue:[]}),ye(this,"emittedSessionRequests",new IZ({limit:500})),ye(this,"requestQueueDelay",ve.ONE_SECOND),ye(this,"expectedPairingMethodMap",new Map),ye(this,"recentlyDeletedMap",new Map),ye(this,"recentlyDeletedLimit",200),ye(this,"relayMessageCache",[]),ye(this,"pendingSessions",new Map),ye(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(Yn)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ve.toMiliseconds(this.requestQueueDelay)))}),ye(this,"connect",async n=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Xn(Pt({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=DY(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:u,authentication:d,walletPay:h}=i,f=((r=d?.[0])==null?void 0:r.ttl)||Yn.wc_sessionPropose.req.ttl||ve.FIVE_MINUTES;this.validateRequestExpiry(f);let p=s,g,y=!1;try{if(p){const U=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),y=U.active}}catch(U){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),U}if(!p||!y){const{topic:U,uri:j}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=U,g=j}if(!p){const{message:U}=Ae("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(U)}const A=await this.client.core.crypto.generateKeyPair(),_=mn(f),v=Pt(Xn(Pt(Pt({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:_I}],proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:_,pairingTopic:p},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:ro()}),(d||h)&&{requests:{authentication:d?.map(U=>{const{domain:j,chains:W,nonce:S,uri:x,exp:I,nbf:m,type:b,statement:$,requestId:N,resources:P,signatureTypes:B}=U;return{domain:j,chains:W,nonce:S,type:b??"caip122",aud:x,version:"1",iat:new Date().toISOString(),exp:I,nbf:m,statement:$,requestId:N,resources:P,signatureTypes:B}}),walletPay:h}}),w=Rt("session_connect",v.id),{reject:T,resolve:O,done:D}=uu(f,f$),F=({id:U})=>{U===v.id&&(this.client.events.off("proposal_expire",F),this.pendingSessions.delete(v.id),this.events.emit(w,{error:{message:f$,code:0}}))};return this.client.events.on("proposal_expire",F),this.events.once(w,({error:U,session:j})=>{this.client.events.off("proposal_expire",F),U?T(U):j&&O(j)}),await this.setProposal(v.id,v),await this.sendProposeSession({proposal:v,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:v.id}}}).catch(U=>{throw this.deleteProposal(v.id),U}),{uri:g,approval:D}}),ye(this,"pair",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(n)}catch(r){throw this.client.logger.error("pair() failed"),r}}),ye(this,"approve",async n=>{var r,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[vs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(j){throw o.setError(Eu.no_internet_connection),j}try{await this.isValidProposalId(n?.id)}catch(j){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(Eu.proposal_not_found),j}try{await this.isValidApprove(n)}catch(j){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Eu.session_approve_namespace_validation_failure),j}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h,proposalRequestsResponses:f}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:y,requiredNamespaces:A,optionalNamespaces:_}=p;let v=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:g});v||(v=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:vs.session_approve_started,properties:{topic:g,trace:[vs.session_approve_started,vs.session_namespaces_validation_success]}}));const w=await this.client.core.crypto.generateKeyPair(),T=y.publicKey,O=await this.client.core.crypto.generateSharedKey(w,T),D=Xn(Pt(Pt(Pt({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:w,metadata:this.client.metadata},expiry:mn(l0)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{proposalRequestsResponses:f}),F=Kt.relay;v.addTrace(vs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:F,internal:{skipSubscribe:!0}})}catch(j){throw v.setError(Eu.subscribe_session_topic_failure),j}v.addTrace(vs.subscribe_session_topic_success);const U=Xn(Pt({},D),{topic:O,requiredNamespaces:A,optionalNamespaces:_,pairingTopic:g,acknowledged:!1,self:D.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:w,transportType:Kt.relay,authentication:f?.authentication,walletPayResult:f?.walletPay});await this.client.session.set(O,U),v.addTrace(vs.store_session);try{await this.sendApproveSession({sessionTopic:O,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:w},sessionSettleRequest:D,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:Pt({correlationId:a},this.getTVFApproveParams(U))}}),v.addTrace(vs.session_approve_publish_success)}catch(j){throw this.client.logger.error(j),this.client.session.delete(O,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(O),j}return this.client.core.eventClient.deleteEvent({eventId:v.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:y.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(O,mn(l0)),{topic:O,acknowledged:()=>Promise.resolve(this.client.session.get(O))}}),ye(this,"reject",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(n)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:i}=n;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:i,rpcOpts:Yn.wc_sessionPropose.reject}),await this.deleteProposal(r)}),ye(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=uu(ve.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=ro(),l=rl().toString(),u=this.client.session.get(r).namespaces;return this.events.once(Rt("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(r,{namespaces:u}),a(d)}),{acknowledged:s}}),ye(this,"extend",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(n)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=n,i=ro(),{done:s,resolve:o,reject:a}=uu(ve.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(Rt("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,mn(l0)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),ye(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:i,topic:s,expiry:o=Yn.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const c=ro(),l=rl().toString(),{done:u,resolve:d,reject:h}=uu(o,"Request expired. Please try again.");this.events.once(Rt("session_request",c),({error:y,result:A})=>{y?h(y):d(A)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:{request:Xn(Pt({},i),{expiryTimestamp:mn(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(y=>h(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await u();const g={request:Xn(Pt({},i),{expiryTimestamp:mn(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:f,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(A=>h(A)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var A;if(!((A=a.sessionConfig)!=null&&A.disableDeepLink)){const _=await AZ(this.client.core.storage,d$);await bZ({id:c,topic:s,wcDeepLink:_})}y()}),u()]).then(y=>y[2])}),ye(this,"respond",async n=>{var r,i;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:n?.topic||((i=(r=n?.response)==null?void 0:r.id)==null?void 0:i.toString()),trace:[vs.session_request_response_started]}});try{await this.isValidRespond(n)}catch(d){throw s.addTrace(d?.message),s.setError(Eu.session_request_response_validation_failure),d}s.addTrace(vs.session_request_response_validation_success);const{topic:o,response:a}=n,{id:c}=a,l=this.client.session.get(o);l.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{s.addTrace(vs.session_request_response_publish_started),io(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):ji(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(n)}catch(d){throw s.addTrace(d?.message),s.setError(Eu.session_request_response_publish_failure),d}}),ye(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=ro(),s=rl().toString(),{done:o,resolve:a,reject:c}=uu(ve.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(Rt("session_ping",i),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),ye(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=rl().toString(),a=ro();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),ye(this,"disconnect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(n);const{topic:r}=n;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:Gt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=Ae("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),ye(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>UY(r,n)))),ye(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),ye(this,"authenticate",async(n,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?Kt.link_mode:Kt.relay;o===Kt.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:f,nbf:p,methods:g=[],expiry:y}=n,A=[...n.resources||[]],{topic:_,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:_,uri:v}});const w=await this.client.core.crypto.generateKeyPair(),T=tm(w);if(await Promise.all([this.client.auth.authKeys.set(mm,{responseTopic:T,publicKey:w}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:_})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${_}`),g.length>0){const{namespace:P}=Ga(a[0]);let B=LG(P,"request",g);zg(A)&&(B=HG(B,A.pop())),A.push(B)}const O=y&&y>Yn.wc_sessionAuthenticate.req.ttl?y:Yn.wc_sessionAuthenticate.req.ttl,D={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:p,resources:A},requester:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:mn(O)},F={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},U={requiredNamespaces:{},optionalNamespaces:F,relays:[{protocol:"irn"}],pairingTopic:_,proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:mn(Yn.wc_sessionPropose.req.ttl),id:ro()},{done:j,resolve:W,reject:S}=uu(O,"Request expired"),x=ro(),I=Rt("session_connect",U.id),m=Rt("session_request",x),b=async({error:P,session:B})=>{this.events.off(m,$),P?S(P):B&&W({session:B})},$=async P=>{var B,V,Z;if(await this.deletePendingAuthRequest(x,{message:"fulfilled",code:0}),P.error){const ue=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===ue.code?void 0:(this.events.off(I,b),S(P.error.message))}await this.deleteProposal(U.id),this.events.off(I,b);const{cacaos:Y,responder:X}=P.result,G=[],ne=[];for(const ue of Y){await k7({cacao:ue,projectId:this.client.core.projectId})||(this.client.logger.error(ue,"Signature verification failed"),S(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ge}=ue,Be=zg(ge.resources),Fe=[b8(ge.iss)],qe=jg(ge.iss);if(Be){const ct=M7(Be),St=D7(Be);G.push(...ct),Fe.push(...St)}for(const ct of Fe)ne.push(`${ct}:${qe}`)}const se=await this.client.core.crypto.generateSharedKey(w,X.publicKey);let we;G.length>0&&(we={topic:se,acknowledged:!0,self:{publicKey:w,metadata:this.client.metadata},peer:X,controller:X.publicKey,expiry:mn(l0),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:_,namespaces:VS([...new Set(G)],[...new Set(ne)]),transportType:o},await this.client.core.relayer.subscribe(se,{transportType:o}),await this.client.session.set(se,we),_&&await this.client.core.pairing.updateMetadata({topic:_,metadata:X.metadata}),we=this.client.session.get(se)),(B=this.client.metadata.redirect)!=null&&B.linkMode&&(V=X.metadata.redirect)!=null&&V.linkMode&&(Z=X.metadata.redirect)!=null&&Z.universal&&r&&(this.client.core.addLinkModeSupportedApp(X.metadata.redirect.universal),this.client.session.update(se,{transportType:Kt.link_mode})),W({auths:Y,session:we})};this.events.once(I,b),this.events.once(m,$);let N;try{if(s){const P=ws("wc_sessionAuthenticate",D,x);this.client.core.history.set(_,P);const B=await this.client.core.crypto.encode("",P,{type:mh,encoding:nl});N=rm(r,_,B)}else await Promise.all([this.sendRequest({topic:_,method:"wc_sessionAuthenticate",params:D,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:x}),this.sendRequest({topic:_,method:"wc_sessionPropose",params:U,expiry:Yn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:U.id})])}catch(P){throw this.events.off(I,b),this.events.off(m,$),P}return await this.setProposal(U.id,U),await this.setAuthRequest(x,{request:Xn(Pt({},D),{verifyContext:{}}),pairingTopic:_,transportType:o}),{uri:N??v,response:j}}),ye(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Au.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw s.setError(Sh.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Sh.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||Kt.relay;a===Kt.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=tm(c),d={type:ec,receiverPublicKey:c,senderPublicKey:l},h=[],f=[];for(const y of i){if(!await k7({cacao:y,projectId:this.client.core.projectId})){s.setError(Sh.invalid_cacao);const T=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:T,encodeOpts:d}),new Error(T.message)}s.addTrace(Au.cacaos_verified);const{p:A}=y,_=zg(A.resources),v=[b8(A.iss)],w=jg(A.iss);if(_){const T=M7(_),O=D7(_);h.push(...T),v.push(...O)}for(const T of v)f.push(`${T}:${w}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Au.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:mn(l0),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:VS([...new Set(h)],[...new Set(f)]),transportType:a},s.addTrace(Au.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(y){throw s.setError(Sh.subscribe_authenticated_session_topic_failure),y}s.addTrace(Au.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Au.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Au.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw s.setError(Sh.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),ye(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:i}=n,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===Kt.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=tm(o),l={type:ec,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:l,rpcOpts:Yn.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),ye(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return R7(r,i)}),ye(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const n=this.relayMessageCache.shift();n&&await this.onRelayMessage(n)}catch(n){this.client.logger.error(n)}},50)}),ye(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),ye(this,"deleteSession",async n=>{var r;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,Gt("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(d$).catch(l=>this.client.logger.warn(l)),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=co.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===i).map(l=>this.deletePendingSessionRequest(l.id,Gt("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),ye(this,"deleteProposal",async(n,r)=>{if(r)try{const i=this.client.proposal.get(n),s=this.client.core.eventClient.getEvent({topic:i.pairingTopic});s?.setError(Eu.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,Gt("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),ye(this,"deletePendingSessionRequest",async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==n),i&&(this.sessionRequestQueue.state=co.idle,this.client.events.emit("session_request_expire",{id:n}))}),ye(this,"deletePendingAuthRequest",async(n,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])}),ye(this,"setExpiry",async(n,r)=>{this.client.session.keys.includes(n)&&(this.client.core.expirer.set(n,r),await this.client.session.update(n,{expiry:r}))}),ye(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,mn(Yn.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),ye(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=Kt.relay}=r;this.client.core.expirer.set(n,i.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:n,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),ye(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||mn(Yn.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:s,verifyContext:o})}),ye(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d,publishOpts:h={}}=n,f=ws(i,s,c);let p;const g=!!u;try{const _=g?nl:Xr;p=await this.client.core.crypto.encode(r,f,{encoding:_})}catch(_){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),_}let y;if(ere.includes(i)){const _=Fi(JSON.stringify(f)),v=Fi(p);y=await this.client.core.verify.register({id:v,decryptedId:_})}const A=Pt(Pt({},Yn[i].req),h);if(A.attestation=y,o&&(A.ttl=o),a&&(A.id=a),this.client.core.history.set(r,f),g){const _=rm(u,r,p);await global.Linking.openURL(_,this.client.name)}else A.tvf=Xn(Pt({},d),{correlationId:f.id}),l?(A.internal=Xn(Pt({},A.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,A)):this.client.core.relayer.publish(r,p,A).catch(_=>this.client.logger.error(_));return f.id}),ye(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=ws("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:Xr}),a=Fi(JSON.stringify(s)),c=Fi(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:Xn(Pt({},i),{publishMethod:"wc_proposeSession",attestation:l})})}),ye(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=Ch(s.id,i),l=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:Xr}),u=ws("wc_sessionSettle",o,a?.id),d=await this.client.core.crypto.encode(r,u,{encoding:Xr});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:d},opts:Xn(Pt({},a),{publishMethod:"wc_approveSession"})})}),ye(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,l=Ch(r,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=d?nl:Xr;u=await this.client.core.crypto.encode(i,l,Xn(Pt({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let h,f;try{h=await this.client.core.history.get(i,r);const p=h.request;try{f=this.getTVFParams(r,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),p}if(d){const p=rm(c,i,u);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=Yn[p].res;g.tvf=Xn(Pt({},f),{correlationId:r}),o?(g.internal=Xn(Pt({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,g)):this.client.core.relayer.publish(i,u,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(l)}),ye(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,l=um(r,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=d?nl:Xr;u=await this.client.core.crypto.encode(i,l,Xn(Pt({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),f}let h;try{h=await this.client.core.history.get(i,r)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),f}if(d){const f=rm(c,i,u);await global.Linking.openURL(f,this.client.name)}else{const f=h.request.method,p=a||Yn[f].res;this.client.core.relayer.publish(i,u,p)}await this.client.core.history.resolve(l)}),ye(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;Qs(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Qs(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),ye(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),ye(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),ye(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===co.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=co.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=co.idle}),ye(this,"processRequest",async n=>{const{topic:r,payload:i,attestation:s,transportType:o,encryptedId:a}=n,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),ye(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i,transportType:s}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),ye(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=Ae("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),ye(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:i}=n,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),ye(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(rc.proposal_listener_not_found)),this.isValidConnect(Pt({},i.params));const u=a.expiryTimestamp||mn(Yn.wc_sessionPropose.req.ttl),d=Pt({id:c,pairingTopic:r,expiryTimestamp:u,attestation:s,encryptedId:o},a);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:s,hash:Fi(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(oo.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:Yn.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),ye(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(io(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:n,proposalId:s,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:n})}else if(ji(r)){await this.deleteProposal(s);const o=Rt("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),ye(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h,proposalRequestsResponses:f}=r.params,p=[...this.pendingSessions.values()].find(A=>A.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const g=this.client.proposal.get(p.proposalId),y=Xn(Pt(Pt(Pt({topic:n,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:Kt.relay,authentication:f?.authentication,walletPayResult:f?.walletPay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:r.id,topic:n,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:y}),this.events.emit(Rt("session_connect",p.proposalId),{session:y})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;io(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(Rt("session_approve",i),{})):ji(r)&&(await this.client.session.delete(n,Gt("USER_DISCONNECTED")),this.events.emit(Rt("session_approve",i),{error:r.error}))}),ye(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=bh.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:n,error:Gt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Pt({topic:n},i));try{bh.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw bh.delete(o),c}this.client.events.emit("session_update",{id:s,topic:n,params:i})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),ye(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=Rt("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_update",i),{}):ji(r)&&this.events.emit(Rt("session_update",i),{error:r.error})}),ye(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,mn(l0)),await this.sendResult({id:i,topic:n,result:!0}),this.client.events.emit("session_extend",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),ye(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=Rt("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_extend",i),{}):ji(r)&&this.events.emit(Rt("session_extend",i),{error:r.error})}),ye(this,"onSessionPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:i,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),ye(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=Rt("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);io(r)?this.events.emit(Rt("session_ping",i),{}):ji(r)&&this.events.emit(Rt("session_ping",i),{error:r.error})},500)}),ye(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{await this.isValidDisconnect({topic:n,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:n,error:Gt("USER_DISCONNECTED")}),await this.deleteSession({topic:n,id:i})}catch(s){this.client.logger.error(s)}}),ye(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=n,{id:d,params:h}=a;try{await this.isValidRequest(Pt({topic:o},h));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Fi(JSON.stringify(ws("wc_sessionRequest",h,d))),encryptedId:l,metadata:f.peer.metadata,transportType:u}),g={id:d,topic:o,params:h,verifyContext:p};await this.setPendingSessionRequest(g),u===Kt.link_mode&&(r=f.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=f.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),ye(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=Rt("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);io(r)?this.events.emit(Rt("session_request",i),{result:r.result}):ji(r)&&this.events.emit(Rt("session_request",i),{error:r.error})}),ye(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=bh.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Pt({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),bh.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),ye(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),io(r)?this.events.emit(Rt("session_request",i),{result:r.result}):ji(r)&&this.events.emit(Rt("session_request",i),{error:r.error})}),ye(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:l,authPayload:u,expiryTimestamp:d}=s.params,h=await this.getVerifyContext({attestationId:o,hash:Fi(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:i,id:s.id,authPayload:u,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(s.id,{request:f,pairingTopic:i,transportType:c}),c===Kt.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),f={type:ec,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:s.id,topic:i,error:l,encodeOpts:f,rpcOpts:Yn.wc_sessionAuthenticate.autoReject,appLink:h})}}),ye(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),ye(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=co.idle,this.processSessionRequestQueue()},ve.toMiliseconds(this.requestQueueDelay))}),ye(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===n&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(Rt("session_request",s.request.id),{error:r})})}),ye(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===co.active){this.client.logger.info("session request queue is already active.");return}const n=this.sessionRequestQueue.queue[0];if(!n){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(n)}catch(r){this.client.logger.error(r)}}),ye(this,"emitSessionRequest",n=>{if(this.emittedSessionRequests.has(n.id)){this.client.logger.warn({id:n.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${n.id}`);return}this.sessionRequestQueue.state=co.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),ye(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:ws("wc_sessionPropose",Xn(Pt({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),ye(this,"isValidConnect",async n=>{if(!Jr(n)){const{message:l}=Ae("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if($n(r)||await this.isValidPairingTopic(r),!YY(c,!0)){const{message:l}=Ae("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(i&&!$n(i)&&no(i)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(i,"requiredNamespaces")}if(s&&!$n(s)&&no(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!$n(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!$n(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),ye(this,"validateNamespaces",(n,r)=>{const i=KY(n,"connect()",r);if(i)throw new Error(i.message)}),ye(this,"isValidApprove",async n=>{if(!Jr(n))throw new Error(Ae("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=W8(i,"approve()");if(l)throw new Error(l.message);const u=KS(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!yn(s,!0)){const{message:d}=Ae("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(d)}if(o&&!$n(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!$n(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(i));if(!Object.keys(a).every(h=>d.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),ye(this,"isValidReject",async n=>{if(!Jr(n)){const{message:s}=Ae("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!JY(i)){const{message:s}=Ae("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),ye(this,"isValidSessionSettleRequest",n=>{if(!Jr(n)){const{message:l}=Ae("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(l)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!ZS(r)){const{message:l}=Ae("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=zY(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=W8(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Qs(o)){const{message:l}=Ae("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),ye(this,"isValidUpdate",async n=>{if(!Jr(n)){const{message:c}=Ae("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:i}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=W8(i,"update()");if(o)throw new Error(o.message);const a=KS(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),ye(this,"isValidExtend",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),ye(this,"isValidRequest",async n=>{if(!Jr(n)){const{message:c}=Ae("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:i,chainId:s,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!GS(a,s)){const{message:c}=Ae("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!QY(i)){const{message:c}=Ae("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!nX(a,s,i.method)){const{message:c}=Ae("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),ye(this,"isValidRespond",async n=>{var r;if(!Jr(n)){const{message:a}=Ae("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(a)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(a){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),a}if(!eX(s)){const{message:a}=Ae("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==i){const{message:a}=Ae("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${i}`);throw new Error(a)}}),ye(this,"isValidPing",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),ye(this,"isValidEmit",async n=>{if(!Jr(n)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:i,chainId:s}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!GS(o,s)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!tX(i)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!rX(o,s,i.name)){const{message:a}=Ae("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),ye(this,"isValidDisconnect",async n=>{if(!Jr(n)){const{message:i}=Ae("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),ye(this,"isValidAuthenticate",n=>{const{chains:r,uri:i,domain:s,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!yn(i,!1))throw new Error("uri is required parameter");if(!yn(s,!1))throw new Error("domain is required parameter");if(!yn(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Ga(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Ga(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),ye(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||_h,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Kt.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),ye(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=Ae("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),ye(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),ye(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),ye(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=Ae("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),ye(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,l,u,d,h;return!n||r!==Kt.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=n?.redirect)==null?void 0:u.universal)!==void 0&&((d=n?.redirect)==null?void 0:d.universal)!==""&&((h=n?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),ye(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),ye(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=o7(n,"topic")||"",i=decodeURIComponent(o7(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:Kt.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),ye(this,"registerLinkModeListeners",async()=>{var n;if(d8()||jc()&&(n=this.client.metadata.redirect)!=null&&n.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),ye(this,"getTVFApproveParams",n=>{try{const r=jS(n.namespaces),i=OY(n.namespaces),s=kY(n.namespaces),o=n.sessionProperties,a=n.scopedProperties;return{approvedChains:r,approvedMethods:i,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}}),ye(this,"getTVFParams",(n,r,i)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const l=this.extractTxHashesFromResult(r.request,i);c.txHashes=l,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),ye(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const i=n?.data||((r=n?.[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),ye(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=Jne[s];if(s==="sui_signTransaction")return[vG(r.transactionBytes)];if(s==="near_signTransaction")return[$7(r)];if(s==="near_signTransactions")return r.map(c=>$7(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[EX({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Hi(r)?r.map(c=>T7(c)):[T7(r)];if(s==="cosmos_signDirect")return[AG(r)];if(s==="wallet_sendCalls")return CG(r);if(typeof r=="string")return[r];const a=r[o.key];if(Hi(a))return s==="solana_signAllTransactions"?a.map(c=>bG(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const t=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(t);for(const[r,i]of Object.entries(n))for(const s of i)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:t}=Ae("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(hn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){const{topic:n,message:r,attestation:i,transportType:s}=t,{publicKey:o}=this.client.auth.authKeys.keys.includes(mm)?this.client.auth.authKeys.get(mm):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===Kt.link_mode?nl:Xr});r4(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:Fi(r)})):dm(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:s}),this.client.core.history.delete(n,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Vi.expired,async t=>{const{topic:n,id:r}=s7(t.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,Ae("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,Ae("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession({topic:n,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(vu.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(vu.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!yn(t,!1)){const{message:n}=Ae("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:n}=Ae("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.core.pairing.pairings.get(t).expiry)){const{message:n}=Ae("EXPIRED",`pairing topic: ${t}`);throw new Error(n)}}async isValidSessionTopic(t){if(!yn(t,!1)){const{message:n}=Ae("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(n)}if(this.checkRecentlyDeleted(t),!this.client.session.keys.includes(t)){const{message:n}=Ae("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});const{message:n}=Ae("EXPIRED",`session topic: ${t}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(t)){const{message:n}=Ae("MISSING_OR_INVALID",`session topic does not exist in keychain: ${t}`);throw await this.deleteSession({topic:t}),new Error(n)}}async isValidSessionOrPairingTopic(t){if(this.checkRecentlyDeleted(t),this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(yn(t,!1)){const{message:n}=Ae("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(n)}else{const{message:n}=Ae("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(n)}}async isValidProposalId(t){if(!XY(t)){const{message:n}=Ae("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(n)}if(!this.client.proposal.keys.includes(t)){const{message:n}=Ae("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(n)}if(Qs(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);const{message:n}=Ae("EXPIRED",`proposal id: ${t}`);throw new Error(n)}}validateRequestExpiry(t){if(t&&!oX(t,E4)){const{message:n}=Ae("MISSING_OR_INVALID",`request() expiry: ${t}. Expiry must be a number (in seconds) between ${E4.min} and ${E4.max}`);throw new Error(n)}}}class fre extends Cu{constructor(t,n){super(t,n,Kne,b4),this.core=t,this.logger=n}}class hre extends Cu{constructor(t,n){super(t,n,Yne,b4),this.core=t,this.logger=n}}class pre extends Cu{constructor(t,n){super(t,n,Qne,b4,r=>r.id),this.core=t,this.logger=n}}class gre extends Cu{constructor(t,n){super(t,n,rre,gm,()=>mm),this.core=t,this.logger=n}}class mre extends Cu{constructor(t,n){super(t,n,ire,gm),this.core=t,this.logger=n}}class yre extends Cu{constructor(t,n){super(t,n,sre,gm,r=>r.id),this.core=t,this.logger=n}}var wre=Object.defineProperty,bre=(e,t,n)=>t in e?wre(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,C4=(e,t,n)=>bre(e,typeof t!="symbol"?t+"":t,n);class vre{constructor(t,n){this.core=t,this.logger=n,C4(this,"authKeys"),C4(this,"pairingTopics"),C4(this,"requests"),this.authKeys=new gre(this.core,this.logger),this.pairingTopics=new mre(this.core,this.logger),this.requests=new yre(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var Ere=Object.defineProperty,Are=(e,t,n)=>t in e?Ere(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,vt=(e,t,n)=>Are(e,typeof t!="symbol"?t+"":t,n);class x4 extends EJ{constructor(t){super(t),vt(this,"protocol",c$),vt(this,"version",l$),vt(this,"name",v4.name),vt(this,"metadata"),vt(this,"core"),vt(this,"logger"),vt(this,"events",new zn.exports.EventEmitter),vt(this,"engine"),vt(this,"session"),vt(this,"proposal"),vt(this,"pendingRequest"),vt(this,"auth"),vt(this,"signConfig"),vt(this,"on",(r,i)=>this.events.on(r,i)),vt(this,"once",(r,i)=>this.events.once(r,i)),vt(this,"off",(r,i)=>this.events.off(r,i)),vt(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),vt(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),vt(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),vt(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),vt(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),vt(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=t?.name||v4.name,this.metadata=hZ(t?.metadata),this.signConfig=t?.signConfig;const n=G8({logger:t?.logger||v4.logger,name:this.name});this.logger=n,this.core=t?.core||new Gne(t),this.session=new hre(this.core,this.logger),this.proposal=new fre(this.core,this.logger),this.pendingRequest=new pre(this.core,this.logger),this.engine=new dre(this),this.auth=new vre(this.core,this.logger)}static async init(t){const n=new x4(t);return await n.initialize(),n}get context(){return Gr(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")}catch(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}}const Cre=x4;var _4={exports:{}};(function(e,t){var n=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Pn<"u"&&Pn,r=function(){function s(){this.fetch=!1,this.DOMException=n.DOMException}return s.prototype=n,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof Pn<"u"&&Pn||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(m){return m&&DataView.prototype.isPrototypeOf(m)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(m){return m&&u.indexOf(Object.prototype.toString.call(m))>-1};function h(m){if(typeof m!="string"&&(m=String(m)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(m)||m==="")throw new TypeError('Invalid character in header field name: "'+m+'"');return m.toLowerCase()}function f(m){return typeof m!="string"&&(m=String(m)),m}function p(m){var b={next:function(){var $=m.shift();return{done:$===void 0,value:$}}};return c.iterable&&(b[Symbol.iterator]=function(){return b}),b}function g(m){this.map={},m instanceof g?m.forEach(function(b,$){this.append($,b)},this):Array.isArray(m)?m.forEach(function(b){if(b.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+b.length);this.append(b[0],b[1])},this):m&&Object.getOwnPropertyNames(m).forEach(function(b){this.append(b,m[b])},this)}g.prototype.append=function(m,b){m=h(m),b=f(b);var $=this.map[m];this.map[m]=$?$+", "+b:b},g.prototype.delete=function(m){delete this.map[h(m)]},g.prototype.get=function(m){return m=h(m),this.has(m)?this.map[m]:null},g.prototype.has=function(m){return this.map.hasOwnProperty(h(m))},g.prototype.set=function(m,b){this.map[h(m)]=f(b)},g.prototype.forEach=function(m,b){for(var $ in this.map)this.map.hasOwnProperty($)&&m.call(b,this.map[$],$,this)},g.prototype.keys=function(){var m=[];return this.forEach(function(b,$){m.push($)}),p(m)},g.prototype.values=function(){var m=[];return this.forEach(function(b){m.push(b)}),p(m)},g.prototype.entries=function(){var m=[];return this.forEach(function(b,$){m.push([$,b])}),p(m)},c.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function y(m){if(!m._noBody){if(m.bodyUsed)return Promise.reject(new TypeError("Already read"));m.bodyUsed=!0}}function A(m){return new Promise(function(b,$){m.onload=function(){b(m.result)},m.onerror=function(){$(m.error)}})}function _(m){var b=new FileReader,$=A(b);return b.readAsArrayBuffer(m),$}function v(m){var b=new FileReader,$=A(b),N=/charset=([A-Za-z0-9_-]+)/.exec(m.type),P=N?N[1]:"utf-8";return b.readAsText(m,P),$}function w(m){for(var b=new Uint8Array(m),$=new Array(b.length),N=0;N<b.length;N++)$[N]=String.fromCharCode(b[N]);return $.join("")}function T(m){if(m.slice)return m.slice(0);var b=new Uint8Array(m.byteLength);return b.set(new Uint8Array(m)),b.buffer}function O(){return this.bodyUsed=!1,this._initBody=function(m){this.bodyUsed=this.bodyUsed,this._bodyInit=m,m?typeof m=="string"?this._bodyText=m:c.blob&&Blob.prototype.isPrototypeOf(m)?this._bodyBlob=m:c.formData&&FormData.prototype.isPrototypeOf(m)?this._bodyFormData=m:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(m)?this._bodyText=m.toString():c.arrayBuffer&&c.blob&&l(m)?(this._bodyArrayBuffer=T(m.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(m)||d(m))?this._bodyArrayBuffer=T(m):this._bodyText=m=Object.prototype.toString.call(m):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof m=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(m)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var m=y(this);if(m)return m;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(){if(this._bodyArrayBuffer){var m=y(this);return m||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(_);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var m=y(this);if(m)return m;if(this._bodyBlob)return v(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)},c.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var D=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function F(m){var b=m.toUpperCase();return D.indexOf(b)>-1?b:m}function U(m,b){if(!(this instanceof U))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');b=b||{};var $=b.body;if(m instanceof U){if(m.bodyUsed)throw new TypeError("Already read");this.url=m.url,this.credentials=m.credentials,b.headers||(this.headers=new g(m.headers)),this.method=m.method,this.mode=m.mode,this.signal=m.signal,!$&&m._bodyInit!=null&&($=m._bodyInit,m.bodyUsed=!0)}else this.url=String(m);if(this.credentials=b.credentials||this.credentials||"same-origin",(b.headers||!this.headers)&&(this.headers=new g(b.headers)),this.method=F(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.signal=b.signal||this.signal||function(){if("AbortController"in a){var B=new AbortController;return B.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&$)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody($),(this.method==="GET"||this.method==="HEAD")&&(b.cache==="no-store"||b.cache==="no-cache")){var N=/([?&])_=[^&]*/;if(N.test(this.url))this.url=this.url.replace(N,"$1_="+new Date().getTime());else{var P=/\?/;this.url+=(P.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}U.prototype.clone=function(){return new U(this,{body:this._bodyInit})};function j(m){var b=new FormData;return m.trim().split("&").forEach(function($){if($){var N=$.split("="),P=N.shift().replace(/\+/g," "),B=N.join("=").replace(/\+/g," ");b.append(decodeURIComponent(P),decodeURIComponent(B))}}),b}function W(m){var b=new g,$=m.replace(/\r?\n[\t ]+/g," ");return $.split("\r").map(function(N){return N.indexOf(`
|
|
42
42
|
`)===0?N.substr(1,N.length):N}).forEach(function(N){var P=N.split(":"),B=P.shift().trim();if(B){var V=P.join(":").trim();try{b.append(B,V)}catch(Z){console.warn("Response "+Z.message)}}}),b}O.call(U.prototype);function S(m,b){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(b||(b={}),this.type="default",this.status=b.status===void 0?200:b.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=b.statusText===void 0?"":""+b.statusText,this.headers=new g(b.headers),this.url=b.url||"",this._initBody(m)}O.call(S.prototype),S.prototype.clone=function(){return new S(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},S.error=function(){var m=new S(null,{status:200,statusText:""});return m.ok=!1,m.status=0,m.type="error",m};var x=[301,302,303,307,308];S.redirect=function(m,b){if(x.indexOf(b)===-1)throw new RangeError("Invalid status code");return new S(null,{status:b,headers:{location:m}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(b,$){this.message=b,this.name=$;var N=Error(b);this.stack=N.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function I(m,b){return new Promise(function($,N){var P=new U(m,b);if(P.signal&&P.signal.aborted)return N(new o.DOMException("Aborted","AbortError"));var B=new XMLHttpRequest;function V(){B.abort()}B.onload=function(){var X={statusText:B.statusText,headers:W(B.getAllResponseHeaders()||"")};P.url.indexOf("file://")===0&&(B.status<200||B.status>599)?X.status=200:X.status=B.status,X.url="responseURL"in B?B.responseURL:X.headers.get("X-Request-URL");var G="response"in B?B.response:B.responseText;setTimeout(function(){$(new S(G,X))},0)},B.onerror=function(){setTimeout(function(){N(new TypeError("Network request failed"))},0)},B.ontimeout=function(){setTimeout(function(){N(new TypeError("Network request timed out"))},0)},B.onabort=function(){setTimeout(function(){N(new o.DOMException("Aborted","AbortError"))},0)};function Z(X){try{return X===""&&a.location.href?a.location.href:X}catch{return X}}if(B.open(P.method,Z(P.url),!0),P.credentials==="include"?B.withCredentials=!0:P.credentials==="omit"&&(B.withCredentials=!1),"responseType"in B&&(c.blob?B.responseType="blob":c.arrayBuffer&&(B.responseType="arraybuffer")),b&&typeof b.headers=="object"&&!(b.headers instanceof g||a.Headers&&b.headers instanceof a.Headers)){var Y=[];Object.getOwnPropertyNames(b.headers).forEach(function(X){Y.push(h(X)),B.setRequestHeader(X,f(b.headers[X]))}),P.headers.forEach(function(X,G){Y.indexOf(G)===-1&&B.setRequestHeader(G,X)})}else P.headers.forEach(function(X,G){B.setRequestHeader(G,X)});P.signal&&(P.signal.addEventListener("abort",V),B.onreadystatechange=function(){B.readyState===4&&P.signal.removeEventListener("abort",V)}),B.send(typeof P._bodyInit>"u"?null:P._bodyInit)})}return I.polyfill=!0,a.fetch||(a.fetch=I,a.Headers=g,a.Request=U,a.Response=S),o.Headers=g,o.Request=U,o.Response=S,o.fetch=I,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=n.fetch?n:r;t=i.fetch,t.default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t})(_4,_4.exports);var p$=JB(_4.exports),xre=Object.defineProperty,_re=Object.defineProperties,Sre=Object.getOwnPropertyDescriptors,g$=Object.getOwnPropertySymbols,Ire=Object.prototype.hasOwnProperty,$re=Object.prototype.propertyIsEnumerable,m$=(e,t,n)=>t in e?xre(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,y$=(e,t)=>{for(var n in t||(t={}))Ire.call(t,n)&&m$(e,n,t[n]);if(g$)for(var n of g$(t))$re.call(t,n)&&m$(e,n,t[n]);return e},w$=(e,t)=>_re(e,Sre(t));const Tre={Accept:"application/json","Content-Type":"application/json"},Nre="POST",b$={headers:Tre,method:Nre},v$=10;class E${constructor(t,n=!1){if(this.url=t,this.disableProviderPing=n,this.events=new zn.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!gI(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);this.url=t,this.disableProviderPing=n}get connected(){return this.isAvailable}get connecting(){return this.registering}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}off(t,n){this.events.off(t,n)}removeListener(t,n){this.events.removeListener(t,n)}async open(t=this.url){await this.register(t)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(t){this.isAvailable||await this.register();try{const n=ou(t),r=await(await p$(this.url,w$(y$({},b$),{body:n}))).json();this.onPayload({data:r})}catch(n){this.onError(t.id,n)}}async register(t=this.url){if(!gI(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));r()})})}this.url=t,this.registering=!0;try{if(!this.disableProviderPing){const n=ou({id:1,jsonrpc:"2.0",method:"test",params:[]});await p$(t,w$(y$({},b$),{body:n}))}this.onOpen()}catch(n){const r=this.parseError(n);throw this.events.emit("register_error",r),this.onClose(),r}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(t){if(typeof t.data>"u")return;const n=typeof t.data=="string"?su(t.data):t.data;this.events.emit("payload",n)}onError(t,n){const r=this.parseError(n),i=r.message||r.toString(),s=um(t,i);this.events.emit("payload",s)}parseError(t,n=this.url){return lI(t,n,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>v$&&this.events.setMaxListeners(v$)}}var Pre=Object.defineProperty,A$=Object.getOwnPropertySymbols,Ore=Object.prototype.hasOwnProperty,kre=Object.prototype.propertyIsEnumerable,C$=(e,t,n)=>t in e?Pre(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,x$=(e,t)=>{for(var n in t||(t={}))Ore.call(t,n)&&C$(e,n,t[n]);if(A$)for(var n of A$(t))kre.call(t,n)&&C$(e,n,t[n]);return e};function Rre(e){return Number.isSafeInteger(e)&&e>=0}function Bre(e){return e!=null&&typeof e!="function"&&Rre(e.length)}function Mre(e){return e==="__proto__"}function S4(e){return e==null||typeof e!="object"&&typeof e!="function"}function _$(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function I4(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Dre="[object RegExp]",S$="[object String]",I$="[object Number]",$$="[object Boolean]",T$="[object Arguments]",Ure="[object Symbol]",Lre="[object Date]",Fre="[object Map]",Hre="[object Set]",jre="[object Array]",zre="[object ArrayBuffer]",N$="[object Object]",Vre="[object DataView]",Wre="[object Uint8Array]",qre="[object Uint8ClampedArray]",Zre="[object Uint16Array]",Gre="[object Uint32Array]",Kre="[object Int8Array]",Yre="[object Int16Array]",Xre="[object Int32Array]",Jre="[object Float32Array]",Qre="[object Float64Array]";function $4(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function eie(e,t){return u0(e,void 0,e,new Map,t)}function u0(e,t,n,r=new Map,i=void 0){const s=i?.(e,t,n,r);if(s!==void 0)return s;if(S4(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){const o=new Array(e.length);r.set(e,o);for(let a=0;a<e.length;a++)o[a]=u0(e[a],a,n,r,i);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){const o=new Map;r.set(e,o);for(const[a,c]of e)o.set(a,u0(c,a,n,r,i));return o}if(e instanceof Set){const o=new Set;r.set(e,o);for(const a of e)o.add(u0(a,void 0,n,r,i));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if($4(e)){const o=new(Object.getPrototypeOf(e)).constructor(e.length);r.set(e,o);for(let a=0;a<e.length;a++)o[a]=u0(e[a],a,n,r,i);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return r.set(e,o),Es(o,e,n,r,i),o}if(typeof File<"u"&&e instanceof File){const o=new File([e],e.name,{type:e.type});return r.set(e,o),Es(o,e,n,r,i),o}if(typeof Blob<"u"&&e instanceof Blob){const o=new Blob([e],{type:e.type});return r.set(e,o),Es(o,e,n,r,i),o}if(e instanceof Error){const o=new e.constructor;return r.set(e,o),o.message=e.message,o.name=e.name,o.stack=e.stack,o.cause=e.cause,Es(o,e,n,r,i),o}if(e instanceof Boolean){const o=new Boolean(e.valueOf());return r.set(e,o),Es(o,e,n,r,i),o}if(e instanceof Number){const o=new Number(e.valueOf());return r.set(e,o),Es(o,e,n,r,i),o}if(e instanceof String){const o=new String(e.valueOf());return r.set(e,o),Es(o,e,n,r,i),o}if(typeof e=="object"&&tie(e)){const o=Object.create(Object.getPrototypeOf(e));return r.set(e,o),Es(o,e,n,r,i),o}return e}function Es(e,t,n=e,r,i){const s=[...Object.keys(t),..._$(t)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(e,a);(c==null||c.writable)&&(e[a]=u0(t[a],a,n,r,i))}}function tie(e){switch(I4(e)){case T$:case jre:case zre:case Vre:case $$:case Lre:case Jre:case Qre:case Kre:case Yre:case Xre:case Fre:case I$:case N$:case Dre:case Hre:case S$:case Ure:case Wre:case qre:case Zre:case Gre:return!0;default:return!1}}function nie(e,t){return eie(e,(n,r,i,s)=>{const o=t?.(n,r,i,s);if(o!==void 0)return o;if(typeof e=="object"){if(I4(e)===N$&&typeof e.constructor!="function"){const a={};return s.set(e,a),Es(a,e,i,s),a}switch(Object.prototype.toString.call(e)){case I$:case S$:case $$:{const a=new e.constructor(e?.valueOf());return Es(a,e),a}case T$:{const a={};return Es(a,e),a.length=e.length,a[Symbol.iterator]=e[Symbol.iterator],a}default:return}}})}function P$(e){return nie(e)}function O$(e){return e!==null&&typeof e=="object"&&I4(e)==="[object Arguments]"}function T4(e){return typeof e=="object"&&e!==null}function rie(e){return T4(e)&&Bre(e)}function iie(){}function N4(e){return $4(e)}function P4(e){var t;if(typeof e!="object"||e==null)return!1;if(Object.getPrototypeOf(e)===null)return!0;if(Object.prototype.toString.call(e)!=="[object Object]"){const r=e[Symbol.toStringTag];return r==null||!((t=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag))!=null&&t.writable)?!1:e.toString()===`[object ${r}]`}let n=e;for(;Object.getPrototypeOf(n)!==null;)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}function sie(e){if(S4(e))return e;if(Array.isArray(e)||$4(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e);if(t==null)return Object.assign(Object.create(t),e);const n=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new n(e);if(e instanceof RegExp){const r=new n(e);return r.lastIndex=e.lastIndex,r}if(e instanceof DataView)return new n(e.buffer.slice(0));if(e instanceof Error){let r;return e instanceof AggregateError?r=new n(e.errors,e.message,{cause:e.cause}):r=new n(e.message,{cause:e.cause}),r.stack=e.stack,Object.assign(r,e),r}if(typeof File<"u"&&e instanceof File)return new n([e],e.name,{type:e.type,lastModified:e.lastModified});if(typeof e=="object"){const r=Object.create(t);return Object.assign(r,e)}return e}function oie(e,...t){const n=t.slice(0,-1),r=t[t.length-1];let i=e;for(let s=0;s<n.length;s++){const o=n[s];i=O4(i,o,r,new Map)}return i}function O4(e,t,n,r){var i;if(S4(e)&&(e=Object(e)),t==null||typeof t!="object")return e;if(r.has(t))return sie(r.get(t));if(r.set(t,e),Array.isArray(t)){t=t.slice();for(let o=0;o<t.length;o++)t[o]=(i=t[o])!=null?i:void 0}const s=[...Object.keys(t),..._$(t)];for(let o=0;o<s.length;o++){const a=s[o];if(Mre(a))continue;let c=t[a],l=e[a];if(O$(c)&&(c=x$({},c)),O$(l)&&(l=x$({},l)),typeof Buffer<"u"&&Buffer.isBuffer(c)&&(c=P$(c)),Array.isArray(c))if(Array.isArray(l)){const d=[],h=Reflect.ownKeys(l);for(let f=0;f<h.length;f++){const p=h[f];d[p]=l[p]}l=d}else if(rie(l)){const d=[];for(let h=0;h<l.length;h++)d[h]=l[h];l=d}else l=[];const u=n(l,c,a,e,t,r);u!==void 0?e[a]=u:Array.isArray(c)||T4(l)&&T4(c)&&(P4(l)||P4(c)||N4(l)||N4(c))?e[a]=O4(l,c,n,r):l==null&&P4(c)?e[a]=O4({},c,n,r):l==null&&N4(c)?e[a]=P$(c):(l===void 0||c!==void 0)&&(e[a]=c)}return e}function aie(e,...t){return oie(e,...t,iie)}const k$="error",cie="wss://relay.walletconnect.org",lie="wc",R$="universal_provider",ym=`${lie}@2:${R$}:`,B$="https://rpc.walletconnect.org/v1/",M$="generic",uie=`${B$}bundler`,d0="call_status",die=86400,k4={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var fie=Object.defineProperty,hie=Object.defineProperties,pie=Object.getOwnPropertyDescriptors,D$=Object.getOwnPropertySymbols,gie=Object.prototype.hasOwnProperty,mie=Object.prototype.propertyIsEnumerable,U$=(e,t,n)=>t in e?fie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wm=(e,t)=>{for(var n in t||(t={}))gie.call(t,n)&&U$(e,n,t[n]);if(D$)for(var n of D$(t))mie.call(t,n)&&U$(e,n,t[n]);return e},yie=(e,t)=>hie(e,pie(t));function L$(e,t,n){var r;const i=Ga(e);return((r=t.rpcMap)==null?void 0:r[i.reference])||`${B$}?chainId=${i.namespace}:${i.reference}&projectId=${n}`}function wie(e){return e.includes(":")?e.split(":")[1]:e}function F$(e){return e.map(t=>`${t.split(":")[0]}:${t.split(":")[1]}`)}function bie(e,t){const n=Object.keys(t.namespaces).filter(i=>i.includes(e));if(!n.length)return[];const r=[];return n.forEach(i=>{const s=t.namespaces[i].accounts;r.push(...s)}),r}function H$(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>{var r,i;return((r=n?.chains)==null?void 0:r.length)&&((i=n?.chains)==null?void 0:i.length)>0}))}function bm(e={},t={}){const n=H$(j$(e)),r=H$(j$(t));return aie(n,r)}function j$(e){var t,n,r,i,s;const o={};if(!no(e))return o;for(const[a,c]of Object.entries(e)){const l=im(a)?[a]:c.chains,u=c.methods||[],d=c.events||[],h=c.rpcMap||{},f=o0(a);o[f]=yie(wm(wm({},o[f]),c),{chains:eo(l,(t=o[f])==null?void 0:t.chains),methods:eo(u,(n=o[f])==null?void 0:n.methods),events:eo(d,(r=o[f])==null?void 0:r.events)}),(no(h)||no(((i=o[f])==null?void 0:i.rpcMap)||{}))&&(o[f].rpcMap=wm(wm({},h),(s=o[f])==null?void 0:s.rpcMap))}return o}function z$(e){return e.includes(":")?e.split(":")[2]:e}function V$(e){const t={};for(const[n,r]of Object.entries(e)){const i=r.methods||[],s=r.events||[],o=r.accounts||[],a=im(n)?[n]:r.chains?r.chains:F$(r.accounts);t[n]={chains:a,methods:i,events:s,accounts:o}}return t}function R4(e){return typeof e=="number"?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}function vie(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)}catch{return!1}}const W$={},f0=e=>W$[e],B4=(e,t)=>{W$[e]=t};var Eie=Object.defineProperty,q$=Object.getOwnPropertySymbols,Aie=Object.prototype.hasOwnProperty,Cie=Object.prototype.propertyIsEnumerable,Z$=(e,t,n)=>t in e?Eie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,G$=(e,t)=>{for(var n in t||(t={}))Aie.call(t,n)&&Z$(e,n,t[n]);if(q$)for(var n of q$(t))Cie.call(t,n)&&Z$(e,n,t[n]);return e};const K$="eip155",xie=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],_ie=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,M4=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,Y$=e=>Object.keys(e).filter(t=>xie.includes(t)).reduce((t,n)=>(t[n]=Sie(e[n]),t),{}),Sie=e=>typeof e=="string"&&vie(e)?JSON.parse(e):e,Iie=(e,t,n)=>{const{sessionProperties:r={},scopedProperties:i={}}=e,s={};if(!no(i)&&!no(r))return;const o=Y$(r);for(const a of n){const c=_ie(a);if(!c)continue;s[M4(c)]=o;const l=i?.[`${K$}:${c}`];if(l){const u=l?.[`${K$}:${c}:${t}`];s[M4(c)]=G$(G$({},s[M4(c)]),Y$(u||l))}}for(const[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0};var $ie=Object.defineProperty,Tie=(e,t,n)=>t in e?$ie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Nie=(e,t,n)=>Tie(e,typeof t!="symbol"?t+"":t,n);let D4;class U4{constructor(t){Nie(this,"storage"),this.storage=t}async getItem(t){return await this.storage.getItem(t)}async setItem(t,n){return await this.storage.setItem(t,n)}async removeItem(t){return await this.storage.removeItem(t)}static getStorage(t){return D4||(D4=new U4(t)),D4}}var Pie=Object.defineProperty,Oie=Object.defineProperties,kie=Object.getOwnPropertyDescriptors,X$=Object.getOwnPropertySymbols,Rie=Object.prototype.hasOwnProperty,Bie=Object.prototype.propertyIsEnumerable,J$=(e,t,n)=>t in e?Pie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mie=(e,t)=>{for(var n in t||(t={}))Rie.call(t,n)&&J$(e,n,t[n]);if(X$)for(var n of X$(t))Bie.call(t,n)&&J$(e,n,t[n]);return e},Die=(e,t)=>Oie(e,kie(t));async function Uie(e,t){const n=Ga(e.result.capabilities.caip345.caip2),r=e.result.capabilities.caip345.transactionHashes,i=await Promise.allSettled(r.map(d=>Lie(n.reference,d,t))),s=i.filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d);i.filter(d=>d.status==="rejected").forEach(d=>console.warn("Failed to fetch transaction receipt:",d.reason));const o=!s.length||s.some(d=>!d),a=s.every(d=>d?.status==="0x1"),c=s.every(d=>d?.status==="0x0"),l=s.some(d=>d?.status==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:s,status:u}}async function Lie(e,t,n){return await n(parseInt(e)).request(ws("eth_getTransactionReceipt",[t]))}async function Fie({sendCalls:e,storage:t}){const n=await t.getItem(d0);await t.setItem(d0,Die(Mie({},n),{[e.result.id]:{request:e.request,result:e.result,expiry:mn(die)}}))}async function Hie({resultId:e,storage:t}){const n=await t.getItem(d0);if(n){delete n[e],await t.setItem(d0,n);for(const r in n)Qs(n[r].expiry)&&delete n[r];await t.setItem(d0,n)}}async function jie({resultId:e,storage:t}){const n=await t.getItem(d0),r=n?.[e];if(r&&!Qs(r.expiry))return r;await Hie({resultId:e,storage:t})}var zie=Object.defineProperty,Vie=Object.defineProperties,Wie=Object.getOwnPropertyDescriptors,Q$=Object.getOwnPropertySymbols,qie=Object.prototype.hasOwnProperty,Zie=Object.prototype.propertyIsEnumerable,L4=(e,t,n)=>t in e?zie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,F4=(e,t)=>{for(var n in t||(t={}))qie.call(t,n)&&L4(e,n,t[n]);if(Q$)for(var n of Q$(t))Zie.call(t,n)&&L4(e,n,t[n]);return e},H4=(e,t)=>Vie(e,Wie(t)),xu=(e,t,n)=>L4(e,typeof t!="symbol"?t+"":t,n);class Gie{constructor(t){xu(this,"name","eip155"),xu(this,"client"),xu(this,"chainId"),xu(this,"namespace"),xu(this,"httpProviders"),xu(this,"events"),xu(this,"storage"),this.namespace=t.namespace,this.events=f0("events"),this.client=f0("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=U4.getStorage(this.client.core.storage)}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(t);case"wallet_getCallsStatus":return await this.getCallStatus(t);case"wallet_sendCalls":return await this.sendCalls(t)}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,n){this.httpProviders[t]||this.setHttpProvider(parseInt(t),n);const r=this.chainId;this.chainId=parseInt(t),this.events.emit(k4.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${r}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,n){const r=n||L$(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${t}`);return new i4(new E$(r,f0("disableProviderPing")))}setHttpProvider(t,n){const r=this.createHttpProvider(t,n);r&&(this.httpProviders[t]=r)}createHttpProviders(){const t={};return this.namespace.chains.forEach(n=>{var r;const i=parseInt(wie(n));t[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[n])}),t}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}getHttpProvider(t){const n=t||this.chainId;return this.httpProviders[n]||(this.httpProviders=H4(F4({},this.httpProviders),{[n]:this.createHttpProvider(n)}),this.httpProviders[n])}async handleSwitchChain(t){var n,r;let i=t.request.params?(n=t.request.params[0])==null?void 0:n.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const s=parseInt(i,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:i}]},chainId:(r=this.namespace.chains)==null?void 0:r[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(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){var n,r,i,s,o;const a=(r=(n=t.request)==null?void 0:n.params)==null?void 0:r[0],c=((s=(i=t.request)==null?void 0:i.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(t.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{},d=c.length>0?c.join(","):`0x${this.chainId.toString(16)}`,h=`${a}${d}`,f=u?.[h];if(f)return f;let p;try{p=Iie(l,a,c)}catch(y){console.warn("Failed to extract capabilities from session",y)}if(p)return p;const g=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:H4(F4({},l.sessionProperties||{}),{capabilities:H4(F4({},u||{}),{[h]:g})})})}catch(y){console.warn("Failed to update session with capabilities",y)}return g}async getCallStatus(t){var n,r,i;const s=this.client.session.get(t.topic),o=(n=s.sessionProperties)==null?void 0:n.bundler_name;if(o){const l=this.getBundlerUrl(t.chainId,o);try{return await this.getUserOperationReceipt(l,t)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(r=s.sessionProperties)==null?void 0:r.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,t)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await jie({resultId:(i=t.request.params)==null?void 0:i[0],storage:this.storage});if(c)try{return await Uie(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(t.request.method))return await this.client.request(t);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(t,n){var r;const i=new URL(t),s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ws("eth_getUserOperationReceipt",[(r=n.request.params)==null?void 0:r[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(t,n){return`${uie}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${n}`}async sendCalls(t){var n,r,i;const s=await this.client.request(t),o=(n=t.request.params)==null?void 0:n[0],a=s?.id,c=s?.capabilities||{},l=(r=c?.caip345)==null?void 0:r.caip2,u=(i=c?.caip345)==null?void 0:i.transactionHashes;return!a||!l||!(u!=null&&u.length)||await Fie({sendCalls:{request:o,result:s},storage:this.storage}),s}}var Kie=Object.defineProperty,Yie=(e,t,n)=>t in e?Kie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,h0=(e,t,n)=>Yie(e,typeof t!="symbol"?t+"":t,n);class Xie{constructor(t){h0(this,"name",M$),h0(this,"client"),h0(this,"httpProviders"),h0(this,"events"),h0(this,"namespace"),h0(this,"chainId"),this.namespace=t.namespace,this.events=f0("events"),this.client=f0("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(t.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(t.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(t.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(t.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider(t.chainId).request(t.request)}setDefaultChain(t,n){this.httpProviders[t]||this.setHttpProvider(t,n);const r=this.chainId;this.chainId=t,this.events.emit(k4.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${r}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getNamespaceName(){const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return Ga(t).namespace}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(n=>n.split(":")[1]===this.chainId.toString()).map(n=>n.split(":")[2]))]:[]}createHttpProviders(){var t,n;const r={};return(n=(t=this.namespace)==null?void 0:t.accounts)==null||n.forEach(i=>{var s,o;const a=Ga(i),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];r[a.reference]=this.createHttpProvider(i,c)}),r}getHttpProvider(t){const n=Ga(t).reference,r=this.httpProviders[n];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return r}setHttpProvider(t,n){const r=this.createHttpProvider(t,n);r&&(this.httpProviders[t]=r)}createHttpProvider(t,n){const r=n||L$(t,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${t}`);return new i4(new E$(r,f0("disableProviderPing")))}}var Jie=Object.defineProperty,Qie=Object.defineProperties,ese=Object.getOwnPropertyDescriptors,eT=Object.getOwnPropertySymbols,tse=Object.prototype.hasOwnProperty,nse=Object.prototype.propertyIsEnumerable,j4=(e,t,n)=>t in e?Jie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Oh=(e,t)=>{for(var n in t||(t={}))tse.call(t,n)&&j4(e,n,t[n]);if(eT)for(var n of eT(t))nse.call(t,n)&&j4(e,n,t[n]);return e},vm=(e,t)=>Qie(e,ese(t)),_i=(e,t,n)=>j4(e,typeof t!="symbol"?t+"":t,n);class Em{constructor(t){_i(this,"client"),_i(this,"namespaces"),_i(this,"optionalNamespaces"),_i(this,"sessionProperties"),_i(this,"scopedProperties"),_i(this,"events",new zn.exports),_i(this,"rpcProviders",{}),_i(this,"session"),_i(this,"providerOpts"),_i(this,"logger"),_i(this,"uri"),_i(this,"disableProviderPing",!1),_i(this,"connectParams");var n,r;this.providerOpts=t,this.logger=G8({logger:(n=t.logger)!=null?n:k$,name:(r=this.providerOpts.name)!=null?r:R$}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){const n=new Em(t);return await n.initialize(),n}async request(t,n,r){const[i,s]=this.validateChain(n);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:Oh({},t),chainId:`${i}:${s}`,topic:this.session.topic,expiry:r})}sendAsync(t,n,r,i){const s=new Date().getTime();this.request(t,r,i).then(o=>n(null,Ch(s,o))).catch(o=>n(o,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,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var t;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(t=this.session)==null?void 0:t.topic,reason:Gt("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=t,this.setNamespaces(t),this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}async authenticate(t,n){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(t),await this.cleanupPendingPairings();const{uri:r,response:i}=await this.client.authenticate(t,n);r&&(this.uri=r,this.events.emit("display_uri",r));const s=await i();if(this.session=s.session,this.session){const o=V$(this.session.namespaces);this.namespaces=bm(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(t,n){this.events.on(t,n)}once(t,n){this.events.once(t,n)}removeListener(t,n){this.events.removeListener(t,n)}off(t,n){this.events.off(t,n)}get isWalletConnect(){return!0}async pair(t){var n,r;const{uri:i,approval:s}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(n=this.connectParams)==null?void 0:n.authentication,walletPay:(r=this.connectParams)==null?void 0:r.walletPay});i&&(this.uri=i,this.events.emit("display_uri",i));const o=await s();this.session=o;const a=V$(o.namespaces);return this.namespaces=bm(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(t,n){try{if(!this.session)return;const[r,i]=this.validateChain(t),s=this.getProvider(r);s?s.setDefaultChain(i,n):this.session&&this.logger.warn(`Provider for namespace '${r}' not found in setDefaultChain`)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(t={}){try{this.logger.info("Cleaning up inactive pairings...");const n=this.client.pairing.getAll();if(!Hi(n))return;for(const r of n)t.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${n.length}`)}catch(n){this.logger.warn(n,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var t,n;if(this.client=this.providerOpts.client||await Cre.init({core:this.providerOpts.core,logger:this.providerOpts.logger||k$,relayUrl:this.providerOpts.relayUrl||cie,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.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(r){throw this.logger.error(r,"Failed to get session"),new Error(`The provided session: ${(n=(t=this.providerOpts)==null?void 0:t.session)==null?void 0:n.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const t=[...new Set(Object.keys(this.session.namespaces).map(n=>o0(n)))];B4("client",this.client),B4("events",this.events),B4("disableProviderPing",this.disableProviderPing),t.forEach(n=>{if(!this.session)return;const r=bie(n,this.session);if(r?.length===0)return;const i=F$(r),s=bm(this.namespaces,this.optionalNamespaces),o=vm(Oh({},s[n]),{accounts:r,chains:i});switch(n){case"eip155":this.rpcProviders[n]=new Gie({namespace:o});break;default:this.rpcProviders[n]=new Xie({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{var n;const{topic:r}=t;r===((n=this.session)==null?void 0:n.topic)&&this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{var n;const{params:r,topic:i}=t;if(i!==((n=this.session)==null?void 0:n.topic))return;const{event:s}=r;if(s.name==="accountsChanged"){const o=s.data;o&&Hi(o)&&this.events.emit("accountsChanged",o.map(z$))}else if(s.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=o0(o),l=R4(o)!==R4(a)?`${c}:${R4(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(s.name,s.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:n})=>{var r,i;if(t!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:s}=n,o=(i=this.client)==null?void 0:i.session.get(t);this.session=vm(Oh({},o),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:n})}),this.client.on("session_delete",async t=>{var n;t.topic===((n=this.session)==null?void 0:n.topic)&&(await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",vm(Oh({},Gt("USER_DISCONNECTED")),{data:t.topic})))}),this.on(k4.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged(vm(Oh({},t),{internal:!0}))})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[M$]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{var n;this.getProvider(t).updateNamespace((n=this.session)==null?void 0:n.namespaces[t])})}setNamespaces(t){const{namespaces:n={},optionalNamespaces:r={},sessionProperties:i,scopedProperties:s}=t;this.optionalNamespaces=bm(n,r),this.sessionProperties=i,this.scopedProperties=s}validateChain(t){const[n,r]=t?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[n,r];if(n&&!Object.keys(this.namespaces||{}).map(o=>o0(o)).includes(n))throw new Error(`Namespace '${n}' is not configured. Please call connect() first with namespace config.`);if(n&&r)return[n,r];const i=o0(Object.keys(this.namespaces)[0]),s=this.rpcProviders[i].getDefaultChain();return[i,s]}async requestAccounts(){const[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}async onChainChanged({currentCaipChainId:t,previousCaipChainId:n,internal:r=!1}){if(!this.namespaces)return;const[i,s]=this.validateChain(t);if(s){if(this.updateNamespaceChain(i,s),r)this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:i,currentCaipChainId:t,previousCaipChainId:n});else{const o=this.getProvider(i);o?o.setDefaultChain(s):this.session&&this.logger.warn(`Provider for namespace '${i}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:t,currentCaipChainId:n,previousCaipChainId:r}){var i,s;try{if(r===n)return;const o=(s=(i=this.session)==null?void 0:i.namespaces[t])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${n}:`)).map(z$);if(!Hi(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(t,n){if(!this.namespaces)return;const r=this.namespaces[t]?t:`${t}:${n}`,i={chains:[],methods:[],events:[],defaultChain:n};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=n):this.namespaces[r]=i}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(t,n){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${ym}/${t}${i}`,n)}async getFromStore(t){var n;const r=((n=this.session)==null?void 0:n.topic)||"";return await this.client.core.storage.getItem(`${ym}/${t}${r}`)}async deleteFromStore(t){var n;const r=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.removeItem(`${ym}/${t}${r}`)}async cleanupStorage(){var t;try{if(((t=this.client)==null?void 0:t.session.length)>0)return;const n=await this.client.core.storage.getKeys();for(const r of n)r.startsWith(ym)&&await this.client.core.storage.removeItem(r)}catch(n){this.logger.warn(n,"Failed to cleanup storage")}}}const rse=Em,ise="wc",sse="ethereum_provider",ose=`${ise}@2:${sse}:`,ase="https://rpc.walletconnect.org/v1/",Am=["eth_sendTransaction","personal_sign"],tT=["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"],Cm=["chainChanged","accountsChanged"],nT=["chainChanged","accountsChanged","message","disconnect","connect"],cse=async()=>{const{createAppKit:e}=await Promise.resolve().then(function(){return wge});return e};var lse=Object.defineProperty,use=Object.defineProperties,dse=Object.getOwnPropertyDescriptors,rT=Object.getOwnPropertySymbols,fse=Object.prototype.hasOwnProperty,hse=Object.prototype.propertyIsEnumerable,z4=(e,t,n)=>t in e?lse(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_u=(e,t)=>{for(var n in t||(t={}))fse.call(t,n)&&z4(e,n,t[n]);if(rT)for(var n of rT(t))hse.call(t,n)&&z4(e,n,t[n]);return e},kh=(e,t)=>use(e,dse(t)),Si=(e,t,n)=>z4(e,typeof t!="symbol"?t+"":t,n);function xm(e){return Number(e[0].split(":")[1])}function _m(e){return`0x${e.toString(16)}`}function pse(e){const{chains:t,optionalChains:n,methods:r,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=e;if(!Hi(t))throw new Error("Invalid chains");const c={chains:t,methods:r||Am,events:s||Cm,rpcMap:_u({},t.length?{[xm(t)]:a[xm(t)]}:{})},l=s?.filter(f=>!Cm.includes(f)),u=r?.filter(f=>!Am.includes(f));if(!n&&!o&&!i&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:t.length?c:void 0};const d=l?.length&&u?.length||!n,h={chains:[...new Set(d?c.chains.concat(n||[]):n)],methods:[...new Set(c.methods.concat(i!=null&&i.length?i:tT))],events:[...new Set(c.events.concat(o!=null&&o.length?o:nT))],rpcMap:a};return{required:t.length?c:void 0,optional:n.length?h:void 0}}class Sm{constructor(){Si(this,"events",new zn.exports.EventEmitter),Si(this,"namespace","eip155"),Si(this,"accounts",[]),Si(this,"signer"),Si(this,"chainId",1),Si(this,"modal"),Si(this,"rpc"),Si(this,"STORAGE_KEY",ose),Si(this,"on",(t,n)=>(this.events.on(t,n),this)),Si(this,"once",(t,n)=>(this.events.once(t,n),this)),Si(this,"removeListener",(t,n)=>(this.events.removeListener(t,n),this)),Si(this,"off",(t,n)=>(this.events.off(t,n),this)),Si(this,"parseAccount",t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t),this.signer={},this.rpc={}}static async init(t){const n=new Sm;return await n.initialize(t),n}async request(t,n){return await this.signer.request(t,this.formatChainId(this.chainId),n)}sendAsync(t,n,r){this.signer.sendAsync(t,n,this.formatChainId(this.chainId),r)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){var n;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:r,optional:i}=pse(this.rpc);try{const s=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const d=t!=null&&t.scopedProperties?{[this.namespace]:t.scopedProperties}:void 0;await this.signer.connect(kh(_u({namespaces:_u({},r&&{[this.namespace]:r})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic,scopedProperties:d})).then(h=>{a(h)}).catch(h=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(h.message))})});if(!s)return;const o=Y_(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:_m(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(n=this.modal)==null||n.close()}}async authenticate(t,n){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{const i=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(kh(_u({},t),{chains:this.rpc.chains}),n).then(u=>{o(u)}).catch(u=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),s=i.session;if(s){const o=Y_(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:_m(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{(r=this.modal)==null||r.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:n}=t,{event:r}=n;r.name==="accountsChanged"?(this.accounts=this.parseAccounts(r.data),this.events.emit("accountsChanged",this.accounts)):r.name==="chainChanged"?this.setChainId(this.formatChainId(r.data)):this.events.emit(r.name,r.data),this.events.emit("session_event",t)}),this.signer.on("accountsChanged",t=>{this.accounts=this.parseAccounts(t),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",t=>{const n=parseInt(t);this.chainId=n,this.events.emit("chainChanged",_m(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",kh(_u({},Gt("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const n=t.filter(r=>this.isCompatibleChainId(r)).map(r=>this.parseChainId(r));n.length&&(this.chainId=n[0],this.events.emit("chainChanged",_m(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const n=this.parseChainId(t);this.chainId=n,this.switchEthereumChain(n)}}parseAccountId(t){const[n,r,i]=t.split(":");return{chainId:`${n}:${r}`,address:i}}setAccounts(t){this.accounts=t.filter(n=>this.parseChainId(this.parseAccountId(n).chainId)===this.chainId).map(n=>this.parseAccountId(n).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var n,r;const i=(n=t?.chains)!=null?n:[],s=(r=t?.optionalChains)!=null?r:[],o=i.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=i.length?t?.methods||Am:[],c=i.length?t?.events||Cm:[],l=t?.optionalMethods||[],u=t?.optionalEvents||[],d=t?.rpcMap||this.buildRpcMap(o,t.projectId),h=t?.qrModalOptions||void 0;return{chains:i?.map(f=>this.formatChainId(f)),optionalChains:s.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:d,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:h,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,n){const r={};return t.forEach(i=>{r[i]=this.getRpcUrl(i,n)}),r}async initialize(t){var n;if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?xm(this.rpc.chains):xm(this.rpc.optionalChains),this.signer=await rse.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storage:t.storage,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled,logger:t.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const i=await cse(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return $ge}),o=s(kh(_u({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect");r=i(kh(_u({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((n=this.rpc.qrModalOptions)==null?void 0:n.enableMobileFullScreen)===!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:n,optionalChains:r,rpcMap:i}=t;n&&Hi(n)&&(this.rpc.chains=n.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),r&&Hi(r)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=r?.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)}))}getRpcUrl(t,n){var r;return((r=this.rpc.rpcMap)==null?void 0:r[t])||`${ase}?chainId=eip155:${t}&projectId=${n||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),n=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:n?.accounts),this.setAccounts(n?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(n=>this.signer.logger.warn(n))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(n=>this.parseAccount(n))}}const gse=Sm,iT={isLowerCaseMatch(e,t){return e?.toLowerCase()===t?.toLowerCase()}};var sT={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Pn,function(){var n=1e3,r=6e4,i=36e5,s="millisecond",o="second",a="minute",c="hour",l="day",u="week",d="month",h="quarter",f="year",p="date",g="Invalid Date",y=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,A=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,_={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(I){var m=["th","st","nd","rd"],b=I%100;return"["+I+(m[(b-20)%10]||m[b]||m[0])+"]"}},v=function(I,m,b){var $=String(I);return!$||$.length>=m?I:""+Array(m+1-$.length).join(b)+I},w={s:v,z:function(I){var m=-I.utcOffset(),b=Math.abs(m),$=Math.floor(b/60),N=b%60;return(m<=0?"+":"-")+v($,2,"0")+":"+v(N,2,"0")},m:function I(m,b){if(m.date()<b.date())return-I(b,m);var $=12*(b.year()-m.year())+(b.month()-m.month()),N=m.clone().add($,d),P=b-N<0,B=m.clone().add($+(P?-1:1),d);return+(-($+(b-N)/(P?N-B:B-N))||0)},a:function(I){return I<0?Math.ceil(I)||0:Math.floor(I)},p:function(I){return{M:d,y:f,w:u,d:l,D:p,h:c,m:a,s:o,ms:s,Q:h}[I]||String(I||"").toLowerCase().replace(/s$/,"")},u:function(I){return I===void 0}},T="en",O={};O[T]=_;var D="$isDayjsObject",F=function(I){return I instanceof S||!(!I||!I[D])},U=function I(m,b,$){var N;if(!m)return T;if(typeof m=="string"){var P=m.toLowerCase();O[P]&&(N=P),b&&(O[P]=b,N=P);var B=m.split("-");if(!N&&B.length>1)return I(B[0])}else{var V=m.name;O[V]=m,N=V}return!$&&N&&(T=N),N||!$&&T},j=function(I,m){if(F(I))return I.clone();var b=typeof m=="object"?m:{};return b.date=I,b.args=arguments,new S(b)},W=w;W.l=U,W.i=F,W.w=function(I,m){return j(I,{locale:m.$L,utc:m.$u,x:m.$x,$offset:m.$offset})};var S=function(){function I(b){this.$L=U(b.locale,null,!0),this.parse(b),this.$x=this.$x||b.x||{},this[D]=!0}var m=I.prototype;return m.parse=function(b){this.$d=function($){var N=$.date,P=$.utc;if(N===null)return new Date(NaN);if(W.u(N))return new Date;if(N instanceof Date)return new Date(N);if(typeof N=="string"&&!/Z$/i.test(N)){var B=N.match(y);if(B){var V=B[2]-1||0,Z=(B[7]||"0").substring(0,3);return P?new Date(Date.UTC(B[1],V,B[3]||1,B[4]||0,B[5]||0,B[6]||0,Z)):new Date(B[1],V,B[3]||1,B[4]||0,B[5]||0,B[6]||0,Z)}}return new Date(N)}(b),this.init()},m.init=function(){var b=this.$d;this.$y=b.getFullYear(),this.$M=b.getMonth(),this.$D=b.getDate(),this.$W=b.getDay(),this.$H=b.getHours(),this.$m=b.getMinutes(),this.$s=b.getSeconds(),this.$ms=b.getMilliseconds()},m.$utils=function(){return W},m.isValid=function(){return this.$d.toString()!==g},m.isSame=function(b,$){var N=j(b);return this.startOf($)<=N&&N<=this.endOf($)},m.isAfter=function(b,$){return j(b)<this.startOf($)},m.isBefore=function(b,$){return this.endOf($)<j(b)},m.$g=function(b,$,N){return W.u(b)?this[$]:this.set(N,b)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(b,$){var N=this,P=!!W.u($)||$,B=W.p(b),V=function(ue,ge){var Be=W.w(N.$u?Date.UTC(N.$y,ge,ue):new Date(N.$y,ge,ue),N);return P?Be:Be.endOf(l)},Z=function(ue,ge){return W.w(N.toDate()[ue].apply(N.toDate("s"),(P?[0,0,0,0]:[23,59,59,999]).slice(ge)),N)},Y=this.$W,X=this.$M,G=this.$D,ne="set"+(this.$u?"UTC":"");switch(B){case f:return P?V(1,0):V(31,11);case d:return P?V(1,X):V(0,X+1);case u:var se=this.$locale().weekStart||0,we=(Y<se?Y+7:Y)-se;return V(P?G-we:G+(6-we),X);case l:case p:return Z(ne+"Hours",0);case c:return Z(ne+"Minutes",1);case a:return Z(ne+"Seconds",2);case o:return Z(ne+"Milliseconds",3);default:return this.clone()}},m.endOf=function(b){return this.startOf(b,!1)},m.$set=function(b,$){var N,P=W.p(b),B="set"+(this.$u?"UTC":""),V=(N={},N[l]=B+"Date",N[p]=B+"Date",N[d]=B+"Month",N[f]=B+"FullYear",N[c]=B+"Hours",N[a]=B+"Minutes",N[o]=B+"Seconds",N[s]=B+"Milliseconds",N)[P],Z=P===l?this.$D+($-this.$W):$;if(P===d||P===f){var Y=this.clone().set(p,1);Y.$d[V](Z),Y.init(),this.$d=Y.set(p,Math.min(this.$D,Y.daysInMonth())).$d}else V&&this.$d[V](Z);return this.init(),this},m.set=function(b,$){return this.clone().$set(b,$)},m.get=function(b){return this[W.p(b)]()},m.add=function(b,$){var N,P=this;b=Number(b);var B=W.p($),V=function(X){var G=j(P);return W.w(G.date(G.date()+Math.round(X*b)),P)};if(B===d)return this.set(d,this.$M+b);if(B===f)return this.set(f,this.$y+b);if(B===l)return V(1);if(B===u)return V(7);var Z=(N={},N[a]=r,N[c]=i,N[o]=n,N)[B]||1,Y=this.$d.getTime()+b*Z;return W.w(Y,this)},m.subtract=function(b,$){return this.add(-1*b,$)},m.format=function(b){var $=this,N=this.$locale();if(!this.isValid())return N.invalidDate||g;var P=b||"YYYY-MM-DDTHH:mm:ssZ",B=W.z(this),V=this.$H,Z=this.$m,Y=this.$M,X=N.weekdays,G=N.months,ne=N.meridiem,se=function(ge,Be,Fe,qe){return ge&&(ge[Be]||ge($,P))||Fe[Be].slice(0,qe)},we=function(ge){return W.s(V%12||12,ge,"0")},ue=ne||function(ge,Be,Fe){var qe=ge<12?"AM":"PM";return Fe?qe.toLowerCase():qe};return P.replace(A,function(ge,Be){return Be||function(Fe){switch(Fe){case"YY":return String($.$y).slice(-2);case"YYYY":return W.s($.$y,4,"0");case"M":return Y+1;case"MM":return W.s(Y+1,2,"0");case"MMM":return se(N.monthsShort,Y,G,3);case"MMMM":return se(G,Y);case"D":return $.$D;case"DD":return W.s($.$D,2,"0");case"d":return String($.$W);case"dd":return se(N.weekdaysMin,$.$W,X,2);case"ddd":return se(N.weekdaysShort,$.$W,X,3);case"dddd":return X[$.$W];case"H":return String(V);case"HH":return W.s(V,2,"0");case"h":return we(1);case"hh":return we(2);case"a":return ue(V,Z,!0);case"A":return ue(V,Z,!1);case"m":return String(Z);case"mm":return W.s(Z,2,"0");case"s":return String($.$s);case"ss":return W.s($.$s,2,"0");case"SSS":return W.s($.$ms,3,"0");case"Z":return B}return null}(ge)||B.replace(":","")})},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(b,$,N){var P,B=this,V=W.p($),Z=j(b),Y=(Z.utcOffset()-this.utcOffset())*r,X=this-Z,G=function(){return W.m(B,Z)};switch(V){case f:P=G()/12;break;case d:P=G();break;case h:P=G()/3;break;case u:P=(X-Y)/6048e5;break;case l:P=(X-Y)/864e5;break;case c:P=X/i;break;case a:P=X/r;break;case o:P=X/n;break;default:P=X}return N?P:W.a(P)},m.daysInMonth=function(){return this.endOf(d).$D},m.$locale=function(){return O[this.$L]},m.locale=function(b,$){if(!b)return this.$L;var N=this.clone(),P=U(b,$,!0);return P&&(N.$L=P),N},m.clone=function(){return W.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},I}(),x=S.prototype;return j.prototype=x,[["$ms",s],["$s",o],["$m",a],["$H",c],["$W",l],["$M",d],["$y",f],["$D",p]].forEach(function(I){x[I[1]]=function(m){return this.$g(m,I[0],I[1])}}),j.extend=function(I,m){return I.$i||(I(m,S,j),I.$i=!0),j},j.locale=U,j.isDayjs=F,j.unix=function(I){return j(1e3*I)},j.en=O[T],j.Ls=O,j.p={},j})})(sT);var V4=sT.exports,oT={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Pn,function(){return{name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(n){var r=["th","st","nd","rd"],i=n%100;return"["+n+(r[(i-20)%10]||r[i]||r[0])+"]"}}})})(oT);var mse=oT.exports,aT={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Pn,function(){return function(n,r,i){n=n||{};var s=r.prototype,o={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function a(l,u,d,h){return s.fromToBase(l,u,d,h)}i.en.relativeTime=o,s.fromToBase=function(l,u,d,h,f){for(var p,g,y,A=d.$locale().relativeTime||o,_=n.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],v=_.length,w=0;w<v;w+=1){var T=_[w];T.d&&(p=h?i(l).diff(d,T.d,!0):d.diff(l,T.d,!0));var O=(n.rounding||Math.round)(Math.abs(p));if(y=p>0,O<=T.r||!T.r){O<=1&&w>0&&(T=_[w-1]);var D=A[T.l];f&&(O=f(""+O)),g=typeof D=="string"?D.replace("%d",O):D(O,u,T.l,y);break}}if(u)return g;var F=y?A.future:A.past;return typeof F=="function"?F(g):F.replace("%s",g)},s.to=function(l,u){return a(l,u,this,!0)},s.from=function(l,u){return a(l,u,this)};var c=function(l){return l.$u?i.utc():i()};s.toNow=function(l){return this.to(c(this),l)},s.fromNow=function(l){return this.from(c(this),l)}}})})(aT);var yse=aT.exports,cT={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Pn,function(){return function(n,r,i){i.updateLocale=function(s,o){var a=i.Ls[s];if(a)return(o?Object.keys(o):[]).forEach(function(c){a[c]=o[c]}),a}}})})(cT);var wse=cT.exports;V4.extend(yse),V4.extend(wse);const bse={...mse,name:"en-web3-modal",relativeTime:{future:"in %s",past:"%s ago",s:"%d sec",m:"1 min",mm:"%d min",h:"1 hr",hh:"%d hrs",d:"1 d",dd:"%d d",M:"1 mo",MM:"%d mo",y:"1 yr",yy:"%d yr"}};V4.locale("en-web3-modal",bse);const J={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",BASE_ACCOUNT:"baseAccount",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122",TON:"ton"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks",ton:"TON"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",TON:"ton"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},NATIVE_IMAGE_IDS_BY_NAMESPACE:{eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"3e8119e5-2a6f-4818-c50c-1937011d5900",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},TOKEN_SYMBOLS_BY_ADDRESS:{"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC","0x833589fcd6edb6e08f4c7c32d4f71b54bda02913":"USDC","0x0b2c639c533813f4aa9d7837caf62653d097ff85":"USDC","0xaf88d065e77c8cc2239327c5edb3a432268e5831":"USDC","0x3c499c542cef5e3811e1192ce70d8cc03d5c3359":"USDC","0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"USDC",EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v:"USDC","0xdac17f958d2ee523a2206206994597c13d831ec7":"USDT","0x94b008aa00579c1307b0ef2c499ad98a8ce58e58":"USDT","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9":"USDT","0xc2132d05d31c914a87c6611c10748aeb04b58e8f":"USDT",Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB:"USDT"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}},HEADLESS_NOT_ENABLED:{DEFAULT:{displayMessage:"",debugMessage:"Headless support is not enabled. Please enable it with the features.headless option in the AppKit configuration and make sure your current plan supports it."}}},IS_DEVELOPMENT:typeof process<"u"&&process.env.NODE_ENV==="development",DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"],METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH"},W4={caipNetworkIdToNumber(e){return e?Number(e.split(":")[1]):void 0},parseEvmChainId(e){return typeof e=="string"?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace(e,t){return e?.filter(n=>n.chainNamespace===t)||[]},getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){if(!t)return;const n=e.find(i=>i.caipNetworkId===t);if(n)return n.name;const[r]=t.split(":");return J.CHAIN_NAME_MAP?.[r]||void 0}},lT=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var vse=20,Ese=1,Su=1e6,uT=1e6,Ase=-7,Cse=21,xse=!1,Rh="[big.js] ",Iu=Rh+"Invalid ",Im=Iu+"decimal places",_se=Iu+"rounding mode",dT=Rh+"Division by zero",Bt={},lo=void 0,Sse=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function fT(){function e(t){var n=this;if(!(n instanceof e))return t===lo?fT():new e(t);if(t instanceof e)n.s=t.s,n.e=t.e,n.c=t.c.slice();else{if(typeof t!="string"){if(e.strict===!0&&typeof t!="bigint")throw TypeError(Iu+"value");t=t===0&&1/t<0?"-0":String(t)}Ise(n,t)}n.constructor=e}return e.prototype=Bt,e.DP=vse,e.RM=Ese,e.NE=Ase,e.PE=Cse,e.strict=xse,e.roundDown=0,e.roundHalfUp=1,e.roundHalfEven=2,e.roundUp=3,e}function Ise(e,t){var n,r,i;if(!Sse.test(t))throw Error(Iu+"number");for(e.s=t.charAt(0)=="-"?(t=t.slice(1),-1):1,(n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),i=t.length,r=0;r<i&&t.charAt(r)=="0";)++r;if(r==i)e.c=[e.e=0];else{for(;i>0&&t.charAt(--i)=="0";);for(e.e=n-r-1,e.c=[],n=0;r<=i;)e.c[n++]=+t.charAt(r++)}return e}function $u(e,t,n,r){var i=e.c;if(n===lo&&(n=e.constructor.RM),n!==0&&n!==1&&n!==2&&n!==3)throw Error(_se);if(t<1)r=n===3&&(r||!!i[0])||t===0&&(n===1&&i[0]>=5||n===2&&(i[0]>5||i[0]===5&&(r||i[1]!==lo))),i.length=1,r?(e.e=e.e-t+1,i[0]=1):i[0]=e.e=0;else if(t<i.length){if(r=n===1&&i[t]>=5||n===2&&(i[t]>5||i[t]===5&&(r||i[t+1]!==lo||i[t-1]&1))||n===3&&(r||!!i[0]),i.length=t,r){for(;++i[--t]>9;)if(i[t]=0,t===0){++e.e,i.unshift(1);break}}for(t=i.length;!i[--t];)i.pop()}return e}function Tu(e,t,n){var r=e.e,i=e.c.join(""),s=i.length;if(t)i=i.charAt(0)+(s>1?"."+i.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)i="0"+i;i="0."+i}else if(r>0)if(++r>s)for(r-=s;r--;)i+="0";else r<s&&(i=i.slice(0,r)+"."+i.slice(r));else s>1&&(i=i.charAt(0)+"."+i.slice(1));return e.s<0&&n?"-"+i:i}Bt.abs=function(){var e=new this.constructor(this);return e.s=1,e},Bt.cmp=function(e){var t,n=this,r=n.c,i=(e=new n.constructor(e)).c,s=n.s,o=e.s,a=n.e,c=e.e;if(!r[0]||!i[0])return r[0]?s:i[0]?-o:0;if(s!=o)return s;if(t=s<0,a!=c)return a>c^t?1:-1;for(o=(a=r.length)<(c=i.length)?a:c,s=-1;++s<o;)if(r[s]!=i[s])return r[s]>i[s]^t?1:-1;return a==c?0:a>c^t?1:-1},Bt.div=function(e){var t=this,n=t.constructor,r=t.c,i=(e=new n(e)).c,s=t.s==e.s?1:-1,o=n.DP;if(o!==~~o||o<0||o>Su)throw Error(Im);if(!i[0])throw Error(dT);if(!r[0])return e.s=s,e.c=[e.e=0],e;var a,c,l,u,d,h=i.slice(),f=a=i.length,p=r.length,g=r.slice(0,a),y=g.length,A=e,_=A.c=[],v=0,w=o+(A.e=t.e-e.e)+1;for(A.s=s,s=w<0?0:w,h.unshift(0);y++<a;)g.push(0);do{for(l=0;l<10;l++){if(a!=(y=g.length))u=a>y?1:-1;else for(d=-1,u=0;++d<a;)if(i[d]!=g[d]){u=i[d]>g[d]?1:-1;break}if(u<0){for(c=y==a?i:h;y;){if(g[--y]<c[y]){for(d=y;d&&!g[--d];)g[d]=9;--g[d],g[y]+=10}g[y]-=c[y]}for(;!g[0];)g.shift()}else break}_[v++]=u?l:++l,g[0]&&u?g[y]=r[f]||0:g=[r[f]]}while((f++<p||g[0]!==lo)&&s--);return!_[0]&&v!=1&&(_.shift(),A.e--,w--),v>w&&$u(A,w,n.RM,g[0]!==lo),A},Bt.eq=function(e){return this.cmp(e)===0},Bt.gt=function(e){return this.cmp(e)>0},Bt.gte=function(e){return this.cmp(e)>-1},Bt.lt=function(e){return this.cmp(e)<0},Bt.lte=function(e){return this.cmp(e)<1},Bt.minus=Bt.sub=function(e){var t,n,r,i,s=this,o=s.constructor,a=s.s,c=(e=new o(e)).s;if(a!=c)return e.s=-c,s.plus(e);var l=s.c.slice(),u=s.e,d=e.c,h=e.e;if(!l[0]||!d[0])return d[0]?e.s=-c:l[0]?e=new o(s):e.s=1,e;if(a=u-h){for((i=a<0)?(a=-a,r=l):(h=u,r=d),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(n=((i=l.length<d.length)?l:d).length,a=c=0;c<n;c++)if(l[c]!=d[c]){i=l[c]<d[c];break}if(i&&(r=l,l=d,d=r,e.s=-e.s),(c=(n=d.length)-(t=l.length))>0)for(;c--;)l[t++]=0;for(c=t;n>a;){if(l[--n]<d[n]){for(t=n;t&&!l[--t];)l[t]=9;--l[t],l[n]+=10}l[n]-=d[n]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(e.s=1,l=[h=0]),e.c=l,e.e=h,e},Bt.mod=function(e){var t,n=this,r=n.constructor,i=n.s,s=(e=new r(e)).s;if(!e.c[0])throw Error(dT);return n.s=e.s=1,t=e.cmp(n)==1,n.s=i,e.s=s,t?new r(n):(i=r.DP,s=r.RM,r.DP=r.RM=0,n=n.div(e),r.DP=i,r.RM=s,this.minus(n.times(e)))},Bt.neg=function(){var e=new this.constructor(this);return e.s=-e.s,e},Bt.plus=Bt.add=function(e){var t,n,r,i=this,s=i.constructor;if(e=new s(e),i.s!=e.s)return e.s=-e.s,i.minus(e);var o=i.e,a=i.c,c=e.e,l=e.c;if(!a[0]||!l[0])return l[0]||(a[0]?e=new s(i):e.s=i.s),e;if(a=a.slice(),t=o-c){for(t>0?(c=o,r=l):(t=-t,r=a),r.reverse();t--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),t=l.length,n=0;t;a[t]%=10)n=(a[--t]=a[t]+l[t]+n)/10|0;for(n&&(a.unshift(n),++c),t=a.length;a[--t]===0;)a.pop();return e.c=a,e.e=c,e},Bt.pow=function(e){var t=this,n=new t.constructor("1"),r=n,i=e<0;if(e!==~~e||e<-uT||e>uT)throw Error(Iu+"exponent");for(i&&(e=-e);e&1&&(r=r.times(t)),e>>=1,!!e;)t=t.times(t);return i?n.div(r):r},Bt.prec=function(e,t){if(e!==~~e||e<1||e>Su)throw Error(Iu+"precision");return $u(new this.constructor(this),e,t)},Bt.round=function(e,t){if(e===lo)e=0;else if(e!==~~e||e<-Su||e>Su)throw Error(Im);return $u(new this.constructor(this),e+this.e+1,t)},Bt.sqrt=function(){var e,t,n,r=this,i=r.constructor,s=r.s,o=r.e,a=new i("0.5");if(!r.c[0])return new i(r);if(s<0)throw Error(Rh+"No square root");s=Math.sqrt(+Tu(r,!0,!0)),s===0||s===1/0?(t=r.c.join(""),t.length+o&1||(t+="0"),s=Math.sqrt(t),o=((o+1)/2|0)-(o<0||o&1),e=new i((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+o)):e=new i(s+""),o=e.e+(i.DP+=4);do n=e,e=a.times(n.plus(r.div(n)));while(n.c.slice(0,o).join("")!==e.c.slice(0,o).join(""));return $u(e,(i.DP-=4)+e.e+1,i.RM)},Bt.times=Bt.mul=function(e){var t,n=this,r=n.constructor,i=n.c,s=(e=new r(e)).c,o=i.length,a=s.length,c=n.e,l=e.e;if(e.s=n.s==e.s?1:-1,!i[0]||!s[0])return e.c=[e.e=0],e;for(e.e=c+l,o<a&&(t=i,i=s,s=t,l=o,o=a,a=l),t=new Array(l=o+a);l--;)t[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=t[l]+s[c]*i[l-c-1]+a,t[l--]=a%10,a=a/10|0;t[l]=a}for(a?++e.e:t.shift(),c=t.length;!t[--c];)t.pop();return e.c=t,e},Bt.toExponential=function(e,t){var n=this,r=n.c[0];if(e!==lo){if(e!==~~e||e<0||e>Su)throw Error(Im);for(n=$u(new n.constructor(n),++e,t);n.c.length<e;)n.c.push(0)}return Tu(n,!0,!!r)},Bt.toFixed=function(e,t){var n=this,r=n.c[0];if(e!==lo){if(e!==~~e||e<0||e>Su)throw Error(Im);for(n=$u(new n.constructor(n),e+n.e+1,t),e=e+n.e+1;n.c.length<e;)n.c.push(0)}return Tu(n,!1,!!r)},Bt[Symbol.for("nodejs.util.inspect.custom")]=Bt.toJSON=Bt.toString=function(){var e=this,t=e.constructor;return Tu(e,e.e<=t.NE||e.e>=t.PE,!!e.c[0])},Bt.toNumber=function(){var e=+Tu(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(e.toString()))throw Error(Rh+"Imprecise conversion");return e},Bt.toPrecision=function(e,t){var n=this,r=n.constructor,i=n.c[0];if(e!==lo){if(e!==~~e||e<1||e>Su)throw Error(Iu+"precision");for(n=$u(new r(n),e,t);n.c.length<e;)n.c.push(0)}return Tu(n,e<=n.e||n.e<=r.NE||n.e>=r.PE,!!i)},Bt.valueOf=function(){var e=this,t=e.constructor;if(t.strict===!0)throw Error(Rh+"valueOf disallowed");return Tu(e,e.e<=t.NE||e.e>=t.PE,!0)};var uo=fT();const Et={bigNumber(e,t={safe:!1}){try{return e?new uo(e):new uo(0)}catch(n){if(t.safe)return new uo(0);throw n}},formatNumber(e,t){const{decimals:n,round:r=8,safe:i=!0}=t;return Et.bigNumber(e,{safe:i}).div(new uo(10).pow(n)).round(r)},multiply(e,t){if(e===void 0||t===void 0)return new uo(0);const n=new uo(e),r=new uo(t);return n.times(r)},toFixed(e,t=2){return e===void 0||e===""?new uo(0).toFixed(t):new uo(e).toFixed(t)},formatNumberToLocalString(e,t=2){return e===void 0||e===""?"0.00":typeof e=="number"?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"})},parseLocalStringToNumber(e){if(e===void 0||e==="")return 0;const t=e.replace(/,/gu,"");return new uo(t).toNumber()}},$se=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],Tse=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Nse=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],hT={getERC20Abi:e=>J.USDT_CONTRACT_ADDRESSES.includes(e)?Nse:$se,getSwapAbi:()=>Tse},p0={ConnectorExplorerIds:{[J.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[J.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[J.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[J.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[J.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[J.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[J.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[J.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[J.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[J.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[J.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[J.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[J.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[J.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[J.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[J.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[J.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[J.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[J.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200","00000008819873e925422c1ff0f99f7c":"b3406e4a-bbfc-44fb-e3a6-89673c78b700","-239":"20f673c0-095e-49b2-07cf-eb5049dcf600","-3":"20f673c0-095e-49b2-07cf-eb5049dcf600"},ConnectorImageIds:{[J.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[J.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[J.CONNECTOR_ID.BASE_ACCOUNT]:"bba2c8be-7fd1-463e-42b1-796ecb0ad200",[J.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[J.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[J.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[J.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[J.CONNECTOR_ID.INJECTED]:"Browser Wallet",[J.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[J.CONNECTOR_ID.COINBASE]:"Coinbase",[J.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[J.CONNECTOR_ID.BASE_ACCOUNT]:"Base Account",[J.CONNECTOR_ID.LEDGER]:"Ledger",[J.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[J.CONNECTOR_ID.INJECTED]:"INJECTED",[J.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[J.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[J.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]},yt={validateCaipAddress(e){if(e.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){const t=e.split(":");if(t.length!==3)throw new Error(`Invalid CAIP-10 address: ${e}`);const[n,r,i]=t;if(!n||!r||!i)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:n,chainId:r,address:i}},parseCaipNetworkId(e){const t=e.split(":");if(t.length!==2)throw new Error(`Invalid CAIP-2 network id: ${e}`);const[n,r]=t;if(!n||!r)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:n,chainId:r}}},As={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3,SEND_TRANSACTION_ERROR:5001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError",SEND_TRANSACTION_ERROR:"SendTransactionError"},isRpcProviderError(e){try{if(typeof e=="object"&&e!==null){const t=e,n=typeof t.message=="string",r=typeof t.code=="number";return n&&r}return!1}catch{return!1}},isUserRejectedMessage(e){return e.toLowerCase().includes("user rejected")||e.toLowerCase().includes("user cancelled")||e.toLowerCase().includes("user canceled")},isUserRejectedRequestError(e){if(As.isRpcProviderError(e)){const t=e.code===As.RPC_ERROR_CODE.USER_REJECTED_REQUEST,n=e.code===As.RPC_ERROR_CODE.USER_REJECTED_METHODS;return t||n||As.isUserRejectedMessage(e.message)}return e instanceof Error?As.isUserRejectedMessage(e.message):!1}};class Pse extends Error{constructor(t,n){super(n.message,{cause:t}),this.name=As.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=n.code}}class pT extends Pse{constructor(t){super(t,{code:As.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=As.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const De={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version",TON_WALLETS_CACHE:"@appkit/ton_wallets_cache"};function q4(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const Ne={setItem(e,t){Bh()&&t!==void 0&&localStorage.setItem(e,t)},getItem(e){if(Bh())return localStorage.getItem(e)||void 0},removeItem(e){Bh()&&localStorage.removeItem(e)},clear(){Bh()&&localStorage.clear()}};function Bh(){return typeof window<"u"&&typeof localStorage<"u"}function $m(e,t){const n=e?.["--apkt-accent"]??e?.["--w3m-accent"];return t==="light"?{"--w3m-accent":n||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":n||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const Ose=Symbol(),gT=Object.getPrototypeOf,Z4=new WeakMap,kse=e=>e&&(Z4.has(e)?Z4.get(e):gT(e)===Object.prototype||gT(e)===Array.prototype),Rse=e=>kse(e)&&e[Ose]||null,mT=(e,t=!0)=>{Z4.set(e,t)},G4=e=>typeof e=="object"&&e!==null,Bse=e=>G4(e)&&!Mh.has(e)&&(Array.isArray(e)||!(Symbol.iterator in e))&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!(e instanceof Error)&&!(e instanceof Number)&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof RegExp)&&!(e instanceof ArrayBuffer)&&!(e instanceof Promise),yT=(e,t)=>{const n=K4.get(e);if(n?.[0]===t)return n[1];const r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return mT(r,!0),K4.set(e,[t,r]),Reflect.ownKeys(e).forEach(i=>{if(Object.getOwnPropertyDescriptor(r,i))return;const s=Reflect.get(e,i),{enumerable:o}=Reflect.getOwnPropertyDescriptor(e,i),a={value:s,enumerable:o,configurable:!0};if(Mh.has(s))mT(s,!1);else if(il.has(s)){const[c,l]=il.get(s);a.value=yT(c,l())}Object.defineProperty(r,i,a)}),Object.preventExtensions(r)},Mse=(e,t,n,r)=>({deleteProperty(i,s){const o=Reflect.get(i,s);n(s);const a=Reflect.deleteProperty(i,s);return a&&r(["delete",[s],o]),a},set(i,s,o,a){const c=!e()&&Reflect.has(i,s),l=Reflect.get(i,s,a);if(c&&(wT(l,o)||Dh.has(o)&&wT(l,Dh.get(o))))return!0;n(s),G4(o)&&(o=Rse(o)||o);const u=!il.has(o)&&Use(o)?Ot(o):o;return t(s,u),Reflect.set(i,s,u,a),r(["set",[s],o,l]),!0}}),il=new WeakMap,Mh=new WeakSet,K4=new WeakMap,Tm=[1],Dh=new WeakMap;let wT=Object.is,Dse=(e,t)=>new Proxy(e,t),Use=Bse,Lse=yT,Fse=Mse;function Ot(e={}){if(!G4(e))throw new Error("object required");const t=Dh.get(e);if(t)return t;let n=Tm[0];const r=new Set,i=(y,A=++Tm[0])=>{n!==A&&(s=n=A,r.forEach(_=>_(y,A)))};let s=n;const o=(y=Tm[0])=>(s!==y&&(s=y,c.forEach(([A])=>{const _=A[1](y);_>n&&(n=_)})),n),a=y=>(A,_)=>{const v=[...A];v[1]=[y,...v[1]],i(v,_)},c=new Map,l=(y,A)=>{const _=!Mh.has(A)&&il.get(A);if(_){if(c.has(y))throw new Error("prop listener already exists");if(r.size){const v=_[2](a(y));c.set(y,[_,v])}else c.set(y,[_])}},u=y=>{var A;const _=c.get(y);_&&(c.delete(y),(A=_[1])==null||A.call(_))},d=y=>(r.add(y),r.size===1&&c.forEach(([_,v],w)=>{if(v)throw new Error("remove already exists");const T=_[2](a(w));c.set(w,[_,T])}),()=>{r.delete(y),r.size===0&&c.forEach(([_,v],w)=>{v&&(v(),c.set(w,[_]))})});let h=!0;const f=Fse(()=>h,l,u,i),p=Dse(e,f);Dh.set(e,p);const g=[e,o,d];return il.set(p,g),Reflect.ownKeys(e).forEach(y=>{const A=Object.getOwnPropertyDescriptor(e,y);"value"in A&&A.writable&&(p[y]=e[y])}),h=!1,p}function bn(e,t,n){const r=il.get(e);r||console.warn("Please use proxy object");let i;const s=[],o=r[2];let a=!1;const l=o(u=>{if(s.push(u),n){t(s.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,a&&t(s.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Uh(e){const t=il.get(e);t||console.warn("Please use proxy object");const[n,r]=t;return Lse(n,r())}function Lh(e){return Mh.add(e),e}function Hse(){return{proxyStateMap:il,refSet:Mh,snapCache:K4,versionHolder:Tm,proxyCache:Dh}}function vn(e,t,n,r){let i=e[t];return bn(e,()=>{const s=e[t];Object.is(i,s)||n(i=s)},r)}const{proxyStateMap:jse,snapCache:zse}=Hse(),Nm=e=>jse.has(e);function Vse(e){const t=[];let n=0;const r=new Map,i=new WeakMap,s=()=>{const l=zse.get(a),u=l?.[1];if(u&&!i.has(u)){const d=new Map(r);i.set(u,d)}},o=l=>i.get(l)||r;if(e){if(typeof e[Symbol.iterator]!="function")throw new TypeError(`proxyMap:
|
|
43
43
|
initial state must be iterable
|
|
44
44
|
tip: structure should be [[key, value]]`);for(const[l,u]of e)r.set(l,n),t[n++]=u}const a={data:t,index:n,epoch:0,get size(){return Nm(this)||s(),o(this).size},get(l){const d=o(this).get(l);if(d===void 0){this.epoch;return}return this.data[d]},has(l){const u=o(this);return this.epoch,u.has(l)},set(l,u){if(!Nm(this))throw new Error("Cannot perform mutations on a snapshot");const d=r.get(l);return d===void 0?(r.set(l,this.index),this.data[this.index++]=u):this.data[d]=u,this.epoch++,this},delete(l){if(!Nm(this))throw new Error("Cannot perform mutations on a snapshot");const u=r.get(l);return u===void 0?!1:(delete this.data[u],r.delete(l),this.epoch++,!0)},clear(){if(!Nm(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,r.clear()},forEach(l){this.epoch,o(this).forEach((d,h)=>{l(this.data[d],h,this)})},*entries(){this.epoch;const l=o(this);for(const[u,d]of l)yield[u,this.data[d]]},*keys(){this.epoch;const l=o(this);for(const u of l.keys())yield u},*values(){this.epoch;const l=o(this);for(const u of l.values())yield this.data[u]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=Ot(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}const Y4=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",bT=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Wse="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",it={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:Y4,SECURE_SITE_DASHBOARD:`${Y4}/dashboard`,SECURE_SITE_FAVICON:`${Y4}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],SUGGESTED_TOKENS_BY_CHAIN:{"eip155:42161":["USD\u20AE0"]},BALANCE_SUPPORTED_CHAINS:[J.CHAIN.EVM,J.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[J.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[J.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[J.CHAIN.EVM,J.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[J.CHAIN.EVM,J.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[J.CHAIN.EVM,J.CHAIN.TON],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x",ton:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[J.CHAIN.EVM,J.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1,headless:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1,headless:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1,headless:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa",ton:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0},MANDATORY_WALLET_IDS_ON_MOBILE:[p0.ConnectorExplorerIds[J.CONNECTOR_ID.COINBASE],p0.ConnectorExplorerIds[J.CONNECTOR_ID.COINBASE_SDK],p0.ConnectorExplorerIds[J.CONNECTOR_ID.BASE_ACCOUNT],p0.ConnectorExplorerIds[J.SOLFLARE_CONNECTOR_NAME],p0.ConnectorExplorerIds[J.PHANTOM_CONNECTOR_NAME],p0.ConnectorExplorerIds[J.BINANCE_CONNECTOR_NAME]],DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"]},me={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5,tonWallets:864e5},isCacheExpired(e,t){return Date.now()-e>t},getActiveNetworkProps(){const e=me.getActiveNamespace(),t=me.getActiveCaipNetworkId(),n=t?t.split(":")[1]:void 0,r=n?isNaN(Number(n))?n:Number(n):void 0;return{namespace:e,caipNetworkId:t,chainId:r}},setWalletConnectDeepLink({name:e,href:t}){try{Ne.setItem(De.DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const e=Ne.getItem(De.DEEPLINK_CHOICE);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Ne.removeItem(De.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{Ne.setItem(De.ACTIVE_NAMESPACE,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{Ne.setItem(De.ACTIVE_CAIP_NETWORK_ID,e),me.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Ne.getItem(De.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Ne.removeItem(De.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{const t=q4(e);Ne.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{const t=me.getRecentWallets();t.find(r=>r.id===e.id)||(t.unshift(e),t.length>2&&t.pop(),Ne.setItem(De.RECENT_WALLETS,JSON.stringify(t)),Ne.setItem(De.RECENT_WALLET,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const e=Ne.getItem(De.RECENT_WALLETS);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const e=Ne.getItem(De.RECENT_WALLET);return e?JSON.parse(e):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{Ne.removeItem(De.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(e,t){try{const n=q4(e);Ne.setItem(n,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Ne.getItem(De.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{const t=q4(e);return Ne.getItem(t)}catch{console.info("Unable to get connected connector id in namespace",e)}},setConnectedSocialProvider(e){try{Ne.setItem(De.CONNECTED_SOCIAL,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Ne.getItem(De.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Ne.removeItem(De.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Ne.getItem(De.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Ne.getItem(De.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(e){try{Ne.setItem(De.CONNECTION_STATUS,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Ne.getItem(De.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const e=Ne.getItem(De.CONNECTED_NAMESPACES);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));Ne.setItem(De.CONNECTED_NAMESPACES,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{const t=me.getConnectedNamespaces();t.includes(e)||(t.push(e),me.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{const t=me.getConnectedNamespaces(),n=t.indexOf(e);n>-1&&(t.splice(n,1),me.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Ne.getItem(De.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{Ne.setItem(De.TELEGRAM_SOCIAL_PROVIDER,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Ne.removeItem(De.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{const t=Ne.getItem(De.PORTFOLIO_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{const t=me.getBalanceCache();Ne.setItem(De.PORTFOLIO_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{const n=me.getBalanceCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.portfolio))return n.balance;me.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{const t=me.getBalanceCache();t[e.caipAddress]=e,Ne.setItem(De.PORTFOLIO_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{const t=Ne.getItem(De.NATIVE_BALANCE_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{const t=me.getBalanceCache();Ne.setItem(De.NATIVE_BALANCE_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getNativeBalanceCacheForCaipAddress(e){try{const n=me.getNativeBalanceCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.nativeBalance))return n;console.info("Discarding cache for address",e),me.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{const t=me.getNativeBalanceCache();t[e.caipAddress]=e,Ne.setItem(De.NATIVE_BALANCE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{const t=Ne.getItem(De.ENS_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{const n=me.getEnsCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.ens))return n.ens;me.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{const t=me.getEnsCache();t[e.address]=e,Ne.setItem(De.ENS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{const t=me.getEnsCache();Ne.setItem(De.ENS_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove ens name from cache",e)}},getIdentityCache(){let e={};try{const t=Ne.getItem(De.IDENTITY_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{const n=me.getIdentityCache()[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.identity))return n.identity;me.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{const t=me.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},Ne.setItem(De.IDENTITY_CACHE,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{const t=me.getIdentityCache();Ne.setItem(De.IDENTITY_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},getTonWalletsCache(){try{const e=Ne.getItem(De.TON_WALLETS_CACHE),t=e?JSON.parse(e):void 0;if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tonWallets))return t;me.removeTonWalletsCache()}catch{console.info("Unable to get ton wallets cache")}},updateTonWalletsCache(e){try{const t=me.getTonWalletsCache()||{timestamp:0,wallets:[]};t.timestamp=new Date().getTime(),t.wallets=e,Ne.setItem(De.TON_WALLETS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ton wallets cache",e)}},removeTonWalletsCache(){try{Ne.removeItem(De.TON_WALLETS_CACHE)}catch{console.info("Unable to remove ton wallets cache")}},clearAddressCache(){try{Ne.removeItem(De.PORTFOLIO_CACHE),Ne.removeItem(De.NATIVE_BALANCE_CACHE),Ne.removeItem(De.ENS_CACHE),Ne.removeItem(De.IDENTITY_CACHE),Ne.removeItem(De.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{Ne.setItem(De.PREFERRED_ACCOUNT_TYPES,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{const e=Ne.getItem(De.PREFERRED_ACCOUNT_TYPES);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{const n=me.getConnections(),r=n[t]??[],i=new Map;for(const o of r)i.set(o.connectorId,{...o});for(const o of e){const a=i.get(o.connectorId),c=o.connectorId===J.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(d=>d.address.toLowerCase())),u=o.accounts.filter(d=>!l.has(d.address.toLowerCase()));a.accounts.push(...u)}else i.set(o.connectorId,{...o})}const s={...n,[t]:Array.from(i.values())};Ne.setItem(De.CONNECTIONS,JSON.stringify(s))}catch(n){console.error("Unable to sync connections to storage",n)}},getConnections(){try{const e=Ne.getItem(De.CONNECTIONS);return e?JSON.parse(e):{}}catch(e){return console.error("Unable to get connections from storage",e),{}}},deleteAddressFromConnection({connectorId:e,address:t,namespace:n}){try{const r=me.getConnections(),i=r[n]??[],s=new Map(i.map(a=>[a.connectorId,a])),o=s.get(e);o&&(o.accounts.filter(c=>c.address.toLowerCase()!==t.toLowerCase()).length===0?s.delete(e):s.set(e,{...o,accounts:o.accounts.filter(c=>c.address.toLowerCase()!==t.toLowerCase())})),Ne.setItem(De.CONNECTIONS,JSON.stringify({...r,[n]:Array.from(s.values())}))}catch{console.error(`Unable to remove address "${t}" from connector "${e}" in namespace "${n}"`)}},getDisconnectedConnectorIds(){try{const e=Ne.getItem(De.DISCONNECTED_CONNECTOR_IDS);return e?JSON.parse(e):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(e,t){try{const n=me.getDisconnectedConnectorIds(),r=n[t]??[];r.push(e),Ne.setItem(De.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...n,[t]:Array.from(new Set(r))}))}catch{console.error(`Unable to set disconnected connector id "${e}" for namespace "${t}"`)}},removeDisconnectedConnectorId(e,t){try{const n=me.getDisconnectedConnectorIds();let r=n[t]??[];r=r.filter(i=>i.toLowerCase()!==e.toLowerCase()),Ne.setItem(De.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...n,[t]:Array.from(new Set(r))}))}catch{console.error(`Unable to remove disconnected connector id "${e}" for namespace "${t}"`)}},isConnectorDisconnected(e,t){try{return(me.getDisconnectedConnectorIds()[t]??[]).some(i=>i.toLowerCase()===e.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${e}" for namespace "${t}"`)}return!1},getTransactionsCache(){try{const e=Ne.getItem(De.HISTORY_TRANSACTIONS_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:e,chainId:t=""}){try{const r=me.getTransactionsCache()[e]?.[t];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;me.removeTransactionsCache({address:e,chainId:t})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:e,chainId:t="",timestamp:n,transactions:r}){try{const i=me.getTransactionsCache();i[e]={...i[e],[t]:{timestamp:n,transactions:r}},Ne.setItem(De.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(i))}catch{console.info("Unable to update transactions cache",{address:e,chainId:t,timestamp:n,transactions:r})}},removeTransactionsCache({address:e,chainId:t}){try{const n=me.getTransactionsCache(),r=n?.[e]||{},{[t]:i,...s}=r;Ne.setItem(De.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...n,[e]:s}))}catch{console.info("Unable to remove transactions cache",{address:e,chainId:t})}},getTokenPriceCache(){try{const e=Ne.getItem(De.TOKEN_PRICE_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(e){try{const n=me.getTokenPriceCache()[e.join(",")];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.tokenPrice))return n.tokenPrice;me.removeTokenPriceCache(e)}catch{console.info("Unable to get token price cache for addresses",e)}},updateTokenPriceCache(e){try{const t=me.getTokenPriceCache();t[e.addresses.join(",")]={timestamp:e.timestamp,tokenPrice:e.tokenPrice},Ne.setItem(De.TOKEN_PRICE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update token price cache",e)}},removeTokenPriceCache(e){try{const t=me.getTokenPriceCache();Ne.setItem(De.TOKEN_PRICE_CACHE,JSON.stringify({...t,[e.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",e)}},getLatestAppKitVersion(){try{const e=this.getLatestAppKitVersionCache(),t=e?.version;return t&&!this.isCacheExpired(e.timestamp,this.cacheExpiry.latestAppKitVersion)?t:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const e=Ne.getItem(De.LATEST_APPKIT_VERSION);return e?JSON.parse(e):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(e){try{const t=me.getLatestAppKitVersionCache();t.timestamp=e.timestamp,t.version=e.version,Ne.setItem(De.LATEST_APPKIT_VERSION,JSON.stringify(t))}catch{console.info("Unable to update latest AppKit version on local storage",e)}}},he={getWindow(){if(!(typeof window>"u"))return window},isMobile(){return this.isClient()?!!(window?.matchMedia&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(e,t=""){return e?.caipNetworkId.toLocaleLowerCase().includes(t.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return he.isMobile()&&e.includes("android")},isIos(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(e){return e?e-Date.now()<=it.TEN_SEC_MS:!0},isAllowedRetry(e,t=it.ONE_SEC_MS){return Date.now()-e>=t},copyToClopboard(e){navigator.clipboard.writeText(e)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(he.isClient()&&window.self!==window.top)try{const e=window?.location?.ancestorOrigins?.[0],t="https://app.safe.global";if(e){const n=new URL(e),r=new URL(t);return n.hostname===r.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+it.FOUR_MINUTES_MS},getNetworkId(e){return e?.split(":")[1]},getPlainAddress(e){return e?.split(":")[2]},async wait(e){return new Promise(t=>{setTimeout(t,e)})},debounce(e,t=500){let n;return(...r)=>{function i(){e(...r)}n&&clearTimeout(n),n=setTimeout(i,t)}},isHttpUrl(e){return e.startsWith("http://")||e.startsWith("https://")},formatNativeUrl(e,t,n=null){if(he.isHttpUrl(e))return this.formatUniversalUrl(e,t);let r=e,i=n;r.includes("://")||(r=e.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),i&&!i?.endsWith("/")&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));const s=encodeURIComponent(t);return{redirect:`${r}wc?uri=${s}`,redirectUniversalLink:i?`${i}wc?uri=${s}`:void 0,href:r}},formatUniversalUrl(e,t){if(!he.isHttpUrl(e))return this.formatNativeUrl(e,t);let n=e;n.endsWith("/")||(n=`${n}/`);const r=encodeURIComponent(t);return{redirect:`${n}wc?uri=${r}`,href:n}},getOpenTargetForPlatform(e){return e==="popupWindow"?e:this.isTelegram()?me.getTelegramSocialProvider()?"_top":"_blank":e},openHref(e,t,n){window?.open(e,this.getOpenTargetForPlatform(t),n||"noreferrer noopener")},returnOpenHref(e,t,n){return window?.open(e,this.getOpenTargetForPlatform(t),n||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const e=window?.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(display-mode: standalone)")?.matches:!1,t=window?.navigator?.standalone;return!!(e||t)},async preloadImage(e){const t=new Promise((n,r)=>{const i=new Image;i.onload=n,i.onerror=r,i.crossOrigin="anonymous",i.src=e});return Promise.race([t,he.wait(2e3)])},parseBalance(e,t){let n="0.000";if(typeof e=="string"){const c=Number(e);if(!isNaN(c)){const l=(Math.floor(c*1e3)/1e3).toFixed(3);l&&(n=l)}}const[r,i]=n.split("."),s=r||"0",o=i||"000";return{formattedText:`${s}.${o}${t?` ${t}`:""}`,value:s,decimals:o,symbol:t}},getApiUrl(){return J.W3M_API_URL},getBlockchainApiUrl(){return J.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return J.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})},parseError(e){return typeof e=="string"?e:typeof e?.issues?.[0]?.message=="string"?e.issues[0].message:e instanceof Error?e.message:"Unknown error"},sortRequestedNetworks(e,t=[]){const n={};return t&&e&&(e.forEach((r,i)=>{n[r]=i}),t.sort((r,i)=>{const s=n[r.id],o=n[i.id];return s!==void 0&&o!==void 0?s-o:s!==void 0?-1:o!==void 0?1:0})),t},calculateBalance(e){let t=0;for(const n of e)t+=n.value??0;return t},formatTokenBalance(e){const t=e.toFixed(2),[n,r]=t.split(".");return{dollars:n,pennies:r}},isAddress(e,t="eip155"){switch(t){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(e)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(e)||/^(?:0x)?[0-9A-F]{40}$/iu.test(e))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(e);case"bip122":{const n=/^[1][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),r=/^[3][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),i=/^bc1[a-z0-9]{39,87}$/u.test(e),s=/^bc1p[a-z0-9]{58}$/u.test(e);return n||r||i||s}default:return!1}},uniqueBy(e,t){const n=new Set;return e.filter(r=>{const i=r[t];return n.has(i)?!1:(n.add(i),!0)})},generateSdkVersion(e,t,n){const i=e.length===0?it.ADAPTER_TYPES.UNIVERSAL:e.map(s=>s.adapterType).join(",");return`${t}-${i}-${n}`},createAccount(e,t,n,r,i){return{namespace:e,address:t,type:n,publicKey:r,path:i}},isCaipAddress(e){if(typeof e!="string")return!1;const t=e.split(":"),n=t[0];return t.filter(Boolean).length===3&&n in J.CHAIN_NAME_MAP},getAccount(e){return e?typeof e=="string"?{address:e,chainId:void 0}:{address:e.address,chainId:e.chainId}:{address:void 0,chainId:void 0}},isMac(){const e=window?.navigator.userAgent.toLowerCase();return e.includes("macintosh")&&!e.includes("safari")},formatTelegramSocialLoginUrl(e){const t=`--${encodeURIComponent(window?.location.href)}`,n="state=";if(new URL(e).host==="auth.magic.link"){const i="provider_authorization_url=",s=e.substring(e.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(s),n,t);return e.replace(s,encodeURIComponent(o))}return this.injectIntoUrl(e,n,t)},injectIntoUrl(e,t,n){const r=e.indexOf(t);if(r===-1)throw new Error(`${t} parameter not found in the URL: ${e}`);const i=e.indexOf("&",r),s=t.length,o=i!==-1?i:e.length,a=e.substring(0,r+s),c=e.substring(r+s,o),l=e.substring(i),u=c+n;return a+u+l},isNumber(e){return typeof e!="number"&&typeof e!="string"?!1:!isNaN(Number(e))}};var vT={},Pm={};Pm.byteLength=Gse,Pm.toByteArray=Yse,Pm.fromByteArray=Qse;for(var fo=[],qi=[],qse=typeof Uint8Array<"u"?Uint8Array:Array,X4="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g0=0,Zse=X4.length;g0<Zse;++g0)fo[g0]=X4[g0],qi[X4.charCodeAt(g0)]=g0;qi[45]=62,qi[95]=63;function ET(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function Gse(e){var t=ET(e),n=t[0],r=t[1];return(n+r)*3/4-r}function Kse(e,t,n){return(t+n)*3/4-n}function Yse(e){var t,n=ET(e),r=n[0],i=n[1],s=new qse(Kse(e,r,i)),o=0,a=i>0?r-4:r,c;for(c=0;c<a;c+=4)t=qi[e.charCodeAt(c)]<<18|qi[e.charCodeAt(c+1)]<<12|qi[e.charCodeAt(c+2)]<<6|qi[e.charCodeAt(c+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=qi[e.charCodeAt(c)]<<2|qi[e.charCodeAt(c+1)]>>4,s[o++]=t&255),i===1&&(t=qi[e.charCodeAt(c)]<<10|qi[e.charCodeAt(c+1)]<<4|qi[e.charCodeAt(c+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function Xse(e){return fo[e>>18&63]+fo[e>>12&63]+fo[e>>6&63]+fo[e&63]}function Jse(e,t,n){for(var r,i=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(Xse(r));return i.join("")}function Qse(e){for(var t,n=e.length,r=n%3,i=[],s=16383,o=0,a=n-r;o<a;o+=s)i.push(Jse(e,o,o+s>a?a:o+s));return r===1?(t=e[n-1],i.push(fo[t>>2]+fo[t<<4&63]+"==")):r===2&&(t=(e[n-2]<<8)+e[n-1],i.push(fo[t>>10]+fo[t>>4&63]+fo[t<<2&63]+"=")),i.join("")}var J4={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */J4.read=function(e,t,n,r,i){var s,o,a=i*8-r-1,c=(1<<a)-1,l=c>>1,u=-7,d=n?i-1:0,h=n?-1:1,f=e[t+d];for(d+=h,s=f&(1<<-u)-1,f>>=-u,u+=a;u>0;s=s*256+e[t+d],d+=h,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=h,u-=8);if(s===0)s=1-l;else{if(s===c)return o?NaN:(f?-1:1)*(1/0);o=o+Math.pow(2,r),s=s-l}return(f?-1:1)*o*Math.pow(2,s-r)},J4.write=function(e,t,n,r,i,s){var o,a,c,l=s*8-i-1,u=(1<<l)-1,d=u>>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,p=r?1:-1,g=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+d>=1?t+=h/c:t+=h*Math.pow(2,1-d),t*c>=2&&(o++,c/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*c-1)*Math.pow(2,i),o=o+d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[n+f]=a&255,f+=p,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;e[n+f]=o&255,f+=p,o/=256,l-=8);e[n+f-p]|=g*128};/*!
|