vendor: 17,098 bytes, lines 1-3
1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-Ciek2xfl.js","assets/index-DID4Juaa.js","assets/index-BUpSYZsf.css"])))=>i.map(i=>d[i]); 2import{cC as ko,dF as U,gQ as eh,gc as ps,fI as ge,jE as ae,i9 as $s,gn as Uo,df as zs,ek as th,eQ as sh,dP as Wt,de as ih,j9 as yn,dj as nh,S as rh,eA as oh,gk as ah,aS as ms,O as Zt,f3 as Ct,aM as ch,c2 as Re,h7 as hh,gW as lh,eL as Ne,bR as yr,bZ as uh,b_ as dh,iJ as fh,iI as mr,hl as Je,fr as Xe,ie as ws,f$ as jt,hP as Dn,f9 as ph,hm as Ln,hn as zn,fs as Cs,aC as jn,fq as Mo,ho as ct,i2 as bt,fa as Do,cX as gh}from"./index-DID4Juaa.js";/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Lo(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function mn(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}function Di(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function _e(s,...e){if(!Lo(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function wr(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function yh(s,e){_e(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Nt(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function gs(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function mh(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}const wh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function bh(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function wn(s){if(typeof s=="string")s=bh(s);else if(Lo(s))s=bn(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function vh(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function Eh(s,e){if(s.length!==e.length)return!1;let t=0;for(let i=0;i<s.length;i++)t|=s[i]^e[i];return t===0}const Ih=(s,e)=>{function t(i,...n){if(_e(i),!wh)throw new Error("Non little-endian hardware is not yet supported");if(s.nonceLength!==void 0){const l=n[0];if(!l)throw new Error("nonce / iv required");s.varSizeNonce?_e(l):_e(l,s.nonceLength)}const r=s.tagLength;r&&n[1]!==void 0&&_e(n[1]);const o=e(i,...n),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");_e(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,_e(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(_e(l),r&&l.length<r)throw new Error("invalid ciphertext length: smaller than tagLength="+r);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(t,s),t};function br(s,e,t=!0){if(e===void 0)return new Uint8Array(s);if(e.length!==s)throw new Error("invalid output length, expected "+s+", got: "+e.length);if(t&&!xh(e))throw new Error("invalid output, must be aligned");return e}function vr(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const n=BigInt(32),r=BigInt(4294967295),o=Number(t>>n&r),a=Number(t&r),c=4,h=0;s.setUint32(e+c,o,i),s.setUint32(e+h,a,i)}function _h(s,e,t){mn(t);const i=new Uint8Array(16),n=mh(i);return vr(n,0,BigInt(e),t),vr(n,8,BigInt(s),t),i}function xh(s){return s.byteOffset%4===0}function bn(s){return Uint8Array.from(s)}const Qs=BigInt(2**32-1),Er=BigInt(32);function zo(s,e=!1){return e?{h:Number(s&Qs),l:Number(s>>Er&Qs)}:{h:Number(s>>Er&Qs)|0,l:Number(s&Qs)|0}}function jo(s,e=!1){const t=s.length;let i=new Uint32Array(t),n=new Uint32Array(t);for(let r=0;r<t;r++){const{h:o,l:a}=zo(s[r],e);[i[r],n[r]]=[o,a]}return[i,n]}const Ir=(s,e,t)=>s>>>t,_r=(s,e,t)=>s<<32-t|e>>>t,At=(s,e,t)=>s>>>t|e<<32-t,Ot=(s,e,t)=>s<<32-t|e>>>t,Ps=(s,e,t)=>s<<64-t|e>>>t-32,As=(s,e,t)=>s>>>t-32|e<<64-t,Sh=(s,e)=>e,Ph=(s,e)=>s,Ah=(s,e,t)=>s<<t|e>>>32-t,Oh=(s,e,t)=>e<<t|s>>>32-t,$h=(s,e,t)=>e<<t-32|s>>>64-t,Rh=(s,e,t)=>s<<t-32|e>>>64-t;function Ke(s,e,t,i){const n=(e>>>0)+(i>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}const Kn=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),Vn=(s,e,t,i)=>e+t+i+(s/2**32|0)|0,Nh=(s,e,t,i)=>(s>>>0)+(e>>>0)+(t>>>0)+(i>>>0),Th=(s,e,t,i,n)=>e+t+i+n+(s/2**32|0)|0,qh=(s,e,t,i,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(i>>>0)+(n>>>0),Ch=(s,e,t,i,n,r)=>e+t+i+n+r+(s/2**32|0)|0,ts=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Oi(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function it(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Ge(s,...e){if(!Oi(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function $i(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");it(s.outputLen),it(s.blockLen)}function Tt(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Hn(s,e){Ge(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Bs(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function De(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Li(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Ze(s,e){return s<<32-e|s>>>e}const Ko=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Vo(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}const ht=Ko?s=>s:s=>Vo(s);function Bh(s){for(let e=0;e<s.length;e++)s[e]=Vo(s[e]);return s}const $t=Ko?s=>s:Bh,Ho=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kh=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function cs(s){if(Ge(s),Ho)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=kh[s[t]];return e}const rt={_0:48,_9:57,A:65,F:70,a:97,f:102};function xr(s){if(s>=rt._0&&s<=rt._9)return s-rt._0;if(s>=rt.A&&s<=rt.F)return s-(rt.A-10);if(s>=rt.a&&s<=rt.f)return s-(rt.a-10)}function di(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Ho)return Uint8Array.fromHex(s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let n=0,r=0;n<t;n++,r+=2){const o=xr(s.charCodeAt(r)),a=xr(s.charCodeAt(r+1));if(o===void 0||a===void 0){const c=s[r]+s[r+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+r)}i[n]=o*16+a}return i}function Uh(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Fe(s){return typeof s=="string"&&(s=Uh(s)),Ge(s),s}function pt(...s){let e=0;for(let i=0;i<s.length;i++){const n=s[i];Ge(n),e+=n.length}const t=new Uint8Array(e);for(let i=0,n=0;i<s.length;i++){const r=s[i];t.set(r,n),n+=r.length}return t}class Ri{}function js(s){const e=i=>s().update(Fe(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Mh(s){const e=(i,n)=>s(n).update(Fe(i)).digest(),t=s({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}function Bt(s=32){if(ts&&typeof ts.getRandomValues=="function")return ts.getRandomValues(new Uint8Array(s));if(ts&&typeof ts.randomBytes=="function")return Uint8Array.from(ts.randomBytes(s));throw new Error("crypto.getRandomValues must be defined")}const Dh=BigInt(0),Es=BigInt(1),Lh=BigInt(2),zh=BigInt(7),jh=BigInt(256),Kh=BigInt(113),Fo=[],Go=[],Wo=[];for(let s=0,e=Es,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Fo.push(2*(5*i+t)),Go.push((s+1)*(s+2)/2%64);let n=Dh;for(let r=0;r<7;r++)e=(e<<Es^(e>>zh)*Kh)%jh,e&Lh&&(n^=Es<<(Es<<BigInt(r))-Es);Wo.push(n)}const Zo=jo(Wo,!0),Vh=Zo[0],Hh=Zo[1],Sr=(s,e,t)=>t>32?$h(s,e,t):Ah(s,e,t),Pr=(s,e,t)=>t>32?Rh(s,e,t):Oh(s,e,t);function Fh(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=Sr(h,l,1)^t[a],d=Pr(h,l,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=u,s[o+f+1]^=d}let n=s[2],r=s[3];for(let o=0;o<24;o++){const a=Go[o],c=Sr(n,r,a),h=Pr(n,r,a),l=Fo[o];n=s[l],r=s[l+1],s[l]=c,s[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=Vh[i],s[1]^=Hh[i]}De(t)}class Fn extends Ri{constructor(e,t,i,n=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=n,this.rounds=r,it(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Bs(this.state)}clone(){return this._cloneInto()}keccak(){$t(this.state32),Fh(this.state32,this.rounds),$t(this.state32),this.posOut=0,this.pos=0}update(e){Tt(this),e=Fe(e),Ge(e);const{blockLen:t,state:i}=this,n=e.length;for(let r=0;r<n;){const o=Math.min(t-this.pos,n-r);for(let a=0;a<o;a++)i[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:n}=this;e[i]^=t,t&128&&i===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Tt(this,!1),Ge(e),this.finish();const t=this.state,{blockLen:i}=this;for(let n=0,r=e.length;n<r;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,r-n);e.set(t.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return it(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Hn(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,De(this.state)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:n,rounds:r,enableXOF:o}=this;return e||(e=new Fn(t,i,n,o,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=i,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Gh=(s,e,t)=>js(()=>new Fn(e,s,t)),Yo=Gh(1,136,256/8),Wh="0.1.1";function Zh(){return Wh}class ee extends Error{constructor(e,t={}){const i=(()=>{var c;if(t.cause instanceof ee){if(t.cause.details)return t.cause.details;if(t.cause.shortMessage)return t.cause.shortMessage}return t.cause&&"details"in t.cause&&typeof t.cause.details=="string"?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),n=t.cause instanceof ee&&t.cause.docsPath||t.docsPath,o=`https://oxlib.sh${n??""}`,a=[e||"An error occurred.",...t.metaMessages?["",...t.metaMessages]:[],...i||n?["",i?`Details: ${i}`:void 0,n?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(` 3`);super(a,t.cause?{cause:t.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@${Zh()}`}),this.cause=t.cause,this.details=i,this.docs=o,this.docsPath=n,this.shortMessage=e}walk(e){return Qo(this,e)}}function Qo(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause?Qo(s.cause,e):e?null:s}function Yh(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const n=BigInt(32),r=BigInt(4294967295),o=Number(t>>n&r),a=Number(t&r),c=i?4:0,h=i?0:4;s.setUint32(e+c,o,i),s.setUint32(e+h,a,i)}function Qh(s,e,t){return s&e^~s&t}function Jh(s,e,t){return s&e^s&t^e&t}class Jo extends Ri{constructor(e,t,i,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Li(this.buffer)}update(e){Tt(this),e=Fe(e),Ge(e);const{view:t,buffer:i,blockLen:n}=this,r=e.length;for(let o=0;o<r;){const a=Math.min(n-this.pos,r-o);if(a===n){const c=Li(e);for(;n<=r-o;o+=n)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Tt(this),Hn(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:n,isLE:r}=this;let{pos:o}=this;t[o++]=128,De(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(i,0),o=0);for(let u=o;u<n;u++)t[u]=0;Yh(i,n-8,BigInt(this.length*8),r),this.process(i,0);const a=Li(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:n,finished:r,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=r,e.length=n,e.pos=a,n%t&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const vt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ue=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),de=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Xh=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]),Et=new Uint32Array(64);class el extends Jo{constructor(e=32){super(64,e,8,!1),this.A=vt[0]|0,this.B=vt[1]|0,this.C=vt[2]|0,this.D=vt[3]|0,this.E=vt[4]|0,this.F=vt[5]|0,this.G=vt[6]|0,this.H=vt[7]|0}get(){const{A:e,B:t,C:i,D:n,E:r,F:o,G:a,H:c}=this;return[e,t,i,n,r,o,a,c]}set(e,t,i,n,r,o,a,c){this.A=e|0,this.B=t|0,this.C=i|0,this.D=n|0,this.E=r|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Et[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const d=Et[u-15],f=Et[u-2],y=Ze(d,7)^Ze(d,18)^d>>>3,g=Ze(f,17)^Ze(f,19)^f>>>10;Et[u]=g+Et[u-7]+y+Et[u-16]|0}let{A:i,B:n,C:r,D:o,E:a,F:c,G:h,H:l}=this;for(let u=0;u<64;u++){const d=Ze(a,6)^Ze(a,11)^Ze(a,25),f=l+d+Qh(a,c,h)+Xh[u]+Et[u]|0,g=(Ze(i,2)^Ze(i,13)^Ze(i,22))+Jh(i,n,r)|0;l=h,h=c,c=a,a=o+f|0,o=r,r=n,n=i,i=f+g|0}i=i+this.A|0,n=n+this.B|0,r=r+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(i,n,r,o,a,c,h,l)}roundClean(){De(Et)}destroy(){this.set(0,0,0,0,0,0,0,0),De(this.buffer)}}const Xo=jo(["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","0xf40e3585
35771202a","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(s=>BigInt(s))),tl=Xo[0],sl=Xo[1],It=new Uint32Array(80),_t=new Uint32Array(80);class Gn extends Jo{constructor(e=64){super(128,e,16,!1),this.Ah=de[0]|0,this.Al=de[1]|0,this.Bh=de[2]|0,this.Bl=de[3]|0,this.Ch=de[4]|0,this.Cl=de[5]|0,this.Dh=de[6]|0,this.Dl=de[7]|0,this.Eh=de[8]|0,this.El=de[9]|0,this.Fh=de[10]|0,this.Fl=de[11]|0,this.Gh=de[12]|0,this.Gl=de[13]|0,this.Hh=de[14]|0,this.Hl=de[15]|0}get(){const{Ah:e,Al:t,Bh:i,Bl:n,Ch:r,Cl:o,Dh:a,Dl:c,Eh:h,El:l,Fh:u,Fl:d,Gh:f,Gl:y,Hh:g,Hl:b}=this;return[e,t,i,n,r,o,a,c,h,l,u,d,f,y,g,b]}set(e,t,i,n,r,o,a,c,h,l,u,d,f,y,g,b){this.Ah=e|0,this.Al=t|0,this.Bh=i|0,this.Bl=n|0,this.Ch=r|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=h|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=y|0,this.Hh=g|0,this.Hl=b|0}process(e,t){for(let O=0;O<16;O++,t+=4)It[O]=e.getUint32(t),_t[O]=e.getUint32(t+=4);for(let O=16;O<80;
vendor: 14,235 bytes, line 3
3O++){const x=It[O-15]|0,N=_t[O-15]|0,q=At(x,N,1)^At(x,N,8)^Ir(x,N,7),k=Ot(x,N,1)^Ot(x,N,8)^_r(x,N,7),B=It[O-2]|0,S=_t[O-2]|0,T=At(B,S,19)^Ps(B,S,61)^Ir(B,S,6),C=Ot(B,S,19)^As(B,S,61)^_r(B,S,6),$=Nh(k,C,_t[O-7],_t[O-16]),m=Th($,q,T,It[O-7],It[O-16]);It[O]=m|0,_t[O]=$|0}let{Ah:i,Al:n,Bh:r,Bl:o,Ch:a,Cl:c,Dh:h,Dl:l,Eh:u,El:d,Fh:f,Fl:y,Gh:g,Gl:b,Hh:A,Hl:L}=this;for(let O=0;O<80;O++){const x=At(u,d,14)^At(u,d,18)^Ps(u,d,41),N=Ot(u,d,14)^Ot(u,d,18)^As(u,d,41),q=u&f^~u&g,k=d&y^~d&b,B=qh(L,N,k,sl[O],_t[O]),S=Ch(B,A,x,q,tl[O],It[O]),T=B|0,C=At(i,n,28)^Ps(i,n,34)^Ps(i,n,39),$=Ot(i,n,28)^As(i,n,34)^As(i,n,39),m=i&r^i&a^r&a,E=n&o^n&c^o&c;A=g|0,L=b|0,g=f|0,b=y|0,f=u|0,y=d|0,{h:u,l:d}=Ke(h|0,l|0,S|0,T|0),h=a|0,l=c|0,a=r|0,c=o|0,r=i|0,o=n|0;const p=Kn(T,$,E);i=Vn(p,S,C,m),n=p|0}({h:i,l:n}=Ke(this.Ah|0,this.Al|0,i|0,n|0)),{h:r,l:o}=Ke(this.Bh|0,this.Bl|0,r|0,o|0),{h:a,l:c}=Ke(this.Ch|0,this.Cl|0,a|0,c|0),{h,l}=Ke(this.Dh|0,this.Dl|0,h|0,l|0),{h:u,l:d}=Ke(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:y}=Ke(this.Fh|0,this.Fl|0,f|0,y|0),{h:g,l:b}=Ke(this.Gh|0,this.Gl|0,g|0,b|0),{h:A,l:L}=Ke(this.Hh|0,this.Hl|0,A|0,L|0),this.set(i,n,r,o,a,c,h,l,u,d,f,y,g,b,A,L)}roundClean(){De(It,_t)}destroy(){De(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class il extends Gn{constructor(){super(48),this.Ah=ue[0]|0,this.Al=ue[1]|0,this.Bh=ue[2]|0,this.Bl=ue[3]|0,this.Ch=ue[4]|0,this.Cl=ue[5]|0,this.Dh=ue[6]|0,this.Dl=ue[7]|0,this.Eh=ue[8]|0,this.El=ue[9]|0,this.Fh=ue[10]|0,this.Fl=ue[11]|0,this.Gh=ue[12]|0,this.Gl=ue[13]|0,this.Hh=ue[14]|0,this.Hl=ue[15]|0}}const fe=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class nl extends Gn{constructor(){super(32),this.Ah=fe[0]|0,this.Al=fe[1]|0,this.Bh=fe[2]|0,this.Bl=fe[3]|0,this.Ch=fe[4]|0,this.Cl=fe[5]|0,this.Dh=fe[6]|0,this.Dl=fe[7]|0,this.Eh=fe[8]|0,this.El=fe[9]|0,this.Fh=fe[10]|0,this.Fl=fe[11]|0,this.Gh=fe[12]|0,this.Gl=fe[13]|0,this.Hh=fe[14]|0,this.Hl=fe[15]|0}}const Ks=js(()=>new el),rl=js(()=>new Gn),ol=js(()=>new il),al=js(()=>new nl),Ni=Ks;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wn=BigInt(0),vn=BigInt(1);function Vs(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Zn(s){if(!Vs(s))throw new Error("Uint8Array expected")}function ks(s,e){if(typeof e!="boolean")throw new Error(s+" boolean expected, got "+e)}function Js(s){const e=s.toString(16);return e.length&1?"0"+e:e}function ea(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Wn:BigInt("0x"+s)}const ta=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",cl=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Us(s){if(Zn(s),ta)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=cl[s[t]];return e}const ot={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ar(s){if(s>=ot._0&&s<=ot._9)return s-ot._0;if(s>=ot.A&&s<=ot.F)return s-(ot.A-10);if(s>=ot.a&&s<=ot.f)return s-(ot.a-10)}function fi(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(ta)return Uint8Array.fromHex(s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let n=0,r=0;n<t;n++,r+=2){const o=Ar(s.charCodeAt(r)),a=Ar(s.charCodeAt(r+1));if(o===void 0||a===void 0){const c=s[r]+s[r+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+r)}i[n]=o*16+a}return i}function Yt(s){return ea(Us(s))}function sa(s){return Zn(s),ea(Us(Uint8Array.from(s).reverse()))}function Hs(s,e){return fi(s.toString(16).padStart(e*2,"0"))}function ia(s,e){return Hs(s,e).reverse()}function ke(s,e,t){let i;if(typeof e=="string")try{i=fi(e)}catch(r){throw new Error(s+" must be hex string or Uint8Array, cause: "+r)}else if(Vs(e))i=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");const n=i.length;if(typeof t=="number"&&n!==t)throw new Error(s+" of length "+t+" expected, got "+n);return i}function pi(...s){let e=0;for(let i=0;i<s.length;i++){const n=s[i];Zn(n),e+=n.length}const t=new Uint8Array(e);for(let i=0,n=0;i<s.length;i++){const r=s[i];t.set(r,n),n+=r.length}return t}const zi=s=>typeof s=="bigint"&&Wn<=s;function Yn(s,e,t){return zi(s)&&zi(e)&&zi(t)&&e<=s&&s<t}function hs(s,e,t,i){if(!Yn(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}function hl(s){let e;for(e=0;s>Wn;s>>=vn,e+=1);return e}const Ti=s=>(vn<<BigInt(s))-vn,ji=s=>new Uint8Array(s),Or=s=>Uint8Array.from(s);function ll(s,e,t){if(typeof s!="number"||s<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let i=ji(s),n=ji(s),r=0;const o=()=>{i.fill(1),n.fill(0),r=0},a=(...u)=>t(n,i,...u),c=(u=ji(0))=>{n=a(Or([0]),u),i=a(),u.length!==0&&(n=a(Or([1]),u),i=a())},h=()=>{if(r++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const d=[];for(;u<e;){i=a();const f=i.slice();d.push(f),u+=i.length}return pi(...d)};return(u,d)=>{o(),c(u);let f;for(;!(f=d(h()));)c();return o(),f}}const ul={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||Vs(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function qi(s,e,t={}){const i=(n,r,o)=>{const a=ul[r];if(typeof a!="function")throw new Error("invalid validator function");const c=s[n];if(!(o&&c===void 0)&&!a(c,s))throw new Error("param "+String(n)+" is invalid. Expected "+r+", got "+c)};for(const[n,r]of Object.entries(e))i(n,r,!1);for(const[n,r]of Object.entries(t))i(n,r,!0);return s}function $r(s){const e=new WeakMap;return(t,...i)=>{const n=e.get(t);if(n!==void 0)return n;const r=s(t,...i);return e.set(t,r),r}}function dl(s,e){if(qr(s)>e)throw new ql({givenSize:qr(s),maxSize:e})}const at={zero:48,nine:57,A:65,F:70,a:97,f:102};function Rr(s){if(s>=at.zero&&s<=at.nine)return s-at.zero;if(s>=at.A&&s<=at.F)return s-(at.A-10);if(s>=at.a&&s<=at.f)return s-(at.a-10)}function fl(s,e={}){const{dir:t,size:i=32}=e;if(i===0)return s;if(s.length>i)throw new Cl({size:s.length,targetSize:i,type:"Bytes"});const n=new Uint8Array(i);for(let r=0;r<i;r++){const o=t==="right";n[o?r:i-r-1]=s[o?r:s.length-r-1]}return n}function na(s,e){if(qt(s)>e)throw new _l({givenSize:qt(s),maxSize:e})}function pl(s,e){if(typeof e=="number"&&e>0&&e>qt(s)-1)throw new aa({offset:e,position:"start",size:qt(s)})}function gl(s,e,t){if(typeof e=="number"&&typeof t=="number"&&qt(s)!==t-e)throw new aa({offset:t,position:"end",size:qt(s)})}function ra(s,e={}){const{dir:t,size:i=32}=e;if(i===0)return s;const n=s.replace("0x","");if(n.length>i*2)throw new xl({size:Math.ceil(n.length/2),targetSize:i,type:"Hex"});return`0x${n[t==="right"?"padEnd":"padStart"](i*2,"0")}`}const yl="#__bigint";function Qn(s,e,t){return JSON.stringify(s,(i,n)=>typeof n=="bigint"?n.toString()+yl:n,t)}const ml=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function wl(s,e={}){const{strict:t=!1}=e;if(!s)throw new Nr(s);if(typeof s!="string")throw new Nr(s);if(t&&!/^0x[0-9a-fA-F]*$/.test(s))throw new Tr(s);if(!s.startsWith("0x"))throw new Tr(s)}function bl(...s){return`0x${s.reduce((e,t)=>e+t.replace("0x",""),"")}`}function Jn(s){return s instanceof Uint8Array?gi(s):Array.isArray(s)?gi(new Uint8Array(s)):s}function gi(s,e={}){let t="";for(let n=0;n<s.length;n++)t+=ml[s[n]];const i=`0x${t}`;return typeof e.size=="number"?(na(i,e.size),oa(i,e.size)):i}function Ki(s,e={}){const{signed:t,size:i}=e,n=BigInt(s);let r;i?t?r=(1n<<BigInt(i)*8n-1n)-1n:r=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(r=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof r=="bigint"&&t?-r-1n:0;if(r&&n>r||n<o){const h=typeof s=="bigint"?"n":"";throw new Il({max:r?`${r}${h}`:void 0,min:`${o}${h}`,signed:t,size:i,value:`${s}${h}`})}const c=`0x${(t&&n<0?(1n<<BigInt(i*8))+BigInt(n):n).toString(16)}`;return i?vl(c,i):c}function vl(s,e){return ra(s,{dir:"left",size:e})}function oa(s,e){return ra(s,{dir:"right",size:e})}function ut(s,e,t,i={}){const{strict:n}=i;pl(s,e);const r=`0x${s.replace("0x","").slice((e??0)*2,(t??s.length)*2)}`;return n&&gl(r,e,t),r}function qt(s){return Math.ceil((s.length-2)/2)}function El(s,e={}){const{strict:t=!1}=e;try{return wl(s,{strict:t}),!0}catch{return!1}}class Il extends ee{constructor({max:e,min:t,signed:i,size:n,value:r}){super(`Number \`${r}\` is not in safe${n?` ${n*8}-bit`:""}${i?" signed":" unsigned"} integer range ${e?`(\`${t}\` to \`${e}\`)`:`(above \`${t}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Nr extends ee{constructor(e){super(`Value \`${typeof e=="object"?Qn(e):e}\` of type \`${typeof e}\` 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 Tr extends ee{constructor(e){super(`Value \`${e}\` 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"})}}let _l=class extends ee{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};class aa extends ee{constructor({offset:e,position:t,size:i}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${i}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let xl=class extends ee{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const Sl=new TextEncoder;function Pl(s){if(!(s instanceof Uint8Array)){if(!s)throw new Xs(s);if(typeof s!="object")throw new Xs(s);if(!("BYTES_PER_ELEMENT"in s))throw new Xs(s);if(s.BYTES_PER_ELEMENT!==1||s.constructor.name!=="Uint8Array")throw new Xs(s)}}function Al(s){return s instanceof Uint8Array?s:typeof s=="string"?$l(s):Ol(s)}function Ol(s){return s instanceof Uint8Array?s:new Uint8Array(s)}function $l(s,e={}){const{size:t}=e;let i=s;t&&(na(s,t),i=oa(s,t));let n=i.slice(2);n.length%2&&(n=`0${n}`);const r=n.length/2,o=new Uint8Array(r);for(let a=0,c=0;a<r;a++){const h=Rr(n.charCodeAt(c++)),l=Rr(n.charCodeAt(c++));if(h===void 0||l===void 0)throw new ee(`Invalid byte sequence ("${n[c-2]}${n[c-1]}" in "${n}").`);o[a]=h*16+l}return o}function Rl(s,e={}){const{size:t}=e,i=Sl.encode(s);return typeof t=="number"?(dl(i,t),Nl(i,t)):i}function Nl(s,e){return fl(s,{dir:"right",size:e})}function qr(s){return s.length}function Tl(s){try{return Pl(s),!0}catch{return!1}}class Xs extends ee{constructor(e){super(`Value \`${typeof e=="object"?Qn(e):e}\` of type \`${typeof e}\` 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 ql extends ee{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class Cl extends ee{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function ca(s,e={}){const{as:t=typeof s=="string"?"Hex":"Bytes"}=e,i=Yo(Al(s));return t==="Bytes"?i:gi(i)}class Bl extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const kl={checksum:new Bl(8192)},Vi=kl.checksum;function ha(s,e={}){const{compressed:t}=e,{prefix:i,x:n,y:r}=s;if(t===!1||typeof n=="bigint"&&typeof r=="bigint"){if(i!==4)throw new Cr({prefix:i,cause:new jl});return}if(t===!0||typeof n=="bigint"&&typeof r>"u"){if(i!==3&&i!==2)throw new Cr({prefix:i,cause:new zl});return}throw new Ll({publicKey:s})}function Ul(s){const e=(()=>{if(El(s))return la(s);if(Tl(s))return Ml(s);const{prefix:t,x:i,y:n}=s;return typeof i=="bigint"&&typeof n=="bigint"?{prefix:t??4,x:i,y:n}:{prefix:t,x:i}})();return ha(e),e}function Ml(s){return la(gi(s))}function la(s){if(s.length!==132&&s.length!==130&&s.length!==68)throw new Kl({publicKey:s});if(s.length===130){const i=BigInt(ut(s,0,32)),n=BigInt(ut(s,32,64));return{prefix:4,x:i,y:n}}if(s.length===132){const i=Number(ut(s,0,1)),n=BigInt(ut(s,1,33)),r=BigInt(ut(s,33,65));return{prefix:i,x:n,y:r}}const e=Number(ut(s,0,1)),t=BigInt(ut(s,1,33));return{prefix:e,x:t}}function Dl(s,e={}){ha(s);const{prefix:t,x:i,y:n}=s,{includePrefix:r=!0}=e;return bl(r?Ki(t,{size:1}):"0x",Ki(i,{size:32}),typeof n=="bigint"?Ki(n,{size:32}):"0x")}class Ll extends ee{constructor({publicKey:e}){super(`Value \`${Qn(e)}\` 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 Cr extends ee{constructor({prefix:e,cause:t}){super(`Prefix "${e}
3" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class zl extends ee{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 jl extends ee{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let Kl=class extends ee{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${qt(Jn(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const Vl=/^0x[a-fA-F0-9]{40}$/;function ua(s,e={}){const{strict:t=!0}=e;if(!Vl.test(s))throw new Br({address:s,cause:new Gl});if(t){if(s.toLowerCase()===s)return;if(da(s)!==s)throw new Br({address:s,cause:new Wl})}}function da(s){if(Vi.has(s))return Vi.get(s);ua(s,{strict:!1});const e=s.substring(2).toLowerCase(),t=ca(Rl(e),{as:"Bytes"}),i=e.split("");for(let r=0;r<40;r+=2)t[r>>1]>>4>=8&&i[r]&&(i[r]=i[r].toUpperCase()),(t[r>>1]&15)>=8&&i[r+1]&&(i[r+1]=i[r+1].toUpperCase());const n=`0x${i.join("")}`;return Vi.set(s,n),n}function Hl(s,e={}){const{checksum:t=!1}=e;return ua(s),t?da(s):s}function Fl(s,e={}){const t=ca(`0x${Dl(s).slice(4)}`).substring(26);return Hl(`0x${t}`,e)}class Br extends ee{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Gl extends ee{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 Wl extends ee{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class fa extends Ri{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,$i(e);const i=Fe(t);if(this.iHash=e.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 n=this.blockLen,r=new Uint8Array(n);r.set(i.length>n?e.create().update(i).digest():i);for(let o=0;o<r.length;o++)r[o]^=54;this.iHash.update(r),this.oHash=e.create();for(let o=0;o<r.length;o++)r[o]^=106;this.oHash.update(r),De(r)}update(e){return Tt(this),this.iHash.update(e),this}digestInto(e){Tt(this),Ge(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:i,finished:n,destroyed:r,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=r,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Fs=(s,e,t)=>new fa(s,e).update(t).digest();Fs.create=(s,e)=>new fa(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Se=BigInt(0),me=BigInt(1),Kt=BigInt(2),Zl=BigInt(3),pa=BigInt(4),ga=BigInt(5),ya=BigInt(8);function xe(s,e){const t=s%e;return t>=Se?t:e+t}function qe(s,e,t){let i=s;for(;e-- >Se;)i*=i,i%=t;return i}function En(s,e){if(s===Se)throw new Error("invert: expected non-zero number");if(e<=Se)throw new Error("invert: expected positive modulus, got "+e);let t=xe(s,e),i=e,n=Se,r=me;for(;t!==Se;){const a=i/t,c=i%t,h=n-r*a;i=t,t=c,n=r,r=h}if(i!==me)throw new Error("invert: does not exist");return xe(n,e)}function ma(s,e){const t=(s.ORDER+me)/pa,i=s.pow(e,t);if(!s.eql(s.sqr(i),e))throw new Error("Cannot find square root");return i}function Yl(s,e){const t=(s.ORDER-ga)/ya,i=s.mul(e,Kt),n=s.pow(i,t),r=s.mul(e,n),o=s.mul(s.mul(r,Kt),n),a=s.mul(r,s.sub(o,s.ONE));if(!s.eql(s.sqr(a),e))throw new Error("Cannot find square root");return a}function Ql(s){if(s<BigInt(3))throw new Error("sqrt is not defined for small field");let e=s-me,t=0;for(;e%Kt===Se;)e/=Kt,t++;let i=Kt;const n=Xn(s);for(;kr(n,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ma;let r=n.pow(i,e);const o=(e+me)/Kt;return function(c,h){if(c.is0(h))return h;if(kr(c,h)!==1)throw new Error("Cannot find square root");let l=t,u=c.mul(c.ONE,r),d=c.pow(h,e),f=c.pow(h,o);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let y=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(y++,g=c.sqr(g),y===l)throw new Error("Cannot find square root");const b=me<<BigInt(l-y-1),A=c.pow(u,b);l=y,u=c.sqr(A),d=c.mul(d,u),f=c.mul(f,A)}return f}}function Jl(s){return s%pa===Zl?ma:s%ya===ga?Yl:Ql(s)}const Xl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function eu(s){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Xl.reduce((i,n)=>(i[n]="function",i),e);return qi(s,t)}function tu(s,e,t){if(t<Se)throw new Error("invalid exponent, negatives unsupported");if(t===Se)return s.ONE;if(t===me)return e;let i=s.ONE,n=e;for(;t>Se;)t&me&&(i=s.mul(i,n)),n=s.sqr(n),t>>=me;return i}function wa(s,e,t=!1){const i=new Array(e.length).fill(t?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(i[c]=o,s.mul(o,a)),s.ONE),r=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(i[c]=s.mul(o,i[c]),s.mul(o,a)),r),i}function kr(s,e){const t=(s.ORDER-me)/Kt,i=s.pow(e,t),n=s.eql(i,s.ONE),r=s.eql(i,s.ZERO),o=s.eql(i,s.neg(s.ONE));if(!n&&!r&&!o)throw new Error("invalid Legendre symbol result");return n?1:r?0:-1}function ba(s,e){e!==void 0&&it(e);const t=e!==void 0?e:s.toString(2).length,i=Math.ceil(t/8);return{nBitLength:t,nByteLength:i}}function Xn(s,e,t=!1,i={}){if(s<=Se)throw new Error("invalid field: expected ORDER > 0, got "+s);const{nBitLength:n,nByteLength:r}=ba(s,e);if(r>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:s,isLE:t,BITS:n,BYTES:r,MASK:Ti(n),ZERO:Se,ONE:me,create:c=>xe(c,s),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Se<=c&&c<s},is0:c=>c===Se,isOdd:c=>(c&me)===me,neg:c=>xe(-c,s),eql:(c,h)=>c===h,sqr:c=>xe(c*c,s),add:(c,h)=>xe(c+h,s),sub:(c,h)=>xe(c-h,s),mul:(c,h)=>xe(c*h,s),pow:(c,h)=>tu(a,c,h),div:(c,h)=>xe(c*En(h,s),s),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>En(c,s),sqrt:i.sqrt||(c=>
vendor: 2,569 bytes, line 3
3(o||(o=Jl(s)),o(a,c))),toBytes:c=>t?ia(c,r):Hs(c,r),fromBytes:c=>{if(c.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+c.length);return t?sa(c):Yt(c)},invertBatch:c=>wa(a,c),cmov:(c,h,l)=>l?h:c});return Object.freeze(a)}function va(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function Ea(s){const e=va(s);return e+Math.ceil(e/2)}function su(s,e,t=!1){const i=s.length,n=va(e),r=Ea(e);if(i<16||i<r||i>1024)throw new Error("expected "+r+"-1024 bytes of input, got "+i);const o=t?sa(s):Yt(s),a=xe(o,e-me)+me;return t?ia(a,n):Hs(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ur=BigInt(0),In=BigInt(1);function Hi(s,e){const t=e.negate();return s?t:e}function Ia(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Fi(s,e){Ia(s,e);const t=Math.ceil(e/s)+1,i=2**(s-1),n=2**s,r=Ti(s),o=BigInt(s);return{windows:t,windowSize:i,mask:r,maxNumber:n,shiftBy:o}}function Mr(s,e,t){const{windowSize:i,mask:n,maxNumber:r,shiftBy:o}=t;let a=Number(s&n),c=s>>o;a>i&&(a-=r,c+=In);const h=e*i,l=h+Math.abs(a)-1,u=a===0,d=a<0,f=e%2!==0;return{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:h}}function iu(s,e){if(!Array.isArray(s))throw new Error("array expected");s.forEach((t,i)=>{if(!(t instanceof e))throw new Error("invalid point at index "+i)})}function nu(s,e){if(!Array.isArray(s))throw new Error("array of scalars expected");s.forEach((t,i)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+i)})}const Gi=new WeakMap,_a=new WeakMap;function Wi(s){return _a.get(s)||1}function ru(s,e){return{constTimeNegate:Hi,hasPrecomputes(t){return Wi(t)!==1},unsafeLadder(t,i,n=s.ZERO){let r=t;for(;i>Ur;)i&In&&(n=n.add(r)),r=r.double(),i>>=In;return n},precomputeWindow(t,i){const{windows:n,windowSize:r}=Fi(i,e),o=[];let a=t,c=a;for(let h=0;h<n;h++){c=a,o.push(c);for(let l=1;l<r;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,i,n){let r=s.ZERO,o=s.BASE;const a=Fi(t,e);for(let c=0;c<a.windows;c++){const{nextN:h,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:y}=Mr(n,c,a);n=h,u?o=o.add(Hi(f,i[y])):r=r.add(Hi(d,i[l]))}return{p:r,f:o}},wNAFUnsafe(t,i,n,r=s.ZERO){const o=Fi(t,e);for(let a=0;a<o.windows&&n!==Ur;a++){const{nextN:c,offset:h,isZero:l,isNeg:u}=Mr(n,a,o);if(n=c,!l){const d=i[h];r=r.add(u?d.negate():d)}}return r},getPrecomputes(t,i,n){let r=Gi.get(i);return r||(r=this.precomputeWindow(i,t),t!==1&&Gi.set(i,n(r))),r},wNAFCached(t,i,n){const r=Wi(t);
vendor: 4,332 bytes, line 3
3return this.wNAF(r,this.getPrecomputes(r,t,n),i)},wNAFCachedUnsafe(t,i,n,r){const o=Wi(t);return o===1?this.unsafeLadder(t,i,r):this.wNAFUnsafe(o,this.getPrecomputes(o,t,n),i,r)},setWindowSize(t,i){Ia(i,e),_a.set(t,i),Gi.delete(t)}}}function ou(s,e,t,i){iu(t,s),nu(i,e);const n=t.length,r=i.length;if(n!==r)throw new Error("arrays of points and scalars must have equal length");const o=s.ZERO,a=hl(BigInt(n));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const h=Ti(c),l=new Array(Number(h)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let d=o;for(let f=u;f>=0;f-=c){l.fill(o);for(let g=0;g<r;g++){const b=i[g],A=Number(b>>BigInt(f)&h);l[A]=l[A].add(t[g])}let y=o;for(let g=l.length-1,b=o;g>0;g--)b=b.add(l[g]),y=y.add(b);if(d=d.add(y),f!==0)for(let g=0;g<c;g++)d=d.double()}return d}function xa(s){return eu(s.Fp),qi(s,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ba(s.n,s.nBitLength),...s,p:s.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Dr(s){s.lowS!==void 0&&ks("lowS",s.lowS),s.prehash!==void 0&&ks("prehash",s.prehash)}function au(s){const e=xa(s);qi(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:t,Fp:i,a:n}=e;if(t){if(!i.eql(n,i.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}let cu=class extends Error{constructor(e=""){super(e)}};const dt={Err:cu,_tlv:{encode:(s,e)=>{const{Err:t}=dt;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const i=e.length/2,n=Js(i);if(n.length/2&128)throw new t("tlv.encode: long form length too big");const r=i>127?Js(n.length/2|128):"";return Js(s)+r+n+e},decode(s,e){const{Err:t}=dt;let i=0;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[i++]!==s)throw new t("tlv.decode: wrong tlv");const n=e[i++],r=!!(n&128);let o=0;if(!r)o=n;else{const c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const h=e.subarray(i,i+c);if(h.length!==c)throw new t("tlv.decode: length bytes not complete");if(h[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const l of h)o=o<<8|l;if(i+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(s){const{Err:e}=dt;if(s<gt)throw new e("integer: negative integers are not allowed");let t=Js(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){const{Err:e}=dt;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Yt(s)}},toSig(s){const{Err:e,_int:t,_tlv:i}=dt,n=ke("signature",s),{v:r,l:o}=i.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,r),{v:h,l}=i.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(h)}},hexFromSig(s){const{_tlv:e,_int:t}=dt,i=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),r=i+n;return e.encode(48,r)}};function Zi(s,e){return Us(Hs(s,e))}const gt=BigInt(0),oe=BigInt(1);BigInt(2);const Yi=BigInt(3),hu=BigInt(4);function lu(s){const e=au(s),{Fp:t}=e,i=Xn(e.n,e.nBitLength),n=e.toBytes||((O,x,N)=>{const q=x.toAffine();return pi(Uint8Array.from([4]),t.toBytes(q.x),t.toBytes(q.y))}),r=e.fromBytes||(O=>{const x=O.subarray(1),N=t.fromBytes(x.subarray(0,t.BYTES)),q=t.fromBytes(x.subarray(t.BYTES,2*t.BYTES));return{x:N,y:q}});function o(O){const{a:x,b:N}=e,q=t.sqr(O),k=t.mul(q,O);return t.add(t.add(k,t.mul(O,x)),N)}function a(O,x){const N=t.sqr(x),q=o(O);return t.eql(N,q)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=t.mul(t.pow(e.a,Yi),hu),h=t.mul(t.sqr(e.b),BigInt(27));
vendor: 42,289 bytes, line 3
3if(t.is0(t.add(c,h)))throw new Error("bad curve params: a or b");function l(O){return Yn(O,oe,e.n)}function u(O){const{allowedPrivateKeyLengths:x,nByteLength:N,wrapPrivateKey:q,n:k}=e;if(x&&typeof O!="bigint"){if(Vs(O)&&(O=Us(O)),typeof O!="string"||!x.includes(O.length))throw new Error("invalid private key");O=O.padStart(N*2,"0")}let B;try{B=typeof O=="bigint"?O:Yt(ke("private key",O,N))}catch{throw new Error("invalid private key, expected hex or "+N+" bytes, got "+typeof O)}return q&&(B=xe(B,k)),hs("private key",B,oe,k),B}function d(O){if(!(O instanceof g))throw new Error("ProjectivePoint expected")}const f=$r((O,x)=>{const{px:N,py:q,pz:k}=O;if(t.eql(k,t.ONE))return{x:N,y:q};const B=O.is0();x==null&&(x=B?t.ONE:t.inv(k));const S=t.mul(N,x),T=t.mul(q,x),C=t.mul(k,x);if(B)return{x:t.ZERO,y:t.ZERO};if(!t.eql(C,t.ONE))throw new Error("invZ was invalid");return{x:S,y:T}}),y=$r(O=>{if(O.is0()){if(e.allowInfinityPoint&&!t.is0(O.py))return;throw new Error("bad point: ZERO")}const{x,y:N}=O.toAffine();if(!t.isValid(x)||!t.isValid(N))throw new Error("bad point: x or y not FE");if(!a(x,N))throw new Error("bad point: equation left != right");if(!O.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(x,N,q){if(x==null||!t.isValid(x))throw new Error("x required");if(N==null||!t.isValid(N)||t.is0(N))throw new Error("y required");if(q==null||!t.isValid(q))throw new Error("z required");this.px=x,this.py=N,this.pz=q,Object.freeze(this)}static fromAffine(x){const{x:N,y:q}=x||{};if(!x||!t.isValid(N)||!t.isValid(q))throw new Error("invalid affine point");if(x instanceof g)throw new Error("projective point not allowed");const k=B=>t.eql(B,t.ZERO);return k(N)&&k(q)?g.ZERO:new g(N,q,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(x){const N=wa(t,x.map(q=>q.pz));return x.map((q,k)=>q.toAffine(N[k])).map(g.fromAffine)}static fromHex(x){const N=g.fromAffine(r(ke("pointHex",x)));return N.assertValidity(),N}static fromPrivateKey(x){return g.BASE.multiply(u(x))}static msm(x,N){return ou(g,i,x,N)}_setWindowSize(x){L.setWindowSize(this,x)}assertValidity(){y(this)}hasEvenY(){const{y:x}=this.toAffine();if(t.isOdd)return!t.isOdd(x);throw new Error("Field doesn't support isOdd")}equals(x){d(x);const{px:N,py:q,pz:k}=this,{px:B,py:S,pz:T}=x,C=t.eql(t.mul(N,T),t.mul(B,k)),$=t.eql(t.mul(q,T),t.mul(S,k));return C&&$}negate(){return new g(this.px,t.neg(this.py),this.pz)}double(){const{a:x,b:N}=e,q=t.mul(N,Yi),{px:k,py:B,pz:S}=this;let T=t.ZERO,C=t.ZERO,$=t.ZERO,m=t.mul(k,k),E=t.mul(B,B),p=t.mul(S,S),w=t.mul(k,B);return w=t.add(w,w),$=t.mul(k,S),$=t.add($,$),T=t.mul(x,$),C=t.mul(q,p),C=t.add(T,C),T=t.sub(E,C),C=t.add(E,C),C=t.mul(T,C),T=t.mul(w,T),$=t.mul(q,$),p=t.mul(x,p),w=t.sub(m,p),w=t.mul(x,w),w=t.add(w,$),$=t.add(m,m),m=t.add($,m),m=t.add(m,p),m=t.mul(m,w),C=t.add(C,m),p=t.mul(B,S),p=t.add(p,p),m=t.mul(p,w),T=t.sub(T,m),$=t.mul(p,E),$=t.add($,$),$=t.add($,$),new g(T,C,$)}add(x){d(x);const{px:N,py:q,pz:k}=this,{px:B,py:S,pz:T}=x;let C=t.ZERO,$=t.ZERO,m=t.ZERO;const E=e.a,p=t.mul(e.b,Yi);let w=t.mul(N,B),I=t.mul(q,S),P=t.mul(k,T),v=t.add(N,q),_=t.add(B,S);v=t.mul(v,_),_=t.add(w,I),v=t.sub(v,_),_=t.add(N,k);let R=t.add(B,T);return _=t.mul(_,R),R=t.add(w,P),_=t.sub(_,R),R=t.add(q,k),C=t.add(S,T),R=t.mul(R,C),C=t.add(I,P),R=t.sub(R,C),m=t.mul(E,_),C=t.mul(p,P),m=t.add(C,m),C=t.sub(I,m),m=t.add(I,m),$=t.mul(C,m),I=t.add(w,w),I=t.add(I,w),P=t.mul(E,P),_=t.mul(p,_),I=t.add(I,P),P=t.sub(w,P),P=t.mul(E,P),_=t.add(_,P),w=t.mul(I,_),$=t.add($,w),w=t.mul(R,_),C=t.mul(v,C),C=t.sub(C,w),w=t.mul(v,I),m=t.mul(R,m),m=t.add(m,w),new g(C,$,m)}subtract(x){return this.add(x.negate())}is0(){return this.equals(g.ZERO)}wNAF(x){return L.wNAFCached(this,x,g.normalizeZ)}multiplyUnsafe(x){const{endo:N,n:q}=e;hs("scalar",x,gt,q);const k=g.ZERO;if(x===gt)return k;if(this.is0()||x===oe)return this;if(!N||L.hasPrecomputes(this))return L.wNAFCachedUnsafe(this,x,g.normalizeZ);let{k1neg:B,k1:S,k2neg:T,k2:C}=N.splitScalar(x),$=k,m=k,E=this;for(;S>gt||C>gt;)S&oe&&($=$.add(E)),C&oe&&(m=m.add(E)),E=E.double(),S>>=oe,C>>=oe;return B&&($=$.negate()),T&&(m=m.negate()),m=new g(t.mul(m.px,N.beta),m.py,m.pz),$.add(m)}multiply(x){const{endo:N,n:q}=e;hs("scalar",x,oe,q);let k,B;if(N){const{k1neg:S,k1:T,k2neg:C,k2:$}=N.splitScalar(x);let{p:m,f:E}=this.wNAF(T),{p,f:w}=this.wNAF($);m=L.constTimeNegate(S,m),p=L.constTimeNegate(C,p),p=new g(t.mul(p.px,N.beta),p.py,p.pz),k=m.add(p),B=E.add(w)}else{const{p:S,f:T}=this.wNAF(x);k=S,B=T}return g.normalizeZ([k,B])[0]}multiplyAndAddUnsafe(x,N,q){const k=g.BASE,B=(T,C)=>C===gt||C===oe||!T.equals(k)?T.multiplyUnsafe(C):T.multiply(C),S=B(this,N).add(B(x,q));return S.is0()?void 0:S}toAffine(x){return f(this,x)}isTorsionFree(){const{h:x,isTorsionFree:N}=e;if(x===oe)return!0;if(N)return N(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:x,clearCofactor:N}=e;return x===oe?this:N?N(g,this):this.multiplyUnsafe(e.h)}toRawBytes(x=!0){return ks("isCompressed",x),this.assertValidity(),n(g,this,x)}toHex(x=!0){return ks("isCompressed",x),Us(this.toRawBytes(x))}}g.BASE=new g(e.Gx,e.Gy,t.ONE),g.ZERO=new g(t.ZERO,t.ONE,t.ZERO);const{endo:b,nBitLength:A}=e,L=ru(g,b?Math.ceil(A/2):A);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:u,weierstrassEquation:o,isWithinCurveOrder:l}}function uu(s){const e=xa(s);return qi(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function du(s){const e=uu(s),{Fp:t,n:i,nByteLength:n,nBitLength:r}=e,o=t.BYTES+1,a=2*t.BYTES+1;function c(p){return xe(p,i)}function h(p){return En(p,i)}const{ProjectivePoint:l,normPrivateKeyToScalar:u,weierstrassEquation:d,isWithinCurveOrder:f}=lu({...e,toBytes(p,w,I){const P=w.toAffine(),v=t.toBytes(P.x),_=pi;return ks("isCompressed",I),I?_(Uint8Array.from([w.hasEvenY()?2:3]),v):_(Uint8Array.from([4]),v,t.toBytes(P.y))},fromBytes(p){const w=p.length,I=p[0],P=p.subarray(1);if(w===o&&(I===2||I===3)){const v=Yt(P);if(!Yn(v,oe,t.ORDER))throw new Error("Point is not on curve");const _=d(v);let R;try{R=t.sqrt(_)}catch(K){const j=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+j)}const M=(R&oe)===oe;return(I&1)===1!==M&&(R=t.neg(R)),{x:v,y:R}}else if(w===a&&I===4){const v=t.fromBytes(P.subarray(0,t.BYTES)),_=t.fromBytes(P.subarray(t.BYTES,2*t.BYTES));return{x:v,y:_}}else{const v=o,_=a;throw new Error("invalid Point, expected length of "+v+", or uncompressed "+_+", got "+w)}}});function y(p){const w=i>>oe;return p>w}function g(p){return y(p)?c(-p):p}const b=(p,w,I)=>Yt(p.slice(w,I));class A{constructor(w,I,P){hs("r",w,oe,i),hs("s",I,oe,i),this.r=w,this.s=I,P!=null&&(this.recovery=P),Object.freeze(this)}static fromCompact(w){const I=n;return w=ke("compactSignature",w,I*2),new A(b(w,0,I),b(w,I,2*I))}static fromDER(w){const{r:I,s:P}=dt.toSig(ke("DER",w));return new A(I,P)}assertValidity(){}addRecoveryBit(w){return new A(this.r,this.s,w)}recoverPublicKey(w){const{r:I,s:P,recovery:v}=this,_=k(ke("msgHash",w));if(v==null||![0,1,2,3].includes(v))throw new Error("recovery id invalid");const R=v===2||v===3?I+e.n:I;if(R>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const M=v&1?"03":"02",V=l.fromHex(M+Zi(R,t.BYTES)),K=h(R),j=c(-_*K),F=c(P*K),G=l.BASE.multiplyAndAddUnsafe(V,j,F);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new A(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return fi(this.toDERHex())}toDERHex(){return dt.hexFromSig(this)}toCompactRawBytes(){return fi(this.toCompactHex())}toCompactHex(){const w=n;return Zi(this.r,w)+Zi(this.s,w)}}const L={isValidPrivateKey(p){try{return u(p),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const p=Ea(e.n);return su(e.randomBytes(p),e.n)},precompute(p=8,w=l.BASE){return w._setWindowSize(p),w.multiply(BigInt(3)),w}};function O(p,w=!0){return l.fromPrivateKey(p).toRawBytes(w)}function x(p){if(typeof p=="bigint")return!1;if(p instanceof l)return!0;const I=ke("key",p).length,P=t.BYTES,v=P+1,_=2*P+1;if(!(e.allowedPrivateKeyLengths||n===v))return I===v||I===_}function N(p,w,I=!0){if(x(p)===!0)throw new Error("first arg must be private key");if(x(w)===!1)throw new Error("second arg must be public key");return l.fromHex(w).multiply(u(p)).toRawBytes(I)}const q=e.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");const w=Yt(p),I=p.length*8-r;return I>0?w>>BigInt(I):w},k=e.bits2int_modN||function(p){return c(q(p))},B=Ti(r);function S(p){return hs("num < 2^"+r,p,gt,B),Hs(p,n)}function T(p,w,I=C){if(["recovered","canonical"].some(H=>H in I))throw new Error("sign() legacy options not supported");const{hash:P,randomBytes:v}=e;let{lowS:_,prehash:R,extraEntropy:M}=I;_==null&&(_=!0),p=ke("msgHash",p),Dr(I),R&&(p=ke("prehashed msgHash",P(p)));const V=k(p),K=u(w),j=[S(K),S(V)];if(M!=null&&M!==!1){const H=M===!0?v(t.BYTES):M;j.push(ke("extraEntropy",H))}const F=pi(...j),G=V;function Z(H){const Y=q(H);if(!f(Y))return;const ve=h(Y),Ee=l.BASE.multiply(Y).toAffine(),ye=c(Ee.x);if(ye===gt)return;const Te=c(ve*c(G+ye*K));if(Te===gt)return;let We=(Ee.x===ye?0:2)|Number(Ee.y&oe),es=Te;return _&&y(Te)&&(es=g(Te),We^=1),new A(ye,es,We)}return{seed:F,k2sig:Z}}const C={lowS:e.lowS,prehash:!1},$={lowS:e.lowS,prehash:!1};function m(p,w,I=C){const{seed:P,k2sig:v}=T(p,w,I),_=e;return ll(_.hash.outputLen,_.nByteLength,_.hmac)(P,v)}l.BASE._setWindowSize(8);function E(p,w,I,P=$){var We;const v=p;w=ke("msgHash",w),I=ke("publicKey",I);const{lowS:_,prehash:R,format:M}=P;if(Dr(P),"strict"in P)throw new Error("options.strict was renamed to lowS");if(M!==void 0&&M!=="compact"&&M!=="der")throw new Error("format must be compact or der");const V=typeof v=="string"||Vs(v),K=!V&&!M&&typeof v=="object"&&v!==null&&typeof v.r=="bigint"&&typeof v.s=="bigint";if(!V&&!K)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let j,F;try{if(K&&(j=new A(v.r,v.s)),V){try{M!=="compact"&&(j=A.fromDER(v))}catch(es){if(!(es instanceof dt.Err))throw es}!j&&M!=="der"&&(j=A.fromCompact(v))}F=l.fromHex(I)}catch{return!1}if(!j||_&&j.hasHighS())return!1;R&&(w=e.hash(w));const{r:G,s:Z}=j,H=k(w),Y=h(Z),ve=c(H*Y),Ee=c(G*Y),ye=(We=l.BASE.multiplyAndAddUnsafe(F,ve,Ee))==null?void 0:We.toAffine();return ye?c(ye.x)===G:!1}return{CURVE:e,getPublicKey:O,getSharedSecret:N,sign:m,verify:E,ProjectivePoint:l,Signature:A,utils:L}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function fu(s){return{hash:s,hmac:(e,...t)=>Fs(s,e,pt(...t)),randomBytes:Bt}}function pu(s,e){const t=i=>du({...s,...fu(i)});return{...t(e),create:t}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Sa=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Lr=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),gu=BigInt(0),yu=BigInt(1),_n=BigInt(2),zr=(s,e)=>(s+e/_n)/e;function mu(s){const e=Sa,t=BigInt(3),i=BigInt(6),n=BigInt(11),r=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),h=s*s*s%e,l=h*h*s%e,u=qe(l,t,e)*l%e,d=qe(u,t,e)*l%e,f=qe(d,_n,e)*h%e,y=qe(f,n,e)*f%e,g=qe(y,r,e)*y%e,b=qe(g,a,e)*g%e,A=qe(b,c,e)*b%e,L=qe(A,a,e)*g%e,O=qe(L,t,e)*l%e,x=qe(O,o,e)*y%e,N=qe(x,i,e)*h%e,q=qe(N,_n,e);if(!xn.eql(xn.sqr(q),s))throw new Error("Cannot find square root");return q}const xn=Xn(Sa,void 0,void 0,{sqrt:mu}),wu=pu({a:gu,b:BigInt(7),Fp:xn,n:Lr,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:s=>{const e=Lr,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),i=-yu*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),n=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),r=t,o=BigInt("0x100000000000000000000000000000000"),a=zr(r*s,e),c=zr(-i*s,e);let h=xe(s-a*t-c*n,e),l=xe(-a*i-c*r,e);const u=h>o,d=l>o;if(u&&(h=e-h),d&&(l=e-l),h>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+s);return{k1neg:u,k1:h,k2neg:d,k2:l}}}},Ks);function bu(s){if(s.length!==130&&s.length!==132)throw new Eu({signature:s});const e=BigInt(ut(s,0,32)),t=BigInt(ut(s,32,64)),i=(()=>{const n=+`0x${s.slice(130)}`;if(!Number.isNaN(n))try{return vu(n)}catch{throw new Iu({value:n})}})();return typeof i>"u"?{r:e,s:t}:{r:e,s:t,yParity:i}}function vu(s){if(s===0||s===27)return 0;if(s===1||s===28)return 1;if(s>=35)return s%2===0?1:0;throw new _u({value:s})}class Eu extends ee{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${qt(Jn(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class Iu extends ee{constructor({value:e}){super(`Value \`${e}\` 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 _u extends ee{constructor({value:e}){super(`Value \`${e}\` 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"})}}const xu=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]),ne=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),z=new Uint32Array(32);function xt(s,e,t,i,n,r){const o=n[r],a=n[r+1];let c=z[2*s],h=z[2*s+1],l=z[2*e],u=z[2*e+1],d=z[2*t],f=z[2*t+1],y=z[2*i],g=z[2*i+1],b=Kn(c,l,o);h=Vn(b,h,u,a),c=b|0,{Dh:g,Dl:y}={Dh:g^h,Dl:y^c},{Dh:g,Dl:y}={Dh:Sh(g,y),Dl:Ph(g)},{h:f,l:d}=Ke(f,d,g,y),{Bh:u,Bl:l}={Bh:u^f,Bl:l^d},{Bh:u,Bl:l}={Bh:At(u,l,24),Bl:Ot(u,l,24)},z[2*s]=c,z[2*s+1]=h,z[2*e]=l,z[2*e+1]=u,z[2*t]=d,z[2*t+1]=f,z[2*i]=y,z[2*i+1]=g}function St(s,e,t,i,n,r){const o=n[r],a=n[r+1];let c=z[2*s],h=z[2*s+1],l=z[2*e],u=z[2*e+1],d=z[2*t],f=z[2*t+1],y=z[2*i],g=z[2*i+1],b=Kn(c,l,o);h=Vn(b,h,u,a),c=b|0,{Dh:g,Dl:y}={Dh:g^h,Dl:y^c},{Dh:g,Dl:y}={Dh:At(g,y,16),Dl:Ot(g,y,16)},{h:f,l:d}=Ke(f,d,g,y),{Bh:u,Bl:l}={Bh:u^f,Bl:l^d},{Bh:u,Bl:l}={Bh:Ps(u,l,63),Bl:As(u,l,63)},z[2*s]=c,z[2*s+1]=h,z[2*e]=l,z[2*e+1]=u,z[2*t]=d,z[2*t+1]=f,z[2*i]=y,z[2*i+1]=g}function Su(s,e={},t,i,n){if(it(t),s<0||s>t)throw new Error("outputLen bigger than keyLen");const{key:r,salt:o,personalization:a}=e;if(r!==void 0&&(r.length<1||r.length>t))throw new Error("key length must be undefined or 1.."+t);if(o!==void 0&&o.length!==i)throw new Error("salt must be undefined or "+i);if(a!==void 0&&a.length!==n)throw new Error("personalization must be undefined or "+n)}class Pu extends Ri{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,it(e),it(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=Bs(this.buffer)}update(e){Tt(this),e=Fe(e),Ge(e);const{blockLen:t,buffer:i,buffer32:n}=this,r=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<r;){this.pos===t&&($t(n),this.compress(n,0,!1),$t(n),this.pos=0);const h=Math.min(t-this.pos,r-c),l=o+c;if(h===t&&!(l%4)&&c+h<r){const u=new Uint32Array(a,l,Math.floor((r-c)/4));$t(u);for(let d=0;c+t<r;d+=n.length,c+=t)this.length+=t,this.compress(u,d,!1);$t(u);continue}i.set(e.subarray(c,c+h),this.pos),this.pos+=h,this.length+=h,c+=h}return this}digestInto(e){Tt(this),Hn(e,this);const{pos:t,buffer32:i}=this;this.finished=!0,De(this.buffer.subarray(t)),$t(i),this.compress(i,0,!0),$t(i);const n=Bs(e);this.get().forEach((r,o)=>n[o]=ht(r))}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){const{buffer:t,length:i,finished:n,destroyed:r,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(t),e.destroyed=r,e.finished=n,e.length=i,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class Au extends Pu{constructor(e={}){const t=e.dkLen===void 0?64:e.dkLen;super(128,t),this.v0l=ne[0]|0,this.v0h=ne[1]|0,this.v1l=ne[2]|0,this.v1h=ne[3]|0,this.v2l=ne[4]|0,this.v2h=ne[5]|0,this.v3l=ne[6]|0,this.v3h=ne[7]|0,this.v4l=ne[8]|0,this.v4h=ne[9]|0,this.v5l=ne[10]|0,this.v5h=ne[11]|0,this.v6l=ne[12]|0,this.v6h=ne[13]|0,this.v7l=ne[14]|0,this.v7h=ne[15]|0,Su(t,e,64,16,16);let{key:i,personalization:n,salt:r}=e,o=0;if(i!==void 0&&(i=Fe(i),o=i.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,r!==void 0){r=Fe(r);const a=Bs(r);this.v4l^=ht(a[0]),this.v4h^=ht(a[1]),this.v5l^=ht(a[2]),this.v5h^=ht(a[3])}if(n!==void 0){n=Fe(n);const a=Bs(n);this.v6l^=ht(a[0]),this.v6h^=ht(a[1]),this.v7l^=ht(a[2]),this.v7h^=ht(a[3])}if(i!==void 0){const a=new Uint8Array(this.blockLen);a.set(i),this.update(a)}}get(){let{v0l:e,v0h:t,v1l:i,v1h:n,v2l:r,v2h:o,v3l:a,v3h:c,v4l:h,v4h:l,v5l:u,v5h:d,v6l:f,v6h:y,v7l:g,v7h:b}=this;return[e,t,i,n,r,o,a,c,h,l,u,d,f,y,g,b]}set(e,t,i,n,r,o,a,c,h,l,u,d,f,y,g,b){this.v0l=e|0,this.v0h=t|0,this.v1l=i|0,this.v1h=n|0,this.v2l=r|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=h|0,this.v4h=l|0,this.v5l=u|0,this.v5h=d|0,this.v6l=f|0,this.v6h=y|0,this.v7l=g|0,this.v7h=b|0}compress(e,t,i){this.get().forEach((c,h)=>z[h]=c),z.set(ne,16);let{h:n,l:r}=zo(BigInt(this.length));z[24]=ne[8]^r,z[25]=ne[9]^n,i&&(z[28]=~z[28],z[29]=~z[29]);let o=0;const a=xu;for(let c=0;c<12;c++)xt(0,4,8,12,e,t+2*a[o++]),St(0,4,8,12,e,t+2*a[o++]),xt(1,5,9,13,e,t+2*a[o++]),St(1,5,9,13,e,t+2*a[o++]),xt(2,6,10,14,e,t+2*a[o++]),St(2,6,10,14,e,t+2*a[o++]),xt(3,7,11,15,e,t+2*a[o++]),St(3,7,11,15,e,t+2*a[o++]),xt(0,5,10,15,e,t+2*a[o++]),St(0,5,10,15,e,t+2*a[o++]),xt(1,6,11,12,e,t+2*a[o++]),St(1,6,11,12,e,t+2*a[o++]),xt(2,7,8,13,e,t+2*a[o++]),St(2,7,8,13,e,t+2*a[o++]),xt(3,4,9,14,e,t+2*a[o++]),St(3,4,9,14,e,t+2*a[o++]);this.v0l^=z[0]^z[16],this.v0h^=z[1]^z[17],this.v1l^=z[2]^z[18],this.v1h^=z[3]^z[19],this.v2l^=z[4]^z[20],this.v2h^=z[5]^z[21],this.v3l^=z[6]^z[22],this.v3h^=z[7]^z[23],this.v4l^=z[8]^z[24],this.v4h^=z[9]^z[25],this.v5l^=z[10]^z[26],this.v5h^=z[11]^z[27],this.v6l^=z[12]^z[28],this.v6h^=z[13]^z[29],this.v7l^=z[14]^z[30],this.v7h^=z[15]^z[31],De(z)}destroy(){this.destroyed=!0,De(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Ou=Mh(s=>new Au(s));function $u(s){return Fl(Ru(s))}function Ru(s){const{payload:e,signature:t}=s,{r:i,s:n,yParity:r}=t,a=new wu.Signature(BigInt(i),BigInt(n)).addRecoveryBit(r).recoverPublicKey(Jn(e).substring(2));return Ul(a)}const Pa=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),Nu=Pa("expand 16-byte k"),Tu=Pa("expand 32-byte k"),qu=Nt(Nu),Cu=Nt(Tu);function W(s,e){return s<<e|s>>>32-e}function Sn(s){return s.byteOffset%4===0}const ei=64,Bu=16,Aa=2**32-1,jr=new Uint32Array;function ku(s,e,t,i,n,r,o,a){const c=n.length,h=new Uint8Array(ei),l=Nt(h),u=Sn(n)&&Sn(r),d=u?Nt(n):jr,f=u?Nt(r):jr;for(let y=0;y<c;o++){if(s(e,t,i,l,o,a),o>=Aa)throw new Error("arx: counter overflow");const g=Math.min(ei,c-y);if(u&&g===ei){const b=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let A=0,L;A<Bu;A++)L=b+A,f[L]=d[L]^l[A];y+=ei;continue}for(let b=0,A;b<g;b++)A=y+b,r[A]=n[A]^h[b];y+=g}}function Uu(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:n,counterRight:r,rounds:o}=vh({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return Di(n),Di(o),mn(r),mn(t),(a,c,h,l,u=0)=>{_e(a),_e(c),_e(h);const d=h.length;if(l===void 0&&(l=new Uint8Array(d)),_e(l),Di(u),u<0||u>=Aa)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const f=[];let y=a.length,g,b;if(y===32)f.push(g=bn(a)),b=Cu;else if(y===16&&t)g=new Uint8Array(32),g.set(a),g.set(a,16),b=qu,f.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${y}`);Sn(c)||f.push(c=bn(c));const A=Nt(g);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(b,A,Nt(c.subarray(0,16)),A),c=c.subarray(16)}const L=16-n;if(L!==c.length)throw new Error(`arx: nonce must be ${L} or 16 bytes`);if(L!==12){const x=new Uint8Array(12);x.set(c,r?0:12-c.length),c=x,f.push(c)}const O=Nt(c);return ku(s,b,A,O,h,l,u,o),gs(...f),l}}const ce=(s,e)=>s[e++]&255|(s[e++]&255)<<8;class Mu{constructor(e){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,e=wn(e),_e(e,32);const t=ce(e,0),i=ce(e,2),n=ce(e,4),r=ce(e,6),o=ce(e,8),a=ce(e,10),c=ce(e,12),h=ce(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|n<<6)&7939,this.r[3]=(n>>>7|r<<9)&8191,this.r[4]=(r>>>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|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=ce(e,16+2*l)}process(e,t,i=!1){const n=i?0:2048,{h:r,r:o}=this,a=o[0],c=o[1],h=o[2],l=o[3],u=o[4],d=o[5],f=o[6],y=o[7],g=o[8],b=o[9],A=ce(e,t+0),L=ce(e,t+2),O=ce(e,t+4),x=ce(e,t+6),N=ce(e,t+8),q=ce(e,t+10),k=ce(e,t+12),B=ce(e,t+14);let S=r[0]+(A&8191),T=r[1]+((A>>>13|L<<3)&8191),C=r[2]+((L>>>10|O<<6)&8191),$=r[3]+((O>>>7|x<<9)&8191),m=r[4]+((x>>>4|N<<12)&8191),E=r[5]+(N>>>1&8191),p=r[6]+((N>>>14|q<<2)&8191),w=r[7]+((q>>>11|k<<5)&8191),I=r[8]+((k>>>8|B<<8)&8191),P=r[9]+(B>>>5|n),v=0,_=v+S*a+T*(5*b)+C*(5*g)+$*(5*y)+m*(5*f);v=_>>>13,_&=8191,_+=E*(5*d)+p*(5*u)+w*(5*l)+I*(5*h)+P*(5*c),v+=_>>>13,_&=8191;let R=v+S*c+T*a+C*(5*b)+$*(5*g)+m*(5*y);v=R>>>13,R&=8191,R+=E*(5*f)+p*(5*d)+w*(5*u)+I*(5*l)+P*(5*h),v+=R>>>13,R&=8191;let M=v+S*h+T*c+C*a+$*(5*b)+m*(5*g);v=M>>>13,M&=8191,M+=E*(5*y)+p*(5*f)+w*(5*d)+I*(5*u)+P*(5*l),v+=M>>>13,M&=8191;let V=v+S*l+T*h+C*c+$*a+m*(5*b);v=V>>>13,V&=8191,V+=E*(5*g)+p*(5*y)+w*(5*f)+I*(5*d)+P*(5*u),v+=V>>>13,V&=8191;let K=v+S*u+T*l+C*h+$*c+m*a;v=K>>>13,K&=8191,K+=E*(5*b)+p*(5*g)+w*(5*y)+I*(5*f)+P*(5*d),v+=K>>>13,K&=8191;let j=v+S*d+T*u+C*l+$*h+m*c;v=j>>>13,j&=8191,j+=E*a+p*(5*b)+w*(5*g)+I*(5*y)+P*(5*f),v+=j>>>13,j&=8191;let F=v+S*f+T*d+C*u+$*l+m*h;v=F>>>13,F&=8191,F+=E*c+p*a+w*(5*b)+I*(5*g)+P*(5*y),v+=F>>>13,F&=8191;let G=v+S*y+T*f+C*d+$*u+m*l;v=G>>>13,G&=8191,G+=E*h+p*c+w*a+I*(5*b)+P*(5*g),v+=G>>>13,G&=8191;let Z=v+S*g+T*y+C*f+$*d+m*u;v=Z>>>13,Z&=8191,Z+=E*l+p*h+w*c+I*a+P*(5*b),v+=Z>>>13,Z&=8191;let H=v+S*b+T*g+C*y+$*f+m*d;v=H>>>13,H&=8191,H+=E*u+p*l+w*h+I*c+P*a,v+=H>>>13,H&=8191,v=(v<<2)+v|0,v=v+_|0,_=v&8191,v=v>>>13,R+=v,r[0]=_,r[1]=R,r[2]=M,r[3]=V,r[4]=K,r[5]=j,r[6]=F,r[7]=G,r[8]=Z,r[9]=H}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=n,n=e[a]>>>13,e[a]&=8191;e[0]+=n*5,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,i[0]=e[0]+5,n=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+n,n=i[a]>>>13,i[a]&=8191;i[9]-=8192;let r=(n^1)-1;for(let a=0;a<10;a++)i[a]&=r;r=~r;for(let a=0;a<10;a++)e[a]=e[a]&r|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;gs(i)}update(e){wr(this),e=wn(e),_e(e);const{buffer:t,blockLen:i}=this,n=e.length;for(let r=0;r<n;){const o=Math.min(i-this.pos,n-r);if(o===i){for(;i<=n-r;r+=i)this.process(e,r);continue}t.set(e.subarray(r,r+o),this.pos),this.pos+=o,r+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){gs(this.h,this.r,this.buffer,this.pad)}digestInto(e){wr(this),yh(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let r=0;for(let o=0;o<8;o++)e[r++]=i[o]>>>0,e[r++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}}function Du(s){const e=(i,n)=>s(n).update(wn(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const Lu=Du(s=>new Mu(s));function zu(s,e,t,i,n,r=20){let o=s[0],a=s[1],c=s[2],h=s[3],l=e[0],u=e[1],d=e[2],f=e[3],y=e[4],g=e[5],b=e[6],A=e[7],L=n,O=t[0],x=t[1],N=t[2],q=o,k=a,B=c,S=h,T=l,C=u,$=d,m=f,E=y,p=g,w=b,I=A,P=L,v=O,_=x,R=N;for(let V=0;V<r;V+=2)q=q+T|0,P=W(P^q,16),E=E+P|0,T=W(T^E,12),q=q+T|0,P=W(P^q,8),E=E+P|0,T=W(T^E,7),k=k+C|0,v=W(v^k,16),p=p+v|0,C=W(C^p,12),k=k+C|0,v=W(v^k,8),p=p+v|0,C=W(C^p,7),B=B+$|0,_=W(_^B,16),w=w+_|0,$=W($^w,12),B=B+$|0,_=W(_^B,8),w=w+_|0,$=W($^w,7),S=S+m|0,R=W(R^S,16),I=I+R|0,m=W(m^I,12),S=S+m|0,R=W(R^S,8),I=I+R|0,m=W(m^I,7),q=q+C|0,R=W(R^q,16),w=w+R|0,C=W(C^w,12),q=q+C|0,R=W(R^q,8),w=w+R|0,C=W(C^w,7),k=k+$|0,P=W(P^k,16),I=I+P|0,$=W($^I,12),k=k+$|0,P=W(P^k,8),I=I+P|0,$=W($^I,7),B=B+m|0,v=W(v^B,16),E=E+v|0,m=W(m^E,12),B=B+m|0,v=W(v^B,8),E=E+v|0,m=W(m^E,7),S=S+T|0,_=W(_^S,16),p=p+_|0,T=W(T^p,12),S=S+T|0,_=W(_^S,8),p=p+_|0,T=W(T^p,7);let M=0;i[M++]=o+q|0,i[M++]=a+k|0,i[M++]=c+B|0,i[M++]=h+S|0,i[M++]=l+T|0,i[M++]=u+C|0,i[M++]=d+$|0,i[M++]=f+m|0,i[M++]=y+E|0,i[M++]=g+p|0,i[M++]=b+w|0,i[M++]=A+I|0,i[M++]=L+P|0,i[M++]=O+v|0,i[M++]=x+_|0,i[M++]=N+R|0}const ju=Uu(zu,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Ku=new Uint8Array(16),Kr=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(Ku.subarray(t))},Vu=new Uint8Array(32);function Vr(s,e,t,i,n){const r=s(e,t,Vu),o=Lu.create(r);n&&Kr(o,n),Kr(o,i);const a=_h(i.length,n?n.length:0,!0);o.update(a);const c=o.digest();return gs(r,a),c}const Hu=s=>(e,t,i)=>({encrypt(r,o){const a=r.length;o=br(a+16,o,!1),o.set(r);const c=o.subarray(0,-16);s(e,t,c,c,1);const h=Vr(s,e,t,c,i);return o.set(h,a),gs(h),o},decrypt(r,o){o=br(r.length-16,o,!1);const a=r.subarray(0,-16),c=r.subarray(-16),h=Vr(s,e,t,a,i);if(!Eh(c,h))throw new Error("invalid tag");return o.set(r.subarray(0,-16)),s(e,t,o,o,1),gs(h),o}}),Oa=Ih({blockSize:64,nonceLength:12,tagLength:16},Hu(ju));function Fu(s,e,t){return $i(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Fs(s,Fe(t),Fe(e))}const Qi=Uint8Array.from([0]),Hr=Uint8Array.of();function Gu(s,e,t,i=32){$i(s),it(i);const n=s.outputLen;if(i>255*n)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/n);t===void 0&&(t=Hr);const o=new Uint8Array(r*n),a=Fs.create(s,e),c=a._cloneInto(),h=new Uint8Array(a.outputLen);for(let l=0;l<r;l++)Qi[0]=l+1,c.update(l===0?Hr:h).update(t).update(Qi).digestInto(h),o.set(h,n*l),a._cloneInto(c);return a.destroy(),c.destroy(),De(h,Qi),o.slice(0,i)}const Wu=(s,e,t,i,n)=>Gu(s,Fu(s,e,t),i,n);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const er=BigInt(0),Pn=BigInt(1);function yi(s,e=""){if(typeof s!="boolean"){const t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof s)}return s}function Vt(s,e,t=""){const i=Oi(s),n=s==null?void 0:s.length,r=e!==void 0;if(!i||r&&n!==e){const o=t&&`"${t}" `,a=r?` of length ${e}`:"",c=i?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function ti(s){const e=s.toString(16);return e.length&1?"0"+e:e}function $a(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?er:BigInt("0x"+s)}function Ci(s){return $a(cs(s))}function mi(s){return Ge(s),$a(cs(Uint8Array.from(s).reverse()))}function tr(s,e){return di(s.toString(16).padStart(e*2,"0"))}function sr(s,e){return tr(s,e).reverse()}function pe(s,e,t){let i;if(typeof e=="string")try{i=di(e)}catch(r){throw new Error(s+" must be hex string or Uint8Array, cause: "+r)}else if(Oi(e))i=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");const n=i.length;if(typeof t=="number"&&n!==t)throw new Error(s+" of length "+t+" expected, got "+n);return i}const Ji=s=>typeof s=="bigint"&&er<=s;function Zu(s,e,t){return Ji(s)&&Ji(e)&&Ji(t)&&e<=s&&s<t}function An(s,e,t,i){if(!Zu(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}function Ra(s){let e;for(e=0;s>er;s>>=Pn,e+=1);return e}const Gs=s=>(Pn<<BigInt(s))-Pn;function Yu(s,e,t){if(typeof s!="number"||s<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");const i=f=>new Uint8Array(f),n=f=>Uint8Array.of(f);let r=i(s),o=i(s),a=0;const c=()=>{r.fill(1),o.fill(0),a=0},h=(...f)=>t(o,r,...f),l=(f=i(0))=>{o=h(n(0),f),r=h(),f.length!==0&&(o=h(n(1),f),r=h())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const y=[];for(;f<e;){r=h();const g=r.slice();y.push(g),f+=r.length}return pt(...y)};return(f,y)=>{c(),l(f);let g;for(;!(g=y(u()));)l();return c(),g}}function Bi(s,e,t={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function i(n,r,o){const a=s[n];if(o&&a===void 0)return;const c=typeof a;if(c!==r||a===null)throw new Error(`param "${n}" is invalid: expected ${r}, got ${c}`)}Object.entries(e).forEach(([n,r])=>i(n,r,!1)),Object.entries(t).forEach(([n,r])=>i(n,r,!0))}function Fr(s){const e=new WeakMap;return(t,...i)=>{const n=e.get(t);if(n!==void 0)return n;const r=s(t,...i);return e.set(t,r),r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Pe=BigInt(0),we=BigInt(1),Ht=BigInt(2),Na=BigInt(3),Ta=BigInt(4),qa=BigInt(5),Qu=BigInt(7),Ca=BigInt(8),Ju=BigInt(9),Ba=BigInt(16);function Oe(s,e){const t=s%e;return t>=Pe?t:e+t}function je(s,e,t){let i=s;for(;e-- >Pe;)i*=i,i%=t;return i}function Gr(s,e){if(s===Pe)throw new Error("invert: expected non-zero number");if(e<=Pe)throw new Error("invert: expected positive modulus, got "+e);let t=Oe(s,e),i=e,n=Pe,r=we;for(;t!==Pe;){const a=i/t,c=i%t,h=n-r*a;i=t,t=c,n=r,r=h}if(i!==we)throw new Error("invert: does not exist");return Oe(n,e)}function ir(s,e,t){if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function ka(s,e){const t=(s.ORDER+we)/Ta,i=s.pow(e,t);return ir(s,i,e),i}function Xu(s,e){const t=(s.ORDER-qa)/Ca,i=s.mul(e,Ht),n=s.pow(i,t),r=s.mul(e,n),o=s.mul(s.mul(r,Ht),n),a=s.mul(r,s.sub(o,s.ONE));return ir(s,a,e),a}function ed(s){const e=kt(s),t=Ua(s),i=t(e,e.neg(e.ONE)),n=t(e,i),r=t(e,e.neg(i)),o=(s+Qu)/Ba;return(a,c)=>{let h=a.pow(c,o),l=a.mul(h,i);const u=a.mul(h,n),d=a.mul(h,r),f=a.eql(a.sqr(l),c),y=a.eql(a.sqr(u),c);h=a.cmov(h,l,f),l=a.cmov(d,u,y);const g=a.eql(a.sqr(l),c),b=a.cmov(h,l,g);return ir(a,b,c),b}}function Ua(s){if(s<Na)throw new Error("sqrt is not defined for small field");let e=s-we,t=0;for(;e%Ht===Pe;)e/=Ht,t++;let i=Ht;const n=kt(s);for(;Wr(n,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ka;let r=n.pow(i,e);const o=(e+we)/Ht;return function(c,h){if(c.is0(h))return h;if(Wr(c,h)!==1)throw new Error("Cannot find square root");let l=t,u=c.mul(c.ONE,r),d=c.pow(h,e),f=c.pow(h,o);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let y=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(y++,g=c.sqr(g),y===l)throw new Error("Cannot find square root");const b=we<<BigInt(l-y-1),A=c.pow(u,b);l=y,u=c.sqr(A),d=c.mul(d,u),f=c.mul(f,A)}return f}}function td(s){return s%Ta===Na?ka:s%Ca===qa?Xu:s%Ba===Ju?ed(s):Ua(s)}const sd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function id(s){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=sd.reduce((i,n)=>(i[n]="function",i),e);return Bi(s,t),s}function nd(s,e,t){if(t<Pe)throw new Error("invalid exponent, negatives unsupported");if(t===Pe)return s.ONE;if(t===we)return e;let i=s.ONE,n=e;for(;t>Pe;)t&we&&(i=s.mul(i,n)),n=s.sqr(n),t>>=we;return i}function Ma(s,e,t=!1){const i=new Array(e.length).fill(t?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(i[c]=o,s.mul(o,a)),s.ONE),r=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(i[c]=s.mul(o,i[c]),s.mul(o,a)),r),i}function Wr(s,e){const t=(s.ORDER-we)/Ht,i=s.pow(e,t),n=s.eql(i,s.ONE),r=s.eql(i,s.ZERO),o=s.eql(i,s.neg(s.ONE));if(!n&&!r&&!o)throw new Error("invalid Legendre symbol result");return n?1:r?0:-1}function Da(s,e){e!==void 0&&it(e);const t=e!==void 0?e:s.toString(2).length,i=Math.ceil(t/8);return{nBitLength:t,nByteLength:i}}function kt(s,e,t=!1,i={}){if(s<=Pe)throw new Error("invalid field: expected ORDER > 0, got "+s);let n,r,o=!1,a;if(typeof e=="object"&&e!=null){if(i.sqrt||t)throw new Error("cannot specify opts in two arguments");const d=e;d.BITS&&(n=d.BITS),d.sqrt&&(r=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(o=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(n=e),i.sqrt&&(r=i.sqrt);const{nBitLength:c,nByteLength:h}=Da(s,n);if(h>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const u=Object.freeze({ORDER:s,isLE:t,BITS:c,BYTES:h,MASK:Gs(c),ZERO:Pe,ONE:we,allowedLengths:a,create:d=>Oe(d,s),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Pe<=d&&d<s},is0:d=>d===Pe,isValidNot0:d=>!u.is0(d)&&u.isValid(d),isOdd:d=>(d&we)===we,neg:d=>Oe(-d,s),eql:(d,f)=>d===f,sqr:d=>Oe(d*d,s),add:(d,f)=>Oe(d+f,s),sub:(d,f)=>Oe(d-f,s),mul:(d,f)=>Oe(d*f,s),pow:(d,f)=>nd(u,d,f),div:(d,f)=>Oe(d*Gr(f,s),s),sqrN:d=>d*d,addN:(d,f)=>d+f,subN:(d,f)=>d-f,mulN:(d,f)=>d*f,inv:d=>Gr(d,s),sqrt:r||(d=>(l||(l=td(s)),l(u,d))),toBytes:d=>t?sr(d,h):tr(d,h),fromBytes:(d,f=!0)=>{if(a){if(!a.includes(d.length)||d.length>h)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const g=new Uint8Array(h);g.set(d,t?0:g.length-d.length),d=g}if(d.length!==h)throw new Error("Field.fromBytes: expected "+h+" bytes, got "+d.length);let y=t?mi(d):Ci(d);if(o&&(y=Oe(y,s)),!f&&!u.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:d=>Ma(u,d),cmov:(d,f,y)=>y?f:d});return Object.freeze(u)}function La(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function za(s){const e=La(s);return e+Math.ceil(e/2)}function rd(s,e,t=!1){const i=s.length,n=La(e),r=za(e);if(i<16||i<r||i>1024)throw new Error("expected "+r+"-1024 bytes of input, got "+i);const o=t?mi(s):Ci(s),a=Oe(o,e-we)+we;return t?sr(a,n):tr(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ys=BigInt(0),Ft=BigInt(1);function wi(s,e){const t=e.negate();return s?t:e}function Xi(s,e){const t=Ma(s.Fp,e.map(i=>i.Z));return e.map((i,n)=>s.fromAffine(i.toAffine(t[n])))}function ja(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function en(s,e){ja(s,e);const t=Math.ceil(e/s)+1,i=2**(s-1),n=2**s,r=Gs(s),o=BigInt(s);return{windows:t,windowSize:i,mask:r,maxNumber:n,shiftBy:o}}function Zr(s,e,t){const{windowSize:i,mask:n,maxNumber:r,shiftBy:o}=t;let a=Number(s&n),c=s>>o;a>i&&(a-=r,c+=Ft);const h=e*i,l=h+Math.abs(a)-1,u=a===0,d=a<0,f=e%2!==0;return{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:h}}function od(s,e){if(!Array.isArray(s))throw new Error("array expected");s.forEach((t,i)=>{if(!(t instanceof e))throw new Error("invalid point at index "+i)})}function ad(s,e){if(!Array.isArray(s))throw new Error("array of scalars expected");s.forEach((t,i)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+i)})}const tn=new WeakMap,Ka=new WeakMap;function sn(s){return Ka.get(s)||1}function Yr(s){if(s!==ys)throw new Error("invalid wNAF")}class cd{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,i=this.ZERO){let n=e;for(;t>ys;)t&Ft&&(i=i.add(n)),n=n.double(),t>>=Ft;return i}precomputeWindow(e,t){const{windows:i,windowSize:n}=en(t,this.bits),r=[];let o=e,a=o;for(let c=0;c<i;c++){a=o,r.push(a);for(let h=1;h<n;h++)a=a.add(o),r.push(a);o=a.double()}return r}wNAF(e,t,i){if(!this.Fn.isValid(i))throw new Error("invalid scalar");let n=this.ZERO,r=this.BASE;const o=en(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:h,isZero:l,isNeg:u,isNegF:d,offsetF:f}=Zr(i,a,o);i=c,l?r=r.add(wi(d,t[f])):n=n.add(wi(u,t[h]))}return Yr(i),{p:n,f:r}}wNAFUnsafe(e,t,i,n=this.ZERO){const r=en(e,this.bits);for(let o=0;o<r.windows&&i!==ys;o++){const{nextN:a,offset:c,isZero:h,isNeg:l}=Zr(i,o,r);if(i=a,!h){const u=t[c];n=n.add(l?u.negate():u)}}return Yr(i),n}getPrecomputes(e,t,i){let n=tn.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof i=="function"&&(n=i(n)),tn.set(t,n))),n}cached(e,t,i){const n=sn(e);return this.wNAF(n,this.getPrecomputes(n,e,i),t)}unsafe(e,t,i,n){const r=sn(e);return r===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(r,this.getPrecomputes(r,e,i),t,n)}createCache(e,t){ja(t,this.bits),Ka.set(e,t),tn.delete(e)}hasCache(e){return sn(e)!==1}}function hd(s,e,t,i){let n=e,r=s.ZERO,o=s.ZERO;for(;t>ys||i>ys;)t&Ft&&(r=r.add(n)),i&Ft&&(o=o.add(n)),n=n.double(),t>>=Ft,i>>=Ft;return{p1:r,p2:o}}function ld(s,e,t,i){od(t,s),ad(i,e);const n=t.length,r=i.length;if(n!==r)throw new Error("arrays of points and scalars must have equal length");const o=s.ZERO,a=Ra(BigInt(n));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const h=Gs(c),l=new Array(Number(h)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let d=o;for(let f=u;f>=0;f-=c){l.fill(o);for(let g=0;g<r;g++){const b=i[g],A=Number(b>>BigInt(f)&h);l[A]=l[A].add(t[g])}let y=o;for(let g=l.length-1,b=o;g>0;g--)b=b.add(l[g]),y=y.add(b);if(d=d.add(y),f!==0)for(let g=0;g<c;g++)d=d.double()}return d}function Qr(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return id(e),e}else return kt(s,{isLE:t})}function ud(s,e,t={},i){if(i===void 0&&(i=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const h=e[c];if(!(typeof h=="bigint"&&h>ys))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Qr(e.p,t.Fp,i),r=Qr(e.n,t.Fn,i),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Is=BigInt(0),ss=BigInt(1),si=BigInt(2);function dd(s){return Bi(s,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...s})}function fd(s){const e=dd(s),{P:t,type:i,adjustScalarBytes:n,powPminus2:r,randomBytes:o}=e,a=i==="x25519";if(!a&&i!=="x448")throw new Error("invalid type");const c=o||Bt,h=a?255:448,l=a?32:56,u=BigInt(a?9:5),d=BigInt(a?121665:39081),f=a?si**BigInt(254):si**BigInt(447),y=a?BigInt(8)*si**BigInt(251)-ss:BigInt(4)*si**BigInt(445)-ss,g=f+y+ss,b=m=>Oe(m,t),A=L(u);function L(m){return sr(b(m),l)}function O(m){const E=pe("u coordinate",m,l);return a&&(E[31]&=127),b(mi(E))}function x(m){return mi(n(pe("scalar",m,l)))}function N(m,E){const p=B(O(E),x(m));if(p===Is)throw new Error("invalid private or public key received");return L(p)}function q(m){return N(m,A)}function k(m,E,p){const w=b(m*(E-p));return E=b(E-w),p=b(p+w),{x_2:E,x_3:p}}function B(m,E){An("u",m,Is,t),An("scalar",E,f,g);const p=E,w=m;let I=ss,P=Is,v=m,_=ss,R=Is;for(let V=BigInt(h-1);V>=Is;V--){const K=p>>V&ss;R^=K,{x_2:I,x_3:v}=k(R,I,v),{x_2:P,x_3:_}=k(R,P,_),R=K;const j=I+P,F=b(j*j),G=I-P,Z=b(G*G),H=F-Z,Y=v+_,ve=v-_,Ee=b(ve*j),ye=b(Y*G),Te=Ee+ye,We=Ee-ye;v=b(Te*Te),_=b(w*b(We*We)),I=b(F*Z),P=b(H*(F+b(d*H)))}({x_2:I,x_3:v}=k(R,I,v)),{x_2:P,x_3:_}=k(R,P,_);const M=r(P);return b(I*M)}const S={secretKey:l,publicKey:l,seed:l},T=(m=c(l))=>(Ge(m,S.seed),m);function C(m){const E=T(m);return{secretKey:E,publicKey:q(E)}}return{keygen:C,getSharedSecret:(m,E)=>N(m,E),getPublicKey:m=>q(m),scalarMult:N,scalarMultBase:q,utils:{randomSecretKey:T,randomPrivateKey:T},GuBytes:A.slice(),lengths:S}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const pd=BigInt(1),Jr=BigInt(2),gd=BigInt(3),yd=BigInt(5),md=BigInt(8),Va=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),wd={p:Va,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:md,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function bd(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),n=BigInt(80),r=Va,a=s*s%r*s%r,c=je(a,Jr,r)*a%r,h=je(c,pd,r)*s%r,l=je(h,yd,r)*h%r,u=je(l,e,r)*l%r,d=je(u,t,r)*u%r,f=je(d,i,r)*d%r,y=je(f,n,r)*f%r,g=je(y,n,r)*f%r,b=je(g,e,r)*l%r;return{pow_p_5_8:je(b,Jr,r)*s%r,b2:a}}function vd(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const Ed=kt(wd.p,{isLE:!0}),On=(()=>{const s=Ed.ORDER;return fd({P:s,type:"x25519",powPminus2:e=>{const{pow_p_5_8:t,b2:i}=bd(e);return Oe(je(t,gd,s)*i,s)},adjustScalarBytes:vd})})();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Xr=(s,e)=>(s+(s>=0?e:-e)/Ha)/e;function Id(s,e,t){const[[i,n],[r,o]]=e,a=Xr(o*s,t),c=Xr(-n*s,t);let h=s-a*i-c*r,l=-a*n-c*o;const u=h<yt,d=l<yt;u&&(h=-h),d&&(l=-l);const f=Gs(Math.ceil(Ra(t)/2))+ls;if(h<yt||h>=f||l<yt||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:u,k1:h,k2neg:d,k2:l}}function $n(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function nn(s,e){const t={};for(let i of Object.keys(e))t[i]=s[i]===void 0?e[i]:s[i];return yi(t.lowS,"lowS"),yi(t.prehash,"prehash"),t.format!==void 0&&$n(t.format),t}
vendor: 4,620 bytes, line 3
3class _d extends Error{constructor(e=""){super(e)}}const ft={Err:_d,_tlv:{encode:(s,e)=>{const{Err:t}=ft;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const i=e.length/2,n=ti(i);if(n.length/2&128)throw new t("tlv.encode: long form length too big");const r=i>127?ti(n.length/2|128):"";return ti(s)+r+n+e},decode(s,e){const{Err:t}=ft;let i=0;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[i++]!==s)throw new t("tlv.decode: wrong tlv");const n=e[i++],r=!!(n&128);let o=0;if(!r)o=n;else{const c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const h=e.subarray(i,i+c);if(h.length!==c)throw new t("tlv.decode: length bytes not complete");if(h[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const l of h)o=o<<8|l;if(i+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(s){const{Err:e}=ft;if(s<yt)throw new e("integer: negative integers are not allowed");let t=ti(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){const{Err:e}=ft;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ci(s)}},toSig(s){const{Err:e,_int:t,_tlv:i}=ft,n=pe("signature",s),{v:r,l:o}=i.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,r),{v:h,l}=i.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(h)}},hexFromSig(s){const{_tlv:e,_int:t}=ft,i=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),r=i+n;return e.encode(48,r)}},yt=BigInt(0),ls=BigInt(1),Ha=BigInt(2),ii=BigInt(3),xd=BigInt(4);function ns(s,e){const{BYTES:t}=s;let i;if(typeof e=="bigint")i=e;else{let n=pe("private key",e);try{i=s.fromBytes(n)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!s.isValidNot0(i))throw new Error("invalid private key: out of range [1..N-1]");return i}function Sd(s,e={}){const t=ud("weierstrass",s,e),{Fp:i,Fn:n}=t;let r=t.CURVE;const{h:o,n:a}=r;Bi(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!i.is0(r.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const h=Ga(i,n);function l(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u($,m,E){const{x:p,y:w}=m.toAffine(),I=i.toBytes(p);if(yi(E,"isCompressed"),E){l();const P=!i.isOdd(w);return pt(Fa(P),I)}else return pt(Uint8Array.of(4),I,i.toBytes(w))}function d($){Vt($,void 0,"Point");const{publicKey:m,publicKeyUncompressed:E}=h,p=$.length,w=$[0],I=$.subarray(1);if(p===m&&(w===2||w===3)){const P=i.fromBytes(I);if(!i.isValid(P))throw new Error("bad point: is not on curve, wrong x");const v=g(P);let _;try{_=i.sqrt(v)}catch(V){const K=V instanceof Error?": "+V.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}l();const R=i.isOdd(_);return(w&1)===1!==R&&(_=i.neg(_)),{x:P,y:_}}else if(p===E&&w===4){const P=i.BYTES,v=i.fromBytes(I.subarray(0,P)),_=i.fromBytes(I.subarray(P,P*2));if(!b(v,_))throw new Error("bad point: is not on curve");return{x:v,y:_}}else throw new Error(`bad point: got length ${p}, expected compressed=${m} or uncompressed=${E}`)}const f=e.toBytes||u,y=e.fromBytes||d;function g($){const m=i.sqr($),E=i.mul(m,$);return i.add(i.add(E,i.mul($,r.a)),r.b)}function b($,m){const E=i.sqr(m),p=g($);return i.eql(E,p)}if(!b(r.Gx,r.Gy))throw new Error("bad curve params: generator point");const A=i.mul(i.pow(r.a,ii),xd),L=i.mul(i.sqr(r.b),BigInt(27));if(i.is0(i.add(A,L)))throw new Error("bad curve params: a or b");function O($,m,E=!1){if(!i.isValid(m)||E&&i.is0(m))throw new Error(`bad point coordinate ${$}`);return m}function x($){if(!($ instanceof S))throw new Error("ProjectivePoint expected")}function N($){if(!c||!c.basises)throw new Error("no endo");return Id($,c.basises,n.ORDER)}const q=Fr(($,m)=>{const{X:E,Y:p,Z:w}=$;if(i.eql(w,i.ONE))return{x:E,y:p};const I=$.is0();m==null&&(m=I?i.ONE:i.inv(w));const P=i.mul(E,m),v=i.mul(p,m),_=i.mul(w,m);if(I)return{x:i.ZERO,y:i.ZERO};
vendor: 17,164 bytes, line 3
3if(!i.eql(_,i.ONE))throw new Error("invZ was invalid");return{x:P,y:v}}),k=Fr($=>{if($.is0()){if(e.allowInfinityPoint&&!i.is0($.Y))return;throw new Error("bad point: ZERO")}const{x:m,y:E}=$.toAffine();if(!i.isValid(m)||!i.isValid(E))throw new Error("bad point: x or y not field elements");if(!b(m,E))throw new Error("bad point: equation left != right");if(!$.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function B($,m,E,p,w){return E=new S(i.mul(E.X,$),E.Y,E.Z),m=wi(p,m),E=wi(w,E),m.add(E)}class S{constructor(m,E,p){this.X=O("x",m),this.Y=O("y",E,!0),this.Z=O("z",p),Object.freeze(this)}static CURVE(){return r}static fromAffine(m){const{x:E,y:p}=m||{};if(!m||!i.isValid(E)||!i.isValid(p))throw new Error("invalid affine point");if(m instanceof S)throw new Error("projective point not allowed");return i.is0(E)&&i.is0(p)?S.ZERO:new S(E,p,i.ONE)}static fromBytes(m){const E=S.fromAffine(y(Vt(m,void 0,"point")));return E.assertValidity(),E}static fromHex(m){return S.fromBytes(pe("pointHex",m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,E=!0){return C.createCache(this,m),E||this.multiply(ii),this}assertValidity(){k(this)}hasEvenY(){const{y:m}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(m)}equals(m){x(m);const{X:E,Y:p,Z:w}=this,{X:I,Y:P,Z:v}=m,_=i.eql(i.mul(E,v),i.mul(I,w)),R=i.eql(i.mul(p,v),i.mul(P,w));return _&&R}negate(){return new S(this.X,i.neg(this.Y),this.Z)}double(){const{a:m,b:E}=r,p=i.mul(E,ii),{X:w,Y:I,Z:P}=this;let v=i.ZERO,_=i.ZERO,R=i.ZERO,M=i.mul(w,w),V=i.mul(I,I),K=i.mul(P,P),j=i.mul(w,I);return j=i.add(j,j),R=i.mul(w,P),R=i.add(R,R),v=i.mul(m,R),_=i.mul(p,K),_=i.add(v,_),v=i.sub(V,_),_=i.add(V,_),_=i.mul(v,_),v=i.mul(j,v),R=i.mul(p,R),K=i.mul(m,K),j=i.sub(M,K),j=i.mul(m,j),j=i.add(j,R),R=i.add(M,M),M=i.add(R,M),M=i.add(M,K),M=i.mul(M,j),_=i.add(_,M),K=i.mul(I,P),K=i.add(K,K),M=i.mul(K,j),v=i.sub(v,M),R=i.mul(K,V),R=i.add(R,R),R=i.add(R,R),new S(v,_,R)}add(m){x(m);const{X:E,Y:p,Z:w}=this,{X:I,Y:P,Z:v}=m;let _=i.ZERO,R=i.ZERO,M=i.ZERO;const V=r.a,K=i.mul(r.b,ii);let j=i.mul(E,I),F=i.mul(p,P),G=i.mul(w,v),Z=i.add(E,p),H=i.add(I,P);Z=i.mul(Z,H),H=i.add(j,F),Z=i.sub(Z,H),H=i.add(E,w);let Y=i.add(I,v);return H=i.mul(H,Y),Y=i.add(j,G),H=i.sub(H,Y),Y=i.add(p,w),_=i.add(P,v),Y=i.mul(Y,_),_=i.add(F,G),Y=i.sub(Y,_),M=i.mul(V,H),_=i.mul(K,G),M=i.add(_,M),_=i.sub(F,M),M=i.add(F,M),R=i.mul(_,M),F=i.add(j,j),F=i.add(F,j),G=i.mul(V,G),H=i.mul(K,H),F=i.add(F,G),G=i.sub(j,G),G=i.mul(V,G),H=i.add(H,G),j=i.mul(F,H),R=i.add(R,j),j=i.mul(Y,H),_=i.mul(Z,_),_=i.sub(_,j),j=i.mul(Z,F),M=i.mul(Y,M),M=i.add(M,j),new S(_,R,M)}subtract(m){return this.add(m.negate())}is0(){return this.equals(S.ZERO)}multiply(m){const{endo:E}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let p,w;const I=P=>C.cached(this,P,v=>Xi(S,v));if(E){const{k1neg:P,k1:v,k2neg:_,k2:R}=N(m),{p:M,f:V}=I(v),{p:K,f:j}=I(R);w=V.add(j),p=B(E.beta,M,K,P,_)}else{const{p:P,f:v}=I(m);p=P,w=v}return Xi(S,[p,w])[0]}multiplyUnsafe(m){const{endo:E}=e,p=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===yt||p.is0())return S.ZERO;if(m===ls)return p;if(C.hasCache(this))return this.multiply(m);if(E){const{k1neg:w,k1:I,k2neg:P,k2:v}=N(m),{p1:_,p2:R}=hd(S,p,I,v);return B(E.beta,_,R,w,P)}else return C.unsafe(p,m)}multiplyAndAddUnsafe(m,E,p){const w=this.multiplyUnsafe(E).add(m.multiplyUnsafe(p));return w.is0()?void 0:w}toAffine(m){return q(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===ls?!0:m?m(S,this):C.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===ls?this:m?m(S,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return yi(m,"isCompressed"),this.assertValidity(),f(S,this,m)}toHex(m=!0){return cs(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(m=!0){return this.toBytes(m)}_setWindowSize(m){this.precompute(m)}static normalizeZ(m){return Xi(S,m)}static msm(m,E){return ld(S,n,m,E)}static fromPrivateKey(m){return S.BASE.multiply(ns(n,m))}}S.BASE=new S(r.Gx,r.Gy,i.ONE),S.ZERO=new S(i.ZERO,i.ONE,i.ZERO),S.Fp=i,S.Fn=n;const T=n.BITS,C=new cd(S,e.endo?Math.ceil(T/2):T);return S.BASE.precompute(8),S}function Fa(s){return Uint8Array.of(s?2:3)}function Ga(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Pd(s,e={}){const{Fn:t}=s,i=e.randomBytes||Bt,n=Object.assign(Ga(s.Fp,t),{seed:za(t.ORDER)});function r(f){try{return!!ns(t,f)}catch{return!1}}function o(f,y){const{publicKey:g,publicKeyUncompressed:b}=n;try{const A=f.length;return y===!0&&A!==g||y===!1&&A!==b?!1:!!s.fromBytes(f)}catch{return!1}}function a(f=i(n.seed)){return rd(Vt(f,n.seed,"seed"),t.ORDER)}function c(f,y=!0){return s.BASE.multiply(ns(t,f)).toBytes(y)}function h(f){const y=a(f);return{secretKey:y,publicKey:c(y)}}function l(f){if(typeof f=="bigint")return!1;if(f instanceof s)return!0;const{secretKey:y,publicKey:g,publicKeyUncompressed:b}=n;if(t.allowedLengths||y===g)return;const A=pe("key",f).length;return A===g||A===b}function u(f,y,g=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(y)===!1)throw new Error("second arg must be public key");const b=ns(t,f);return s.fromHex(y).multiply(b).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:s,utils:{isValidSecretKey:r,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:r,randomPrivateKey:a,normPrivateKeyToScalar:f=>ns(t,f),precompute(f=8,y=s.BASE){return y.precompute(f,!1)}},lengths:n})}function Ad(s,e,t={}){$i(e),Bi(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const i=t.randomBytes||Bt,n=t.hmac||((E,...p)=>Fs(e,E,pt(...p))),{Fp:r,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:h,getPublicKey:l,getSharedSecret:u,utils:d,lengths:f}=Pd(s,t),y={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function b(E){const p=a>>ls;return E>p}function A(E,p){if(!o.isValidNot0(p))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return p}function L(E,p){$n(p);const w=f.signature,I=p==="compact"?w:p==="recovered"?w+1:void 0;return Vt(E,I,`${p} signature`)}class O{constructor(p,w,I){this.r=A("r",p),this.s=A("s",w),I!=null&&(this.recovery=I),Object.freeze(this)}static fromBytes(p,w=g){L(p,w);let I;if(w==="der"){const{r:R,s:M}=ft.toSig(Vt(p));return new O(R,M)}w==="recovered"&&(I=p[0],w="compact",p=p.subarray(1));const P=o.BYTES,v=p.subarray(0,P),_=p.subarray(P,P*2);return new O(o.fromBytes(v),o.fromBytes(_),I)}static fromHex(p,w){return this.fromBytes(di(p),w)}addRecoveryBit(p){return new O(this.r,this.s,p)}recoverPublicKey(p){const w=r.ORDER,{r:I,s:P,recovery:v}=this;if(v==null||![0,1,2,3].includes(v))throw new Error("recovery id invalid");if(a*Ha<w&&v>1)throw new Error("recovery id is ambiguous for h>1 curve");const R=v===2||v===3?I+a:I;if(!r.isValid(R))throw new Error("recovery id 2 or 3 invalid");const M=r.toBytes(R),V=s.fromBytes(pt(Fa((v&1)===0),M)),K=o.inv(R),j=N(pe("msgHash",p)),F=o.create(-j*K),G=o.create(P*K),Z=s.BASE.multiplyUnsafe(F).add(V.multiplyUnsafe(G));if(Z.is0())throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return b(this.s)}toBytes(p=g){if($n(p),p==="der")return di(ft.hexFromSig(this));const w=o.toBytes(this.r),I=o.toBytes(this.s);if(p==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return pt(Uint8Array.of(this.recovery),w,I)}return pt(w,I)}toHex(p){return cs(this.toBytes(p))}assertValidity(){}static fromCompact(p){return O.fromBytes(pe("sig",p),"compact")}static fromDER(p){return O.fromBytes(pe("sig",p),"der")}normalizeS(){return this.hasHighS()?new O(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return cs(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return cs(this.toBytes("compact"))}}const x=t.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");const w=Ci(p),I=p.length*8-c;return I>0?w>>BigInt(I):w},N=t.bits2int_modN||function(p){return o.create(x(p))},q=Gs(c);function k(E){return An("num < 2^"+c,E,yt,q),o.toBytes(E)}function B(E,p){return Vt(E,void 0,"message"),p?Vt(e(E),void 0,"prehashed message"):E}function S(E,p,w){if(["recovered","canonical"].some(F=>F in w))throw new Error("sign() legacy options not supported");const{lowS:I,prehash:P,extraEntropy:v}=nn(w,y);E=B(E,P);const _=N(E),R=ns(o,p),M=[k(R),k(_)];if(v!=null&&v!==!1){const F=v===!0?i(f.secretKey):v;M.push(pe("extraEntropy",F))}const V=pt(...M),K=_;function j(F){const G=x(F);if(!o.isValidNot0(G))return;const Z=o.inv(G),H=s.BASE.multiply(G).toAffine(),Y=o.create(H.x);if(Y===yt)return;const ve=o.create(Z*o.create(K+Y*R));if(ve===yt)return;let Ee=(H.x===Y?0:2)|Number(H.y&ls),ye=ve;return I&&b(ve)&&(ye=o.neg(ve),Ee^=1),new O(Y,ye,Ee)}return{seed:V,k2sig:j}}function T(E,p,w={}){E=pe("message",E);const{seed:I,k2sig:P}=S(E,p,w);return Yu(e.outputLen,o.BYTES,n)(I,P)}function C(E){let p;const w=typeof E=="string"||Oi(E),I=!w&&E!==null&&typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!w&&!I)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(I)p=new O(E.r,E.s);else if(w){try{p=O.fromBytes(pe("sig",E),"der")}catch(P){if(!(P instanceof ft.Err))throw P}if(!p)try{p=O.fromBytes(pe("sig",E),"compact")}catch{return!1}}return p||!1}function $(E,p,w,I={}){const{lowS:P,prehash:v,format:_}=nn(I,y);if(w=pe("publicKey",w),p=B(pe("message",p),v),"strict"in I)throw new Error("options.strict was renamed to lowS");const R=_===void 0?C(E):O.fromBytes(pe("sig",E),_);if(R===!1)return!1;try{const M=s.fromBytes(w);if(P&&R.hasHighS())return!1;const{r:V,s:K}=R,j=N(p),F=o.inv(K),G=o.create(j*F),Z=o.create(V*F),H=s.BASE.multiplyUnsafe(G).add(M.multiplyUnsafe(Z));return H.is0()?!1:o.create(H.x)===V}catch{return!1}}function m(E,p,w={}){const{prehash:I}=nn(w,y);return p=B(p,I),O.fromBytes(E,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:h,getPublicKey:l,getSharedSecret:u,utils:d,lengths:f,Point:s,sign:T,verify:$,recoverPublicKey:m,Signature:O,hash:e})}function Od(s){const e={a:s.a,b:s.b,p:s.Fp.ORDER,n:s.n,h:s.h,Gx:s.Gx,Gy:s.Gy},t=s.Fp;let i=s.allowedPrivateKeyLengths?Array.from(new Set(s.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const n=kt(e.n,{BITS:s.nBitLength,allowedLengths:i,modFromBytes:s.wrapPrivateKey}),r={Fp:t,Fn:n,allowInfinityPoint:s.allowInfinityPoint,endo:s.endo,isTorsionFree:s.isTorsionFree,clearCofactor:s.clearCofactor,fromBytes:s.fromBytes,toBytes:s.toBytes};return{CURVE:e,curveOpts:r}}function $d(s){const{CURVE:e,curveOpts:t}=Od(s),i={hmac:s.hmac,randomBytes:s.randomBytes,lowS:s.lowS,bits2int:s.bits2int,bits2int_modN:s.bits2int_modN};return{CURVE:e,curveOpts:t,hash:s.hash,ecdsaOpts:i}}function Rd(s,e){const t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},s,Da(t.Fn.ORDER,t.Fn.BITS))})}function Nd(s){const{CURVE:e,curveOpts:t,hash:i,ecdsaOpts:n}=$d(s),r=Sd(e,t),o=Ad(r,i,n);return Rd(s,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function nr(s,e){const t=i=>Nd({...s,hash:i});return{...t(e),create:t}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wa={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Za={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Ya={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Td=kt(Wa.p),qd=kt(Za.p),Cd=kt(Ya.p),Bd=nr({...Wa,Fp:Td,lowS:!1},Ks);nr({...Za,Fp:qd,lowS:!1},ol);nr({...Ya,Fp:Cd,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},rl);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kd=Bd;var Ud={};const Md=":";function mt(s){const[e,t]=s.split(Md);return{namespace:e,reference:t}}function eo(s,e=[]){const t=[];return Object.keys(s).forEach(i=>{if(e.length&&!e.includes(i))return;const n=s[i];t.push(...n.accounts)}),t}function Qa(s,e){return s.includes(":")?[s]:e.chains||[]}const Dd={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}},Ld={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 D(s,e){const{message:t,code:i}=Ld[s];return{message:e?`${t} ${e}`:t,code:i}}function X(s,e){const{message:t,code:i}=Dd[s];return{message:e?`${t} ${e}`:t,code:i}}const zd="ReactNative",$e={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},jd="js";function bi(){return typeof $s<"u"&&typeof $s.versions<"u"&&typeof $s.versions.node<"u"}function Ut(){return!ps()&&!!Uo()&&navigator.product===zd}function Kd(){return Ut()&&typeof globalThis<"u"&&typeof(globalThis==null?void 0:globalThis.Platform)<"u"&&(globalThis==null?void 0:globalThis.Platform.OS)==="android"}function Vd(){return Ut()&&typeof globalThis<"u"&&typeof(globalThis==null?void 0:globalThis.Platform)<"u"&&(globalThis==null?void 0:globalThis.Platform.OS)==="ios"}function bs(){return!bi()&&!!Uo()&&!!ps()}function Ws(){return Ut()?$e.reactNative:bi()?$e.node:bs()?$e.browser:$e.unknown}function to(){var s;try{return Ut()&&typeof globalThis<"u"&&typeof(globalThis==null?void 0:globalThis.Application)<"u"?(s=globalThis.Application)==null?void 0:s.applicationId:void 0}catch{return}}function Hd(s,e){const t=new URLSearchParams(s);return Object.entries(e).sort(([i],[n])=>
3i.localeCompare(n)).forEach(([i,n])=>{n!=null&&t.set(i,String(n))}),t.toString()}function Fd(s){var t,i;const e=Ja();try{return s!=null&&s.url&&e.url&&new URL(s.url).host!==new URL(e.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${s.url} differs from the actual page url:${e.url}. This is probably unintended and can lead to issues.`),s.url=e.url),(t=s==null?void 0:s.icons)!=null&&t.length&&s.icons.length>0&&(s.icons=s.icons.filter(n=>n!=="")),{...e,...s,url:(s==null?void 0:s.url)||e.url,name:(s==null?void 0:s.name)||e.name,description:(s==null?void 0:s.description)||e.description,icons:(i=s==null?void 0:s.icons)!=null&&i.length&&s.icons.length>0?s.icons:e.icons}}catch(n){return console.warn("Error populating app metadata",n),s||e}}function Ja(){return eh()||{name:"",description:"",url:"",icons:[""]}}function Gd(){if(Ws()===$e.reactNative&&typeof globalThis<"u"&&typeof(globalThis==null?void 0:globalThis.Platform)<"u"){const{OS:t,Version:i}=globalThis.Platform;return[t,i].join("-")}const s=oh();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function Wd(){var e;const s=Ws();return s===$e.browser?[s,((e=ah())==null?void 0:e.host)||"unknown"].join(":"):s}function Xa(s,e,t){const i=Gd(),n=Wd();return[[s,e].join("-"),[jd,t].join("-"),i,n].join("/")}function Zd({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:n,projectId:r,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Xa(s,e,i),u={auth:n,ua:l,projectId:r,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=Hd(h[1]||"",u);return h[0]+"?"+d}function Gt(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Rn(s){return Object.fromEntries(s.entries())}function Nn(s){return new Map(Object.entries(s))}function Lt(s=U.FIVE_MINUTES,e){const t=U.toMiliseconds(s||U.FIVE_MINUTES);let i,n,r,o;return{resolve:a=>{r&&i&&(clearTimeout(r),i(a),o=Promise.resolve(a))},reject:a=>{r&&n&&(clearTimeout(r),n(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);r=setTimeout(()=>{const h=D("EXPIRED"),l=new Error(e||h.message);l.code=h.code,c(l)},t),i=a,n=c})}}function He(s,e,t){return new Promise(async(i,n)=>{const r=setTimeout(()=>n(new Error(t)),e);try{const o=await s;i(o)}catch(o){n(o)}clearTimeout(r)})}function ec(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${s}`)}function Yd(s){return ec("topic",s)}function Qd(s){return ec("id",s)}function tc(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function se(s,e){return U.fromMiliseconds(Date.now()+U.toMiliseconds(s))}function et(s){return Date.now()>=U.toMiliseconds(s)}function Q(s,e){return`${s}${e?`:${e}`:""}`}function tt(s=[],e=[]){return[...new Set([...s,...e])]}async function Jd({id:s,topic:e,wcDeepLink:t}){var i,n;try{if(!t)return;const r=(i=typeof t=="string"?JSON.parse(t):t)==null?void 0:i.href;if(typeof r!="string")return;const o=Xd(r,s,e),a=Ws();if(a===$e.browser){if(!((n=ps())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}
3ef(o)}else a===$e.reactNative&&typeof(globalThis==null?void 0:globalThis.Linking)<"u"&&await globalThis.Linking.openURL(o)}catch(r){console.error(r)}}function Xd(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let n=`${s}`;if(s.startsWith("https://t.me")){const r=s.includes("?")?"&startapp=":"?startapp=";n=`${n}${r}${rf(i,!0)}`}else n=`${n}/wc?${i}`;return n}function ef(s){let e="_self";nf()?e="_top":(sf()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function tf(s,e){let t="";try{if(bs()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function so(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function io(){return typeof crypto<"u"&&(crypto!=null&&crypto.randomUUID)?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function rr(){return typeof $s<"u"&&Ud.IS_VITEST==="true"}function sf(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function nf(){try{return window.self!==window.top}catch{return!1}}function rf(s,e=!1){const t=new TextEncoder().encode(s),i=new Array(t.length);for(let r=0;r<t.length;r++)i[r]=String.fromCharCode(t[r]);const n=btoa(i.join(""));return e?n.replace(/[=]/g,""):n}function sc(s){const e=s+"=".repeat((4-s.length%4)%4),t=atob(e),i=new Uint8Array(t.length);for(let n=0;n<t.length;n++)i[n]=t.charCodeAt(n);return new TextDecoder().decode(i)}function of(s){return new Promise(e=>setTimeout(e,s))}class af{constructor({limit:e}){this.limit=e,this.set=new Set}
vendor: 9,450 bytes, lines 3-6
3add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const t=this.set.values().next().value;t&&this.set.delete(t)}this.set.add(e)}}has(e){return this.set.has(e)}}const cf="https://rpc.walletconnect.org/v1";function us(s){const e=s+"=".repeat((4-s.length%4)%4),t=atob(e),i=new Uint8Array(t.length);for(let n=0;n<t.length;n++)i[n]=t.charCodeAt(n);return i}function ic(s){const e=`�Ethereum Signed Message: 4${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+ae(Yo(t),"base16")}async function hf(s,e,t,i,n,r){switch(t.t){case"eip191":return await lf(s,e,t.s);case"eip1271":return await uf(s,e,t.s,i,n,r);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}function lf(s,e,t){const i=bu(t);return $u({payload:ic(e),signature:i}).toLowerCase()===s.toLowerCase()}async function uf(s,e,t,i,n,r){const o=mt(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",h=t.substring(2),l=(h.length/2).toString(16).padStart(64,"0"),u=(e.startsWith("0x")?e:ic(e)).substring(2),d=a+u+c+l+h,f=await fetch(`${r||cf}/?chainId=${i}&projectId=${n}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:df(),jsonrpc:"2.0",method:"eth_call",params:[{to:s,data:d},"latest"]})}),{result:y}=await f.json();return y?y.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function df(){return Date.now()+Math.floor(Math.random()*1e3)}function ff(s){const e=us(s),t=e[0];if(t===0)throw new Error("No signatures found");const i=1+t*64;if(e.length<i)throw new Error("Transaction data too short for claimed signature count");if(e.length<100)throw new Error("Transaction too short");const n=e.slice(1,65);return zs.encode(n)}function pf(s){const e=us(s),t=new TextEncoder().encode("TransactionData::"),i=new Uint8Array(t.length+e.length);i.set(t),i.set(e,t.length);const n=Ou(i,{dkLen:32});return zs.encode(n)}function no(s){const e=new Uint8Array(Ks(gf(s)));return zs.encode(e)}function gf(s){if(s instanceof Uint8Array)return s;if(Array.isArray(s))return new Uint8Array(s);if(typeof s=="object"&&(s!=null&&s.data))return new Uint8Array(Object.values(s.data));if(typeof s=="object"&&s)return new Uint8Array(Object.values(s));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function ro(s){const e=us(s),t=th(e).txn;if(!t)throw new Error("Invalid signed transaction: missing 'txn' field");const i=sh(t),n=new TextEncoder().encode("TX"),r=Wt([n,new Uint8Array(i)]),o=al(r);return ih.encode(o).replace(/=+$/,"")}function rn(s){const e=[];let t=BigInt(s);for(;t>=0x80n;)e.push(Number(t&0x7fn|0x80n)),t>>=7n;return e.push(Number(t)),new Uint8Array(e)}function yf(s){const e=us(s.signed.bodyBytes),t=us(s.signed.authInfoBytes),i=us(s.signature.signature),n=[];n.push(new Uint8Array([10])),n.push(rn(e.length)),n.push(e),n.push(new Uint8Array([18])),n.push(rn(t.length)),n.push(t),n.push(new Uint8Array([26])),n.push(rn(i.length)),n.push(i);const r=Wt(n),o=Ks(r);return ae(o,"base16").toUpperCase()}function mf(s){var t,i;const e=[];try{if(typeof s=="string")return e.push(s),e;if(typeof s!="object")return e;s!=null&&s.id&&e.push(s.id);const n=(i=(t=s==null?void 0:s.capabilities)==null?void 0:t.caip345)==null?void 0:i.transactionHashes;n&&e.push(...n)}catch(n){console.warn("getWalletSendCallsHashes failed: ",n)}return e}const nc="did:pkh:",wf={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},bf=s=>s?wf[s]||s:"",ki=s=>s==null?void 0:s.split(":"),vf=s=>{const e=s&&ki(s);if(e)return s.includes(nc)?e[3]:e[1]},Ef=s=>{const e=s&&ki(s);if(e)return s.includes(nc)?e[2]:e[0]},Tn=s=>{const e=s&&ki(s);if(e)return e[2]+":"+e[3]},vi=s=>{const e=s&&ki(s);if(e)return e.pop()};async function oo(s){const{cacao:e,projectId:t}=s,{s:i,p:n}=e,r=rc(n,n.iss),o=vi(n.iss);return await hf(o,r,i,Tn(n.iss),t)}const rc=(s,e)=>{const t=Ef(e);if(!t)throw new Error("Invalid issuer: "+e);const i=`${s.domain} wants you to sign in with your ${bf(t)} account:`,n=vi(e);if(!s.aud&&!s.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=s.statement||void 0;const o=`URI: ${s.aud||s.uri}`,a=`Version: ${s.version}`,c=`Chain ID: ${vf(e)}`,h=`Nonce: ${s.nonce}`,l=`Issued At: ${s.iat}`,u=s.exp?`Expiration Time: ${s.exp}`:void 0,d=s.nbf?`Not Before: ${s.nbf}`:void 0,f=s.requestId?`Request ID: ${s.requestId}`:void 0,y=s.resources?`Resources:${s.resources.map(b=>` 5- ${b}`).join("")}`:void 0,g=ci(s.resources);if(g){const b=Ms(g);r=Rf(r,b)}return[i,n,"",r,"",o,a,c,h,l,u,d,f,y].filter(b=>b!=null).join(` 6`)};function If(s){const e=JSON.stringify(s),t=new TextEncoder().encode(e),i=new Array(t.length);for(let n=0;n<t.length;n++)i[n]=String.fromCharCode(t[n]);return btoa(i.join(""))}function _f(s){const e=s+"=".repeat((4-s.length%4)%4),t=atob(e),i=new Uint8Array(t.length);for(let n=0;n<t.length;n++)i[n]=t.charCodeAt(n);return JSON.parse(new TextDecoder().decode(i))}function Qt(s){if(!s)throw new Error("No recap provided, value is undefined");if(!s.att)throw new Error("No `att` property found");const e=Object.keys(s.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=s.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(n=>{const r=i[n];if(!Array.isArray(r))throw new Error(`Ability limits ${n} must be an array of objects, found: ${r}`);if(!r.length)throw new Error(`Value of ${n} is empty array, must be an array with objects`);r.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${n}) must be an array of objects, found: ${o}`)})})})}function xf(s,e,t,i={}){return t==null||t.sort((n,r)=>n.localeCompare(r)),{att:{[s]:Sf(e,t,i)}}}function Sf(s,e,t={}){e=e==null?void 0:e.sort((n,r)=>n.localeCompare(r));const i=e.map(n=>({[`${s}/${n}`]:[t]}));return Object.assign({},...i)}function oc(s){return Qt(s),`urn:recap:${If(s).replace(/=/g,"")}`}function Ms(s){const e=_f(s.replace("urn:recap:",""));return Qt(e),e}function Pf(s,e,t){const i=xf(s,e,t);return oc(i)}function Af(s){return s&&s.includes("urn:recap:")}function Of(s,e){const t=Ms(s),i=Ms(e),n=$f(t,i);return oc(n)}function $f(s,e){Qt(s),Qt(e);const t=Object.keys(s.att).concat(Object.keys(e.att)).sort((n,r)=>n.localeCompare(r)),i={att:{}};return t.forEach(n=>{var r,o;Object.keys(((r=s.att)==null?void 0:r[n])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[n])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,h;i.att[n]={...i.att[n],[a]:((c=s.att[n])==null?void 0:c[a])||((h=e.att[n])==null?void 0:h[a])}})}),i}function Rf(s="",e){Qt(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(s.includes(t))return s;const i=[];let n=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,d)=>u.action.localeCompare(d.action));const h={};c.forEach(u=>{h[u.ability]||(h[u.ability]=[]),h[u.ability].push(u.action)});const l=Object.keys(h).map(u=>(n++,`(${n}) '${u}': '${h[u].join("', '")}' for '${a}'.`));i.push(l.join(", ").replace(".,","."))});const r=i.join(" "),o=`${t}${r}`;return`${s?s+" ":""}${o}`}function ao(s){var i;const e=Ms(s);Qt(e);const t=(i=e.att)==null?void 0:i.eip155;return t?Object.keys(t).map(n=>n.split("/")[1]):[]}function co(s){const e=Ms(s);Qt(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(n=>{var r;(r=n==null?void 0:n[0])!=null&&r.chains&&t.push(n[0].chains)})}),[...new Set(t.flat())]}function ci(s){if(!s)return;const e=s==null?void 0:s[s.length-1];return Af(e)?e:void 0}const ac="base10",be="base16",le="base64pad",Rt="base64url",Zs="utf8",cc=0,wt=1,Ys=2,Nf=0,ho=1,Rs=12,or=32;function Tf(){const s=On.utils.randomPrivateKey(),e=On.getPublicKey(s);return{privateKey:ae(s,be),publicKey:ae(e,be)}}function qn(){const s=Bt(or);return ae(s,be)}function qf(s,e){const t=On.getSharedSecret(ge(s,be),ge(e,be)),i=Wu(Ni,t,void 0,void 0,or);return ae(i,be)}function hi(s){const e=Ni(ge(s,be));return ae(e,be)}function Ue(s){const e=Ni(ge(s,Zs));return ae(e,be)}function hc(s){return ge(`${s}`,ac)}function Jt(s){return Number(ae(s,ac))}function lc(s){return s.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ei(s){const e=s.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Cf(s){const e=hc(typeof s.type<"u"?s.type:cc);if(Jt(e)===wt&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?ge(s.senderPublicKey,be):void 0,i=typeof s.iv<"u"?ge(s.iv,be):Bt(Rs),n=ge(s.symKey,be),r=Oa(n,i).encrypt(ge(s.message,Zs)),o=uc({type:e,sealed:r,iv:i,senderPublicKey:t});return s.encoding===Rt?lc(o):o}function Bf(s){const e=ge(s.symKey,be),{sealed:t,iv:i}=Ds({encoded:s.encoded,encoding:s.encoding}),n=Oa(e,i).decrypt(t);if(n===null)throw new Error("Failed to decrypt");return ae(n,Zs)}function kf(s,e){const t=hc(Ys),i=Bt(Rs),n=ge(s,Zs),r=uc({type:t,sealed:n,iv:i});return e===Rt?lc(r):r}function Uf(s,e){const{sealed:t}=Ds({encoded:s,encoding:e});return ae(t,Zs)}
6function uc(s){if(Jt(s.type)===Ys)return ae(Wt([s.type,s.sealed]),le);if(Jt(s.type)===wt){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return ae(Wt([s.type,s.senderPublicKey,s.iv,s.sealed]),le)}return ae(Wt([s.type,s.iv,s.sealed]),le)}function Ds(s){const e=(s.encoding||le)===Rt?Ei(s.encoded):s.encoded,t=ge(e,le),i=t.slice(Nf,ho),n=ho;if(Jt(i)===wt){const c=n+or,h=c+Rs,l=t.slice(n,c),u=t.slice(c,h),d=t.slice(h);return{type:i,sealed:d,iv:u,senderPublicKey:l}}if(Jt(i)===Ys){const c=t.slice(n),h=Bt(Rs);return{type:i,sealed:c,iv:h}}const r=n+Rs,o=t.slice(n,r),a=t.slice(r);return{type:i,sealed:a,iv:o}}function Mf(s,e){const t=Ds({encoded:s,encoding:e==null?void 0:e.encoding});return dc({type:Jt(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?ae(t.senderPublicKey,be):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function dc(s){const e=(s==null?void 0:s.type)||cc;if(e===wt){if(typeof(s==null?void 0:s.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(s==null?void 0:s.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:s==null?void 0:s.senderPublicKey,receiverPublicKey:s==null?void 0:s.receiverPublicKey}}function lo(s){return s.type===wt&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function uo(s){return s.type===Ys}function Df(s){const e=ge(Ei(s.x),le),t=ge(Ei(s.y),le);return Wt([new Uint8Array([4]),e,t])}function Lf(s,e){const[t,i,n]=s.split("."),r=ge(Ei(n),le);if(r.length!==64)throw new Error("Invalid signature length");const o=r.slice(0,32),a=r.slice(32,64),c=`${t}.${i}`,h=Ni(c),l=Df(e);if(!kd.verify(Wt([o,a]),h,l))throw new Error("Invalid signature");return yn(s).payload}const zf="irn";function Ii(s){return(s==null?void 0:s.relay)||{protocol:zf}}function rs(s){const e=rh[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function jf(s,e="-"){const t={},i="relay"+e;return Object.keys(s).forEach(n=>{if(n.startsWith(i)){const r=n.replace(i,""),o=s[n];t[r]=o}}),t}function fo(s){if(!s.includes("wc:")){const h=sc(s);h!=null&&h.includes("wc:")&&(s=h)}s=s.includes("wc://")?s.replace("wc://",""):s,s=s.includes("wc:")?s.replace("wc:",""):s;const e=s.indexOf(":"),t=s.indexOf("?")!==-1?s.indexOf("?"):void 0,i=s.substring(0,e),n=s.substring(e+1,t).split("@"),r=typeof t<"u"?s.substring(t):"",o=new URLSearchParams(r),a=Object.fromEntries(o.entries()),c=typeof a.methods=="str
6ing"?a.methods.split(","):void 0;return{protocol:i,topic:Kf(n[0]),version:parseInt(n[1],10),symKey:a.symKey,relay:jf(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Kf(s){return s.startsWith("//")?s.substring(2):s}function Vf(s,e="-"){const t="relay",i={};return Object.keys(s).forEach(n=>{const r=n,o=t+e+r;s[r]&&(i[o]=s[r])}),i}function po(s){const e=new URLSearchParams,t={...Vf(s.relay),symKey:s.symKey,...s.expiryTimestamp&&{expiryTimestamp:s.expiryTimestamp.toString()},...s.methods&&{methods:s.methods.join(",")}};return Object.entries(t).sort(([i],[n])=>i.localeCompare(n)).forEach(([i,n])=>{n!==void 0&&e.append(i,String(n))}),`${s.protocol}:${s.topic}@${s.version}?${e}`}function ni(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function vs(s){const e=[];return s.forEach(t=>{const[i,n]=t.split(":");e.push(`${i}:${n}`)}),e}function fc(s){const e=[];return Object.values(s).forEach(t=>{e.push(...vs(t.accounts))}),[...new Set(e)]}function Hf(s){const e=[];return Object.values(s).forEach(t=>{e.push(...t.methods)}),[...new Set(e)]}function Ff(s){const e=[];return Object.values(s).forEach(t=>{e.push(...t.events)}),[...new Set(e)]}function Gf(s,e){const t=[];return Object.values(s).forEach(i=>{vs(i.accounts).includes(e)&&t.push(...i.methods)}),t}function Wf(s,e){const t=[];return Object.values(s).forEach(i=>{vs(i.accounts).includes(e)&&t.push(...i.events)}),t}function Ui(s){return s.includes(":")}function os(s){return Ui(s)?s.split(":")[0]:s}function go(s){var t,i,n;const e={};if(!st(s))return e;for(const[r,o]of Object.entries(s)){const a=Ui(r)?[r]:o.chains,c=o.methods||[],h=o.events||[],l=os(r);e[l]={...e[l],chains:tt(a,(t=e[l])==null?void 0:t.chains),methods:tt(c,(i=e[l])==null?void 0:i.methods),events:tt(h,(n=e[l])==null?void 0:n.events)}}return e}function Zf(s){const e={};return s==null||s.forEach(t=>{var r;const[i,n]=t.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(t),(r=e[i].chains)==null||r.push(`${i}:${n}`)}),e}function yo(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=Zf(e);for(const[i,n]of Object.entries(t))n.methods?n.methods=tt(n.methods,s):n.methods=s,n.events=["chainChanged","accountsChanged"];return t}function Yf(s,e){var o,a,c,h,l,u;const t=go(s),i=go(e),n={},r=Object.keys(t).concat(Object.keys(i));for(const d of r)n[d]={chains:tt((o=t[d])==null?void 0:o.chains,(a=i[d])==null?void 0:a.chains),methods:tt((c=t[d])==null?void 0:c.methods,(h=i[d])==null?void 0:h.methods),events:tt((l=t[d])==null?void 0:l.events,(u=i[d])==null?void 0:u.events)};return n}function Me(s,e){return!!Array.isArray(s)}function st(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function re(s){return typeof s>"u"}function ie(s,e){return e&&re(s)?!0:typeof s=="string"&&!!s.trim().length}function ar(s,e){return e&&re(s)?!0:typeof s=="number"&&!isNaN(s)}function Qf(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),n=Object.keys(t);let r=!0;return Gt(n,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:h}=s.namespaces[o],l=vs(a),u=t[o];(!Gt(Qa(o,u),l)||!Gt(u.methods,c)||!Gt(u.events,h))&&(r=!1)}),r):!1}function _i(s){return ie(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function Jf(s){if(ie(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&_i(t)}}return!1}function Xf(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(ie(s,!1)){if(e(s))return!0;const t=sc(s);return e(t)}}catch{}return!1}function ep(s){var e;return(e=s==null?void 0:s.proposer)==null?void 0:e.publicKey}function tp(s){return s==null?void 0:s.topic}function sp(s,e){let t=null;return ie(s==null?void 0:s.publicKey,!1)||(t=D("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function mo(s){let e=!0;return Me(s)?s.length&&(e=s.every(t=>ie(t,!1))):e=!1,e}function ip(s,e,t){let i=null;return Me(e)&&e.length?e.forEach(n=>{i||_i(n)||(i=X("UNSUPPORTED_CHAINS",`${t}, chain ${n} should be a string and conform to "namespace:chainId" format`))}):_i(s)||(i=X("UNSUPPORTED_CHAINS",`${t}, 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:
65"] }`)),i}function np(s,e,t){let i=null;return Object.entries(s).forEach(([n,r])=>{if(i)return;const o=ip(n,Qa(n,r),`${e} ${t}`);o&&(i=o)}),i}function rp(s,e){let t=null;return Me(s)?s.forEach(i=>{t||Jf(i)||(t=X("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=X("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function op(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const n=rp(i==null?void 0:i.accounts,`${e} namespace`);n&&(t=n)}),t}function ap(s,e){let t=null;return mo(s==null?void 0:s.methods)?mo(s==null?void 0:s.events)||(t=X("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=X("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function pc(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const n=ap(i,`${e}, namespace`);n&&(t=n)}),t}function cp(s,e,t){let i=null;if(s&&st(s)){const n=pc(s,e);n&&(i=n);const r=np(s,e,t);r&&(i=r)}else i=D("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function on(s,e){let t=null;if(s&&st(s)){const i=pc(s,e);i&&(t=i);const n=op(s,e);n&&(t=n)}else t=D("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function gc(s){return ie(s.protocol,!0)}function hp(s,e){let t=!1;return s?s&&Me(s)&&s.length&&s.forEach(i=>{t=gc(i)}):t=!0,t}function lp(s){return typeof s=="number"}function Ie(s){return typeof s<"u"&&typeof s!==null}function up(s){return!(!s||typeof s!="object"||!s.code||!ar(s.code,!1)||!s.message||!ie(s.message,!1))}function dp(s){return!(re(s)||!ie(s.method,!1))}function fp(s){return!(re(s)||re(s.result)&&re(s.error)||!ar(s.id,!1)||!ie(s.jsonrpc,!1))}function pp(s){return!(re(s)||!ie(s.name,!1))}function wo(s,e){return!(!_i(e)||!fc(s).includes(e))}function gp(s,e,t){return ie(t,!1)?Gf(s,e).includes(t):!1}function yp(s,e,t){return ie(t,!1)?Wf(s,e).includes(t):!1}function bo(s,e,t){let i=null;const n=mp(s),r=wp(e),o=Object.keys(n),a=Object.keys(r),c=vo(Object.keys(s)),h=vo(Object.keys(e)),l=c.filter(u=>!h.includes(u));return l.length&&(i=D("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces. 7 Required: ${l.toString()} 8 Received: ${Object.keys(e).toString()}`)),Gt(o,a)||(i=D("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces. 9 Required: ${o.toString()} 10 Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||i)return;const d=vs(e[u].accounts);d.includes(u)||(i=D("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${u} 11 Required: ${u} 12 Approved: ${d.toString()}`))}),o.forEach(u=>{i||(Gt(n[u].methods,r[u].methods)?Gt(n[u].events,r[u].events)||(i=D("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):i=D("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),i}function mp(s){const e={};return Object.keys(s).forEach(t=>{var i;t.includes(":")?e[t]=s[t]:(i=s[t].chains)==null||i.forEach(n=>{e[n]={methods:s[t].methods,events:s[t].events}})}),e}function vo(s){return[...new Set(s.map(e=>e.includes(":")?e.split(":")[0]:e))]}function wp(s){const e={};return Object.keys(s).forEach(t=>{var i;t.includes(":")?e[t]=s[t]:(i=vs(s[t].accounts))==null||i.forEach(n=>{e[n]={accounts:s[t].accounts.filter(r=>r.includes(`${n}:`)),methods:s[t].methods,events:s[t].events}})}),e}function bp(s,e){return ar(s,!1)&&s<=e.max&&s>=e.min}function Eo(){const s=Ws();return new Promise(e=>{switch(s){case $e.browser:e(vp());break;case $e.reactNative:e(Ep());break;case $e.node:e(Ip());break;default:e(!0)}})}function vp(){return bs()&&(navigator==null?void 0:navigator.onLine)}async function Ep(){var s;return Ut()&&typeof globalThis<"u"&&(globalThis!=null&&globalThis.NetInfo)?(s=await(globalThis==null?void 0:globalThis.NetInfo.fetch()))==null?void 0:s.isConnected:!0}function Ip(){return!0}function _p(s){switch(Ws()){case $e.browser:xp(s);break;case $e.reactNative:Sp(s);break}}function xp(s){!Ut()&&bs()&&(window.addEventListener("online",()=>s(!0)),window.addEventListener("offline",()=>s(!1)))}function Sp(s){Ut()&&typeof globalThis<"u"&&(globalThis!=null&&globalThis.NetInfo)&&(globalThis==null||globalThis.NetInfo.addEventListener(e=>s(e==null?void 0:e.isConnected)))}function Pp(){var s;return bs()&&ps()?((s=ps())==null?void 0:s.visibilityState)==="visible":!0}const an={};class _s{static get(e){return an[e]}static set(e,t){an[e]=t}static delete(e){delete an[e]}}function Ap(s){const e=zs.decode(s);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function Op({publicKey:s,signature:e,payload:t}){var f;const i=xi(t.method),n=128|parseInt(((f=t.version)==null?void 0:f.toString())||"4"),r=Np(t.address),o=t.era==="00"?new Uint8Array([0]):xi(t.era);if(o.length!==1&&o.length!==2)throw new Error("Invalid era length");const a=parseInt(t.nonce,16),c=new Uint8Array([a&255,a>>8&255]),h=BigInt(`0x${Rp(t.tip)}`),l=qp(h),u=new Uint8Array([0,...s,r,...e,...o,...c,...l,...i]),d=Tp(u.length+1);return new Uint8Array([...d,n,...u])}function $p(s){const e=xi(s),t=nh.blake2b(e,void 0,32);return"0x"+ae(t,"base16")}function xi(s){return new Uint8Array(s.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Rp(s){return s.startsWith("0x")?s.slice(2):s}function Np(s){const e=zs.decode(s)[0];return e===42?0:e===60?2:1}function Tp(s){if(s<64)return new Uint8Array([s<<2]);if(s<16384){const e=s<<2|1;return new Uint8Array([e&255,e>>
vendor: 19,844 bytes, line 12
128&255])}else if(s<1<<30){const e=s<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function qp(s){if(s<1n<<6n)return new Uint8Array([Number(s<<2n)]);if(s<1n<<14n){const e=s<<2n|0x01n;return new Uint8Array([Number(e&0xffn),Number(e>>8n&0xffn)])}else if(s<1n<<30n){const e=s<<2n|0x02n;return new Uint8Array([Number(e&0xffn),Number(e>>8n&0xffn),Number(e>>16n&0xffn),Number(e>>24n&0xffn)])}else throw new Error("BigInt compact encoding not supported > 2^30")}function Cp(s){const e=xi(s.signature),t=Ap(s.transaction.address),i=Op({publicKey:t,signature:e,payload:s.transaction}),n=ae(i,"base16");return $p(n)}function cr({logger:s,name:e}){const t=typeof s=="string"?ko({opts:{level:s,name:e}}).logger:s;return t.level=typeof s=="string"?s:s.level,t}class Bp extends ms{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class kp extends ms{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}}class Up{constructor(e,t){this.logger=e,this.core=t}}let Mp=class extends ms{constructor(e,t){super(),this.relayer=e,this.logger=t}},Dp=class extends ms{constructor(e){super()}},Lp=class{constructor(e,t,i,n){this.core=e,this.logger=t,this.name=i}},zp=class extends ms{constructor(e,t){super(),this.relayer=e,this.logger=t}},jp=class extends ms{constructor(e,t){super(),this.core=e,this.logger=t}},Kp=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},Vp=class{constructor(e,t){this.projectId=e,this.logger=t}};class Hp{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}}let Fp=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},Gp=class{constructor(e){this.client=e}};function Wp(s){return Number.isSafeInteger(s)&&s>=0}function Zp(s){return s!=null&&typeof s!="function"&&Wp(s.length)}function Yp(s){return s==="__proto__"}function hr(s){return s==null||typeof s!="object"&&typeof s!="function"}function Qp(s,e){return s===e||Number.isNaN(s)&&Number.isNaN(e)}function Si(s){return Object.getOwnPropertySymbols(s).filter(e=>Object.prototype.propertyIsEnumerable.call(s,e))}function Ls(s){return s==null?s===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(s)}const yc="[object RegExp]",lr="[object String]",ur="[object Number]",dr="[object Boolean]",Pi="[object Arguments]",mc="[object Symbol]",wc="[object Date]",bc="[object Map]",vc="[object Set]",Ec="[object Array]",Jp="[object Function]",Ic="[object ArrayBuffer]",Ns="[object Object]",Xp="[object Error]",_c="[object DataView]",xc="[object Uint8Array]",Sc="[object Uint8ClampedArray]",Pc="[object Uint16Array]",Ac="[object Uint32Array]",eg="[object BigUint64Array]",Oc="[object Int8Array]",$c="[object Int16Array]",Rc="[object Int32Array]",tg="[object BigInt64Array]",Nc="[object Float32Array]",Tc="[object Float64Array]";function fr(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)}function sg(s,e){return as(s,void 0,s,new Map,e)}function as(s,e,t,i=new Map,n=void 0){const r=n==null?void 0:n(s,e,t,i);if(r!==void 0)return r;if(hr(s))return s;if(i.has(s))return i.get(s);if(Array.isArray(s)){const o=new Array(s.length);i.set(s,o);for(let a=0;a<s.length;a++)o[a]=as(s[a],a,t,i,n);return Object.hasOwn(s,"index")&&(o.index=s.index),Object.hasOwn(s,"input")&&(o.input=s.input),o}if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp){const o=new RegExp(s.source,s.flags);return o.lastIndex=s.lastIndex,o}if(s instanceof Map){const o=new Map;i.set(s,o);for(const[a,c]of s)o.set(a,as(c,a,t,i,n));return o}if(s instanceof Set){const o=new Set;i.set(s,o);for(const a of s)o.add(as(a,void 0,t,i,n));return o}if(typeof Zt<"u"&&Zt.isBuffer(s))return s.subarray();if(fr(s)){const o=new(Object.getPrototypeOf(s)).constructor(s.length);i.set(s,o);for(let a=0;a<s.length;a++)o[a]=as(s[a],a,t,i,n);return o}if(s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer)return s.slice(0);if(s instanceof DataView){const o=new DataView(s.buffer.slice(0),s.byteOffset,s.byteLength);return i.set(s,o),Ve(o,s,t,i,n),o}if(typeof File<"u"&&s instanceof File){const o=new File([s],s.name,{type:s.type});return i.set(s,o),Ve(o,s,t,i,n),o}if(typeof Blob<"u"&&s instanceof Blob){const o=new Blob([s],{type:s.type});return i.set(s,o),Ve(o,s,t,i,n),o}if(s instanceof Error){const o=new s.constructor;return i.set(s,o),o.message=s.message,o.name=s.name,o.stack=s.stack,o.cause=s.cause,Ve(o,s,t,i,n),o}if(s instanceof Boolean){const o=new Boolean(s.valueOf());return i.set(s,o),Ve(o,s,t,i,n),o}if(s instanceof Number){const o=new Number(s.valueOf());return i.set(s,o),Ve(o,s,t,i,n),o}if(s instanceof String){const o=new String(s.valueOf());return i.set(s,o),Ve(o,s,t,i,n),o}if(typeof s=="object"&&ig(s)){const o=Object.create(Object.getPrototypeOf(s));return i.set(s,o),Ve(o,s,t,i,n),o}return s}function Ve(s,e,t=s,i,n){const r=[...Object.keys(e),...Si(e)];for(let o=0;o<r.length;o++){const a=r[o],c=Object.getOwnPropertyDescriptor(s,a);(c==null||c.writable)&&(s[a]=as(e[a],a,t,i,n))}}function ig(s){switch(Ls(s)){case Pi:case Ec:case Ic:case _c:case dr:case wc:case Nc:case Tc:case Oc:case $c:case Rc:case bc:case ur:case Ns:case yc:case vc:case lr:case mc:case xc:case Sc:case Pc:case Ac:return!0;default:return!1}}function ng(s,e){return sg(s,(t,i,n,r)=>{if(typeof s=="object"){if(Ls(s)===Ns&&typeof s.constructor!="function"){const o={};return r.set(s,o),Ve(o,s,n,r),o}switch(Object.prototype.toString.call(s)){case ur:case lr:case dr:{const o=new s.constructor(s==null?void 0:s.valueOf());return Ve(o,s),o}case Pi:{const o={};return Ve(o,s),o.length=s.length,o[Symbol.iterator]=s[Symbol.iterator],o}default:return}}})}function Io(s){return ng(s)}function _o(s){return s!==null&&typeof s=="object"&&Ls(s)==="[object Arguments]"}function Cn(s){return typeof s=="object"&&s!==null}function rg(s){return Cn(s)&&Zp(s)}function xo(s){if(!s||typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(s)==="[object Object]":!1}function og(s,e,t){return Os(s,e,void 0,void 0,void 0,void 0,t)}function Os(s,e,t,i,n,r,o){const a=o(s,e,t,i,n,r);if(a!==void 0)return a;if(typeof s==typeof e)switch(typeof s){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return s===e;case"number":return s===e||Object.is(s,e);case"function":return s===e;case"object":return Ts(s,e,r,o)}return Ts(s,e,r,o)}function Ts(s,e,t,i){if(Object.is(s,e))return!0;let n=Ls(s),r=Ls(e);if(n===Pi&&(n=Ns),r===Pi&&(r=Ns),n!==r)return!1;switch(n){case lr:return s.toString()===e.toString();case ur:{const c=s.valueOf(),h=e.valueOf();return Qp(c,h)}case dr:case wc:case mc:return Object.is(s.valueOf(),e.valueOf());case yc:return s.source===e.source&&s.flags===e.flags;case Jp:return s===e}t=t??new Map;const o=t.get(s),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(s,e),t.set(e,s);try{switch(n){case bc:{if(s.size!==e.size)return!1;for(const[c,h]of s.entries())if(!e.has(c)||!Os(h,e.get(c),c,s,e,t,i))return!1;return!0}case vc:{if(s.size!==e.size)return!1;const c=Array.from(s.values()),h=Array.from(e.values());for(let l=0;l<c.length;l++){const u=c[l],d=h.findIndex(f=>Os(u,f,void 0,s,e,t,i));if(d===-1)return!1;h.splice(d,1)}return!0}case Ec:case xc:case Sc:case Pc:case Ac:case eg:case Oc:case $c:case Rc:case tg:case Nc:case Tc:{if(typeof Zt<"u"&&Zt.isBuffer(s)!==Zt.isBuffer(e)||s.length!==e.length)return!1;for(let c=0;c<s.length;c++)if(!Os(s[c],e[c],c,s,e,t,i))return!1;return!0}case Ic:return s.byteLength!==e.byteLength?!1:Ts(new Uint8Array(s),new Uint8Array(e),t,i);case _c:return s.byteLength!==e.byteLength||s.byteOffset!==e.byteOffset?!1:Ts(new Uint8Array(s),new Uint8Array(e),t,i);case Xp:return s.name===e.name&&s.message===e.message;case Ns:{if(!(Ts(s.constructor,e.constructor,t,i)||xo(s)&&xo(e)))return!1;const h=[...Object.keys(s),...Si(s)],l=[...Object.keys(e),...Si(e)];if(h.length!==l.length)return!1;for(let u=0;u<h.length;u++){const d=h[u],f=s[d];if(!Object.hasOwn(e,d))return!1;const y=e[d];if(!Os(f,y,d,s,e,t,i))return!1}return!0}default:return!1}}finally{t.delete(s),t.delete(e)}}function qc(){}function ag(s,e){return og(s,e,qc)}function cn(s){return fr(s)}function hn(s){var t;if(typeof s!="object"||s==null)return!1;if(Object.getPrototypeOf(s)===null)return!0;if(Object.prototype.toString.call(s)!=="[object Object]"){const i=s[Symbol.toStringTag];return i==null||!((t=Object.getOwnPropertyDescriptor(s,Symbol.toStringTag))!=null&&t.writable)?!1:s.toString()===`[object ${i}]`}let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}function cg(s){if(hr(s))return s;if(Array.isArray(s)||fr(s)||s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer)return s.slice(0);const e=Object.getPrototypeOf(s);if(e==null)return Object.assign(Object.create(e),s);const t=e.constructor;if(s instanceof Date||s instanceof Map||s instanceof Set)return new t(s);if(s instanceof RegExp){const i=new t(s);return i.lastIndex=s.lastIndex,i}if(s instanceof DataView)return new t(s.buffer.slice(0));if(s instanceof Error){let i;return s instanceof AggregateError?i=new t(s.errors,s.message,{cause:s.cause}):i=new t(s.message,{cause:s.cause}),i.stack=s.stack,Object.assign(i,s),i}if(typeof File<"u"&&s instanceof File)return new t([s],s.name,{type:s.type,lastModified:s.lastModified});if(typeof s=="object"){const i=Object.create(e);return Object.assign(i,s)}return s}function hg(s,...e){const t=e.slice(0,-1),i=e[e.length-1];let n=s;for(let r=0;r<t.length;r++){const o=t[r];n=li(n,o,i,new Map)}return n}function li(s,e,t,i){if(hr(s)&&(s=Object(s)),e==null||typeof e!="object")return s;if(i.has(e))return cg(i.get(e));if(i.set(e,s),Array.isArray(e)){e=e.slice();for(let r=0;r<e.length;r++)e[r]=e[r]??void 0}const n=[...Object.keys(e),...Si(e)];for(let r=0;r<n.length;r++){const o=n[r];if(Yp(o))continue;let a=e[o],c=s[o];if(_o(a)&&(a={...a}),_o(c)&&(c={...c}),typeof Zt<"u"&&Zt.isBuffer(a)&&(a=Io(a)),Array.isArray(a))if(Array.isArray(c)){const l=[],u=Reflect.ownKeys(c);for(let d=0;d<u.length;d++){const f=u[d];l[f]=c[f]}c=l}else if(rg(c)){const l=[];for(let u=0;u<c.length;u++)l[u]=c[u];c=l}else c=[];const h=t(c,a,o,s,e,i);h!==void 0?s[o]=h:Array.isArray(a)||Cn(c)&&Cn(a)&&(hn(c)||hn(a)||cn(c)||cn(a))?s[o]=li(c,a,t,i):c==null&&hn(a)?s[o]=li({},a,t,i):c==null&&cn(a)?s[o]=Io(a):(c===void 0||a!==void 0)&&(s[o]=a)}return s}function lg(s,...e){return hg(s,...e,qc)}var ug={};const Cc="wc",Bc=2,Bn="core",nt=`${Cc}@2:${Bn}:`,dg={logger:"error"},fg={database:":memory:"},pg="crypto",So="client_ed25519_seed",gg=U.ONE_DAY,yg="keychain",mg="0.3",wg="messages",bg="0.3",vg=U.SIX_HOURS,Eg="publisher",kc="irn",Ig="error",Uc="wss://relay.walletconnect.org",_g="relayer",te={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"},xg="_subscription",Ce={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Sg=.1,kn="2.23.9",J={link_mode:"link_mode",relay:"relay"},ui={inbound:"inbound",outbound:"outbound"},Pg="0.3",Ag="WALLETCONNECT_CLIENT_ID",Po="WALLETCONNECT_LINK_MODE_APPS",Ae={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Og="subscription",$g="0.3",Rg="pairing",Ng="0.3",xs={wc_pairingDelete:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:U.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:U.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:U.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:U.ONE_DAY,prompt:!1,tag:0},res:{ttl:U.ONE_DAY,prompt:!1,tag:0}}},zt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Le={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Tg="history",qg="0.3",Cg="expirer",Be={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Bg="0.3",kg="verify-api",Ug="https://verify.walletconnect.com",Mc="https://verify.walletconnect.org",qs=Mc,Mg=`${qs}/v3`,Dg=[Ug,Mc],Lg="echo",zg="https://echo.walletconnect.com",Qe={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"},lt={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"},ze={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"},Mt={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"},Dt={authenticated_session_approve_started:"authenticated_session_approve_started",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"},Ss={no_internet_connection:"no_internet_connection",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"},jg=.1,Kg="event-client",Vg=86400,Hg="https://pulse.walletconnect.org/batch";let Fg=class{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name=yg,this.version=mg,this.initialized=!1,this.storagePrefix=nt,this.init=async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}},this.has=i=>(this.isInitialized(),this.keychain.has(i)),this.set=async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()},this.get=i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:r}=D("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(r)}return n},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=Re(t,this.name)}get context(){return Ne(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Rn(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Nn(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}},Gg=class{constructor(e,t,i){this.core=e,this.logger=t,this.name=pg,this.randomSessionIdentifier=qn(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=n=>(this.isInitialized(),this.keychain.has(n)),this.getClientId=async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const n=await this.getClientSeed(),r=yr(n),o=uh(r.publicKey);return this.clientId=o,o},this.generateKeyPair=()=>{this.isInitialized();const n=Tf();return this.setPrivateKey(n.publicKey,n.privateKey)},this.signJWT=async n=>{this.isInitialized();const r=await this.getClientSeed(),o=yr(r),a=this.randomSessionIdentifier;return await dh(a,n,gg,o)},this.generateSharedKey=(n,r,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=qf(a,r);return this.setSymKey(c,o)},this.setSymKey=async(n,r)=>{this.isInitialized();const o=r||hi(n);return await this.keychain.set(o,n),o},this.deleteKeyPair=async n=>{this.isInitialized(),await this.keychain.del(n)},this.deleteSymKey=async n=>{this.isInitialized(),await this.keychain.del(n)},this.encode=async(n,r,o)=>{this.isInitialized();const a=dc(o),c=fh(r);if(uo(a))return kf(c,o==null?void 0:o.encoding);if(lo(a)){const d=a.senderPublicKey,f=a.receiverPublicKey;n=await this.generateSharedKey(d,f)}const h=this.getSymKey(n),{type:l,senderPublicKey:u}=a;return Cf({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})},this.decode=async(n,r,o)=>{this.isInitialized();const a=Mf(r,o);if(uo(a)){const c=Uf(r,o==null?void 0:o.encoding);return mr(c)}if(lo(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;n=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(n),h=Bf({symKey:c,encoded:r,encoding:o==null?void 0:o.encoding});return mr(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}},this.getPayloadType=(n,r=le)=>{const o=Ds({encoded:n,encoding:r});return Jt(o.type)},this.getPayloadSenderPublicKey=(n,r=le)=>{const o=Ds({encoded:n,encoding:r});return o.senderPublicKey?ae(o.senderPublicKey,be):void 0},this.core=e,this.logger=Re(t,this.name),this.keychain=i||new Fg(this.core,this.logger)}get context(){return Ne(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(So)}catch{e=qn(),await this.keychain.set(So,e)}return ge(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}},Wg=class extends Up{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.messagesWithoutClientAck=new Map,this.name=wg,this.version=bg,this.initialized=!1,this.storagePrefix=nt,this.init=async()=>
12{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const n=await this.getRelayerMessagesWithoutClientAck();typeof n<"u"&&(this.messagesWithoutClientAck=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}},this.set=async(i,n,r)=>{this.isInitialized();const o=Ue(n);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(i,a),r===ui.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,{...c,[o]:n})}return await this.persist(),o},this.get=i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n},this.getWithoutAck=i=>{this.isInitialized();const n={};for(const r of i){const o=this.messagesWithoutClientAck.get(r)||{};n[r]=Object.values(o)}return n},this.has=(i,n)=>{this.isInitialized();const r=this.get(i),o=Ue(n);return typeof r[o]<"u"},this.ack=async(i,n)=>{this.isInitialized();const r=this.messagesWithoutClientAck.get(i);if(typeof r>"u")return;const o=Ue(n);delete r[o],Object.keys(r).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,r),await this.persist()},this.del=async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()},this.logger=Re(e,this.name),this.core=t}get context(){return Ne(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Rn(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Rn(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Nn(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Nn(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}};class Zg extends Mp{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new Ct.EventEmitter,this.name=Eg,this.queue=new Map,this.publishTimeout=U.toMiliseconds(U.ONE_MINUTE),this.initialPublishTimeout=U.toMiliseconds(U.ONE_SECOND*15),this.needsTransportRestart=!1,this.publish=async(i,n,r)=>{var f,y,g,b,A;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:r}});const o=(r==null?void 0:r.ttl)||vg,a=(r==null?void 0:r.prompt)||!1,c=(r==null?void 0:r.tag)||0,h=(r==null?void 0:r.id)||jt().toString(),l=rs(Ii().protocol),u={id:h,method:(r==null?void 0:r.publishMethod)||l.publish,params:{topic:i,message:n,ttl:o,prompt:a,tag:c,attestation:r==null?void 0:r.attestation,...r==null?void 0:r.tvf}},d=`Failed to publish payload, please try again. id:${h} tag:${c}`;try{re((f=u.params)==null?void 0:f.prompt)&&((y=u.params)==null||delete y.prompt),re((g=u.params)==null?void 0:g.tag)&&((b=u.params)==null||delete b.tag);const L=new Promise(async O=>{const x=({id:q})=>{var k;((k=u.id)==null?void 0:k.toString())===q.toString()&&(this.removeRequestFromQueue(q),this.relayer.events.removeListener(te.publish,x),O())};this.relayer.events.on(te.publish,x);const N=He(new Promise((q,k)=>{this.rpcPublish(u,r).then(q).catch(B=>{this.logger.warn(B,B==null?void 0:B.message),k(B)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${c}`);try{await N,this.events.removeListener(te.publish,x)}catch(q){this.queue.set(h,{request:u,opts:r,attempt:1}),this.logger.warn(q,q==null?void 0:q.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:i,message:n,opts:r}}),await He(L,this.publishTimeout,d)}catch(L){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(L),(A=r==null?void 0:r.internal)==null?void 0:A.throwOnFailedPublish)throw L}finally{this.queue.delete(h)}},this.publishCustom=async i=>{var A,L,O,x,N;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:n,opts:r={}}=i,{attestation:o,tvf:a,publishMethod:c,prompt:h,tag:l,ttl:u=U.FIVE_MINUTES}=r,d=r.id||jt().toString(),f=rs(Ii().protocol),y=c||f.publish,g={id:d,method:y,params:{...n,ttl:u,prompt:h,tag:l,attestation:o,...a}},b=`Failed to publish custom payload, please try again. id:${d} tag:${l}`;try{re((A=g.params)==null?void 0:A.prompt)&&((L=g.params)==null||delete L.prompt),re((O=g.params)==null?void 0:O.tag)&&((x=g.params)==null||delete x.tag);const q=new Promise(async k=>{const B=({id:T})=>{var C;((C=g.id)==null?void 0:C.toString())===T.toString()&&(this.removeRequestFromQueue(T),this.relayer.events.removeListener(te.publish,B),k())};this.relayer.events.on(te.publish,B);const S=He(new Promise((T,C)=>{this.rpcPublish(g,r).then(T).catch($=>{this.logger.warn($,$==null?void 0:$.message),C($)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${y} id:${d} tag:${l}`);try{await S,this.events.removeListener(te.publish,B)}catch(T){this.queue.set(d,{request:g,opts:r,attempt:1}),this.logger.warn(T,T==null?void 0:T.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,payload:n,opts:r}}),await He(q,this.publishTimeout,b)}catch(q){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(q),(N=r==null?void 0:r.internal)==null?void 0:N.throwOnFailedPublish)throw q}finally{this.queue.delete(d)}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.relayer=e,this.logger=Re(t,this.name),this.registerEventListeners()}get context(){return Ne(this.logger)}async rpcPublish(e,t){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(te.publish,{...e,...t}),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{var n;const i=e.attempt+1;this.queue.set(t,{...e,attempt:i}),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(ws.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(te.connection_stalled);return}this.checkQueue()}),this.relayer.on(te.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class Yg{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>
vendor: 13,251 bytes, line 12
12{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const n=i.filter(r=>r!==t);if(!n.length){this.map.delete(e);return}this.map.set(e,n)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}let Qg=class extends zp{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new Yg,this.events=new Ct.EventEmitter,this.name=Og,this.version=$g,this.pending=new Map,this.cached=[],this.initialized=!1,this.storagePrefix=nt,this.subscribeTimeout=U.toMiliseconds(U.ONE_MINUTE),this.initialSubscribeTimeout=U.toMiliseconds(U.ONE_SECOND*15),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0},this.subscribe=async(i,n)=>{var r;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const o=Ii(n),a={topic:i,relay:o,transportType:n==null?void 0:n.transportType};(r=n==null?void 0:n.internal)!=null&&r.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,o,n);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}},this.unsubscribe=async(i,n)=>{this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)},this.isSubscribed=i=>new Promise(n=>{n(this.topicMap.topics.includes(i))}),this.isKnownTopic=i=>new Promise(n=>{n(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(r=>r.topic===i))}),this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(ws.pulse,async()=>{await this.checkPending()}),this.events.on(Ae.created,async i=>{const n=Ae.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(Ae.deleted,async i=>{const n=Ae.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})},this.relayer=e,this.logger=Re(t,this.name),this.clientId=""}get context(){return Ne(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const n=X("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n);const r=Ii(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,t,i){var a,c;const n=await this.getSubscriptionId(e);if((a=i==null?void 0:i.internal)!=null&&a.skipSubscribe)return n;(!i||(i==null?void 0:i.transportType)===J.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const r={method:rs(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});const o=(c=i==null?void 0:i.internal)==null?void 0:c.throwOnFailedPublish;try{if((i==null?void 0:i.transportType)===J.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(r).catch(u=>this.logger.warn(u))},U.toMiliseconds(U.ONE_SECOND)),n;const h=new Promise(async u=>{const d=f=>{f.topic===e&&(this.events.removeListener(Ae.created,d),u(f.id))};this.events.on(Ae.created,d);try{const f=await He(new Promise((y,g)=>{this.relayer.request(r).catch(b=>{this.logger.warn(b,b==null?void 0:b.message),g(b)}).then(y)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Ae.created,d),u(f)}catch{}}),l=await He(h,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?n:null}catch(h){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(te.connection_stalled),o)throw h}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const t=e[0].relay,i={method:rs(t.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await He(new Promise((n,r)=>{this.relayer.request(i).then(n).catch(o=>{this.logger.warn(o),r(o)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(te.connection_stalled),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:rs(t.protocol).batchFetchMessages,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await He(new Promise((r,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(r)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(te.connection_stalled)}return n}rpcUnsubscribe(e,t,i){const n={method:rs(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,t){this.setSubscription(e,{...t,id:e}),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,{...t}),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,{...t}),this.topicMap.set(t.topic,e),this.events.emit(Ae.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=D("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(Ae.deleted,{...i,reason:t})}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ae.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const n=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(Ae.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(t=>{var i;return t.topic===((i=this.subscriptions.get(t.id))==null?void 0:i.topic)})){const{message:t}=D("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(e.length){if(!await this.rpcBatchSubscribe(e)){this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),e.forEach(t=>{this.pending.set(t.topic,t)});return}this.onBatchSubscribe(await Promise.all(e.map(async t=>({...t,id:await this.getSubscriptionId(t.topic)}))))}}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await of(U.toMiliseconds(U.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Ue(e+await this.getClientId())}},Jg=class extends Dp{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Ct.EventEmitter,this.name=_g,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=U.toMiliseconds(U.THIRTY_SECONDS+U.FIVE_SECONDS),this.reconnectInProgress=!1,this.requestsInFlight=[],this.connectTimeout=U.toMiliseconds(U.ONE_SECOND*15),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,this.stalledRestartBaseInterval=U.toMiliseconds(U.ONE_SECOND*2),this.stalledRestartMaxInterval=U.toMiliseconds(U.THIRTY_SECONDS),this.request=async t=>{var n,r;this.logger.debug("Publishing Request Payload");const i=t.id||jt().toString();await this.toEstablishConnection();try{this.logger.trace({id:i,method:t.method,topic:(n=t.params)==null?void 0:n.topic},"relayer.request - publishing...");const o=`${i}:${((r=t.params)==null?void 0:r.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${i}`),o}},this.resetPingTimeout=()=>{bi()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,n,r;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(r=(n=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null?void 0:n.terminate)==null||r.call(n)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))},this.onPayloadHandler=t=>{this.onProviderPayload(t),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.stalledRestartBackoff=0,this.events.emit(te.connect)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(te.error,t),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))},this.registerProviderListeners=()=>{this.provider.on(Ce.payload,this.onPayloadHandler),this.provider.on(Ce.connect,this.onConnectHandler),this.provider.on(Ce.disconnect,this.onDisconnectHandler),this.provider.on(Ce.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=cr({logger:e.logger??Ig,name:this.name}),this.messages=new Wg(this.logger,e.core),this.subscriber=new Qg(this,this.logger),this.publisher=new Zg(this,this.logger),this.projectId=e.projectId,this.relayUrl=e.relayUrl||Uc,Kd()?this.packageName=to():Vd()&&(this.bundleId=to()),this.provider={}}
12async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e==null?void 0:e.message))}get context(){return Ne(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:J.relay},ui.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,t){var a,c;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const i=((a=t==null?void 0:t.internal)==null?void 0:a.throwOnFailedPublish)??!0;let n=((c=this.subscriber.topicMap.get(e))==null?void 0:c[0])||"",r;const o=h=>{h.topic===e&&(this.subscriber.off(Ae.created,o),r())};return await Promise.all([new Promise(h=>{r=h,this.subscriber.on(Ae.created,o)}),new Promise((h,l)=>{this.subscriber.subscribe(e,{internal:{throwOnFailedPublish:i},...t}).then(u=>{n=u||n,h()}).catch(u=>{i?l(u):h()})})]),n}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await He(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(e){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=this.connect(e).finally(()=>{this.connectPromise=void 0}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.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 Eo())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+(n==null?void 0:n.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const n=se(U.FIVE_MINUTES),r={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,r)}this.events.emit(te.message,e),await this.recordMessageEvent(e,ui.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.transportExplicitlyClosed=!1;let t=1;try{for(;t<6;){this.connectionAttemptInProgress=!0;try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise((i,n)=>{const r=()=>
vendor: 17,569 bytes, line 12
12{n(new Error("Connection interrupted while trying to connect"))};this.provider.once(Ce.disconnect,r),He(this.provider.connect(),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).then(()=>i()).catch(n).finally(()=>{this.provider.off(Ce.disconnect,r),clearTimeout(this.reconnectTimeout)})}),await new Promise((i,n)=>{const r=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ce.disconnect,r),this.subscriber.start().then(i).catch(n).finally(()=>{this.provider.off(Ce.disconnect,r)})}),this.hasExperiencedNetworkDisruption=!1}catch(i){await this.subscriber.stop();const n=i;this.logger.warn({},n.message),this.hasExperiencedNetworkDisruption=!0}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(i=>setTimeout(i,U.toMiliseconds(t*1))),t++}}finally{this.connectionAttemptInProgress=!1,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}}startPingTimeout(){var e,t,i;if(bi())try{(i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null||i.on("ping",()=>{this.resetPingTimeout()}),this.resetPingTimeout()}catch(n){this.logger.warn(n,n==null?void 0:n.message)}}async createProvider(){if(this.provider.connection&&(this.unregisterProviderListeners(),this.connected))try{await He(this.provider.disconnect(),1e3,"Closing previous provider")}catch{}const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Dn(new ph(Zd({sdkVersion:kn,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:i,message:n}=e;await this.messages.set(i,n,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const n=this.messages.has(t,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Ln(e)){if(!e.method.endsWith(xg))return;const t=e.params,{topic:i,message:n,publishedAt:r,attestation:o}=t.data,a={topic:i,message:n,publishedAt:r,transportType:J.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace({type:"event",event:t.id,...a}),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else zn(e)&&this.events.emit(te.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ui.inbound),this.events.emit(te.message,e))}async acknowledgePayload(e){const t=Cs(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Ce.payload,this.onPayloadHandler),this.provider.off(Ce.connect,this.onConnectHandler),this.provider.off(Ce.disconnect,this.onDisconnectHandler),this.provider.off(Ce.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Eo();_p(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(ws.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Pp())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t==null?void 0:t.message)}}),this.events.on(te.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const t=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${t?` in ${t}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(i){this.logger.error(i,i==null?void 0:i.message)}finally{this.stalledRestartInProgress=!1}},t)})}async onProviderDisconnect(){if(clearTimeout(this.pingTimeout),this.events.emit(te.disconnect),!this.reconnectInProgress){this.reconnectInProgress=!0;try{await this.subscriber.stop()}catch(e){this.logger.warn(e,"subscriber.stop() failed during disconnect")}if(!this.subscriber.hasAnyTopics||this.transportExplicitlyClosed){this.reconnectInProgress=!1;return}this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},U.toMiliseconds(Sg))}}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}this.connectPromise=this.connect().finally(()=>{this.connectPromise=void 0}),await this.connectPromise}}},Xt=class extends Lp{constructor(e,t,i,n=nt,r=void 0){super(e,t,i,n),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version=Pg,this.cached=[],this.initialized=!1,this.storagePrefix=nt,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!re(o)?this.map.set(this.getKey(o),o):ep(o)?this.map.set(o.id,o):tp(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},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())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>ag(a[c],o[c]))):this.values),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={...this.getData(o),...a};this.map.set(o,c),await this.persist()},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=Re(t,this.name),this.storagePrefix=n,this.getKey=r}get context(){return Ne(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:n}=D("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=D("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=D("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}};class Xg{constructor(e,t){this.core=e,this.logger=t,this.name=Rg,this.version=Ng,this.events=new jn,this.initialized=!1,this.storagePrefix=nt,this.ignoredPayloadTypes=[wt],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async i=>{this.isInitialized();const n=qn(),r=await this.core.crypto.setSymKey(n),o=se(U.FIVE_MINUTES),a={protocol:kc},c={topic:r,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},h=po({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:n,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(zt.create,c),this.core.expirer.set(r,o),await this.pairings.set(r,c),await this.core.relayer.subscribe(r,{transportType:i==null?void 0:i.transportType,internal:i==null?void 0:i.internal}),{topic:r,uri:h}},this.pair=async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[Qe.pairing_started]}});this.isValidPair(i,n);const{topic:r,symKey:o,relay:a,expiryTimestamp:c,methods:h}=fo(i.uri);n.props.properties.topic=r,n.addTrace(Qe.pairing_uri_validation_success),n.addTrace(Qe.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(r)){if(l=this.pairings.get(r),n.addTrace(Qe.existing_pairing),l.active)throw n.setError(lt.active_pairing_already_exists),new Error(`Pairing already exists: ${r}. Please try again with a new connection URI.`);n.addTrace(Qe.pairing_not_expired)}const u=c||se(U.FIVE_MINUTES),d={topic:r,relay:a,expiry:u,active:!1,methods:h};this.core.expirer.set(r,u),await this.pairings.set(r,d),n.addTrace(Qe.store_new_pairing),i.activatePairing&&await this.activate({topic:r}),this.events.emit(zt.create,d),n.addTrace(Qe.emit_inactive_pairing),this.core.crypto.keychain.has(r)||await this.core.crypto.setSymKey(o,r),n.addTrace(Qe.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(lt.no_internet_connection)}try{await this.core.relayer.subscribe(r,{relay:a})}catch(f){throw n.setError(lt.subscribe_pairing_topic_failure),f}return n.addTrace(Qe.subscribe_pairing_topic_success),d},this.activate=async({topic:i})=>{this.isInitialized();const n=se(U.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=i;if(this.pairings.keys.includes(n)){const r=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Lt();this.events.once(Q("pairing_ping",r),({error:h})=>{h?c(h):a()}),await o()}},this.updateExpiry=async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})},this.updateMetadata=async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",X("USER_DISCONNECTED")),await this.deletePairing(n))},this.formatUriFromPairing=i=>{this.isInitialized();const{topic:n,relay:r,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return po({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:r,expiryTimestamp:o,methods:a})},this.sendRequest=async(i,n,r)=>{const o=Xe(n,r),a=await this.core.crypto.encode(i,o),c=xs[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id},this.sendResult=async(i,n,r)=>{const o=Cs(i,r),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,h=xs[c].res;await this.core.relayer.publish(n,a,h),await this.core.history.resolve(o)},this.sendError=async(i,n,r)=>{const o=Mo(i,r),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,h=xs[c]?xs[c].res:xs.unregistered_method.res;await this.core.relayer.publish(n,a,h),await this.core.history.resolve(o)},this.deletePairing=async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,X("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(n=>et(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))},this.onRelayEventRequest=async i=>{const{topic:n,payload:r}=i;switch(r.method){case"wc_pairingPing":return await this.onPairingPingRequest(n,r);case"wc_pairingDelete":return await this.onPairingDeleteRequest(n,r);default:return await this.onUnknownRpcMethodRequest(n,r)}},this.onRelayEventResponse=async i=>{const{topic:n,payload:r}=i,o=(await this.core.history.get(n,r.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(n,r);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(i,n)=>{const{id:r}=n;try{this.isValidPing({topic:i}),await this.sendResult(r,i,!0),this.events.emit(zt.ping,{id:r,topic:i})}catch(o){await this.sendError(r,i,o),this.logger.error(o)}},this.onPairingPingResponse=(i,n)=>{const{id:r}=n;setTimeout(()=>{ct(n)?this.events.emit(Q("pairing_ping",r),{}):Je(n)&&this.events.emit(Q("pairing_ping",r),{error:n.error})},500)},this.onPairingDeleteRequest=async(i,n)=>{const{id:r}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(zt.delete,{id:r,topic:i})}catch(o){await this.sendError(r,i,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(i,n)=>{const{id:r,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=X("WC_METHOD_UNSUPPORTED",o);await this.sendError(r,i,a),this.logger.error(a)}catch(a){await this.sendError(r,i,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(X("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=(i,n)=>{var o;if(!Ie(i)){const{message:a}=D("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(lt.malformed_pairing_uri),new Error(a)}if(!Xf(i.uri)){const{message:a}=D("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(lt.malformed_pairing_uri),new Error(a)}const r=fo(i==null?void 0:i.uri);if(!((o=r==null?void 0:r.relay)!=null&&o.protocol)){const{message:a}=D("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(lt.malformed_pairing_uri),new Error(a)}if(!(r!=null&&r.symKey)){const{message:a}=D("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(lt.malformed_pairing_uri),new Error(a)}if(r!=null&&r.expiryTimestamp&&U.toMiliseconds(r==null?void 0:r.expiryTimestamp)<Date.now()){n.setError(lt.pairing_expired);const{message:a}=D("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}},this.isValidPing=async i=>{if(!Ie(i)){const{message:r}=D("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(r)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidDisconnect=async i=>{if(!Ie(i)){const{message:r}=D("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(r)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidPairingTopic=async i=>{if(!ie(i,!1)){const{message:n}=D("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=D("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(et(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=D("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}},this.core=e,this.logger=Re(t,this.name),this.pairings=new Xt(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ne(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(te.message,async e=>{const{topic:t,message:i,transportType:n}=e;if(this.pairings.keys.includes(t)&&n!==J.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const r=await this.core.crypto.decode(t,i);Ln(r)?(this.core.history.set(t,r),await this.onRelayEventRequest({topic:t,payload:r})):zn(r)&&(await this.core.history.resolve(r),await this.onRelayEventResponse({topic:t,payload:r}),this.core.history.delete(t,r.id)),await this.core.relayer.messages.ack(t,i)}catch(r){this.logger.error(r)}})}registerExpirerEvents(){this.core.expirer.on(Be.expired,async e=>{const{topic:t}=tc(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(zt.expire,{topic:t}))})}}class ey extends kp{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new Ct.EventEmitter,this.name=Tg,this.version=qg,this.cached=[],this.initialized=!1,this.storagePrefix=nt,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(
vendor: 4,183 bytes, line 12
12),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(i,n,r)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:r}),this.records.has(n.id))return;const o={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:r,expiry:se(U.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Le.created,o)},this.resolve=async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response<"u"||(n.response=Je(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Le.updated,n))},this.get=async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n)),this.delete=(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(r=>{if(r.topic===i){if(typeof n<"u"&&r.id!==n)return;this.records.delete(r.id),this.events.emit(Le.deleted,r)}}),this.persist()},this.exists=async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1),this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=Re(t,this.name)}get context(){return Ne(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:Xe(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=D("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Le.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=D("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Le.created,e=>{const t=Le.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Le.updated,e=>{const t=Le.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Le.deleted,e=>{const t=Le.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(ws.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{U.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Le.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ty extends jp{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new Ct.EventEmitter,this.name=Cg,this.version=Bg,this.cached=[],this.initialized=!1,this.storagePrefix=nt,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(
vendor: 4,183 bytes, line 12
12),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}},this.set=(i,n)=>{this.isInitialized();const r=this.formatTarget(i),o={target:r,expiry:n};this.expirations.set(r,o),this.checkExpiry(r,o),this.events.emit(Be.created,{target:r,expiration:o})},this.get=i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)},this.del=i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),r=this.getExpiration(n);this.expirations.delete(n),this.events.emit(Be.deleted,{target:n,expiration:r})}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=Re(t,this.name)}get context(){return Ne(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return Yd(e);if(typeof e=="number")return Qd(e);const{message:t}=D("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Be.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=D("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:i}=D("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;U.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Be.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(ws.pulse,()=>this.checkExpirations()),this.events.on(Be.created,e=>{const t=Be.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Be.expired,e=>{const t=Be.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Be.deleted,e=>{const t=Be.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}}class sy extends Kp{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,this.name=kg,this.verifyUrlV3=Mg,this.storagePrefix=nt,this.version=Bc,this.init=async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&U.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async n=>{if(!bs()||this.isDevEnv)return;const r=window.location.origin,{id:o,decryptedId:a}=n,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${r}&id=${o}&decryptedId=${a}`;try{const h=ps(),l=this.startAbortTimer(U.ONE_SECOND*5),u=await new Promise((d,f)=>{const y=()=>{window.removeEventListener("message",b),h.body.removeChild(g),f("attestation aborted")};this.abortController.signal.addEventListener("abort",y);const g=h.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",y,{signal:this.abortController.signal});const b=A=>
vendor: 4,146 bytes, line 12
12{if(A.data&&typeof A.data=="string")try{const L=JSON.parse(A.data);if(L.type==="verify_attestation"){if(yn(L.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(g),this.abortController.signal.removeEventListener("abort",y),window.removeEventListener("message",b),d(L.attestation===null?"":L.attestation)}}catch(L){this.logger.warn(L)}};h.body.appendChild(g),window.addEventListener("message",b,{signal:this.abortController.signal})});return this.logger.debug(u,"jwt attestation"),u}catch(h){this.logger.warn(h)}return""},this.resolve=async n=>{if(this.isDevEnv)return"";const{attestationId:r,hash:o,encryptedId:a}=n;if(r===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(r){if(yn(r).payload.id!==a)return;const h=await this.isValidJwtAttestation(r);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(n==null?void 0:n.verifyUrl);return this.fetchAttestation(o,c)},this.fetchAttestation=async(n,r)=>{this.logger.debug(`resolving attestation: ${n} from url: ${r}`);const o=this.startAbortTimer(U.ONE_SECOND*5),a=await fetch(`${r}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0},this.getVerifyUrl=n=>{let r=n||qs;return Dg.includes(r)||(this.logger.info(`verify url: ${r}, not included in trusted list, assigning default: ${qs}`),r=qs),r},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(U.FIVE_SECONDS),r=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await r.json()}catch(n){this.logger.warn(n)}},this.persistPublicKey=async n=>{this.logger.debug(n,"persisting public key to local storage"),await this.store.setItem(this.storeKey,n),this.publicKey=n},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async n=>{const r=await this.getPublicKey();try{if(r)return this.validateAttestation(n,r)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(n,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async r=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),r(o))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n},this.validateAttestation=(n,r)=>{const o=Lf(n,r.publicKey),a={hasExpired:U.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=Re(t,this.name),this.abortController=new AbortController,this.isDevEnv=rr(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ne(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),U.toMiliseconds(e))}}class iy extends Vp{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context=Lg,this.registerDeviceToken=async i=>{const{clientId:n,token:r,notificationType:o,enableEncrypted:a=!1}=i,c=`${zg}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:o,token:r,always_raw:a})})},this.logger=Re(t,this.context)}}let ny=class extends Hp{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,this.context=Kg,this.storagePrefix=nt,this.storageVersion=jg,this.events=new Map,this.shouldPersist=!1,this.init=async()=>
12{if(!rr())try{const n={eventId:io(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Xa(this.core.relayer.protocol,this.core.relayer.version,kn)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}},this.createEvent=n=>{const{event:r="ERROR",type:o="",properties:{topic:a,trace:c}}=n,h=io(),l=this.core.projectId||"",u=Date.now(),d={eventId:h,timestamp:u,props:{event:r,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain(),...this.setMethods(h)};return this.telemetryEnabled&&(this.events.set(h,d),this.shouldPersist=!0),d},this.getEvent=n=>{const{eventId:r,topic:o}=n;if(r)return this.events.get(r);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return{...a,...this.setMethods(a.eventId)}},this.deleteEvent=n=>{const{eventId:r}=n;this.events.delete(r),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(ws.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{U.fromMiliseconds(Date.now())-U.fromMiliseconds(n.timestamp)>Vg&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})},this.setMethods=n=>({addTrace:r=>this.addTrace(n,r),setError:r=>this.setError(n,r)}),this.addTrace=(n,r)=>{const o=this.events.get(n);o&&(o.props.properties.trace.push(r),this.events.set(n,o),this.shouldPersist=!0)},this.setError=(n,r)=>{const o=this.events.get(n);o&&(o.props.type=r,o.timestamp=Date.now(),this.events.set(n,o),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(r=>{this.events.set(r.eventId,{...r,...this.setMethods(r.eventId)})})}catch(n){this.logger.warn(n)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[r,o]of this.events)o.props.type&&n.push(o);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const r of n)this.events.delete(r.eventId),this.shouldPersist=!0}catch(r){this.logger.warn(r)}},this.sendEvent=async n=>{const r=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Hg}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${kn}${r}`,{method:"POST",body:JSON.stringify(n)})},this.getAppDomain=()=>Ja().url,this.logger=Re(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}},ry=class Dc extends Bp{constructor(e){var o;super(e),this.protocol=Cc,this.version=Bc,this.name=Bn,this.events=new Ct.EventEmitter,this.initialized=!1,this.on=(a,c)=>this.events.on(a,c),this.once=(a,c)=>this.events.once(a,c),this.off=(a,c)=>this.events.off(a,c),this.removeListener=(a,c)=>this.events.removeListener(a,c),this.dispatchEnvelope=({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:J.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})};const t=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(t)try{return this.customStoragePrefix=t.customStoragePrefix,this.logger=t.logger,this.heartbeat=t.heartbeat,this.crypto=t.crypto,this.history=t.history,this.expirer=t.expirer,this.storage=t.storage,this.relayer=t.relayer,this.pairing=t.pairing,this.verify=t.verify,this.echoClient=t.echoClient,this.linkModeSupportedApps=t.linkModeSupportedApps,this.eventClient=t.eventClient,this.initialized=t.initialized,this.logChunkController=t.logChunkController,t}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Uc,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=ch({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:dg.logger,name:Bn}),{logger:n,chunkLoggerController:r}=ko({opts:i,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=r,(o=this.logChunkController)!=null&&o.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=Re(n,this.name),this.heartbeat=new hh,this.crypto=new Gg(this,this.logger,e==null?void 0:e.keychain),this.history=new ey(this,this.logger),this.expirer=new ty(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new lh({...fg,...e==null?void 0:e.storageOptions}),this.relayer=new Jg({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Xg(this,this.logger),this.verify=new sy(this,this.logger,this.storage),this.echoClient=new iy(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new ny(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Dc(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(Ag,i),t}get context(){return Ne(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Po,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(
vendor: 63,155 bytes, line 12
12),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(Po)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,i=`${t}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[t]}catch(t){console.warn("Failed to get global WalletConnect core",t);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((t=e.opts)==null?void 0:t.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof $s<"u"&&ug.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const oy=ry,Lc="wc",zc=2,jc="client",pr=`${Lc}@${zc}:${jc}:`,ln={name:jc,logger:"error"},Ao="WALLETCONNECT_DEEPLINK_CHOICE",ay="proposal",Oo="Proposal expired",cy="session",is=U.SEVEN_DAYS,hy="engine",he={wc_sessionPropose:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1104},res:{ttl:U.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1106},res:{ttl:U.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:U.FIVE_MINUTES*3,prompt:!0,tag:1108},res:{ttl:U.FIVE_MINUTES*3,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1112},res:{ttl:U.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1114},res:{ttl:U.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:U.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:U.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1119}}},un={min:U.FIVE_MINUTES,max:U.SEVEN_DAYS},Ye={idle:"IDLE",active:"ACTIVE"},ly={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:""}},uy="request",dy=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],fy="wc",py="auth",gy="authKeys",yy="pairingTopics",my="requests",Mi=`${fy}@${1.5}:${py}:`,Pt=`${Mi}:PUB_KEY`;class wy extends Gp{constructor(e){super(e),this.name=hy,this.events=new jn,this.initialized=!1,this.requestQueue={state:Ye.idle,queue:[]},this.sessionRequestQueue={state:Ye.idle,queue:[]},this.emittedSessionRequests=new af({limit:500}),this.requestQueueDelay=U.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.pendingSessions=new Map,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.registerSubscriptionCleanup(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(he)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay)))},this.connect=async t=>{var B;this.isInitialized(),await this.confirmOnlineStateOrThrow();const i={...t,requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}};await this.isValidConnect(i),i.optionalNamespaces=Yf(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:n,requiredNamespaces:r,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h,authentication:l,walletPay:u}=i,d=((B=l==null?void 0:l[0])==null?void 0:B.ttl)||he.wc_sessionPropose.req.ttl||U.FIVE_MINUTES;this.validateRequestExpiry(d);let f=n,y,g=!1;try{if(f){const S=this.client.core.pairing.pairings.get(f);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),g=S.active}}catch(S){throw this.client.logger.error(`connect() -> pairing.get(${f}) failed`),S}if(!f||!g){const{topic:S,uri:T}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});f=S,y=T}if(!f){const{message:S}=D("NO_MATCHING_KEY",`connect() pairing topic: ${f}`);throw new Error(S)}const b=await this.client.core.crypto.generateKeyPair(),A=se(d),L={requiredNamespaces:r,optionalNamespaces:o,relays:h??[{protocol:kc}],proposer:{publicKey:b,metadata:this.client.metadata},expiryTimestamp:A,pairingTopic:f,...a&&{sessionProperties:a},...c&&{scopedProperties:c},id:bt(),...(l||u)&&{requests:{authentication:l==null?void 0:l.map(S=>{const{domain:T,chains:C,nonce:$,uri:m,exp:E,nbf:p,type:w,statement:I,requestId:P,resources:v,signatureTypes:_}=S;return{domain:T,chains:C,nonce:$,type:w??"caip122",aud:m,version:"1",iat:new Date().toISOString(),exp:E,nbf:p,statement:I,requestId:P,resources:v,signatureTypes:_}}),walletPay:u}}},O=Q("session_connect",L.id),{reject:x,resolve:N,done:q}=Lt(d,Oo),k=({id:S})=>{if(S===L.id){this.client.events.off("proposal_expire",k);const T=this.pendingSessions.get(L.id);if(T){const{sessionTopic:C,publicKey:$}=T;Promise.all([this.client.core.relayer.unsubscribe(C),this.client.core.crypto.keychain.has(C)?this.client.core.crypto.deleteSymKey(C):Promise.resolve(),this.client.core.crypto.keychain.has($)?this.client.core.crypto.deleteKeyPair($):Promise.resolve()]).catch(m=>this.client.logger.warn(m))}this.pendingSessions.delete(L.id),this.events.emit(O,{error:{message:Oo,code:0}})}};return this.client.events.on("proposal_expire",k),this.events.once(O,({error:S,session:T})=>{this.client.events.off("proposal_expire",k),S?x(S):T&&N(T)}),await this.setProposal(L.id,L),await this.sendProposeSession({proposal:L,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:L.id}}}).catch(S=>{throw this.deleteProposal(L.id),S}),{uri:y,approval:q}},this.pair=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}},this.approve=async t=>{var k,B,S;const i=this.client.core.eventClient.createEvent({properties:{topic:(k=t==null?void 0:t.id)==null?void 0:k.toString(),trace:[ze.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(T){throw i.setError(Mt.no_internet_connection),T}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(T){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),i.setError(Mt.proposal_not_found),T}try{await this.isValidApprove(t)}catch(T){throw this.client.logger.error("approve() -> isValidApprove() failed"),i.setError(Mt.session_approve_namespace_validation_failure),T}const{id:n,relayProtocol:r,namespaces:o,sessionProperties:a,scopedProperties:c,sessionConfig:h,proposalRequestsResponses:l}=t,u=this.client.proposal.get(n);this.client.core.eventClient.deleteEvent({eventId:i.eventId});const{pairingTopic:d,proposer:f,requiredNamespaces:y,optionalNamespaces:g}=u;let b=(B=this.client.core.eventClient)==null?void 0:B.getEvent({topic:d});b||(b=(S=this.client.core.eventClient)==null?void 0:S.createEvent({type:ze.session_approve_started,properties:{topic:d,trace:[ze.session_approve_started,ze.session_namespaces_validation_success]}}));const A=await this.client.core.crypto.generateKeyPair(),L=f.publicKey,O=await this.client.core.crypto.generateSharedKey(A,L),x={relay:{protocol:r??"irn"},namespaces:o,controller:{publicKey:A,metadata:this.client.metadata},expiry:se(is),...a&&{sessionProperties:a},...c&&{scopedProperties:c},...h&&{sessionConfig:h},proposalRequestsResponses:l},N=J.relay;b.addTrace(ze.subscribing_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:N,internal:{skipSubscribe:!0}})}catch(T){throw b.setError(Mt.subscribe_session_topic_failure),T}b.addTrace(ze.subscribe_session_topic_success);const q={...x,topic:O,requiredNamespaces:y,optionalNamespaces:g,pairingTopic:d,acknowledged:!1,self:x.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:A,transportType:J.relay,authentication:l==null?void 0:l.authentication,walletPayResult:l==null?void 0:l.walletPay};await this.client.session.set(O,q),b.addTrace(ze.store_session);try{await this.sendApproveSession({sessionTopic:O,proposal:u,pairingProposalResponse:{relay:{protocol:r??"irn"},responderPublicKey:A},sessionSettleRequest:x,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:n,...this.getTVFApproveParams(q)}}}),b.addTrace(ze.session_approve_publish_success)}catch(T){throw this.client.logger.error(T),this.client.session.delete(O,X("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(O),T}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:d,metadata:f.metadata}),await this.deleteProposal(n),await this.client.core.pairing.activate({topic:d}),await this.setExpiry(O,se(is)),{topic:O,acknowledged:()=>Promise.resolve(this.client.session.get(O))}},this.reject=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:n}=t;let r;try{r=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}r&&await this.sendError({id:i,topic:r,error:n,rpcOpts:he.wc_sessionPropose.reject}),await this.deleteProposal(i)},this.update=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:i,namespaces:n}=t,{done:r,resolve:o,reject:a}=Lt(U.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=bt(),h=jt().toString(),l=this.client.session.get(i).namespaces;return this.events.once(Q("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(u=>{this.client.logger.error(u),this.client.session.update(i,{namespaces:l}),a(u)}),{acknowledged:r}},this.extend=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=t,n=bt(),{done:r,resolve:o,reject:a}=Lt(U.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(Q("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,se(is)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:r}},this.request=async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:i,request:n,topic:r,expiry:o=he.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(r);(a==null?void 0:a.transportType)===J.relay&&await this.confirmOnlineStateOrThrow();const c=bt(),h=jt().toString(),{done:l,resolve:u,reject:d}=Lt(o,"Request expired. Please try again.");this.events.once(Q("session_request",c),({error:b,result:A})=>{b?d(b):u(A)});const f="wc_sessionRequest",y=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(y)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:r,method:f,params:{request:{...n,expiryTimestamp:se(o)},chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:y}).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:r,request:n,chainId:i,id:c}),await l();const g={request:{...n,expiryTimestamp:se(o)},chainId:i};return await Promise.all([new Promise(async b=>{await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:r,method:f,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(A=>d(A)),this.client.events.emit("session_request_sent",{topic:r,request:n,chainId:i,id:c}),b()}),new Promise(async b=>{var A;if(!((A=a.sessionConfig)!=null&&A.disableDeepLink)){const L=await tf(this.client.core.storage,Ao);await Jd({id:c,topic:r,wcDeepLink:L})}b()}),l()]).then(b=>b[2])},this.respond=async t=>{var h,l;this.isInitialized();const i=this.client.core.eventClient.createEvent({properties:{topic:(t==null?void 0:t.topic)||((l=(h=t==null?void 0:t.response)==null?void 0:h.id)==null?void 0:l.toString()),trace:[ze.session_request_response_started]}});try{await this.isValidRespond(t)}catch(u){throw i.addTrace(u==null?void 0:u.message),i.setError(Mt.session_request_response_validation_failure),u}i.addTrace(ze.session_request_response_validation_success);const{topic:n,response:r}=t,{id:o}=r,a=this.client.session.get(n);a.transportType===J.relay&&await this.confirmOnlineStateOrThrow();const c=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);try{i.addTrace(ze.session_request_response_publish_started),ct(r)?await this.sendResult({id:o,topic:n,result:r.result,throwOnFailedPublish:!0,appLink:c}):Je(r)&&await this.sendError({id:o,topic:n,error:r.error,appLink:c}),this.cleanupAfterResponse(t)}catch(u){throw i.addTrace(u==null?void 0:u.message),i.setError(Mt.session_request_response_publish_failure),u}},this.ping=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=t;if(this.client.session.keys.includes(i)){const n=bt(),r=jt().toString(),{done:o,resolve:a,reject:c}=Lt(U.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(Q("session_ping",n),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:r}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(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:i}))},this.emit=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:n,chainId:r}=t,o=jt().toString(),a=bt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:r},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})},this.disconnect=async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:X("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=D("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}},this.find=t=>(this.isInitialized(),this.client.session.getAll().filter(i=>Qf(i,t))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(t,i)=>{var P;this.isInitialized(),this.isValidAuthenticate(t);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((P=this.client.metadata.redirect)==null?void 0:P.linkMode),r=n?J.link_mode:J.relay;r===J.relay&&await this.confirmOnlineStateOrThrow();const{chains:o,statement:a="",uri:c,domain:h,nonce:l,type:u,exp:d,nbf:f,methods:y=[],expiry:g}=t,b=[...t.resources||[]],{topic:A,uri:L}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:r});if(this.client.logger.info({message:"Generated new pairing",pairing:{topic:A,uri:L}}),this.client.auth.authKeys.keys.includes(Pt)){const{responseTopic:v,publicKey:_}=this.client.auth.authKeys.get(Pt);v&&(await this.client.core.relayer.unsubscribe(v).catch(R=>this.client.logger.warn(R)),await this.client.auth.pairingTopics.delete(v,{message:"replaced",code:0}).catch(R=>this.client.logger.warn(R))),_&&this.client.core.crypto.keychain.has(_)&&await this.client.core.crypto.deleteKeyPair(_)}const O=await this.client.core.crypto.generateKeyPair(),x=hi(O);if(await Promise.all([this.client.auth.authKeys.set(Pt,{responseTopic:x,publicKey:O}),this.client.auth.pairingTopics.set(x,{topic:x,pairingTopic:A})]),await this.client.core.relayer.subscribe(x,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${A}`),y.length>0){const{namespace:v}=mt(o[0]);let _=Pf(v,"request",y);ci(b)&&(_=Of(_,b.pop())),b.push(_)}const N=g&&g>he.wc_sessionAuthenticate.req.ttl?g:he.wc_sessionAuthenticate.req.ttl,q={authPayload:{type:u??"caip122",chains:o,statement:a,aud:c,domain:h,version:"1",nonce:l,iat:new Date().toISOString(),exp:d,nbf:f,resources:b},requester:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:se(N)},k={eip155:{chains:o,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},B={requiredNamespaces:{},optionalNamespaces:k,relays:[{protocol:"irn"}],pairingTopic:A,proposer:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:se(he.wc_sessionPropose.req.ttl),id:bt()},{done:S,resolve:T,reject:C}=Lt(N,"Request expired"),$=bt(),m=Q("session_connect",B.id),E=Q("session_request",$),p=async({error:v,session:_})=>{this.events.off(E,w),v?C(v):_&&T({session:_})},w=async v=>{var F,G,Z;if(await this.deletePendingAuthRequest($,{message:"fulfilled",code:0}),v.error){const H=X("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return v.error.code===H.code?void 0:(this.events.off(m,p),C(v.error.message))}await this.deleteProposal(B.id),this.events.off(m,p);const{cacaos:_,responder:R}=v.result,M=[],V=[];for(const H of _){await oo({cacao:H,projectId:this.client.core.projectId})||(this.client.logger.error(H,"Signature verification failed"),C(X("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Y}=H,ve=ci(Y.resources),Ee=[Tn(Y.iss)],ye=vi(Y.iss);if(ve){const Te=ao(ve),We=co(ve);M.push(...Te),Ee.push(...We)}for(const Te of Ee)V.push(`${Te}:${ye}`)}const K=await this.client.core.crypto.generateSharedKey(O,R.publicKey);let j;M.length>0&&(j={topic:K,acknowledged:!0,self:{publicKey:O,metadata:this.client.metadata},peer:R,controller:R.publicKey,expiry:se(is),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:A,namespaces:yo([...new Set(M)],[...new Set(V)]),transportType:r},await this.client.core.relayer.subscribe(K,{transportType:r}),await this.client.session.set(K,j),A&&await this.client.core.pairing.updateMetadata({topic:A,metadata:R.metadata}),j=this.client.session.get(K)),(F=this.client.metadata.redirect)!=null&&F.linkMode&&((G=R.metadata.redirect)!=null&&G.linkMode)&&((Z=R.metadata.redirect)!=null&&Z.universal)&&i&&(this.client.core.addLinkModeSupportedApp(R.metadata.redirect.universal),this.client.session.update(K,{transportType:J.link_mode})),T({auths:_,session:j})};this.events.once(m,p),this.events.once(E,w);let I;try{if(n){const v=Xe("wc_sessionAuthenticate",q,$);this.client.core.history.set(A,v);const _=await this.client.core.crypto.encode("",v,{type:Ys,encoding:Rt});I=ni(i,A,_)}else await Promise.all([this.sendRequest({topic:A,method:"wc_sessionAuthenticate",params:q,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:$}),this.sendRequest({topic:A,method:"wc_sessionPropose",params:B,expiry:he.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:B.id})])}catch(v){throw this.events.off(m,p),this.events.off(E,w),v}return await this.setProposal(B.id,B),await this.setAuthRequest($,{request:{...q,verifyContext:{}},pairingTopic:A,transportType:r}),{uri:I??L,response:S}},this.approveSessionAuthenticate=async t=>{const{id:i,auths:n}=t,r=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Dt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(b){throw r.setError(Ss.no_internet_connection),b}const o=this.getPendingAuthRequest(i);if(!o)throw r.setError(Ss.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||J.relay;a===J.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=hi(c),u={type:wt,receiverPublicKey:c,senderPublicKey:h},d=[],f=[];for(const b of n){if(!await oo({cacao:b,projectId:this.client.core.projectId})){r.setError(Ss.invalid_cacao);const N=X("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:l,error:N,encodeOpts:u}),new Error(N.message)}r.addTrace(Dt.cacaos_verified);const{p:A}=b,L=ci(A.resources),O=[Tn(A.iss)],x=vi(A.iss);if(L){const N=ao(L),q=co(L);d.push(...N),O.push(...q)}for(const N of O)f.push(`${N}:${x}`)}const y=await this.client.core.crypto.generateSharedKey(h,c);r.addTrace(Dt.create_authenticated_session_topic);let g;if((d==null?void 0:d.length)>0){g={topic:y,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:se(is),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:yo([...new Set(d)],[...new Set(f)]),transportType:a},r.addTrace(Dt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(y,{transportType:a})}catch(b){throw r.setError(Ss.subscribe_authenticated_session_topic_failure),b}r.addTrace(Dt.subscribe_authenticated_session_topic_success),await this.client.session.set(y,g),r.addTrace(Dt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}r.addTrace(Dt.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:i,result:{cacaos:n,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(b){throw r.setError(Ss.authenticated_session_approve_publish_failure),b}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:r.eventId}),{session:g}},this.rejectSessionAuthenticate=async t=>{this.isInitialized();const{id:i,reason:n}=t,r=this.getPendingAuthRequest(i);if(!r)throw new Error(`Could not find pending auth request with id ${i}`);r.transportType===J.relay&&await this.confirmOnlineStateOrThrow();const o=r.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=hi(o),h={type:wt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:n,encodeOpts:h,rpcOpts:he.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(r.requester.metadata,r.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.deleteProposal(i)},this.formatAuthMessage=t=>{this.isInitialized();const{request:i,iss:n}=t;return rc(i,n)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)},this.cleanupDuplicatePairings=async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(r=>{var o,a;return((o=r.peerMetadata)==null?void 0:o.url)&&((a=r.peerMetadata)==null?void 0:a.url)===t.peer.metadata.url&&r.topic&&r.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(r=>this.client.core.pairing.disconnect({topic:r.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}},this.deleteSession=async t=>{var c;const{topic:i,expirerHasDeleted:n=!1,emitEvent:r=!0,id:o=0}=t,{self:a}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,X("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(a.publicKey)&&await this.client.core.crypto.deleteKeyPair(a.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),n||this.client.core.expirer.del(i),this.client.core.storage.removeItem(Ao).catch(h=>this.client.logger.warn(h)),i===((c=this.sessionRequestQueue.queue[0])==null?void 0:c.topic)&&(this.sessionRequestQueue.state=Ye.idle),await Promise.all(this.getPendingSessionRequests().filter(h=>h.topic===i).map(h=>this.deletePendingSessionRequest(h.id,X("USER_DISCONNECTED")))),r&&this.client.events.emit("session_delete",{id:o,topic:i})},this.deleteProposal=async(t,i)=>{var n;if(i)try{const r=this.client.proposal.get(t);(n=this.client.core.eventClient.getEvent({topic:r.pairingTopic}))==null||n.setError(Mt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,X("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")},this.deletePendingSessionRequest=async(t,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),n?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(r=>r.id!==t),n&&(this.sessionRequestQueue.state=Ye.idle,this.client.events.emit("session_request_expire",{id:t}))},this.deletePendingAuthRequest=async(t,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),n?Promise.resolve():this.client.core.expirer.del(t)])},this.setExpiry=async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))},this.setProposal=async(t,i)=>{this.client.core.expirer.set(t,se(he.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)},this.setAuthRequest=async(t,i)=>{const{request:n,pairingTopic:r,transportType:o=J.relay}=i;this.client.core.expirer.set(t,n.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:t,pairingTopic:r,verifyContext:n.verifyContext,transportType:o})},this.setPendingSessionRequest=async t=>{const{id:i,topic:n,params:r,verifyContext:o}=t,a=r.request.expiryTimestamp||se(he.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:n,params:r,verifyContext:o})},this.sendRequest=async t=>{const{topic:i,method:n,params:r,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:u,publishOpts:d={}}=t,f=Xe(n,r,c);let y;const g=!!l;try{const L=g?Rt:le;y=await this.client.core.crypto.encode(i,f,{encoding:L})}catch(L){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),L}let b;if(dy.includes(n)){const L=Ue(JSON.stringify(f)),O=Ue(y);b=await this.client.core.verify.register({id:O,decryptedId:L})}const A={...he[n].req,...d};if(A.attestation=b,o&&(A.ttl=o),a&&(A.id=a),this.client.core.history.set(i,f),g){const L=ni(l,i,y);await globalThis.Linking.openURL(L,this.client.name)}else A.tvf={...u,correlationId:f.id},h?(A.internal={...A.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(i,y,A)):this.client.core.relayer.publish(i,y,A).catch(L=>this.client.logger.error(L));return f.id},this.sendProposeSession=async t=>{const{proposal:i,publishOpts:n}=t,r=Xe("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,r);const o=await this.client.core.crypto.encode(i.pairingTopic,r,{encoding:le}),a=Ue(JSON.stringify(r)),c=Ue(o),h=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:i.pairingTopic,sessionProposal:o},opts:{...n,publishMethod:"wc_proposeSession",attestation:h}})},this.sendApproveSession=async t=>{const{sessionTopic:i,pairingProposalResponse:n,proposal:r,sessionSettleRequest:o,publishOpts:a}=t,c=Cs(r.id,n),h=await this.client.core.crypto.encode(r.pairingTopic,c,{encoding:le}),l=Xe("wc_sessionSettle",o,a==null?void 0:a.id),u=await this.client.core.crypto.encode(i,l,{encoding:le});this.client.core.history.set(i,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:r.pairingTopic,sessionProposalResponse:h,sessionSettlementRequest:u},opts:{...a,publishMethod:"wc_approveSession"}})},this.sendResult=async t=>{const{id:i,topic:n,result:r,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=Cs(i,r);let l;const u=c&&typeof(globalThis==null?void 0:globalThis.Linking)<"u";try{const y=u?Rt:le;l=await this.client.core.crypto.encode(n,h,{...a||{},encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),y}let d,f;try{d=await this.client.core.history.get(n,i);const y=d.request;try{f=this.getTVFParams(i,y.params,r)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g==null?void 0:g.message}`)}}catch(y){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),y}if(u){const y=ni(c,n,l);await globalThis.Linking.openURL(y,this.client.name)}else{const y=d.request.method,g=he[y].res;g.tvf={...f,correlationId:i},o?(g.internal={...g.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(n,l,g)):this.client.core.relayer.publish(n,l,g).catch(b=>this.client.logger.error(b))}await this.client.core.history.resolve(h)},this.sendError=async t=>{const{id:i,topic:n,error:r,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=Mo(i,r);let l;const u=c&&typeof(globalThis==null?void 0:globalThis.Linking)<"u";try{const f=u?Rt:le;l=await this.client.core.crypto.encode(n,h,{...o||{},encoding:f})}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),f}let d;try{d=await this.client.core.history.get(n,i)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),f}if(u){const f=ni(c,n,l);await globalThis.Linking.openURL(f,this.client.name)}else{const f=d.request.method,y=a||he[f].res;this.client.core.relayer.publish(n,l,y)}await this.client.core.history.resolve(h)},this.cleanup=async()=>{const t=[],i=[];this.client.session.getAll().forEach(n=>{let r=!1;et(n.expiry)&&(r=!0),this.client.core.crypto.keychain.has(n.topic)||(r=!0),r&&t.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{et(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...t.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])},this.onProviderMessageEvent=async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)},this.onRelayEventRequest=async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===Ye.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=Ye.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Ye.idle},this.processRequest=async t=>{const{topic:i,payload:n,attestation:r,transportType:o,encryptedId:a}=t,c=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:r,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:r,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:r,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}},this.onRelayEventResponse=async t=>{const{topic:i,payload:n,transportType:r}=t,o=(await this.client.core.history.get(i,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,r);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onRelayEventUnknownPayload=t=>{const{topic:i}=t,{message:n}=D("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)},this.shouldIgnorePairingRequest=t=>{const{topic:i,requestMethod:n}=t,r=this.expectedPairingMethodMap.get(i);return!r||r.includes(n)?!1:!!(r.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async t=>{const{topic:i,payload:n,attestation:r,encryptedId:o}=t,{params:a,id:c}=n;try{const h=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),h==null||h.setError(lt.proposal_listener_not_found)),this.isValidConnect({...n.params});const l=a.expiryTimestamp||se(he.wc_sessionPropose.req.ttl),u={id:c,pairingTopic:i,expiryTimestamp:l,attestation:r,encryptedId:o,...a};await this.setProposal(c,u);const d=await this.getVerifyContext({attestationId:r,hash:Ue(JSON.stringify(n)),encryptedId:o,metadata:u.proposer.metadata});h==null||h.addTrace(Qe.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:d})}catch(h){await this.sendError({id:c,topic:i,error:h,rpcOpts:he.wc_sessionPropose.autoReject}),this.client.logger.error(h)}},this.onSessionProposeResponse=async(t,i,n)=>{const{id:r}=i;if(ct(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(r);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 h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(c,h);this.pendingSessions.set(r,{sessionTopic:l,pairingTopic:t,proposalId:r,publicKey:c});const u=await this.client.core.relayer.subscribe(l,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(Je(i)){await this.deleteProposal(r);const o=Q("session_connect",r);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}},this.onSessionSettleRequest=async(t,i)=>{const{id:n,params:r}=i;try{this.isValidSessionSettleRequest(r);const{relay:o,controller:a,expiry:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:d,proposalRequestsResponses:f}=i.params,y=[...this.pendingSessions.values()].find(A=>A.sessionTopic===t);if(!y)return this.client.logger.error(`Pending session not found for topic ${t}`);const g=this.client.proposal.get(y.proposalId),b={topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:y.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:y.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata},...l&&{sessionProperties:l},...u&&{scopedProperties:u},...d&&{sessionConfig:d},transportType:J.relay,authentication:f==null?void 0:f.authentication,walletPayResult:f==null?void 0:f.walletPay};await this.client.session.set(b.topic,b),await this.setExpiry(b.topic,b.expiry),await this.client.core.pairing.updateMetadata({topic:y.pairingTopic,metadata:b.peer.metadata}),this.pendingSessions.delete(y.proposalId),this.deleteProposal(y.proposalId,!1),this.cleanupDuplicatePairings(b),await this.sendResult({id:i.id,topic:t,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:b}),this.events.emit(Q("session_connect",y.proposalId),{session:b})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}},this.onSessionSettleResponse=async(t,i)=>{const{id:n}=i;ct(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Q("session_approve",n),{})):Je(i)&&(await this.deleteSession({topic:t,emitEvent:!1}),this.events.emit(Q("session_approve",n),{error:i.error}))},this.onSessionUpdateRequest=async(t,i)=>{const{params:n,id:r}=i;try{const o=`${t}_session_update`,a=_s.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.warn(`Discarding out of sync request - ${r}`),this.sendError({id:r,topic:t,error:X("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate({topic:t,...n});try{_s.set(o,r),await this.client.session.update(t,{namespaces:n.namespaces}),await this.sendResult({id:r,topic:t,result:!0})}catch(c){throw _s.delete(o),c}this.client.events.emit("session_update",{id:r,topic:t,params:n})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}},this.isRequestOutOfSync=(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3),this.onSessionUpdateResponse=(t,i)=>{const{id:n}=i,r=Q("session_update",n);if(this.events.listenerCount(r)===0)throw new Error(`emitting ${r} without any listeners`);ct(i)?this.events.emit(Q("session_update",n),{}):Je(i)&&this.events.emit(Q("session_update",n),{error:i.error})},this.onSessionExtendRequest=async(t,i)=>{const{id:n}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,se(is)),await this.sendResult({id:n,topic:t,result:!0}),this.client.events.emit("session_extend",{id:n,topic:t})}catch(r){await this.sendError({id:n,topic:t,error:r}),this.client.logger.error(r)}},this.onSessionExtendResponse=(t,i)=>{const{id:n}=i,r=Q("session_extend",n);if(this.events.listenerCount(r)===0)throw new Error(`emitting ${r} without any listeners`);ct(i)?this.events.emit(Q("session_extend",n),{}):Je(i)&&this.events.emit(Q("session_extend",n),{error:i.error})},this.onSessionPingRequest=async(t,i)=>{const{id:n}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:t})}catch(r){await this.sendError({id:n,topic:t,error:r}),this.client.logger.error(r)}},this.onSessionPingResponse=(t,i)=>{const{id:n}=i,r=Q("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(r)===0)throw new Error(`emitting ${r} without any listeners 2176`);ct(i)?this.events.emit(Q("session_ping",n),{}):Je(i)&&this.events.emit(Q("session_ping",n),{error:i.error})},500)},this.onSessionDeleteRequest=async(t,i)=>{const{id:n}=i;try{await this.isValidDisconnect({topic:t,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:t,error:X("USER_DISCONNECTED")}),await this.deleteSession({topic:t,id:n})}catch(r){this.client.logger.error(r)}},this.onSessionRequest=async t=>{var l,u,d;const{topic:i,payload:n,attestation:r,encryptedId:o,transportType:a}=t,{id:c,params:h}=n;try{await this.isValidRequest({topic:i,...h});const f=this.client.session.get(i),y=await this.getVerifyContext({attestationId:r,hash:Ue(JSON.stringify(Xe("wc_sessionRequest",h,c))),encryptedId:o,metadata:f.peer.metadata,transportType:a}),g={id:c,topic:i,params:h,verifyContext:y};await this.setPendingSessionRequest(g),a===J.link_mode&&((l=f.peer.metadata.redirect)!=null&&l.universal)&&this.client.core.addLinkModeSupportedApp((u=f.peer.metadata.redirect)==null?void 0:u.universal),(d=this.client.signConfig)!=null&&d.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(f){await this.sendError({id:c,topic:i,error:f}),this.client.logger.error(f)}},this.onSessionRequestResponse=(t,i)=>{const{id:n}=i,r=Q("session_request",n);if(this.events.listenerCount(r)===0)throw new Error(`emitting ${r} without any listeners`);ct(i)?this.events.emit(Q("session_request",n),{result:i.result}):Je(i)&&this.events.emit(Q("session_request",n),{error:i.error})},this.onSessionEventRequest=async(t,i)=>{const{id:n,params:r}=i;try{const o=`${t}_session_event_${r.event.name}`,a=_s.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit({topic:t,...r}),this.client.events.emit("session_event",{id:n,topic:t,params:r}),_s.set(o,n)}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}},this.onSessionAuthenticateResponse=(t,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),ct(i)?this.events.emit(Q("session_request",n),{result:i.result}):Je(i)&&this.events.emit(Q("session_request",n),{error:i.error})},this.onSessionAuthenticateRequest=async t=>{var c;const{topic:i,payload:n,attestation:r,encryptedId:o,transportType:a}=t;try{const{requester:h,authPayload:l,expiryTimestamp:u}=n.params,d=await this.getVerifyContext({attestationId:r,hash:Ue(JSON.stringify(n)),encryptedId:o,metadata:h.metadata,transportType:a}),f={requester:h,pairingTopic:i,id:n.id,authPayload:l,verifyContext:d,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:f,pairingTopic:i,transportType:a}),a===J.link_mode&&((c=h.metadata.redirect)!=null&&c.universal)&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:n.params,id:n.id,verifyContext:d})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,a),f={type:wt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:i,error:h,encodeOpts:f,rpcOpts:he.wc_sessionAuthenticate.autoReject,appLink:d})}},this.addSessionRequestToSessionRequestQueue=t=>{this.sessionRequestQueue.queue.push(t)},this.cleanupAfterResponse=t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ye.idle,this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:t,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(r=>r.topic===t&&r.request.method==="wc_sessionRequest").forEach(r=>{this.events.emit(Q("session_request",r.request.id),{error:i})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Ye.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}},this.emitSessionRequest=t=>{if(this.emittedSessionRequests.has(t.id)){this.client.logger.warn({id:t.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${t.id}`);return}this.sessionRequestQueue.state=Ye.active,this.emittedSessionRequests.add(t.id),this.client.events.emit("session_request",t)},this.cleanupInProgress=!1,this.cleanupOrphanedSubscriptions=async()=>{const t=this.client.core.relayer.subscriber.topics;if(t.length===0)return;const i=new Set(this.client.session.keys),n=new Set(this.client.core.pairing.pairings.keys),r=new Set([...this.pendingSessions.values()].map(a=>a.sessionTopic));let o;if(this.client.auth.authKeys.keys.includes(Pt)){const{responseTopic:a}=this.client.auth.authKeys.get(Pt);o=a}for(const a of t)if(!i.has(a)&&!n.has(a)&&!r.has(a)&&a!==o){this.client.logger.info(`Cleaning up orphaned subscriber topic: ${a}`);try{await this.client.core.relayer.subscriber.unsubscribe(a)}catch(c){this.client.logger.warn(c,`Failed to clean up orphaned subscription: ${a}`)}}},this.onPairingCreated=t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:Xe("wc_sessionPropose",{...i,requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties},i.id),attestation:i.attestation,encryptedId:i.encryptedId})},this.isValidConnect=async t=>{if(!Ie(t)){const{message:h}=D("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:r,sessionProperties:o,scopedProperties:a,relays:c}=t;if(re(i)||await this.isValidPairingTopic(i),!hp(c)){const{message:h}=D("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(n&&!re(n)&&st(n)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(n,"requiredNamespaces")}if(r&&!re(r)&&st(r)!==0&&this.validateNamespaces(r,"optionalNamespaces"),o&&!re(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!re(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(n||{}).concat(Object.keys(r||{}));if(!Object.keys(a).every(l=>h.includes(l.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(h)}`)}},this.validateNamespaces=(t,i)=>{const n=cp(t,"connect()",i);if(n)throw new Error(n.message)},this.isValidApprove=async t=>{if(!Ie(t))throw new Error(D("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:n,relayProtocol:r,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),h=on(n,"approve()");if(h)throw new Error(h.message);const l=bo(c.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!ie(r,!0)){const{message:u}=D("MISSING_OR_INVALID",`approve() relayProtocol: ${r}`);throw new Error(u)}if(o&&!re(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!re(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(n));if(!Object.keys(a).every(d=>u.has(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}},this.isValidReject=async t=>{if(!Ie(t)){const{message:r}=D("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(r)}const{id:i,reason:n}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!up(n)){const{message:r}=D("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(r)}},this.isValidSessionSettleRequest=t=>{if(!Ie(t)){const{message:h}=D("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:i,controller:n,namespaces:r,expiry:o}=t;if(!gc(i)){const{message:h}=D("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=sp(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=on(r,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(et(o)){const{message:h}=D("EXPIRED","onSessionSettleRequest()");throw new Error(h)}},this.isValidUpdate=async t=>{if(!Ie(t)){const{message:c}=D("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:i,namespaces:n}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const r=this.client.session.get(i),o=on(n,"update()");if(o)throw new Error(o.message);const a=bo(r.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async t=>{if(!Ie(t)){const{message:n}=D("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(n)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)},this.isValidRequest=async t=>{if(!Ie(t)){const{message:c}=D("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:i,request:n,chainId:r,expiry:o}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!wo(a,r)){const{message:c}=D("MISSING_OR_INVALID",`request() chainId: ${r}`);throw new Error(c)}if(!dp(n)){const{message:c}=D("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!gp(a,r,n.method)){const{message:c}=D("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}this.validateRequestExpiry(o)},this.isValidRespond=async t=>{var o;if(!Ie(t)){const{message:a}=D("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(a)}const{topic:i,response:n}=t;try{await this.isValidSessionTopic(i)}catch(a){throw(o=t==null?void 0:t.response)!=null&&o.id&&this.cleanupAfterResponse(t),a}if(!fp(n)){const{message:a}=D("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(a)}const r=this.client.pendingRequest.get(n.id);if(r.topic!==i){const{message:a}=D("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${n.id}, expected topic: ${r.topic}, received topic: ${i}`);throw new Error(a)}},this.isValidPing=async t=>{if(!Ie(t)){const{message:n}=D("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(n)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.isValidEmit=async t=>{if(!Ie(t)){const{message:a}=D("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:i,event:n,chainId:r}=t;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!wo(o,r)){const{message:a}=D("MISSING_OR_INVALID",`emit() chainId: ${r}`);throw new Error(a)}if(!pp(n)){const{message:a}=D("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!yp(o,r,n.name)){const{message:a}=D("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}},this.isValidDisconnect=async t=>{if(!Ie(t)){const{message:n}=D("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(n)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.isValidAuthenticate=t=>{const{chains:i,uri:n,domain:r,nonce:o}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!ie(n,!1))throw new Error("uri is required parameter");if(!ie(r,!1))throw new Error("domain is required parameter");if(!ie(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>mt(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=mt(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async t=>{const{attestationId:i,hash:n,encryptedId:r,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||qs,validation:"UNKNOWN",origin:o.url||""}};try{if(a===J.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const h=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:r,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c},this.validateSessionProps=(t,i)=>{Object.values(t).forEach((n,r)=>{if(n==null){const{message:o}=D("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${n} for key ${Object.keys(t)[r]}`);throw new Error(o)}})},this.getPendingAuthRequest=t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0},this.addToRecentlyDeleted=(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const r=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(n++>=r)break;this.recentlyDeletedMap.delete(o)}}},this.checkRecentlyDeleted=t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:n}=D("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(n)}},this.isLinkModeEnabled=(t,i)=>{var n,r,o,a,c,h,l,u,d;return!t||i!==J.link_mode?!1:((r=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:r.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((l=t==null?void 0:t.redirect)==null?void 0:l.universal)!==void 0&&((u=t==null?void 0:t.redirect)==null?void 0:u.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(globalThis==null?void 0:globalThis.Linking)<"u"},this.getAppLinkIfEnabled=(t,i)=>{var n;return this.isLinkModeEnabled(t,i)?(n=t==null?void 0:t.redirect)==null?void 0:n.universal:void 0},this.handleLinkModeMessage=({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=so(t,"topic")||"",n=decodeURIComponent(so(t,"wc_ev")||""),r=this.client.session.keys.includes(i);r&&this.client.session.update(i,{transportType:J.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:r})},this.registerLinkModeListeners=async()=>{var t;if(rr()||Ut()&&((t=this.client.metadata.redirect)!=null&&t.linkMode)){const i=globalThis==null?void 0:globalThis.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}},this.getTVFApproveParams=t=>{try{const i=fc(t.namespaces),n=Hf(t.namespaces),r=Ff(t.namespaces),o=t.sessionProperties,a=t.scopedProperties;return{approvedChains:i,approvedMethods:n,approvedEvents:r,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}},this.getTVFParams=(t,i,n)=>{var o,a,c;if(!((o=i.request)!=null&&o.method))return{};const r={correlationId:t,rpcMethods:[i.request.method],chainId:i.chainId};try{const h=this.extractTxHashesFromResult(i.request,n);r.txHashes=h,r.contractAddresses=this.isValidContractData(i.request.params)?[(c=(a=i.request.params)==null?void 0:a[0])==null?void 0:c.to]:[]}catch(h){this.client.logger.warn(h,"Error getting TVF params")}return r},this.isValidContractData=t=>{var i;if(!t)return!1;try{const n=(t==null?void 0:t.data)||((i=t==null?void 0:t[0])==null?void 0:i.data);if(!n.startsWith("0x"))return!1;const r=n.slice(2);return/^[0-9a-fA-F]*$/.test(r)?r.length%2===0:!1}catch{}return!1},this.extractTxHashesFromResult=(t,i)=>{var n;try{if(!i)return[];const r=t.method,o=ly[r];if(r==="sui_signTransaction")return[pf(i.transactionBytes)];if(r==="near_signTransaction")return[no(i)];if(r==="near_signTransactions")return i.map(c=>no(c));if(r==="xrpl_signTransactionFor"||r==="xrpl_signTransaction")return[(n=i.tx_json)==null?void 0:n.hash];if(r==="polkadot_signTransaction")return[Cp({transaction:t.params.transactionPayload,signature:i.signature})];if(r==="algo_signTxn")return Me(i)?i.map(c=>ro(c)):[ro(i)];if(r==="cosmos_signDirect")return[yf(i)];if(r==="wallet_sendCalls")return mf(i);if(typeof i=="string")return[i];const a=i[o.key];if(Me(a))return r==="solana_signAllTransactions"?a.map(c=>ff(c)):a;if(typeof a=="string")return[a]}catch(r){this.client.logger.warn(r,"Error extracting tx hashes from result")}return[]}}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,n]of Object.entries(t))for(const r of n)try{await this.onProviderMessageEvent({topic:i,message:r,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${r}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(te.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:n,transportType:r}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Pt)?this.client.auth.authKeys.get(Pt):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:r===J.link_mode?Rt:le});Ln(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:n,transportType:r,encryptedId:Ue(i)})):zn(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:r}),this.client.core.history.delete(t,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:r})),await this.client.core.relayer.messages.ack(t,i)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Be.expired,async e=>{const{topic:t,id:i}=tc(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,D("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,D("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerSubscriptionCleanup(){this.client.core.heartbeat.on("heartbeat_pulse",async()=>{if(!this.cleanupInProgress){this.cleanupInProgress=!0;try{await this.cleanupOrphanedSubscriptions()}catch(e){this.client.logger.warn(e)}finally{this.cleanupInProgress=!1}}})}registerPairingEvents(){this.client.core.pairing.events.on(zt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(zt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ie(e,!1)){const{message:t}=D("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=D("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(et(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=D("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ie(e,!1)){const{message:t}=D("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=D("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(et(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=D("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=D("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ie(e,!1)){const{message:t}=D("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=D("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!lp(e)){const{message:t}=D("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=D("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(et(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=D("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}validateRequestExpiry(e){if(e&&!bp(e,un)){const{message:t}=D("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${un.min} and ${un.max}`);throw new Error(t)}}}class by extends Xt{constructor(e,t){super(e,t,ay,pr),this.core=e,this.logger=t}}class vy extends Xt{constructor(e,t){super(e,t,cy,pr),this.core=e,this.logger=t}}class Ey extends Xt{constructor(e,t){super(e,t,uy,pr,i=>i.id),this.core=e,this.logger=t}}class Iy extends Xt{constructor(e,t){super(e,t,gy,Mi,()=>Pt),this.core=e,this.logger=t}}class _y extends Xt{constructor(e,t){super(e,t,yy,Mi),this.core=e,this.logger=t}}class xy extends Xt{constructor(e,t){super(e,t,my,Mi,i=>i.id),this.core=e,this.logger=t}}class Sy{constructor(e,t){this.core=e,this.logger=t,this.authKeys=new Iy(this.core,this.logger),this.pairingTopics=new _y(this.core,this.logger),this.requests=new xy(this.core,this.logger)}
12async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}let Py=class Kc extends Fp{constructor(e){super(e),this.protocol=Lc,this.version=zc,this.name=ln.name,this.events=new Ct.EventEmitter,this.on=(i,n)=>this.events.on(i,n),this.once=(i,n)=>this.events.once(i,n),this.off=(i,n)=>this.events.off(i,n),this.removeListener=(i,n)=>this.events.removeListener(i,n),this.removeAllListeners=i=>this.events.removeAllListeners(i),this.connect=async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}},this.pair=async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}},this.approve=async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}},this.reject=async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}},this.update=async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}},this.extend=async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}},this.request=async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}},this.respond=async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}},this.ping=async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}},this.emit=async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}},this.disconnect=async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}},this.find=i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}},this.authenticate=async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(r){throw this.logger.error(r.message),r}},this.formatAuthMessage=i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}},this.approveSessionAuthenticate=async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.rejectSessionAuthenticate=async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.name=(e==null?void 0:e.name)||ln.name,this.metadata=Fd(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const t=cr({logger:(e==null?void 0:e.logger)||ln.logger,name:this.name});this.logger=t,this.core=(e==null?void 0:e.core)||new oy(e),this.session=new vy(this.core,this.logger),this.proposal=new by(this.core,this.logger),this.pendingRequest=new Ey(this.core,this.logger),this.engine=new wy(this),this.auth=new Sy(this.core,this.logger)}static async init(e){const t=new Kc(e);return await t.initialize(),t}get context(){return Ne(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(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Ay=Py,$o="error",Oy="wss://relay.walletconnect.org",$y="wc",Vc="universal_provider",ri=`${$y}@2:${Vc}:`,Hc="https://rpc.walletconnect.org/v1/",Fc="generic",Ry=`${Hc}bundler`,ds="call_status",Ny=86400,gr={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Gc(s,e,t){var n;const i=mt(s);return((n=e.rpcMap)==null?void 0:n[i.reference])||`${Hc}?chainId=${i.namespace}:${i.reference}&projectId=${t}`}function Ty(s){return s.includes(":")?s.split(":")[1]:s}function Wc(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function qy(s,e){const t=Object.keys(e.namespaces).filter(n=>n.includes(s));if(!t.length)return[];const i=[];return t.forEach(n=>{const r=e.namespaces[n].accounts;i.push(...r)}),i}function Ro(s){return Object.fromEntries(Object.entries(s).filter(([e,t])=>{var i,n;return((i=t==null?void 0:t.chains)==null?void 0:i.length)&&((n=t==null?void 0:t.chains)==null?void 0:n.length)>0}))}function oi(s={},e={}){const t=Ro(No(s)),i=Ro(No(e));return lg(t,i)}function No(s){var t,i,n,r,o;const e={};if(!st(s))return e;for(const[a,c]of Object.entries(s)){const h=Ui(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],d=c.rpcMap||{},f=os(a);e[f]={...e[f],...c,chains:tt(h,(t=e[f])==null?void 0:t.chains),methods:tt(l,(i=e[f])==null?void 0:i.methods),events:tt(u,(n=e[f])==null?void 0:n.events)},(st(d)||st(((r=e[f])==null?void 0:r.rpcMap)||{}))&&(e[f].rpcMap={...d,...(o=e[f])==null?void 0:o.rpcMap})}return e}function To(s){return s.includes(":")?s.split(":")[2]:s}function qo(s){const e={};for(const[t,i]of Object.entries(s)){const n=i.methods||[],r=i.events||[],o=i.accounts||[],a=Ui(t)?[t]:i.chains?i.chains:Wc(i.accounts);e[t]={chains:a,methods:n,events:r,accounts:o}}return e}function dn(s){return typeof s=="number"?s:s.includes("0x")?parseInt(s,16):(s=s.includes(":")?s.split(":")[1]:s,isNaN(Number(s))?s:Number(s))}function Cy(s){try{const e=JSON.parse(s);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const Zc={},fs=s=>Zc[s],fn=(s,e)=>{Zc[s]=e},Co="eip155",By=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],ky=s=>s&&s.startsWith("0x")?BigInt(s).toString(10):s,pn=s=>s&&s.startsWith("0x")?s:`0x${BigInt(s).toString(16)}`,Bo=s=>Object.keys(s).filter(e=>By.includes(e)).reduce((e,t)=>
vendor: 16,289 bytes, line 12
12(e[t]=Uy(s[t]),e),{}),Uy=s=>typeof s=="string"&&Cy(s)?JSON.parse(s):s,My=(s,e,t)=>{const{sessionProperties:i={},scopedProperties:n={}}=s,r={};if(!st(n)&&!st(i))return;const o=Bo(i);for(const a of t){const c=ky(a);if(!c)continue;r[pn(c)]=o;const h=n==null?void 0:n[`${Co}:${c}`];if(h){const l=h==null?void 0:h[`${Co}:${c}:${e}`];r[pn(c)]={...r[pn(c)],...Bo(l||h)}}}for(const[a,c]of Object.entries(r))Object.keys(c).length===0&&delete r[a];return Object.keys(r).length>0?r:void 0};let gn,Dy=class Yc{constructor(e){this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,t){return await this.storage.setItem(e,t)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return gn||(gn=new Yc(e)),gn}};async function Ly(s,e){const t=mt(s.result.capabilities.caip345.caip2),i=s.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(i.map(u=>zy(t.reference,u,e))),r=n.filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u);n.filter(u=>u.status==="rejected").forEach(u=>console.warn("Failed to fetch transaction receipt:",u.reason));const o=!r.length||r.some(u=>!u),a=r.every(u=>(u==null?void 0:u.status)==="0x1"),c=r.every(u=>(u==null?void 0:u.status)==="0x0"),h=r.some(u=>(u==null?void 0:u.status)==="0x0");let l;return o?l=100:a?l=200:c?l=500:h&&(l=600),{id:s.result.id,version:s.request.version,atomic:s.request.atomicRequired,chainId:s.request.chainId,capabilities:s.result.capabilities,receipts:r,status:l}}async function zy(s,e,t){return await t(parseInt(s)).request(Xe("eth_getTransactionReceipt",[e]))}async function jy({sendCalls:s,storage:e}){const t=await e.getItem(ds);await e.setItem(ds,{...t,[s.result.id]:{request:s.request,result:s.result,expiry:se(Ny)}})}async function Ky({resultId:s,storage:e}){const t=await e.getItem(ds);if(t){delete t[s],await e.setItem(ds,t);for(const i in t)et(t[i].expiry)&&delete t[i];await e.setItem(ds,t)}}async function Vy({resultId:s,storage:e}){var i;const t=(i=await e.getItem(ds))==null?void 0:i[s];if(t&&!et(t.expiry))return t;await Ky({resultId:s,storage:e})}class Hy{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=fs("events"),this.client=fs("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=Dy.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t);const i=this.chainId;this.chainId=parseInt(e),this.events.emit(gr.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const i=t||Gc(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Dn(new Do(i,fs("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var n;const i=parseInt(Ty(t));e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(e){const t=e||this.chainId;return this.httpProviders[t]||(this.httpProviders={...this.httpProviders,[t]:this.createHttpProvider(t)},this.httpProviders[t])}async handleSwitchChain(e){var n,r;let t=e.request.params?(n=e.request.params[0])==null?void 0:n.chainId:"0x0";t=t.startsWith("0x")?t:`0x${t}`;const i=parseInt(t,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:t}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${i}`);else throw new Error(`Failed to switch to chain 'eip155:${i}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var u,d,f,y,g;const t=(d=(u=e.request)==null?void 0:u.params)==null?void 0:d[0],i=((y=(f=e.request)==null?void 0:f.params)==null?void 0:y[1])||[];if(!t)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const n=this.client.session.get(e.topic),r=((g=n==null?void 0:n.sessionProperties)==null?void 0:g.capabilities)||{},o=i.length>0?i.join(","):`0x${this.chainId.toString(16)}`,a=`${t}${o}`,c=r==null?void 0:r[a];if(c)return c;let h;try{h=My(n,t,i)}catch(b){console.warn("Failed to extract capabilities from session",b)}if(h)return h;const l=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:{...n.sessionProperties||{},capabilities:{...r||{},[a]:l}}})}catch(b){console.warn("Failed to update session with capabilities",b)}return l}async getCallStatus(e){var o,a,c;const t=this.client.session.get(e.topic),i=(o=t.sessionProperties)==null?void 0:o.bundler_name;if(i){const h=this.getBundlerUrl(e.chainId,i);try{return await this.getUserOperationReceipt(h,e)}catch(l){console.warn("Failed to fetch call status from bundler",l,h)}}const n=(a=t.sessionProperties)==null?void 0:a.bundler_url;if(n)try{return await this.getUserOperationReceipt(n,e)}catch(h){console.warn("Failed to fetch call status from custom bundler",h,n)}const r=await Vy({resultId:(c=e.request.params)==null?void 0:c[0],storage:this.storage});if(r)try{return await Ly(r,this.getHttpProvider.bind(this))}catch(h){console.warn("Failed to fetch call status from stored send calls",h,r)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var r;const i=new URL(e),n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Xe("eth_getUserOperationReceipt",[(r=t.request.params)==null?void 0:r[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${Ry}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}async sendCalls(e){var c,h,l;const t=await this.client.request(e),i=(c=e.request.params)==null?void 0:c[0],n=t==null?void 0:t.id,r=(t==null?void 0:t.capabilities)||{},o=(h=r==null?void 0:r.caip345)==null?void 0:h.caip2,a=(l=r==null?void 0:r.caip345)==null?void 0:l.transactionHashes;return!n||!o||!(a!=null&&a.length)||await jy({sendCalls:{request:i,result:t},storage:this.storage}),t}}class Fy{constructor(e){this.name=Fc,this.namespace=e.namespace,this.events=fs("events"),this.client=fs("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t);const i=this.chainId;this.chainId=e,this.events.emit(gr.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return mt(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var t,i;const e={};return(i=(t=this.namespace)==null?void 0:t.accounts)==null||i.forEach(n=>{var a,c;const r=mt(n),o=(c=(a=this.namespace)==null?void 0:a.rpcMap)==null?void 0:c[`${r.namespace}:${r.reference}`];e[r.reference]=this.createHttpProvider(n,o)}),e}getHttpProvider(e){const t=mt(e).reference,i=this.httpProviders[t];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Gc(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Dn(new Do(i,fs("disableProviderPing")))}}let Gy=class Qc{constructor(e){this.events=new jn,this.rpcProviders={},this.disableProviderPing=!1,this.providerOpts=e,this.logger=cr({logger:e.logger??$o,name:this.providerOpts.name??Vc}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Qc(e);return await t.initialize(),t}async request(e,t,i){const[n,r]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:{...e},chainId:`${n}:${r}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,n){const r=new Date().getTime();this.request(e,i,n).then(o=>t(null,Cs(r,o))).catch(o=>t(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 e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:X("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const r=await n();if(this.session=r.session,this.session){const o=qo(this.session.namespaces);this.namespaces=oi(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return r}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){var o,a;const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(o=this.connectParams)==null?void 0:o.authentication,walletPay:(a=this.connectParams)==null?void 0:a.walletPay});t&&(this.uri=t,this.events.emit("display_uri",t));const n=await i();this.session=n;const r=qo(n.namespaces);return this.namespaces=oi(this.namespaces,r),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,n]=this.validateChain(e),r=this.getProvider(i);r?r.setDefaultChain(n,t):this.session&&this.logger.warn(`Provider for namespace '${i}' not found in setDefaultChain`)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(!Me(t))return;for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}catch(t){this.logger.warn(t,"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 e,t;if(this.client=this.providerOpts.client||await Ay.init({core:this.providerOpts.core,logger:this.providerOpts.logger||$o,relayUrl:this.providerOpts.relayUrl||Oy,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(i){throw this.logger.error(i,"Failed to get session"),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[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 e=[...new Set(Object.keys(this.session.namespaces).map(t=>os(t)))];fn("client",this.client),fn("events",this.events),fn("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=qy(t,this.session);if((i==null?void 0:i.length)===0)return;const n=Wc(i),r={...oi(this.namespaces,this.optionalNamespaces)[t],accounts:i,chains:n};switch(t){case"eip155":this.rpcProviders[t]=new Hy({namespace:r});break;default:this.rpcProviders[t]=new Fy({namespace:r})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var i;const{topic:t}=e;t===((i=this.session)==null?void 0:i.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:t,topic:i}=e;if(i!==((r=this.session)==null?void 0:r.topic))return;const{event:n}=t;if(n.name==="accountsChanged"){const o=n.data;o&&Me(o)&&this.events.emit("accountsChanged",o.map(To))}else if(n.name==="chainChanged"){const o=t.chainId,a=t.event.data,c=os(o),h=dn(o)!==dn(a)?`${c}:${dn(a)}`:o;this.onChainChanged({currentCaipChainId:h})}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var r,o;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:i}=t,n=(o=this.client)==null?void 0:o.session.get(e);this.session={...n,namespaces:i},this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;
12e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",{...X("USER_DISCONNECTED"),data:e.topic}))}),this.on(gr.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged({...e,internal:!0})})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Fc]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:i={},sessionProperties:n,scopedProperties:r}=e;this.optionalNamespaces=oi(t,i),this.sessionProperties=n,this.scopedProperties=r}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>os(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const n=os(Object.keys(this.namespaces)[0]),r
12=this.rpcProviders[n].getDefaultChain();return[n,r]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:t,internal:i=!1}){if(!this.namespaces)return;const[n,r]=this.validateChain(e);if(r){if(this.updateNamespaceChain(n,r),i)this.events.emit("chainChanged",r),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:t});else{const o=this.getProvider(n);o?o.setDefaultChain(r):this.session&&this.logger.warn(`Provider for namespace '${n}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:t,previousCaipChainId:i}){var n,r;try{if(i===t)return;const o=(r=(n=this.session)==null?void 0:n.namespaces[e])==null?void 0:r.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${t}:`)).map(To);if(!Me(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,t){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${t}`,n={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=t):this.namespaces[i]=n}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(e,t){var n;const i=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${ri}/${e}${i}`,t)}async getFromStore(e){var i;const t=((i=this.session)==null?void 0:i.topic)||"";return await this.client.core.storage.getItem(`${ri}/${e}${t}`)}async deleteFromStore(e){var i;const t=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.removeItem(`${ri}/${e}${t}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const i of t)i.startsWith(ri)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn(t,"Failed to cleanup storage")}}};const Wy=Gy,Zy="wc",Yy="ethereum_provider",Qy=`${Zy}@2:${Yy}:`,Jy="https://rpc.walletconnect.org/v1/",Un=["eth_sendTransaction","personal_sign"],Xy=["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"],Mn=["chainChanged","accountsChanged"],em=["chainChanged","accountsChanged","message","disconnect","connect"],tm=async()=>{const{createAppKit:s}=await gh(()=>import("./core-Ciek2xfl.js").then(e=>e.y),__vite__mapDeps([0,1,2]));return s};function Ai(s){return Number(s[0].split(":")[1])}function ai(s){return`0x${s.toString(16)}`}function sm(s){const{chains:e,optionalChains:t,methods:i,optionalMethods:n,events:r,optionalEvents:o,rpcMap:a}=s;if(!Me(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Un,events:r||Mn,rpcMap:{...e.length?{[Ai(e)]:a[Ai(e)]}:{}}},h=r==null?void 0:r.filter(f=>!Mn.includes(f)),l=i==null?void 0:i.filter(f=>!Un.includes(f));if(!t&&!o&&!n&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=(h==null?void 0:h.length)&&(l==null?void 0:l.length)||!t,d={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:Xy))],events:[...new Set(c.events.concat(o!=null&&o.length?o:em))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?d:void 0}}let im=class Jc{constructor(){this.events=new Ct.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=Qy,this.on=(e,t)=>(this.events.on(e,t),this),this.once=(e,t)=>(this.events.once(e,t),this),this.removeListener=(e,t)=>(this.events.removeListener(e,t),this),this.off=(e,t)=>(this.events.off(e,t),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const t=new Jc;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var n;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:t,optional:i}=sm(this.rpc);try{const r=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;
12await this.signer.connect({namespaces:{...t&&{[this.namespace]:t}},...i&&{optionalNamespaces:{[this.namespace]:i}},pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h}).then(d=>{a(d)}).catch(d=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!r)return;const o=eo(r.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ai(this.chainId)})}catch(r){throw this.signer.logger.error(r),r}finally{(n=this.modal)==null||n.close()}}async authenticate(e,t){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const n=await new Promise(async(o,a)=>{var c,h;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(h=this.modal)==null||h.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate({...e,chains:this.rpc.chains},t).then(l=>{o(l)}).catch(l=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),r=n.session;if(r){const o=eo(r.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ai(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{(i=this.modal)==null||i.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",e=>{const{params:t}=e,{event:i}=t;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",ai(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",{...X("USER_DISCONNECTED"),data:e.topic,name:"USER_DISCONNECTED"})}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",ai(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,n]=e.split(":");return{chainId:`${t}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){const t=(e==null?void 0:e.chains)??[],i=(e==null?void 0:e.optionalChains)??[],n=t.concat(i);if(!n.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const r=t.length?(e==null?void 0:e.methods)||Un:[],o=t.length?(e==null?void 0:e.events)||Mn:[],a=(e==null?void 0:e.optionalMethods)||[],c=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(n,e.projectId),l=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:t==null?void 0:t.map(u=>this.formatChainId(u)),optionalChains:i.map(u=>this.formatChainId(u)),methods:r,events:o,optionalMethods:a,optionalEvents:c,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:l,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,t)}),i}async initialize(e){var t;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ai(this.rpc.chains):Ai(this.rpc.optionalChains),this.signer=await Wy.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let i;try{const n=await tm(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return am}),o=r({...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");i=n({...o,universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((t=this.rpc.qrModalOptions)==null?void 0:t.enableMobileFullScreen)===!0})}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectMod
12al Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:n}=e;t&&Me(t)&&(this.rpc.chains=t.map(r=>this.formatChainId(r)),t.forEach(r=>{this.rpc.rpcMap[r]=(n==null?void 0:n[r])||this.getRpcUrl(r)})),i&&Me(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(r=>this.formatChainId(r)),i.forEach(r=>{this.rpc.rpcMap[r]=(n==null?void 0:n[r])||this.getRpcUrl(r)}))}getRpcUrl(e,t){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${Jy}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t==null?void 0:t.accounts),this.setAccounts(t==null?void 0:t.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}};const $m=im;function nm(s){if(s)return{"--w3m-font-family":s["--wcm-font-family"],"--w3m-accent":s["--wcm-accent-color"],"--w3m-color-mix":s["--wcm-background-color"],"--w3m-z-index":s["--wcm-z-index"]?Number(s["--wcm-z-index"]):void 0,"--w3m-qr-color":s["--wcm-accent-color"],"--w3m-font-size-master":s["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":s["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const rm=s=>{const[e,t]=s.split(":");return Xc({id:t,caipNetworkId:s,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function om(s){var n,r,o,a,c,h,l;const e=(n=s.chains)==null?void 0:n.map(rm).filter(Boolean);if(e.length===0)throw new Error("At least one chain must be specified");const t=e.find(u=>{var d;return u.id===((d=s.defaultChain)==null?void 0:d.id)}),i={projectId:s.projectId,networks:e,themeMode:s.themeMode,themeVariables:nm(s.themeVariables),chainImages:s.chainImages,connectorImages:s.walletImages,defaultNetwork:t,metadata:{...s.metadata,name:((r=s.metadata)==null?void 0:r.name)||"WalletConnect",description:((o=s.metadata)==null?void 0:o.description)||"Connect to WalletConnect-compatible wallets",url:((a=s.metadata)==null?void 0:a.url)||"https://walletconnect.org",icons:((c=s.metadata)==null?void 0:c.icons)||["https://walletconnect.org/walletconnect-logo.png"]},showWallets:!0,featuredWalletIds:s.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(s.explorerRecommendedWalletIds)?s.explorerRecommendedWalletIds:[],excludeWalletIds:s.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(s.explorerExcludedWalletIds)?s.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((h=s.mobileWallets)!=null&&h.length||(l=s.desktopWallets)!=null&&l.length){const u=[...(s.mobileWallets||[]).map(y=>({id:y.id,name:y.name,links:y.links})),...(s.desktopWallets||[]).map(y=>({id:y.id,name:y.name,links:{native:y.links.native,universal:y.links.universal}}))],d=[...i.featuredWalletIds||[],...i.excludeWalletIds||[]],f=u.filter(y=>!d.includes(y.id));f.length&&(i.customWallets=f)}return i}function Xc(s){return{formatters:void 0,fees:void 0,serializers:void 0,...s}}var am=Object.freeze({__proto__:null,convertWCMToAppKitOptions:om,defineChain:Xc});export{$m as EthereumProvider,em as OPTIONAL_EVENTS,Xy as OPTIONAL_METHODS,Mn as REQUIRED_EVENTS,Un as REQUIRED_METHODS,im as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.