PageSourceSearch

https://x402-cybercentry.up.railway.app/_next/static/chunks/355jat7qu-pgx.js

js x402-cybercentry.up.railway.app collected 2026-10-03 12:15:46 UTC 545,708 bytes, 25 lines download raw bytes

1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,635138,(e,t,i)=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.toBig=i.shrSL=i.shrSH=i.rotrSL=i.rotrSH=i.rotrBL=i.rotrBH=i.rotr32L=i.rotr32H=i.rotlSL=i.rotlSH=i.rotlBL=i.rotlBH=i.add5L=i.add5H=i.add4L=i.add4H=i.add3L=i.add3H=void 0,i.add=v,i.fromBig=n,i.split=a;let r=BigInt(0x100000000-1),s=BigInt(32);function n(e,t=!1){return t?{h:Number(e&r),l:Number(e>>s&r)}:{h:0|Number(e>>s&r),l:0|Number(e&r)}}function a(e,t=!1){let i=e.length,r=new Uint32Array(i),s=new Uint32Array(i);for(let a=0;a<i;a++){let{h:i,l:o}=n(e[a],t);[r[a],s[a]]=[i,o]}return[r,s]}let o=(e,t)=>BigInt(e>>>0)<<s|BigInt(t>>>0);i.toBig=o;let l=(e,t,i)=>e>>>i;i.shrSH=l;let c=(e,t,i)=>e<<32-i|t>>>i;i.shrSL=c;let h=(e,t,i)=>e>>>i|t<<32-i;i.rotrSH=h;let d=(e,t,i)=>e<<32-i|t>>>i;i.rotrSL=d;let u=(e,t,i)=>e<<64-i|t>>>i-32;i.rotrBH=u;let p=(e,t,i)=>e>>>i-32|t<<64-i;i.rotrBL=p;let f=(e,t)=>t;i.rotr32H=f;let g=(e,t)=>e;i.rotr32L=g;let y=(e,t,i)=>e<<i|t>>>32-i;i.rotlSH=y;let m=(e,t,i)=>t<<i|e>>>32-i;i.rotlSL=m;let w=(e,t,i)=>t<<i-32|e>>>64-i;i.rotlBH=w;let b=(e,t,i)=>e<<i-32|t>>>64-i;function v(e,t,i,r){let s=(t>>>0)+(r>>>0);return{h:e+i+(s/0x100000000|0)|0,l:0|s}}i.rotlBL=b;let E=(e,t,i)=>(e>>>0)+(t>>>0)+(i>>>0);i.add3L=E;let I=(e,t,i,r)=>t+i+r+(e/0x100000000|0)|0;i.add3H=I;let S=(e,t,i,r)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0);i.add4L=S;let A=(e,t,i,r,s)=>t+i+r+s+(e/0x100000000|0)|0;i.add4H=A;let x=(e,t,i,r,s)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0)+(s>>>0);i.add5L=x;let P=(e,t,i,r,s,n)=>t+i+r+s+n+(e/0x100000000|0)|0;i.add5H=P,i.default={fromBig:n,split:a,toBig:o,shrSH:l,shrSL:c,rotrSH:h,rotrSL:d,rotrBH:u,rotrBL:p,rotr32H:f,rotr32L:g,rotlSH:y,rotlSL:m,rotlBH:w,rotlBL:b,add:v,add3L:E,add3H:I,add4L:S,add4H:A,add5H:P,add5L:x}},581918,(e,t,i)=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.crypto=void 0,i.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0},857024,(e,t,i)=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.wrapXOFConstructorWithOpts=i.wrapConstructorWithOpts=i.wrapConstructor=i.Hash=i.nextTick=i.swap32IfBE=i.byteSwapIfBE=i.swap8IfBE=i.isLE=void 0,i.isBytes=s,i.anumber=n,i.abytes=a,i.ahash=function(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.createHasher");n(e.outputLen),n(e.blockLen)},i.aexists=function(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")},i.aoutput=function(e,t){a(e);let i=t.outputLen;if(e.length<i)throw Error("digestInto() expects output buffer of length at least "+i)},i.u8=function(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)},i.u32=function(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))},i.clean=function(...e){for(let t=0;t<e.length;t++)e[t].fill(0)},i.createView=function(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)},i.rotr=function(e,t){return e<<32-t|e>>>t},i.rotl=function(e,t){return e<<t|e>>>32-t>>>0},i.byteSwap=o,i.byteSwap32=l,i.bytesToHex=function(e){if(a(e),c)return e.toHex();let t="";for(let i=0;i<e.length;i++)t+=h[e[i]];return t},i.hexToBytes=function(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(c)return Uint8Array.fromHex(e);let t=e.length,i=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(i);for(let t=0,s=0;t<i;t++,s+=2){let i=d(e.charCodeAt(s)),n=d(e.charCodeAt(s+1));if(void 0===i||void 0===n)throw Error('hex string expected, got non-hex character "'+(e[s]+e[s+1])+'" at index '+s);r[t]=16*i+n}return r},i.asyncLoop=u,i.utf8ToBytes=p,i.bytesToUtf8=function(e){return new TextDecoder().decode(e)},i.toBytes=f,i.kdfInputToBytes=function(e){return"string"==typeof e&&(e=p(e)),a(e),e},i.concatBytes=function(...e){let t=0;for(let i=0;i<e.length;i++){let r=e[i];a(r),t+=r.length}let i=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let s=e[t];i.set(s,r),r+=s.length}return i},i.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==({}).toString.call(t))throw Error("options should be object or undefined");return Object.assign(e,t)},i.createHasher=g,i.createOptHasher=y,i.createXOFer=m,i.randomBytes=function(e=32){if(r.crypto&&"function"==typeof r.crypto.getRandomValues)return r.crypto.getRandomValues(new Uint8Array(e));if(r.crypto&&"function"==typeof r.crypto.randomBytes)return Uint8Array.from(r.crypto.randomBytes(e));throw Error("crypto.getRandomValues must be defined")};let r=e.r(581918);function s(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function n(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function a(e,...t){if(!s(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function o(e){return e<<24&0xff000000|e<<8&0xff0000|e>>>8&65280|e>>>24&255}function l(e){for(let t=0;t<e.length;t++)e[t]=o(e[t]);return e}i.isLE=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],i.swap8IfBE=i.isLE?e=>e:e=>o(e),i.byteSwapIfBE=i.swap8IfBE,i.swap32IfBE=i.isLE?e=>e:l;let c="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,h=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function d(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}async function u(e,t,r){let s=Date.now();for(let n=0;n<e;n++){r(n);let e=Date.now()-s;e>=0&&e<t||(await (0,i.nextTick)(),s+=e)}}function p(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function f(e){return"string"==typeof e&&(e=p(e)),a(e),e}function g(e){let t=t=>e().update(f(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}function y(e){let t=(t,i)=>e(i).update(f(t)).digest(),i=e({});return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=t=>e(t),t}function m(e){let t=(t,i)=>e(i).update(f(t)).digest(),i=e({});return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=t=>e(t),t}i.nextTick=async()=>{},i.Hash=class{},i.wrapConstructor=g,i.wrapConstructorWithOpts=y,i.wrapXOFConstructorWithOpts=m},13959,(e,t,i)=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.shake256=i.shake128=i.keccak_512=i.keccak_384=i.keccak_256=i.keccak_224=i.sha3_512=i.sha3_384=i.sha3_256=i.sha3_224=i.Keccak=void 0,i.keccakP=b;let r=e.r(635138),s=e.r(857024),n=BigInt(0),a=BigInt(1),o=BigInt(2),l=BigInt(7),c=BigInt(256),h=BigInt(113),d=[],u=[],p=[];for(let e=0,t=a,i=1,r=0;e<24;e++){[i,r]=[r,(2*i+3*r)%5],d.push(2*(5*r+i)),u.push((e+1)*(e+2)/2%64);let s=n;for(let e=0;e<7;e++)(t=(t<<a^(t>>l)*h)%c)&o&&(s^=a<<(a<<BigInt(e))-a);p.push(s)}let f=(0,r.split)(p,!0),g=f[0],y=f[1],m=(e,t,i)=>i>32?(0,r.rotlBH)(e,t,i):(0,r.rotlSH)(e,t,i),w=(e,t,i)=>i>32?(0,r.rotlBL)(e,t,i):(0,r.rotlSL)(e,t,i);function b(e,t=24){let i=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)i[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let r=(t+8)%10,s=(t+2)%10,n=i[s],a=i[s+1],o=m(n,a,1)^i[r],l=w(n,a,1)^i[r+1];for(let i=0;i<50;i+=10)e[t+i]^=o,e[t+i+1]^=l}let t=e[2],s=e[3];for(let i=0;i<24;i++){let r=u[i],n=m(t,s,r),a=w(t,s,r),o=d[i];t=e[o],s=e[o+1],e[o]=n,e[o+1]=a}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)i[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~i[(r+2)%10]&i[(r+4)%10]}e[0]^=g[r],e[1]^=y[r]}(0,s.clean)(i)}class v extends s.Hash{constructor(e,t,i,r=!1,n=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=r,this.rounds=n,(0,s.anumber)(i),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=(0,s.u32)(this.state)}clone(){return this._cloneInto()}keccak(){(0,s.swap32IfBE)(this.state32),b(this.state32,this.rounds),(0,s.swap32IfBE)(this.state32),this.posOut=0,this.pos=0}update(e){(0,s.aexists)(this),e=(0,s.toBytes)(e),(0,s.abytes)(e);let{blockLen:t,state:i}=this,r=e.length;for(let s=0;s<r;){let n=Math.min(t-this.pos,r-s);for(let t=0;t<n;t++)i[this.pos++]^=e[s++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,(128&t)!=0&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){(0,s.aexists)(this,!1),(0,s.abytes)(e),this.finish();let t=this.state,{blockLen:i}=this;for(let r=0,s=e.length;r<s;){this.posOut>=i&&this.keccak();let n=Math.min(i-this.posOut,s-r);e.set(t.subarray(this.posOut,this.posOut+n),r),this.posOut+=n,r+=n}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,s.anumber)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,s.aoutput)(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,(0,s.clean)(this.state)}_cloneInto(e){let{blockLen:t,suffix:i,outputLen:r,rounds:s,enableXOF:n}=this;return e||(e=new v(t,i,r,n,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=i,e.outputLen=r,e.enableXOF=n,e.destroyed=this.destroyed,e}}i.Keccak=v;let E=(e,t,i)=>(0,s.createHasher)(()=>new v(t,e,i));i.sha3_224=E(6,144,28),i.sha3_256=E(6,136,32),i.sha3_384=E(6,104,48),i.sha3_512=E(6,72,64),i.keccak_224=E(1,144,28),i.keccak_256=E(1,136,32),i.keccak_384=E(1,104,48),i.keccak_512=E(1,72,64);let I=(e,t,i)=>(0,s.createXOFer)((r={})=>new v(t,e,void 0===r.dkLen?i:r.dkLen,!0));i.shake128=I(31,168,16),i.shake256=I(31,136,32)},347558,(e,t,i)=>{var r=e.i(467034);let{keccak_256:s}=e.r(13959);function n(e){return r.Buffer.allocUnsafe(e).fill(0)}function a(e,t){let i=e.toString(16);i.length%2!=0&&(i="0"+i);let s=i.match(/.{1,2}/g).map(e=>parseInt(e,16));for(;s.length<t;)s.unshift(0);return r.Buffer.from(s)}function o(e,t,i){let r=n(t);return(e=l(e),i)?e.length<t?(e.copy(r),r):e.slice(0,t):e.length<t?(e.copy(r,t-e.length),r):e.slice(-t)}function l(e){if(!r.Buffer.isBuffer(e))if(Array.isArray(e))e=r.Buffer.from(e);else if("string"==typeof e){var t;e=c(e)?r.Buffer.from((t=h(e)).length%2?"0"+t:t,"hex"):r.Buffer.from(e)}else if("number"==typeof e)e=intToBuffer(e);else if(null==e)e=r.Buffer.allocUnsafe(0);else if("bigint"==typeof e)e=a(e);else if(e.toArray)e=r.Buffer.from(e.toArray());else throw Error("invalid type");return e}function c(e){return"string"==typeof e&&e.match(/^0x[0-9A-Fa-f]*$/)}function h(e){return"string"==typeof e&&e.startsWith("0x")?e.slice(2):e}t.exports={zeros:n,setLength:o,setLengthRight:function(e,t){return o(e,t,!0)},isHexString:c,stripHexPrefix:h,toBuffer:l,bufferToHex:function(e){return"0x"+(e=l(e)).toString("hex")},keccak:function(e,t){if(e=l(e),t||(t=256),256!==t)throw Error("unsupported");return r.Buffer.from(s(new Uint8Array(e)))},bitLengthFromBigInt:function(e){return e.toString(2).length},bufferBEFromBigInt:a,twosFromBigInt:function(e,t){return(e<0n?(~e&(1n<<BigInt(t))-1n)+1n:e)&(1n<<BigInt(t))-1n}}},626979,(e,t,i)=>{var r=e.i(467034);let s=e.r(347558);function n(e){if(e.startsWith("int["))return"int256"+e.slice(3);if("int"===e)return"int256";if(e.startsWith("uint["))return"uint256"+e.slice(4);if("uint"===e)return"uint256";if(e.startsWith("fixed["))return"fixed128x128"+e.slice(5);else if("fixed"===e)return"fixed128x128";else if(e.startsWith("ufixed["))return"ufixed128x128"+e.slice(6);else if("ufixed"===e)return"ufixed128x128";return e}function a(e){return Number.parseInt(/^\D+(\d+)$/.exec(e)[1],10)}function o(e){var t=/^\D+(\d+)x(\d+)$/.exec(e);return[Number.parseInt(t[1],10),Number.parseInt(t[2],10)]}function l(e){var t=e.match(/(.*)\[(.*?)\]$/);return t?""===t[2]?"dynamic":Number.parseInt(t[2],10):null}function c(e){var t=typeof e;if("string"===t||"number"===t)return BigInt(e);if("bigint"===t)return e;throw Error("Argument is not a number")}function h(e,t){if("address"===e)return h("uint160",c(t));if("bool"===e)return h("uint8",+!!t);if("string"===e)return h("bytes",new r.Buffer(t,"utf8"));if((p=e).lastIndexOf("]")===p.length-1){if(void 0===t.length)throw Error("Not an array?");if("dynamic"!==(i=l(e))&&0!==i&&t.length>i)throw Error("Elements exceed array size: "+i);for(u in d=[],e=e.slice(0,e.lastIndexOf("[")),"string"==typeof t&&(t=JSON.parse(t)),t)d.push(h(e,t[u]));if("dynamic"===i){var i,n,d,u,p,f=h("uint256",t.length);d.unshift(f)}return r.Buffer.concat(d)}else if("bytes"===e)return t=new r.Buffer(t),d=r.Buffer.concat([h("uint256",t.length),t]),t.length%32!=0&&(d=r.Buffer.concat([d,s.zeros(32-t.length%32)])),d;else if(e.startsWith("bytes")){if((i=a(e))<1||i>32)throw Error("Invalid bytes<N> width: "+i);return s.setLengthRight(t,32)}else if(e.startsWith("uint")){if((i=a(e))%8||i<8||i>256)throw Error("Invalid uint<N> width: "+i);n=c(t);let r=s.bitLengthFromBigInt(n);if(r>i)throw Error("Supplied uint exceeds width: "+i+" vs "+r);if(n<0)throw Error("Supplied uint is negative");return s.bufferBEFromBigInt(n,32)}else if(e.startsWith("int")){if((i=a(e))%8||i<8||i>256)throw Error("Invalid int<N> width: "+i);n=c(t);let r=s.bitLengthFromBigInt(n);if(r>i)throw Error("Supplied int exceeds width: "+i+" vs "+r);let o=s.twosFromBigInt(n,256);return s.bufferBEFromBigInt(o,32)}else if(e.startsWith("ufixed")){if(i=o(e),(n=c(t))<0)throw Error("Supplied ufixed is negative");return h("uint256",n*BigInt(2)**BigInt(i[1]))}else if(e.startsWith("fixed"))return i=o(e),h("int256",c(t)*BigInt(2)**BigInt(i[1]));throw Error("Unsupported or invalid type: "+e)}function d(e,t){if(e.length!==t.length)throw Error("Number of types are not matching the values");for(var i,o,l=[],h=0;h<e.length;h++){var d=n(e[h]),u=t[h];if("bytes"===d)l.push(u);else if("string"===d)l.push(new r.Buffer(u,"utf8"));else if("bool"===d)l.push(new r.Buffer(u?"01":"00","hex"));else if("address"===d)l.push(s.setLength(u,20));else if(d.startsWith("bytes")){if((i=a(d))<1||i>32)throw Error("Invalid bytes<N> width: "+i);l.push(s.setLengthRight(u,i))}else if(d.startsWith("uint")){if((i=a(d))%8||i<8||i>256)throw Error("Invalid uint<N> width: "+i);o=c(u);let e=s.bitLengthFromBigInt(o);if(e>i)throw Error("Supplied uint exceeds width: "+i+" vs "+e);l.push(s.bufferBEFromBigInt(o,i/8))}else if(d.startsWith("int")){if((i=a(d))%8||i<8||i>256)throw Error("Invalid int<N> width: "+i);o=c(u);let e=s.bitLengthFromBigInt(o);if(e>i)throw Error("Supplied int exceeds width: "+i+" vs "+e);let t=s.twosFromBigInt(o,i);l.push(s.bufferBEFromBigInt(t,i/8))}else throw Error("Unsupported or invalid type: "+d)}return r.Buffer.concat(l)}t.exports={rawEncode:function(e,t){var i=[],s=[],a=32*e.length;for(var o in e){var c=n(e[o]),d=h(c,t[o]);"string"===c||"bytes"===c||"dynamic"===l(c)?(i.push(h("uint256",a)),s.push(d),a+=d.length):i.push(d)}return r.Buffer.concat(i.concat(s))},solidityPack:d,soliditySHA3:function(e,t){return s.keccak(d(e,t))}}},622207,(e,t,i)=>{var r=e.i(467034);let s=e.r(347558),n=e.r(626979),a={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},o={encodeData(e,t,i,a=!0){let o=["bytes32"],l=[this.hashType(e,i)];if(a){let c=(e,t,o)=>{if(void 0!==i[t])return["bytes32",null==o?"0x0000000000000000000000000000000000000000000000000000000000000000":s.keccak(this.encodeData(t,o,i,a))];if(void 0===o)throw Error(`missing value for field ${e} of type ${t}`);if("bytes"===t)return["bytes32",s.keccak(o)];if("string"===t)return"string"==typeof o&&(o=r.Buffer.from(o,"utf8")),["bytes32",s.keccak(o)];if(t.lastIndexOf("]")===t.length-1){let i=t.slice(0,t.lastIndexOf("[")),r=o.map(t=>c(e,i,t));return["bytes32",s.keccak(n.rawEncode(r.map(([e])=>e),r.map(([,e])=>e)))]}return[t,o]};for(let r of i[e]){let[e,i]=c(r.name,r.type,t[r.name]);o.push(e),l.push(i)}}else for(let n of i[e]){let e=t[n.name];
1if(void 0!==e)if("bytes"===n.type)o.push("bytes32"),e=s.keccak(e),l.push(e);else if("string"===n.type)o.push("bytes32"),"string"==typeof e&&(e=r.Buffer.from(e,"utf8")),e=s.keccak(e),l.push(e);else if(void 0!==i[n.type])o.push("bytes32"),e=s.keccak(this.encodeData(n.type,e,i,a)),l.push(e);else if(n.type.lastIndexOf("]")===n.type.length-1)throw Error("Arrays currently unimplemented in encodeData");else o.push(n.type),l.push(e)}return n.rawEncode(o,l)},encodeType(e,t){let i="",r=this.findTypeDependencies(e,t).filter(t=>t!==e);for(let s of r=[e].concat(r.sort())){if(!t[s])throw Error("No type definition specified: "+s);i+=s+"("+t[s].map(({name:e,type:t})=>t+" "+e).join(",")+")"}return i},findTypeDependencies(e,t,i=[]){if(e=e.match(/^\w*/)[0],i.includes(e)||void 0===t[e])return i;for(let r of(i.push(e),t[e]))for(let e of this.findTypeDependencies(r.type,t,i))i.includes(e)||i.push(e);return i},hashStruct(e,t,i,r=!0){return s.keccak(this.encodeData(e,t,i,r))},hashType(e,t){return s.keccak(this.encodeType(e,t))},sanitizeData(e){let t={};for(let i in a.properties)e[i]&&(t[i]=e[i]);return t.types&&(t.types=Object.assign({EIP712Domain:[]},t.types)),t},hash(e,t=!0){let i=this.sanitizeData(e),n=[r.Buffer.from("1901","hex")];return n.push(this.hashStruct("EIP712Domain",i.domain,i.types,t)),"EIP712Domain"!==i.primaryType&&n.push(this.hashStruct(i.primaryType,i.message,i.types,t)),s.keccak(r.Buffer.concat(n))}};t.exports={TYPED_MESSAGE_SCHEMA:a,TypedDataUtils:o,hashForSignTypedDataLegacy:function(e){return function(e){let t=Error("Expect argument to be non-empty array");if("object"!=typeof e||!e.length)throw t;let i=e.map(function(e){return"bytes"===e.type?s.toBuffer(e.value):e.value}),r=e.map(function(e){return e.type}),a=e.map(function(e){if(!e.name)throw t;return e.type+" "+e.name});return n.soliditySHA3(["bytes32","bytes32"],[n.soliditySHA3(Array(e.length).fill("string"),a),n.soliditySHA3(r,i)])}(e.data)},hashForSignTypedData_v3:function(e){return o.hash(e.data,!1)},hashForSignTypedData_v4:function(e){return o.hash(e.data)}}},572206,(e,t,i)=>{"use strict";let r=e.r(71187);t.exports=h;let s=function(){function e(e){return void 0!==e&&e}try{if("u">typeof globalThis)return globalThis;return Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch(t){return e(self)||e(window)||e(this)||{}}}().console||{};function n(e,t){return"silent"===e?1/0:t.levels.values[e]}let a=Symbol("pino.logFuncs"),o=Symbol("pino.hierarchy"),l={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function c(e,t){let i={logger:t,parent:e[o]};t[o]=i}function h(e){var t,i,r;let o,f,g;(e=e||{}).browser=e.browser||{};let y=e.browser.transmit;if(y&&"function"!=typeof y.send)throw Error("pino: transmit option must have a send function");let v=e.browser.write||s;e.browser.write&&(e.browser.asObject=!0);let E=e.serializers||{},I=(t=e.browser.serialize,Array.isArray(t)?t.filter(function(e){return"!stdSerializers.err"!==e}):!0===t&&Object.keys(E)),S=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(S=!1);let A=Object.keys(e.customLevels||{}),x=["error","fatal","warn","info","debug","trace"].concat(A);"function"==typeof v&&x.forEach(function(e){v[e]=v}),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");let P=e.level||"info",C=Object.create(v);C.log||(C.log=m),o={},x.forEach(e=>{o[e]=v[e]?v[e]:s[e]||s[l[e]||"log"]||m}),C[a]=o,c({},C),Object.defineProperty(C,"levelVal",{get:function(){return n(this.level,this)}}),Object.defineProperty(C,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,d(this,_,C,"error"),d(this,_,C,"fatal"),d(this,_,C,"warn"),d(this,_,C,"info"),d(this,_,C,"debug"),d(this,_,C,"trace"),A.forEach(e=>{d(this,_,C,e)})}});let _={transmit:y,serialize:I,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:x,timestamp:"function"==typeof(i=e).timestamp?i.timestamp:!1===i.timestamp?w:b,messageKey:e.messageKey||"msg",onChild:e.onChild||m};function k(t,i,r){if(!i)throw Error("missing bindings for child Pino");r=r||{},I&&i.serializers&&(r.serializers=i.serializers);let s=r.serializers;if(I&&s){var n=Object.assign({},E,s),a=!0===e.browser.serialize?Object.keys(n):I;delete i.serializers,u([i],a,n,this._stdErrSerialize)}function o(e){this._childLevel=(0|e._childLevel)+1,this.bindings=i,n&&(this.serializers=n,this._serialize=a),y&&(this._logEvent=p([].concat(e._logEvent.bindings,i)))}o.prototype=this;let l=new o(this);return c(this,l),l.child=function(...e){return k.call(this,t,...e)},l.level=r.level||this.level,t.onChild(l),l}return f=e.customLevels||{},C.levels={values:Object.assign({},h.levels.values,f),labels:Object.assign({},h.levels.labels,(g={},Object.keys(r=f).forEach(function(e){g[r[e]]=e}),g))},C.level=P,C.isLevelEnabled=function(e){return!!this.levels.values[e]&&this.levels.values[e]>=this.levels.values[this.level]}
1,C.setMaxListeners=C.getMaxListeners=C.emit=C.addListener=C.on=C.prependListener=C.once=C.prependOnceListener=C.removeListener=C.removeAllListeners=C.listeners=C.listenerCount=C.eventNames=C.write=C.flush=m,C.serializers=E,C._serialize=I,C._stdErrSerialize=S,C.child=function(...e){return k.call(this,_,...e)},y&&(C._logEvent=p()),C}function d(e,t,i,l){var c,h,d,f,g,y,w;if(Object.defineProperty(e,l,{value:n(e.level,i)>n(l,i)?m:i[a][l],writable:!0,enumerable:!0,configurable:!0}),e[l]===m){if(!t.transmit)return;let r=n(t.transmit.level||e.level,i);if(n(l,i)<r)return}e[l]=(c=e,h=t,d=i,f=l,g=c[a][f],function(){let e=h.timestamp(),t=Array(arguments.length),i=Object.getPrototypeOf&&Object.getPrototypeOf(this)===s?s:this;for(var a=0;a<t.length;a++)t[a]=arguments[a];var o=!1;if(h.serialize&&(u(t,this._serialize,this.serializers,this._stdErrSerialize),o=!0),h.asObject||h.formatters?g.call(i,...function(e,t,i,s,n){let{level:a,log:o=e=>e}=n.formatters||{},l=i.slice(),c=l[0],h={},d=(0|e._childLevel)+1;if(d<1&&(d=1),s&&(h.time=s),a?Object.assign(h,a(t,e.levels.values[t])):h.level=e.levels.values[t],n.asObjectBindingsOnly){if(null!==c&&"object"==typeof c)for(;d--&&"object"==typeof l[0];)Object.assign(h,l.shift());return[o(h),...l]}if(null!==c&&"object"==typeof c){for(;d--&&"object"==typeof l[0];)Object.assign(h,l.shift());c=l.length?r(l.shift(),l):void 0}else"string"==typeof c&&(c=r(l.shift(),l));return void 0!==c&&(h[n.messageKey]=c),[o(h)]}(this,f,t,e,h)):g.apply(i,t),h.transmit){let i=h.transmit.level||c._level,r=n(i,d),s=n(f,d);if(s<r)return;!function(e,t,i,r=!1){let s=t.send,n=t.ts,a=t.methodLevel,o=t.methodValue,l=t.val,c=e._logEvent.bindings;r||u(i,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize),e._logEvent.ts=n,e._logEvent.messages=i.filter(function(e){return -1===c.indexOf(e)}),e._logEvent.level.label=a,e._logEvent.level.value=o,s(a,e._logEvent,l),e._logEvent=p(c)}(this,{ts:e,methodLevel:f,methodValue:s,transmitLevel:i,transmitValue:d.levels.values[h.transmit.level||c._level],send:h.transmit.send,val:n(c._level,d)},t,o)}});let b=function(e){let t=[];e.bindings&&t.push(e.bindings);let i=e[o];for(;i.parent;)(i=i.parent).logger.bindings&&t.push(i.logger.bindings);return t.reverse()}(e);0!==b.length&&(e[l]=(y=b,w=e[l],function(){return w.apply(this,[...y,...arguments])}))}function u(e,t,i,r){for(let s in e)if(r&&e[s]instanceof Error)e[s]=h.stdSerializers.err(e[s]);else if("object"==typeof e[s]&&!Array.isArray(e[s])&&t)for(let r in e[s])t.indexOf(r)>-1&&r in i&&(e[s][r]=i[r](e[s][r]))}function p(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function f(e){let t={type:e.constructor.name,msg:e.message,stack:e.stack};for(let i in e)void 0===t[i]&&(t[i]=e[i]);return t}function g(){return{}}function y(e){return e}function m(){}function w(){return!1}function b(){return Date.now()}h.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},h.stdSerializers={mapHttpRequest:g,mapHttpResponse:g,wrapRequestSerializer:y,wrapResponseSerializer:y,wrapErrorSerializer:y,req:g,res:g,err:f,errWithCause:f},h.stdTimeFunctions=Object.assign({},{nullTime:w,epochTime:b,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),t.exports.default=h,t.exports.pino=h},324607,992744,e=>{"use strict";let t,i,r,s,n,a,o,l,c,h,d,u,p;class f extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(e){var t;super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,null==(t=Error.captureStackTrace)||t.call(Error,this,this.constructor)}}class g extends f{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(e,t="unspecified",i="unspecified"){super(e),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=i}}class y extends f{static get code(){return"ERR_JWT_EXPIRED"}constructor(e,t="unspecified",i="unspecified"){super(e),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=i}}class m extends f{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}}class w extends f{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class b extends f{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}}class v extends f{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}}class E extends f{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class I extends f{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}class S extends f{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}}class A extends f{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}}class x extends f{constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}}class P extends f{constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}class C extends f{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}}class _ extends f{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}e.s(["JOSEAlgNotAllowed",0,m,"JOSEError",0,f,"JOSENotSupported",0,w,"JWEDecompressionFailed",0,class extends f{constructor(){super(...arguments),this.code="ERR_JWE_DECOMPRESSION_FAILED",this.message="decompression o
1peration failed"}static get code(){return"ERR_JWE_DECOMPRESSION_FAILED"}},"JWEDecryptionFailed",0,b,"JWEInvalid",0,v,"JWKInvalid",0,S,"JWKSInvalid",0,A,"JWKSMultipleMatchingKeys",0,P,"JWKSNoMatchingKey",0,x,"JWKSTimeout",0,C,"JWSInvalid",0,E,"JWSSignatureVerificationFailed",0,_,"JWTClaimValidationFailed",0,g,"JWTExpired",0,y,"JWTInvalid",0,I],935572);var k=e.i(935572),O=e.i(86346);e.s([],893606),e.i(893606);var T=e.i(913970),R=e.i(248488),N=e.i(888840);let j=N.default.getRandomValues.bind(N.default);function D(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new w(`Unsupported JWE Algorithm: ${e}`)}}let M=e=>j(new Uint8Array(D(e)>>3)),U=(e,t)=>{if(t.length<<3!==D(e))throw new v("Invalid Initialization Vector length")},B=(e,t)=>{let i=e.byteLength<<3;if(i!==t)throw new v(`Invalid Content Encryption Key length. Expected ${t} bits, got ${i} bits`)};function L(e,t="algorithm.name"){return TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function q(e,t){return e.name===t}function K(e){return parseInt(e.name.slice(4),10)}function H(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let i=t.pop();e+=`one of ${t.join(", ")}, or ${i}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw TypeError(e)}}function $(e,t,...i){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!q(e.algorithm,"AES-GCM"))throw L("AES-GCM");let i=parseInt(t.slice(1,4),10);if(e.algorithm.length!==i)throw L(i,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!q(e.algorithm,"AES-KW"))throw L("AES-KW");let i=parseInt(t.slice(1,4),10);if(e.algorithm.length!==i)throw L(i,"algorithm.length");break}case"ECDH":switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw L("ECDH, X25519, or X448")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!q(e.algorithm,"PBKDF2"))throw L("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!q(e.algorithm,"RSA-OAEP"))throw L("RSA-OAEP");let i=parseInt(t.slice(9),10)||1;if(K(e.algorithm.hash)!==i)throw L(`SHA-${i}`,"algorithm.hash");break}default:throw TypeError("CryptoKey does not support this operation")}H(e,i)}function W(e,t,...i){if(i.length>2){let t=i.pop();e+=`one of type ${i.join(", ")}, or ${t}.`}else 2===i.length?e+=`one of type ${i[0]} or ${i[1]}.`:e+=`of type ${i[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}let z=(e,...t)=>W("Key must be ",e,...t);function F(e,t,...i){return W(`Key for the ${e} algorithm must be `,t,...i)}let V=e=>(0,N.isCryptoKey)(e),J=["CryptoKey"];async function G(e,t,i,r,s,n){let a,o;if(!(t instanceof Uint8Array))throw TypeError(z(t,"Uint8Array"));let l=parseInt(e.slice(1,4),10),c=await N.default.subtle.importKey("raw",t.subarray(l>>3),"AES-CBC",!1,["decrypt"]),h=await N.default.subtle.importKey("raw",t.subarray(0,l>>3),{hash:`SHA-${l<<1}`,name:"HMAC"},!1,["sign"]),d=(0,R.concat)(n,r,i,(0,R.uint64be)(n.length<<3)),u=new Uint8Array((await N.default.subtle.sign("HMAC",h,d)).slice(0,l>>3));try{a=((e,t)=>{if(!(e instanceof Uint8Array))throw TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw TypeError("Second argument must be a buffer");if(e.length!==t.length)throw TypeError("Input buffers must have the same length");let i=e.length,r=0,s=-1;for(;++s<i;)r|=e[s]^t[s];return 0===r})(s,u)}catch(e){}if(!a)throw new b;try{o=new Uint8Array(await N.default.subtle.decrypt({iv:r,name:"AES-CBC"},c,i))}catch(e){}if(!o)throw new b;return o}async function Y(e,t,i,r,s,n){let a;t instanceof Uint8Array?a=await N.default.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):($(t,e,"decrypt"),a=t);try{return new Uint8Array(await N.default.subtle.decrypt({additionalData:n,iv:r,name:"AES-GCM",tagLength:128},a,(0,R.concat)(i,s)))}catch(e){throw new b}}let Z=async(e,t,i,r,s,n)=>{if(!(0,N.isCryptoKey)(t)&&!(t instanceof Uint8Array))throw TypeError(z(t,...J,"Uint8Array"));switch(U(e,r),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&B(t,parseInt(e.slice(-3),10)),G(e,t,i,r,s,n);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&B(t,parseInt(e.slice(1,4),10)),Y(e,t,i,r,s,n);default:throw new w("Unsupported JWE Content Encryption Algorithm")}},Q=async()=>{throw new w('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},X=async()=>{throw new w('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')},ee=(...e)=>
1{let t,i=e.filter(Boolean);if(0===i.length||1===i.length)return!0;for(let e of i){let i=Object.keys(e);if(!t||0===t.size){t=new Set(i);continue}for(let e of i){if(t.has(e))return!1;t.add(e)}}return!0};function et(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}let ei=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]];function er(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function es(e,t,i){if((0,N.isCryptoKey)(e))return $(e,t,i),e;if(e instanceof Uint8Array)return N.default.subtle.importKey("raw",e,"AES-KW",!0,[i]);throw TypeError(z(e,...J,"Uint8Array"))}let en=async(e,t,i)=>{let r=await es(t,e,"wrapKey");er(r,e);let s=await N.default.subtle.importKey("raw",i,...ei);return new Uint8Array(await N.default.subtle.wrapKey("raw",s,r,"AES-KW"))},ea=async(e,t,i)=>{let r=await es(t,e,"unwrapKey");er(r,e);let s=await N.default.subtle.unwrapKey("raw",i,r,"AES-KW",...ei);return new Uint8Array(await N.default.subtle.exportKey("raw",s))};async function eo(e,t,i,r,s=new Uint8Array(0),n=new Uint8Array(0)){let a;if(!(0,N.isCryptoKey)(e))throw TypeError(z(e,...J));if($(e,"ECDH"),!(0,N.isCryptoKey)(t))throw TypeError(z(t,...J));$(t,"ECDH","deriveBits");let o=(0,R.concat)((0,R.lengthAndInput)(R.encoder.encode(i)),(0,R.lengthAndInput)(s),(0,R.lengthAndInput)(n),(0,R.uint32be)(r));a="X25519"===e.algorithm.name?256:"X448"===e.algorithm.name?448:Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;let l=new Uint8Array(await N.default.subtle.deriveBits({name:e.algorithm.name,public:e},t,a));return(0,R.concatKdf)(l,r,o)}async function el(e){if(!(0,N.isCryptoKey)(e))throw TypeError(z(e,...J));return N.default.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function ec(e){if(!(0,N.isCryptoKey)(e))throw TypeError(z(e,...J));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||"X25519"===e.algorithm.name||"X448"===e.algorithm.name}async function eh(e,t,i,r){if(!(e instanceof Uint8Array)||e.length<8)throw new v("PBES2 Salt Input must be 8 or more octets");let s=(0,R.p2s)(t,e),n=parseInt(t.slice(13,16),10),a={hash:`SHA-${t.slice(8,11)}`,iterations:i,name:"PBKDF2",salt:s},o=await function(e,t){if(e instanceof Uint8Array)return N.default.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if((0,N.isCryptoKey)(e))return $(e,t,"deriveBits","deriveKey"),e;throw TypeError(z(e,...J,"Uint8Array"))}(r,t);if(o.usages.includes("deriveBits"))return new Uint8Array(await N.default.subtle.deriveBits(a,o,n));if(o.usages.includes("deriveKey"))return N.default.subtle.deriveKey(a,o,{length:n,name:"AES-KW"},!1,["wrapKey","unwrapKey"]);throw TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}let ed=async(e,t,i,r=2048,s=j(new Uint8Array(16)))=>{let n=await eh(s,e,r,t);return{encryptedKey:await en(e.slice(-6),n,i),p2c:r,p2s:(0,T.encode)(s)}},eu=async(e,t,i,r,s)=>{let n=await eh(s,e,r,t);return ea(e.slice(-6),n,i)};function ep(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new w(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}let ef=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:i}=t.algorithm;if("number"!=typeof i||i<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}},eg=async(e,t,i)=>{if(!(0,N.isCryptoKey)(t))throw TypeError(z(t,...J));if($(t,e,"encrypt","wrapKey"),ef(e,t),t.usages.includes("encrypt"))return new Uint8Array(await N.default.subtle.encrypt(ep(e),t,i));if(t.usages.includes("wrapKey")){let r=await N.default.subtle.importKey("raw",i,...ei);return new Uint8Array(await N.default.subtle.wrapKey("raw",r,t,ep(e)))}throw TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},ey=async(e,t,i)=>{if(!(0,N.isCryptoKey)(t))throw TypeError(z(t,...J));if($(t,e,"decrypt","unwrapKey"),ef(e,t),t.usages.includes("decrypt"))return new Uint8Array(await N.default.subtle.decrypt(ep(e),t,i));if(t.usages.includes("unwrapKey")){let r=await N.default.subtle.unwrapKey("raw",i,t,ep(e),...ei);return new Uint8Array(await N.default.subtle.exportKey("raw",r))}throw TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')};function em(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new w(`Unsupported JWE Algorithm: ${e}`)}}let ew=e=>j(new Uint8Array(em(e)>>3)),eb=(e,t)=>{let i=(e.match(/.{1,64}/g)||[]).join("\n");return`-----BEGIN ${t}-----
2${i}
3-----END ${t}-----`},ev=async(e,t,i)=>{if(!(0,N.isCryptoKey)(i))throw TypeError(z(i,...J));if(!i.extractable)throw TypeError("CryptoKey is not extractable");if(i.type!==e)throw TypeError(`key is not a ${e} key`);return eb((0,T.encodeBase64)(new Uint8Array(await N.default.subtle.exportKey(t,i))),`${e.toUpperCase()} KEY`)},eE=(e,t,i=0)=>{0===i&&(t.unshift(t.length),t.unshift(6));let r=e.indexOf(t[0],i);if(-1===r)return!1;let s=e.subarray(r,r+t.length);return s.length===t.length&&(s.every((e,i)=>e===t[i])||eE(e,t,r+1))},eI=e=>{switch(!0){case eE(e,[42,134,72,206,61,3,1,7]):return"P-256";case eE(e,[43,129,4,0,34]):return"P-384";case eE(e,[43,129,4,0,35]):return"P-521";case eE(e,[43,101,110]):return"X25519";case eE(e,[43,101,111]):return"X448";case eE(e,[43,101,112]):return"Ed25519";case eE(e,[43,101,113]):return"Ed448";default:throw new w("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},eS=async(e,t,i,r,s)=>{var n;let a,o,l=new Uint8Array(atob(i.replace(e,"")).split("").map(e=>e.charCodeAt(0))),c="spki"===t;switch(r){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},o=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},o=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},o=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},o=c?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},o=c?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},o=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let e=eI(l);a=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},o=c?[]:["deriveBits"];break}
3case"EdDSA":a={name:eI(l)},o=c?["verify"]:["sign"];break;default:throw new w('Invalid or unsupported "alg" (Algorithm) value')}return N.default.subtle.importKey(t,l,a,null!=(n=null==s?void 0:s.extractable)&&n,o)};function eA(e){let t=[],i=0;for(;i<e.length;){let r=ex(e.subarray(i));t.push(r),i+=r.byteLength}return t}function ex(e){let t=0,i=31&e[0];if(t++,31===i){for(i=0;e[t]>=128;)i=128*i+e[t]-128,t++;i=128*i+e[t]-128,t++}let r=0;if(e[t]<128)r=e[t],t++;else if(128===r){for(r=0;0!==e[t+r]||0!==e[t+r+1];){if(r>e.byteLength)throw TypeError("invalid indefinite form length");r++}let i=t+r+2;return{byteLength:i,contents:e.subarray(t,t+r),raw:e.subarray(0,i)}}else{let i=127&e[t];t++,r=0;for(let s=0;s<i;s++)r=256*r+e[t],t++}let s=t+r;return{byteLength:s,contents:e.subarray(t,s),raw:e.subarray(0,s)}}let eP=async e=>{var t,i;if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:r,keyUsages:s}=function(e){let t,i;switch(e.kty){case"oct":switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},i=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new w(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},i=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},i=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},i=["deriveBits"];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},i=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},i=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},i=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},i=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},i=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},i=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},i=e.d?["deriveBits"]:[];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"EdDSA":t={name:e.crv},i=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},i=e.d?["deriveBits"]:[];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new w('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:i}}(e),n=[r,null!=(t=e.ext)&&t,null!=(i=e.key_ops)?i:s];if("PBKDF2"===r.name)return N.default.subtle.importKey("raw",(0,T.decode)(e.k),...n);let a={...e};return delete a.alg,delete a.use,N.default.subtle.importKey("jwk",a,...n)};async function eC(e,t,i){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw TypeError('"spki" must be SPKI formatted string');return eS(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,i)}async function e_(e,t,i){let r;if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw TypeError('"x509" must be X.509 formatted string');try{let t,i;i=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=eb((t=eA(eA(ex((0,T.decodeBase64)(i)).contents)[0].contents),(0,T.encodeBase64)(t[160===t[0].raw[0]?6:5].raw)),"PUBLIC KEY")}catch(e){throw TypeError("Failed to parse the X.509 certificate",{cause:e})}return eS(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",r,t,i)}async function ek(e,t,i){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw TypeError('"pkcs8" must be PKCS#8 formatted string');
3return eS(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,i)}async function eO(e,t,i){var r;if(!et(e))throw TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');if(null!=i||(i=!0!==e.ext),i)return eP({...e,alg:t,ext:null!=(r=e.ext)&&r});return(0,T.decode)(e.k);case"RSA":if(void 0!==e.oth)throw new w('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return eP({...e,alg:t});default:throw new w('Unsupported "kty" (Key Type) Parameter value')}}let eT=(e,t,i)=>{if(e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)){if(!(t instanceof Uint8Array)){if(!V(t))throw TypeError(F(e,t,...J,"Uint8Array"));if("secret"!==t.type)throw TypeError(`${J.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}}else{if(!V(t))throw TypeError(F(e,t,...J));if("secret"===t.type)throw TypeError(`${J.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===i&&"public"===t.type)throw TypeError(`${J.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===i&&"public"===t.type)throw TypeError(`${J.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===i&&"private"===t.type)throw TypeError(`${J.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===i&&"private"===t.type)throw TypeError(`${J.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)}};async function eR(e,t,i,r,s){if(!(i instanceof Uint8Array))throw TypeError(z(i,"Uint8Array"));let n=parseInt(e.slice(1,4),10),a=await N.default.subtle.importKey("raw",i.subarray(n>>3),"AES-CBC",!1,["encrypt"]),o=await N.default.subtle.importKey("raw",i.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]),l=new Uint8Array(await N.default.subtle.encrypt({iv:r,name:"AES-CBC"},a,t)),c=(0,R.concat)(s,r,l,(0,R.uint64be)(s.length<<3));return{ciphertext:l,tag:new Uint8Array((await N.default.subtle.sign("HMAC",o,c)).slice(0,n>>3))}}async function eN(e,t,i,r,s){let n;i instanceof Uint8Array?n=await N.default.subtle.importKey("raw",i,"AES-GCM",!1,["encrypt"]):($(i,e,"encrypt"),n=i);let a=new Uint8Array(await N.default.subtle.encrypt({additionalData:s,iv:r,name:"AES-GCM",tagLength:128},n,t)),o=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:o}}let ej=async(e,t,i,r,s)=>{if(!(0,N.isCryptoKey)(i)&&!(i instanceof Uint8Array))throw TypeError(z(i,...J,"Uint8Array"));switch(U(e,r),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return i instanceof Uint8Array&&B(i,parseInt(e.slice(-3),10)),eR(e,t,i,r,s);case"A128GCM":case"A192GCM":case"A256GCM":return i instanceof Uint8Array&&B(i,parseInt(e.slice(1,4),10)),eN(e,t,i,r,s);default:throw new w("Unsupported JWE Content Encryption Algorithm")}};async function eD(e,t,i,r){let s=e.slice(0,7);r||(r=M(s));let{ciphertext:n,tag:a}=await ej(s,i,t,r,new Uint8Array(0));return{encryptedKey:n,iv:(0,T.encode)(r),tag:(0,T.encode)(a)}}async function eM(e,t,i,r,s){return Z(e.slice(0,7),t,i,r,s,new Uint8Array(0))}async function eU(e,t,i,r,s){switch(eT(e,t,"decrypt"),e){case"dir":if(void 0!==i)throw new v("Encountered unexpected JWE Encrypted Key");return t;case"ECDH-ES":if(void 0!==i)throw new v("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let s,n;if(!et(r.epk))throw new v('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!ec(t))throw new w("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await eO(r.epk,e);if(void 0!==r.apu){if("string"!=typeof r.apu)throw new v('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{s=(0,T.decode)(r.apu)}catch(e){throw new v("Failed to base64url decode the apu")}}if(void 0!==r.apv){if("string"!=typeof r.apv)throw new v('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{n=(0,T.decode)(r.apv)}catch(e){throw new v("Failed to base64url decode the apv")}}let o=await eo(a,t,"ECDH-ES"===e?r.enc:e,"ECDH-ES"===e?em(r.enc):parseInt(e.slice(-5,-2),10),s,n);if("ECDH-ES"===e)return o;if(void 0===i)throw new v("JWE Encrypted Key missing");return ea(e.slice(-6),o,i)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if(void 0===i)throw new v("JWE Encrypted Key missing");return ey(e,t,i);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{let n;if(void 0===i)throw new v("JWE Encrypted Key missing");if("number"!=typeof r.p2c)throw new v('JOSE Header "p2c" (PBES2 Count) missing or invalid');let a=(null==s?void 0:s.maxPBES2Count)||1e4;if(r.p2c>a)throw new v('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof r.p2s)throw new v('JOSE Header "p2s" (PBES2 Salt) missing or invalid');try{n=(0,T.decode)(r.p2s)}catch(e){throw new v("Failed to base64url decode the p2s")}return eu(e,t,i,r.p2c,n)}
3case"A128KW":case"A192KW":case"A256KW":if(void 0===i)throw new v("JWE Encrypted Key missing");return ea(e,t,i);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{let s,n;if(void 0===i)throw new v("JWE Encrypted Key missing");if("string"!=typeof r.iv)throw new v('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof r.tag)throw new v('JOSE Header "tag" (Authentication Tag) missing or invalid');try{s=(0,T.decode)(r.iv)}catch(e){throw new v("Failed to base64url decode the iv")}try{n=(0,T.decode)(r.tag)}catch(e){throw new v("Failed to base64url decode the tag")}return eM(e,t,i,s,n)}default:throw new w('Invalid or unsupported "alg" (JWE Algorithm) header value')}}let eB=function(e,t,i,r,s){let n;if(void 0!==s.crit&&void 0===r.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||void 0===r.crit)return new Set;if(!Array.isArray(r.crit)||0===r.crit.length||r.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let a of(n=void 0!==i?new Map([...Object.entries(i),...t.entries()]):t,r.crit)){if(!n.has(a))throw new w(`Extension Header Parameter "${a}" is not recognized`);if(void 0===s[a])throw new e(`Extension Header Parameter "${a}" is missing`);if(n.get(a)&&void 0===r[a])throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(r.crit)},eL=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};async function eq(e,t,i){var r;let s,n,a,o,l,c,h;if(!et(e))throw new v("Flattened JWE must be an object");if(void 0===e.protected&&void 0===e.header&&void 0===e.unprotected)throw new v("JOSE Header missing");if("string"!=typeof e.iv)throw new v("JWE Initialization Vector missing or incorrect type");if("string"!=typeof e.ciphertext)throw new v("JWE Ciphertext missing or incorrect type");if("string"!=typeof e.tag)throw new v("JWE Authentication Tag missing or incorrect type");if(void 0!==e.protected&&"string"!=typeof e.protected)throw new v("JWE Protected Header incorrect type");if(void 0!==e.encrypted_key&&"string"!=typeof e.encrypted_key)throw new v("JWE Encrypted Key incorrect type");if(void 0!==e.aad&&"string"!=typeof e.aad)throw new v("JWE AAD incorrect type");if(void 0!==e.header&&!et(e.header))throw new v("JWE Shared Unprotected Header incorrect type");if(void 0!==e.unprotected&&!et(e.unprotected))throw new v("JWE Per-Recipient Unprotected Header incorrect type");if(e.protected)try{let t=(0,T.decode)(e.protected);s=JSON.parse(R.decoder.decode(t))}catch(e){throw new v("JWE Protected Header is invalid")}if(!ee(s,e.header,e.unprotected))throw new v("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let d={...s,...e.header,...e.unprotected};if(eB(v,new Map,null==i?void 0:i.crit,s,d),void 0!==d.zip){if(!s||!s.zip)throw new v('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==d.zip)throw new w('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:u,enc:p}=d;if("string"!=typeof u||!u)throw new v("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof p||!p)throw new v("missing JWE Encryption Algorithm (enc) in JWE Header");let f=i&&eL("keyManagementAlgorithms",i.keyManagementAlgorithms),g=i&&eL("contentEncryptionAlgorithms",i.contentEncryptionAlgorithms);if(f&&!f.has(u))throw new m('"alg" (Algorithm) Header Parameter not allowed');if(g&&!g.has(p))throw new m('"enc" (Encryption Algorithm) Header Parameter not allowed');if(void 0!==e.encrypted_key)try{n=(0,T.decode)(e.encrypted_key)}catch(e){throw new v("Failed to base64url decode the encrypted_key")}let y=!1;"function"==typeof t&&(t=await t(s,e),y=!0);try{a=await eU(u,t,n,d,i)}catch(e){if(e instanceof TypeError||e instanceof v||e instanceof w)throw e;a=ew(p)}try{o=(0,T.decode)(e.iv)}catch(e){throw new v("Failed to base64url decode the iv")}try{l=(0,T.decode)(e.tag)}catch(e){throw new v("Failed to base64url decode the tag")}let b=R.encoder.encode(null!=(r=e.protected)?r:"");c=void 0!==e.aad?(0,R.concat)(b,R.encoder.encode("."),R.encoder.encode(e.aad)):b;try{h=(0,T.decode)(e.ciphertext)}catch(e){throw new v("Failed to base64url decode the ciphertext")}let E=await Z(p,a,h,o,l,c);"DEF"===d.zip&&(E=await ((null==i?void 0:i.inflateRaw)||Q)(E));let I={plaintext:E};if(void 0!==e.protected&&(I.protectedHeader=s),void 0!==e.aad)try{I.additionalAuthenticatedData=(0,T.decode)(e.aad)}catch(e){throw new v("Failed to base64url decode the aad")}return(void 0!==e.unprotected&&(I.sharedUnprotectedHeader=e.unprotected),void 0!==e.header&&(I.unprotectedHeader=e.header),y)?{...I,key:t}:I}async function eK(e,t,i){if(e instanceof Uint8Array&&(e=R.decoder.decode(e)),"string"!=typeof e)throw new v("Compact JWE must be a string or Uint8Array");let{0:r,1:s,2:n,3:a,4:o,length:l}=e.split(".");if(5!==l)throw new v("Invalid Compact JWE");let c=await eq({ciphertext:a,iv:n||void 0,protected:r||void 0,tag:o||void 0,encrypted_key:s||void 0},t,i),h={plaintext:c.plaintext,protectedHeader:c.protectedHeader};return"function"==typeof t?{...h,key:c.key}:h}async function eH(e,t,i){if(!et(e))throw new v("General JWE must be an object");
3if(!Array.isArray(e.recipients)||!e.recipients.every(et))throw new v("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new v("JWE Recipients has no members");for(let r of e.recipients)try{return await eq({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:r.encrypted_key,header:r.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,i)}catch(e){}throw new b}let e$=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:(0,T.encode)(e)};if(!(0,N.isCryptoKey)(e))throw TypeError(z(e,...J,"Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:i,alg:r,use:s,...n}=await N.default.subtle.exportKey("jwk",e);return n};async function eW(e){return ev("public","spki",e)}async function ez(e){return ev("private","pkcs8",e)}async function eF(e){return e$(e)}async function eV(e,t,i,r,s={}){let n,a,o;switch(eT(e,i,"encrypt"),e){case"dir":o=i;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!ec(i))throw new w("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:l,apv:c}=s,{epk:h}=s;h||(h=(await el(i)).privateKey);let{x:d,y:u,crv:p,kty:f}=await eF(h),g=await eo(i,h,"ECDH-ES"===e?t:e,"ECDH-ES"===e?em(t):parseInt(e.slice(-5,-2),10),l,c);if(a={epk:{x:d,crv:p,kty:f}},"EC"===f&&(a.epk.y=u),l&&(a.apu=(0,T.encode)(l)),c&&(a.apv=(0,T.encode)(c)),"ECDH-ES"===e){o=g;break}o=r||ew(t);let y=e.slice(-6);n=await en(y,g,o);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o=r||ew(t),n=await eg(e,i,o);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{o=r||ew(t);let{p2c:l,p2s:c}=s;({encryptedKey:n,...a}=await ed(e,i,o,l,c));break}case"A128KW":case"A192KW":case"A256KW":o=r||ew(t),n=await en(e,i,o);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{o=r||ew(t);let{iv:l}=s;({encryptedKey:n,...a}=await eD(e,i,o,l));break}default:throw new w('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:o,encryptedKey:n,parameters:a}}let eJ=Symbol();class eG{constructor(e){if(!(e instanceof Uint8Array))throw TypeError("plaintext must be an instance of Uint8Array");this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw TypeError("setInitializationVector can only be called once");return this._iv=e,this}async encrypt(e,t){let i,r,s,n,a,o,l;if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new v("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!ee(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new v("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let c={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(eB(v,new Map,null==t?void 0:t.crit,this._protectedHeader,c),void 0!==c.zip){if(!this._protectedHeader||!this._protectedHeader.zip)throw new v('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==c.zip)throw new w('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:h,enc:d}=c;if("string"!=typeof h||!h)throw new v('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof d||!d)throw new v('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if("dir"===h){if(this._cek)throw TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if("ECDH-ES"===h&&this._cek)throw TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");{let s;({cek:r,encryptedKey:i,parameters:s}=await eV(h,d,e,this._cek,this._keyManagementParameters)),s&&(t&&eJ in t?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...s}:this.setUnprotectedHeader(s):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...s}:this.setProtectedHeader(s))}if(this._iv||(this._iv=M(d)),n=this._protectedHeader?R.encoder.encode((0,T.encode)(JSON.stringify(this._protectedHeader))):R.encoder.encode(""),this._aad?(a=(0,T.encode)(this._aad),s=(0,R.concat)(n,R.encoder.encode("."),R.encoder.encode(a))):s=n,"DEF"===c.zip){let e=await ((null==t?void 0:t.deflateRaw)||X)(this._plaintext);({ciphertext:o,tag:l}=await ej(d,e,r,this._iv,s))}else({ciphertext:o,tag:l}=await ej(d,this._plaintext,r,this._iv,s));let u={ciphertext:(0,T.encode)(o),iv:(0,T.encode)(this._iv),tag:(0,T.encode)(l)};return i&&(u.encrypted_key=(0,T.encode)(i)),a&&(u.aad=a),this._protectedHeader&&(u.protected=R.decoder.decode(n)),this._sharedUnprotectedHeader&&(u.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(u.header=this._unprotectedHeader),u}}class eY{constructor(e,t,i){this.parent=e,this.key=t,this.options=i}setUnprotectedHeader(e){if(this.unprotectedHeader)throw TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}}function eZ(e,t){let i=`SHA-${e.slice(-3)}`;
3switch(e){case"HS256":case"HS384":case"HS512":return{hash:i,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:i,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:i,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:i,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new w(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function eQ(e,t,i){if((0,N.isCryptoKey)(t))return!function(e,t,...i){switch(t){case"HS256":case"HS384":case"HS512":{if(!q(e.algorithm,"HMAC"))throw L("HMAC");let i=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==i)throw L(`SHA-${i}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!q(e.algorithm,"RSASSA-PKCS1-v1_5"))throw L("RSASSA-PKCS1-v1_5");let i=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==i)throw L(`SHA-${i}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!q(e.algorithm,"RSA-PSS"))throw L("RSA-PSS");let i=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==i)throw L(`SHA-${i}`,"algorithm.hash");break}
3case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw L("Ed25519 or Ed448");break;case"ES256":case"ES384":case"ES512":{if(!q(e.algorithm,"ECDSA"))throw L("ECDSA");let i=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(t);if(e.algorithm.namedCurve!==i)throw L(i,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}H(e,i)}(t,e,i),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(z(t,...J));return N.default.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[i])}throw TypeError(z(t,...J,"Uint8Array"))}let eX=async(e,t,i,r)=>{let s=await eQ(e,t,"verify");ef(e,s);let n=eZ(e,s.algorithm);try{return await N.default.subtle.verify(n,s,i,r)}catch(e){return!1}};async function e0(e,t,i){var r;let s,n;if(!et(e))throw new E("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new E('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new E("JWS Protected Header incorrect type");if(void 0===e.payload)throw new E("JWS Payload missing");if("string"!=typeof e.signature)throw new E("JWS Signature missing or incorrect type");if(void 0!==e.header&&!et(e.header))throw new E("JWS Unprotected Header incorrect type");let a={};if(e.protected)try{let t=(0,T.decode)(e.protected);a=JSON.parse(R.decoder.decode(t))}catch(e){throw new E("JWS Protected Header is invalid")}if(!ee(a,e.header))throw new E("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...a,...e.header},l=eB(E,new Map([["b64",!0]]),null==i?void 0:i.crit,a,o),c=!0;if(l.has("b64")&&"boolean"!=typeof(c=a.b64))throw new E('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:h}=o;if("string"!=typeof h||!h)throw new E('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=i&&eL("algorithms",i.algorithms);if(d&&!d.has(h))throw new m('"alg" (Algorithm) Header Parameter not allowed');if(c){if("string"!=typeof e.payload)throw new E("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new E("JWS Payload must be a string or an Uint8Array instance");let u=!1;"function"==typeof t&&(t=await t(a,e),u=!0),eT(h,t,"verify");let p=(0,R.concat)(R.encoder.encode(null!=(r=e.protected)?r:""),R.encoder.encode("."),"string"==typeof e.payload?R.encoder.encode(e.payload):e.payload);try{s=(0,T.decode)(e.signature)}catch(e){throw new E("Failed to base64url decode the signature")}if(!await eX(h,t,s,p))throw new _;if(c)try{n=(0,T.decode)(e.payload)}catch(e){throw new E("Failed to base64url decode the payload")}else n="string"==typeof e.payload?R.encoder.encode(e.payload):e.payload;let f={payload:n};return(void 0!==e.protected&&(f.protectedHeader=a),void 0!==e.header&&(f.unprotectedHeader=e.header),u)?{...f,key:t}:f}async function e1(e,t,i){if(e instanceof Uint8Array&&(e=R.decoder.decode(e)),"string"!=typeof e)throw new E("Compact JWS must be a string or Uint8Array");let{0:r,1:s,2:n,length:a}=e.split(".");if(3!==a)throw new E("Invalid Compact JWS");let o=await e0({payload:s,protected:r,signature:n},t,i),l={payload:o.payload,protectedHeader:o.protectedHeader};return"function"==typeof t?{...l,key:o.key}:l}async function e2(e,t,i){if(!et(e))throw new E("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(et))throw new E("JWS Signatures missing or incorrect type");for(let r of e.signatures)try{return await e0({header:r.header,payload:e.payload,protected:r.protected,signature:r.signature},t,i)}catch(e){}throw new _}let e5=e=>Math.floor(e.getTime()/1e3),e3=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,e8=e=>{let t=e3.exec(e);if(!t)throw TypeError("Invalid time period format");let i=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(i);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(60*i);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(3600*i);case"day":case"days":case"d":return Math.round(86400*i);case"week":case"weeks":case"w":return Math.round(604800*i);default:return Math.round(0x1e187e0*i)}},e6=e=>e.toLowerCase().replace(/^application\//,""),e4=(e,t,i={})=>{var r,s;let n,a,{typ:o}=i;if(o&&("string"!=typeof e.typ||e6(e.typ)!==e6(o)))throw new g('unexpected "typ" JWT header value',"typ","check_failed");try{n=JSON.parse(R.decoder.decode(t))}catch(e){}if(!et(n))throw new I("JWT Claims Set must be a top-level JSON object");let{requiredClaims:l=[],issuer:c,subject:h,audience:d,maxTokenAge:u}=i;for(let e of(void 0!==u&&l.push("iat"),void 0!==d&&l.push("aud"),void 0!==h&&l.push("sub"),void 0!==c&&l.push("iss"),new Set(l.reverse())))if(!(e in n))throw new g(`missing required "${e}" claim`,e,"missing");if(c&&!(Array.isArray(c)?c:[c]).includes(n.iss))throw new g('unexpected "iss" claim value',"iss","check_failed");if(h&&n.sub!==h)throw new g('unexpected "sub" claim value',"sub","check_failed");if(d&&(r=n.aud,s="string"==typeof d?[d]:d,"string"==typeof r?!s.includes(r):!(Array.isArray(r)&&s.some(Set.prototype.has.bind(new Set(r))))))throw new g('unexpected "aud" claim value',"aud","check_failed");switch(typeof i.clockTolerance){case"string":a=e8(i.clockTolerance);break;case"number":a=i.clockTolerance;break;case"undefined":a=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:p}=i,f=e5(p||new Date);if((void 0!==n.iat||u)&&"number"!=typeof n.iat)throw new g('"iat" claim must be a number',"iat","invali
3d");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new g('"nbf" claim must be a number',"nbf","invalid");if(n.nbf>f+a)throw new g('"nbf" claim timestamp check failed',"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new g('"exp" claim must be a number',"exp","invalid");if(n.exp<=f-a)throw new y('"exp" claim timestamp check failed',"exp","check_failed")}if(u){let e=f-n.iat;if(e-a>("number"==typeof u?u:e8(u)))throw new y('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(e<0-a)throw new g('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return n};async function e7(e,t,i){var r;let s=await e1(e,t,i);if((null==(r=s.protectedHeader.crit)?void 0:r.includes("b64"))&&!1===s.protectedHeader.b64)throw new I("JWTs MUST NOT use unencoded payload");let n={payload:e4(s.protectedHeader,s.payload,i),protectedHeader:s.protectedHeader};return"function"==typeof t?{...n,key:s.key}:n}async function e9(e,t,i){let r=await eK(e,t,i),s=e4(r.protectedHeader,r.plaintext,i),{protectedHeader:n}=r;if(void 0!==n.iss&&n.iss!==s.iss)throw new g('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(void 0!==n.sub&&n.sub!==s.sub)throw new g('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(void 0!==n.aud&&JSON.stringify(n.aud)!==JSON.stringify(s.aud))throw new g('replicated "aud" claim header parameter mismatch',"aud","mismatch");let a={payload:s,protectedHeader:n};return"function"==typeof t?{...a,key:r.key}:a}class te{constructor(e){this._flattened=new eG(e)}setContentEncryptionKey(e){return this._flattened.setContentEncryptionKey(e),this}setInitializationVector(e){return this._flattened.setInitializationVector(e),this}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}setKeyManagementParameters(e){return this._flattened.setKeyManagementParameters(e),this}async encrypt(e,t){let i=await this._flattened.encrypt(e,t);return[i.protected,i.encrypted_key,i.iv,i.ciphertext,i.tag].join(".")}}let tt=async(e,t,i)=>{let r=await eQ(e,t,"sign");return ef(e,r),new Uint8Array(await N.default.subtle.sign(eZ(e,r.algorithm),r,i))};class ti{constructor(e){if(!(e instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){let i;if(!this._protectedHeader&&!this._unprotectedHeader)throw new E("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!ee(this._protectedHeader,this._unprotectedHeader))throw new E("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this._protectedHeader,...this._unprotectedHeader},s=eB(E,new Map([["b64",!0]]),null==t?void 0:t.crit,this._protectedHeader,r),n=!0;if(s.has("b64")&&"boolean"!=typeof(n=this._protectedHeader.b64))throw new E('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=r;if("string"!=typeof a||!a)throw new E('JWS "alg" (Algorithm) Header Parameter missing or invalid');eT(a,e,"sign");let o=this._payload;n&&(o=R.encoder.encode((0,T.encode)(o))),i=this._protectedHeader?R.encoder.encode((0,T.encode)(JSON.stringify(this._protectedHeader))):R.encoder.encode("");let l=(0,R.concat)(i,R.encoder.encode("."),o),c=await tt(a,e,l),h={signature:(0,T.encode)(c),payload:""};return n&&(h.payload=R.decoder.decode(o)),this._unprotectedHeader&&(h.header=this._unprotectedHeader),this._protectedHeader&&(h.protected=R.decoder.decode(i)),h}}class tr{constructor(e){this._flattened=new ti(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){let i=await this._flattened.sign(e,t);if(void 0===i.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${i.protected}.${i.payload}.${i.signature}`}}class ts{constructor(e,t,i){this.parent=e,this.key=t,this.options=i}setProtectedHeader(e){if(this.protectedHeader)throw TypeError("setProtectedHeader can only be called once");return this.protectedHeader=e,this}setUnprotectedHeader(e){if(this.unprotectedHeader)throw TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addSignature(...e){return this.parent.addSignature(...e)}sign(...e){return this.parent.sign(...e)}done(){return this.parent}}class tn{constructor(e){if(!et(e))throw TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:e}:this._payload={...this._payload,nbf:e5(new Date)+e8(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:e}:this._payload={...this._payload,exp:e5(new Date)+e8(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:e5(new Date)}:this._payload={...this._payload,iat:e},this}}var ta=e.i(174368);let to=(e,t)=>{if("string"!=typeof e||!e)throw new S(`${t} missing or invalid`)};async function tl(e,t){let i;if(!et(e))throw TypeError("JWK must be an object");
3if(null!=t||(t="sha256"),"sha256"!==t&&"sha384"!==t&&"sha512"!==t)throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');switch(e.kty){case"EC":to(e.crv,'"crv" (Curve) Parameter'),to(e.x,'"x" (X Coordinate) Parameter'),to(e.y,'"y" (Y Coordinate) Parameter'),i={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":to(e.crv,'"crv" (Subtype of Key Pair) Parameter'),to(e.x,'"x" (Public Key) Parameter'),i={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":to(e.e,'"e" (Exponent) Parameter'),to(e.n,'"n" (Modulus) Parameter'),i={e:e.e,kty:e.kty,n:e.n};break;case"oct":to(e.k,'"k" (Key Value) Parameter'),i={k:e.k,kty:e.kty};break;default:throw new w('"kty" (Key Type) Parameter missing or unsupported')}let r=R.encoder.encode(JSON.stringify(i));return(0,T.encode)(await (0,ta.default)(t,r))}async function tc(e,t){null!=t||(t="sha256");let i=await tl(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${i}`}async function th(e,t){let i={...e,...null==t?void 0:t.header};if(!et(i.jwk))throw new E('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let r=await eO({...i.jwk,ext:!0},i.alg,!0);if(r instanceof Uint8Array||"public"!==r.type)throw new E('"jwk" (JSON Web Key) Header Parameter must be a public key');return r}function td(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(tu)}function tu(e){return et(e)}class tp{constructor(e){if(this._cached=new WeakMap,!td(e))throw new A("JSON Web Key Set malformed");this._jwks=function(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}(e)}async getKey(e,t){let{alg:i,kid:r}={...e,...null==t?void 0:t.header},s=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new w('Unsupported "alg" value for a JSON Web Key Set')}}(i),n=this._jwks.keys.filter(e=>{let t=s===e.kty;if(t&&"string"==typeof r&&(t=r===e.kid),t&&"string"==typeof e.alg&&(t=i===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t&&"EdDSA"===i&&(t="Ed25519"===e.crv||"Ed448"===e.crv),t)switch(i){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv}return t}),{0:a,length:o}=n;if(0===o)throw new x;if(1!==o){let e=new P,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(let e of n)try{yield await tf(t,e,i)}catch(e){continue}},e}return tf(this._cached,a,i)}}async function tf(e,t,i){let r=e.get(t)||e.set(t,{}).get(t);if(void 0===r[i]){let e=await eO({...t,ext:!0},i);if(e instanceof Uint8Array||"public"!==e.type)throw new A("JSON Web Key Set members must be public keys");r[i]=e}return r[i]}let tg=async(e,t,i)=>{let r,s,n=!1;"function"==typeof AbortController&&(r=new AbortController,s=setTimeout(()=>{n=!0,r.abort()},t));let a=await fetch(e.href,{signal:r?r.signal:void 0,redirect:"manual",headers:i.headers}).catch(e=>{if(n)throw new C;throw e});if(void 0!==s&&clearTimeout(s),200!==a.status)throw new f("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch(e){throw new f("Failed to parse the JSON Web Key Set HTTP response as JSON")}};class ty extends tp{constructor(e,t){if(super({keys:[]}),this._jwks=void 0,!(e instanceof URL))throw TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:null==t?void 0:t.agent,headers:null==t?void 0:t.headers},this._timeoutDuration="number"==typeof(null==t?void 0:t.timeoutDuration)?null==t?void 0:t.timeoutDuration:5e3,this._cooldownDuration="number"==typeof(null==t?void 0:t.cooldownDuration)?null==t?void 0:t.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof(null==t?void 0:t.cacheMaxAge)?null==t?void 0:t.cacheMaxAge:6e5}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._jwks&&this.fresh()||await this.reload();try{return await super.getKey(e,t)}catch(i){if(i instanceof x&&!1===this.coolingDown())return await this.reload(),super.getKey(e,t);throw i}}async reload(){this._pendingFetch&&("u">typeof WebSocketPair||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"u">
3typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=tg(this._url,this._timeoutDuration,this._options).then(e=>{if(!td(e))throw new A("JSON Web Key Set malformed");this._jwks={keys:e.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}}function tm(e){let t,i;if("string"!=typeof e)throw new I("JWTs must use Compact JWS serialization, JWT must be a string");let{1:r,length:s}=e.split(".");if(5===s)throw new I("Only JWTs using Compact JWS serialization can be decoded");if(3!==s)throw new I("Invalid JWT");if(!r)throw new I("JWTs must contain a payload");try{t=(0,O.decode)(r)}catch(e){throw new I("Failed to base64url decode the payload")}try{i=JSON.parse(R.decoder.decode(t))}catch(e){throw new I("Failed to parse the decoded payload as JSON")}if(!et(i))throw new I("Invalid JWT Claims Set");return i}async function tw(e,t){var i;let r,s,n;switch(e){case"HS256":case"HS384":case"HS512":r=parseInt(e.slice(-3),10),s={name:"HMAC",hash:`SHA-${r}`,length:r},n=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return j(new Uint8Array((r=parseInt(e.slice(-3),10))>>3));case"A128KW":case"A192KW":case"A256KW":s={name:"AES-KW",length:r=parseInt(e.slice(1,4),10)},n=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":s={name:"AES-GCM",length:r=parseInt(e.slice(1,4),10)},n=["encrypt","decrypt"];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return N.default.subtle.generateKey(s,null!=(i=null==t?void 0:t.extractable)&&i,n)}function tb(e){var t;let i=null!=(t=null==e?void 0:e.modulusLength)?t:2048;if("number"!=typeof i||i<2048)throw new w("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return i}async function tv(e,t){var i,r,s;let n,a;switch(e){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:tb(t)},a=["sign","verify"];break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:tb(t)},a=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:tb(t)},a=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"},a=["sign","verify"];break;case"ES384":n={name:"ECDSA",namedCurve:"P-384"},a=["sign","verify"];break;case"ES512":n={name:"ECDSA",namedCurve:"P-521"},a=["sign","verify"];break;case"EdDSA":a=["sign","verify"];let o=null!=(i=null==t?void 0:t.crv)?i:"Ed25519";
3switch(o){case"Ed25519":case"Ed448":n={name:o};break;default:throw new w("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{a=["deriveKey","deriveBits"];let e=null!=(r=null==t?void 0:t.crv)?r:"P-256";switch(e){case"P-256":case"P-384":case"P-521":n={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":n={name:e};break;default:throw new w("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return N.default.subtle.generateKey(n,null!=(s=null==t?void 0:t.extractable)&&s,a)}async function tE(e,t){return tv(e,t)}async function tI(e,t){return tw(e,t)}e.s(["CompactEncrypt",0,te,"CompactSign",0,tr,"EmbeddedJWK",0,th,"EncryptJWT",0,class extends tn{setProtectedHeader(e){if(this._protectedHeader)throw TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setKeyManagementParameters(e){if(this._keyManagementParameters)throw TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setContentEncryptionKey(e){if(this._cek)throw TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw TypeError("setInitializationVector can only be called once");return this._iv=e,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(e,t){let i=new te(R.encoder.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),i.setProtectedHeader(this._protectedHeader),this._iv&&i.setInitializationVector(this._iv),this._cek&&i.setContentEncryptionKey(this._cek),this._keyManagementParameters&&i.setKeyManagementParameters(this._keyManagementParameters),i.encrypt(e,t)}},"FlattenedEncrypt",0,eG,"FlattenedSign",0,ti,"GeneralEncrypt",0,class{constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,t){let i=new eY(this,e,{crit:null==t?void 0:t.crit});return this._recipients.push(i),i}setProtectedHeader(e){if(this._protectedHeader)throw TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(e){var t,i,r;let s;if(!this._recipients.length)throw new v("at least one recipient must be added");if(e={deflateRaw:null==e?void 0:e.deflateRaw},1===this._recipients.length){let[t]=this._recipients,i=await new eG(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(t.unprotectedHeader).encrypt(t.key,{...t.options,...e}),r={ciphertext:i.ciphertext,iv:i.iv,recipients:[{}],tag:i.tag};return i.aad&&(r.aad=i.aad),i.protected&&(r.protected=i.protected),i.unprotected&&(r.unprotected=i.unprotected),i.encrypted_key&&(r.recipients[0].encrypted_key=i.encrypted_key),i.header&&(r.recipients[0].header=i.header),r}for(let e=0;e<this._recipients.length;e++){let t=this._recipients[e];if(!ee(this._protectedHeader,this._unprotectedHeader,t.unprotectedHeader))throw new v("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let i={...this._protectedHeader,...this._unprotectedHeader,...t.unprotectedHeader},{alg:r}=i;if("string"!=typeof r||!r)throw new v('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("dir"===r||"ECDH-ES"===r)throw new v('"dir" and "ECDH-ES" alg may only be used with a single recipient');if("string"!=typeof i.enc||!i.enc)throw new v('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(s){if(s!==i.enc)throw new v('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}else s=i.enc;if(eB(v,new Map,t.options.crit,this._protectedHeader,i),void 0!==i.zip&&(!this._protectedHeader||!this._protectedHeader.zip))throw new v('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let n=ew(s),a={ciphertext:"",iv:"",recipients:[],tag:""};for(let o=0;o<this._recipients.length;o++){let l=this._recipients[o],c={};a.recipients.push(c);let h=({...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}).alg.startsWith("PBES2")?2048+o:void 0;if(0===o){let t=await new eG(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(n).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:h}
3).encrypt(l.key,{...l.options,...e,[eJ]:!0});a.ciphertext=t.ciphertext,a.iv=t.iv,a.tag=t.tag,t.aad&&(a.aad=t.aad),t.protected&&(a.protected=t.protected),t.unprotected&&(a.unprotected=t.unprotected),c.encrypted_key=t.encrypted_key,t.header&&(c.header=t.header);continue}let{encryptedKey:d,parameters:u}=await eV((null==(t=l.unprotectedHeader)?void 0:t.alg)||(null==(i=this._protectedHeader)?void 0:i.alg)||(null==(r=this._unprotectedHeader)?void 0:r.alg),s,l.key,n,{p2c:h});c.encrypted_key=(0,T.encode)(d),(l.unprotectedHeader||u)&&(c.header={...l.unprotectedHeader,...u})}return a}},"GeneralSign",0,class{constructor(e){this._signatures=[],this._payload=e}addSignature(e,t){let i=new ts(this,e,t);return this._signatures.push(i),i}async sign(){if(!this._signatures.length)throw new E("at least one signature must be added");let e={signatures:[],payload:""};for(let t=0;t<this._signatures.length;t++){let i=this._signatures[t],r=new ti(this._payload);r.setProtectedHeader(i.protectedHeader),r.setUnprotectedHeader(i.unprotectedHeader);let{payload:s,...n}=await r.sign(i.key,i.options);if(0===t)e.payload=s;else if(e.payload!==s)throw new E("inconsistent use of JWS Unencoded Payload (RFC7797)");e.signatures.push(n)}return e}},"SignJWT",0,class extends tn{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){var i;let r=new tr(R.encoder.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(null==(i=this._protectedHeader)?void 0:i.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new I("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}},"UnsecuredJWT",0,class extends tn{encode(){let e=T.encode(JSON.stringify({alg:"none"})),t=T.encode(JSON.stringify(this._payload));return`${e}.${t}.`}static decode(e,t){let i;if("string"!=typeof e)throw new I("Unsecured JWT must be a string");let{0:r,1:s,2:n,length:a}=e.split(".");if(3!==a||""!==n)throw new I("Invalid Unsecured JWT");try{if(i=JSON.parse(R.decoder.decode(T.decode(r))),"none"!==i.alg)throw Error()}catch(e){throw new I("Invalid Unsecured JWT")}return{payload:e4(i,T.decode(s),t),header:i}}},"base64url",0,O,"calculateJwkThumbprint",0,tl,"calculateJwkThumbprintUri",0,tc,"compactDecrypt",0,eK,"compactVerify",0,e1,"createLocalJWKSet",0,function(e){let t=new tp(e);return async function(e,i){return t.getKey(e,i)}},"createRemoteJWKSet",0,function(e,t){let i=new ty(e,t);return async function(e,t){return i.getKey(e,t)}},"cryptoRuntime",0,"WebCryptoAPI","decodeJwt",0,tm,"decodeProtectedHeader",0,function(e){let t;if("string"==typeof e){let i=e.split(".");(3===i.length||5===i.length)&&([t]=i)}else if("object"==typeof e&&e)if("protected"in e)t=e.protected;else throw TypeError("Token does not contain a Protected Header");try{if("string"!=typeof t||!t)throw Error();let e=JSON.parse(R.decoder.decode((0,O.decode)(t)));if(!et(e))throw Error();return e}catch(e){throw TypeError("Invalid Token or Protected Header formatting")}},"errors",0,k,"exportJWK",0,eF,"exportPKCS8",0,ez,"exportSPKI",0,eW,"flattenedDecrypt",0,eq,"flattenedVerify",0,e0,"generalDecrypt",0,eH,"generalVerify",0,e2,"generateKeyPair",0,tE,"generateSecret",0,tI,"importJWK",0,eO,"importPKCS8",0,ek,"importSPKI",0,eC,"importX509",0,e_,"jwtDecrypt",0,e9,"jwtVerify",0,e7],520904),e.i(520904);var tS=e.i(43624),tA=e.i(600476),tx=e.i(595932),tP=e.i(117887),tC=e.i(95537),t_=e.i(662123),tk=e.i(843476);class tO{constructor(e,t){this.scope=e,this.module=t}storeObject(e,t){this.setItem(e,JSON.stringify(t))}loadObject(e){let t=this.getItem(e);return t?JSON.parse(t):void 0}setItem(e,t){localStorage.setItem(this.scopedKey(e),t)}getItem(e){return localStorage.getItem(this.scopedKey(e))}removeItem(e){localStorage.removeItem(this.scopedKey(e))}clear(){let e=this.scopedKey(""),t=[];for(let i=0;i<localStorage.length;i++){let r=localStorage.key(i);"string"==typeof r&&r.startsWith(e)&&t.push(r)}t.forEach(e=>localStorage.removeItem(e))}scopedKey(e){return`-${this.scope}${this.module?`:${this.module}`:""}:${e}`}static clearAll(){new tO("CBWSDK").clear(),new tO("walletlink").clear()}}var tT=e.i(467034);let tR=-32602,tN=-32603,tj=4001,tD=4100,tM=4200,tU=4900,tB={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}},tL="Unspecified error message.";
vendor: 4,751 bytes, line 3
3function tq(e,t=tL){if(e&&Number.isInteger(e)){var i;let t=e.toString();if(tH(tB,t))return tB[t].message;if((i=e)>=-32099&&i<=-32e3)return"Unspecified server error."}return t}function tK(e){return e&&"object"==typeof e&&!Array.isArray(e)?Object.assign({},e):e}function tH(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function t$(e,t){return"object"==typeof e&&null!==e&&t in e&&"string"==typeof e[t]}let tW=e=>tZ(tR,e),tz=e=>tZ(tN,e),tF=e=>tQ(tj,e),tV=e=>tQ(tD,e),tJ=e=>tQ(tM,e),tG=e=>tQ(tU,e),tY=e=>{if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Ethereum Provider custom errors must provide single object argument.");let{code:t,message:i,data:r}=e;if(!i||"string"!=typeof i)throw Error('"message" must be a nonempty string');return new t1(t,i,r)};function tZ(e,t){let[i,r]=tX(t);return new t0(e,i||tq(e),r)}function tQ(e,t){let[i,r]=tX(t);return new t1(e,i||tq(e),r)}function tX(e){if(e){if("string"==typeof e)return[e];else if("object"==typeof e&&!Array.isArray(e)){let{message:t,data:i}=e;if(t&&"string"!=typeof t)throw Error("Must specify string message.");return[t||void 0,i]}}return[]}class t0 extends Error{constructor(e,t,i){if(!Number.isInteger(e))throw Error('"code" must be an integer.');if(!t||"string"!=typeof t)throw Error('"message" must be a nonempty string.');super(t),this.code=e,void 0!==i&&(this.data=i)}}class t1 extends t0{constructor(e,t,i){if(!function(e){return Number.isInteger(e)&&e>=1e3&&e<=4999}(e))throw Error('"code" must be an integer such that: 1000 <= code <= 4999');super(e,t,i)}}function t2(e){return Math.floor(e)}let t5=/^[0-9]*$/,t3=/^[a-f0-9]*$/;function t8(e){return t6(crypto.getRandomValues(new Uint8Array(e)))}function t6(e){return[...e].map(e=>e.toString(16).padStart(2,"0")).join("")}function t4(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>Number.parseInt(e,16)))}function t7(e,t=!1){let i=e.toString("hex");return t?`0x${i}`:i}function t9(e){return t7(ic(e),!0)}function ie(e){return e.toString(10)}function it(e){return`0x${BigInt(e).toString(16)}`}function ii(e){return e.startsWith("0x")||e.startsWith("0X")}function ir(e){return ii(e)?e.slice(2):e}function is(e){return ii(e)?`0x${e.slice(2)}`:`0x${e}`}function ia(e){if("string"!=typeof e)return!1;let t=ir(e).toLowerCase();return t3.test(t)}function io(e,t=!1){let i=function(e,t=!1){if("string"==typeof e){let i=ir(e).toLowerCase();if(t3.test(i))return t?`0x${i}`:i}throw tW(`"${String(e)}" is not a hexadecimal string`)}(e,!1);return i.length%2==1&&(i=`0${i}`),t?`0x${i}`:i}function il(e){if("string"==typeof e){let t=ir(e).toLowerCase();if(ia(t)&&40===t.length)return is(t)}throw tW(`Invalid Ethereum address: ${String(e)}`)}function ic(e){if(tT.Buffer.isBuffer(e))return e;if("string"==typeof e){if(ia(e)){let t=io(e,!1);return tT.Buffer.from(t,"hex")}return tT.Buffer.from(e,"utf8")}throw tW(`Not binary data: ${String(e)}`)}function ih(e){if("number"==typeof e&&Number.isInteger(e))return t2(e);if("string"==typeof e){if(t5.test(e))return t2(Number(e));if(ia(e))return t2(Number(BigInt(io(e,!0))))}throw tW(`Not an integer: ${String(e)}`)}function id(e){if(null!==e&&("bigint"==typeof e||function(e){if(null==e||"function"!=typeof e.constructor)return!1;let{constructor:t}=e;return"function"==typeof t.config&&"number"==typeof t.EUCLID}(e)))return BigInt(e.toString(10));if("number"==typeof e)return BigInt(ih(e));if("string"==typeof e){if(t5.test(e))return BigInt(e);if(ia(e))return BigInt(io(e,!0))}throw tW(`Not an integer: ${String(e)}`)}async function iu(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"])}async function ip(e,t){return crypto.subtle.deriveKey({name:"ECDH",public:t},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function ig(e,t){let i=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:i},e,new TextEncoder().encode(t));return{iv:i,cipherText:r}}async function iy(e,{iv:t,cipherText:i}){let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:t},e,i);return new TextDecoder().decode(r)}function im(e){switch(e){case"public":return"spki";case"private":return"pkcs8"}}async function iw(e,t){let i=im(e);return t6(new Uint8Array(await crypto.subtle.exportKey(i,t)))}async function ib(e,t){let i=im(e),r=t4(t).buffer;return await crypto.subtle.importKey(i,new Uint8Array(r),{name:"ECDH",namedCurve:"P-256"},!0,"private"===e?["deriveKey"]:[])}async function iv(e,t){return ig(t,JSON.stringify(e,(e,t)=>t instanceof Error?Object.assign(Object.assign({},t.code?{code:t.code}:{}),{message:t.message}):t))}async function iE(e,t){return JSON.parse(await iy(t,e))}let iI={storageKey:"ownPrivateKey",keyType:"private"},iS={storageKey:"ownPublicKey",keyType:"public"},iA={storageKey:"peerPublicKey",keyType:"public"};
3class ix{constructor(){this.storage=new tO("CBWSDK","SCWKeyManager"),this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null}async getOwnPublicKey(){return await this.loadKeysIfNeeded(),this.ownPublicKey}async getSharedSecret(){return await this.loadKeysIfNeeded(),this.sharedSecret}async setPeerPublicKey(e){this.sharedSecret=null,this.peerPublicKey=e,await this.storeKey(iA,e),await this.loadKeysIfNeeded()}async clear(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null,this.storage.removeItem(iS.storageKey),this.storage.removeItem(iI.storageKey),this.storage.removeItem(iA.storageKey)}async generateKeyPair(){let e=await iu();this.ownPrivateKey=e.privateKey,this.ownPublicKey=e.publicKey,await this.storeKey(iI,e.privateKey),await this.storeKey(iS,e.publicKey)}async loadKeysIfNeeded(){null===this.ownPrivateKey&&(this.ownPrivateKey=await this.loadKey(iI)),null===this.ownPublicKey&&(this.ownPublicKey=await this.loadKey(iS)),(null===this.ownPrivateKey||null===this.ownPublicKey)&&await this.generateKeyPair(),null===this.peerPublicKey&&(this.peerPublicKey=await this.loadKey(iA)),null===this.sharedSecret&&null!==this.ownPrivateKey&&null!==this.peerPublicKey&&(this.sharedSecret=await ip(this.ownPrivateKey,this.peerPublicKey))}async loadKey(e){let t=this.storage.getItem(e.storageKey);return t?ib(e.keyType,t):null}async storeKey(e,t){let i=await iw(e.keyType,t);this.storage.setItem(e.storageKey,i)}}let iP="4.3.2",iC="@coinbase/wallet-sdk";async function i_(e,t){let i=Object.assign(Object.assign({},e),{jsonrpc:"2.0",id:crypto.randomUUID()}
vendor: 4,298 bytes, line 3
3),r=await window.fetch(t,{method:"POST",body:JSON.stringify(i),mode:"cors",headers:{"Content-Type":"application/json","X-Cbw-Sdk-Version":iP,"X-Cbw-Sdk-Platform":iC}}),{result:s,error:n}=await r.json();if(n)throw n;return s}let ik="accounts",iO="activeChain",iT="availableChains",iR="walletCapabilities";class iN{constructor(e){var t,i,r;this.metadata=e.metadata,this.communicator=e.communicator,this.callback=e.callback,this.keyManager=new ix,this.storage=new tO("CBWSDK","SCWStateManager"),this.accounts=null!=(t=this.storage.loadObject(ik))?t:[],this.chain=this.storage.loadObject(iO)||{id:null!=(r=null==(i=e.metadata.appChainIds)?void 0:i[0])?r:1},this.handshake=this.handshake.bind(this),this.request=this.request.bind(this),this.createRequestMessage=this.createRequestMessage.bind(this),this.decryptResponseMessage=this.decryptResponseMessage.bind(this)}async handshake(e){var t,i,r,s;await (null==(i=(t=this.communicator).waitForPopupLoaded)?void 0:i.call(t));let n=await this.createRequestMessage({handshake:{method:e.method,params:Object.assign({},this.metadata,null!=(r=e.params)?r:{})}}),a=await this.communicator.postRequestAndWaitForResponse(n);if("failure"in a.content)throw a.content.failure;let o=await ib("public",a.sender);await this.keyManager.setPeerPublicKey(o);let l=(await this.decryptResponseMessage(a)).result;if("error"in l)throw l.error;if("eth_requestAccounts"===e.method){let e=l.value;this.accounts=e,this.storage.storeObject(ik,e),null==(s=this.callback)||s.call(this,"accountsChanged",e)}}async request(e){var t;if(0===this.accounts.length)if("wallet_sendCalls"===e.method)return this.sendRequestToPopup(e);else throw tV();switch(e.method){case"eth_requestAccounts":return null==(t=this.callback)||t.call(this,"connect",{chainId:it(this.chain.id)}),this.accounts;case"eth_accounts":return this.accounts;case"eth_coinbase":return this.accounts[0];case"net_version":return this.chain.id;case"eth_chainId":return it(this.chain.id);case"wallet_getCapabilities":return this.storage.loadObject(iR);case"wallet_switchEthereumChain":return this.handleSwitchChainRequest(e);case"eth_ecRecover":case"personal_sign":case"wallet_sign":case"personal_ecRecover":case"eth_signTransaction":case"eth_sendTransaction":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":case"eth_signTypedData":case"wallet_addEthereumChain":case"wallet_watchAsset":case"wallet_sendCalls":case"wallet_showCallsStatus":case"wallet_grantPermissions":return this.sendRequestToPopup(e);default:if(!this.chain.rpcUrl)throw tz("No RPC URL set for chain");return i_(e,this.chain.rpcUrl)}}async sendRequestToPopup(e){var t,i;await (null==(i=(t=this.communicator).waitForPopupLoaded)?void 0:i.call(t));let r=await this.sendEncryptedRequest(e),s=(await this.decryptResponseMessage(r)).result;if("error"in s)throw s.error;return s.value}async cleanup(){var e,t;this.storage.clear(),await this.keyManager.clear(),this.accounts=[],this.chain={id:null!=(t=null==(e=this.metadata.appChainIds)?void 0:e[0])?t:1}}async handleSwitchChainRequest(e){var t;let i=e.params;if(!i||!(null==(t=i[0])?void 0:t.chainId))throw tW();let r=ih(i[0].chainId);if(this.updateChain(r))return null;let s=await this.sendRequestToPopup(e);return null===s&&this.updateChain(r),s}async sendEncryptedRequest(e){let t=await this.keyManager.getSharedSecret();if(!t)throw tV("No valid session found, try requestAccounts before other methods");let i=await iv({action:e,chainId:this.chain.id},t),r=await this.createRequestMessage({encrypted:i});return this.communicator.postRequestAndWaitForResponse(r)}async createRequestMessage(e){let t=await iw("public",await this.keyManager.getOwnPublicKey());return{id:crypto.randomUUID(),sender:t,content:e,timestamp:new Date}}async decryptResponseMessage(e){var t,i;let r=e.content;if("failure"in r)throw r.failure;let s=await this.keyManager.getSharedSecret();if(!s)throw tV("Invalid session");let n=await iE(r.encrypted,s),a=null==(t=n.data)?void 0:t.chains;if(a){let e=Object.entries(a).map(([e,t])=>({id:Number(e),rpcUrl:t}));this.storage.storeObject(iT,e),this.updateChain(this.chain.id,e)}let o=null==(i=n.data)?void 0:i.capabilities;return o&&this.storage.storeObject(iR,o),n}updateChain(e,t){var i;let r=null!=t?t:this.storage.loadObject(iT),s=null==r?void 0:r.find(t=>
3t.id===e);return!!s&&(s!==this.chain&&(this.chain=s,this.storage.storeObject(iO,s),null==(i=this.callback)||i.call(this,"chainChanged",it(s.id))),!0)}}var ij=e.i(622207);let iD="Addresses";function iM(e){return void 0!==e.errorMessage}class iU{constructor(e){this.secret=e}async encrypt(e){let t=this.secret;if(64!==t.length)throw Error("secret must be 256 bits");let i=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.importKey("raw",t4(t),{name:"aes-gcm"},!1,["encrypt","decrypt"]),s=new TextEncoder,n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:i},r,s.encode(e)),a=n.slice(n.byteLength-16),o=n.slice(0,n.byteLength-16),l=new Uint8Array(a),c=new Uint8Array(o);return t6(new Uint8Array([...i,...l,...c]))}async decrypt(e){let t=this.secret;if(64!==t.length)throw Error("secret must be 256 bits");return new Promise((i,r)=>{!async function(){let s=await crypto.subtle.importKey("raw",t4(t),{name:"aes-gcm"},!1,["encrypt","decrypt"]),n=t4(e),a=n.slice(0,12),o=n.slice(12,28),l=new Uint8Array([...n.slice(28),...o]),c={name:"AES-GCM",iv:new Uint8Array(a)};try{let e=await window.crypto.subtle.decrypt(c,s,l),t=new TextDecoder;i(t.decode(e))}catch(e){r(e)}}()})}}class iB{constructor(e,t,i){this.linkAPIUrl=e,this.sessionId=t;const r=`${t}:${i}`;this.auth=`Basic ${btoa(r)}`}async markUnseenEventsAsSeen(e){return Promise.all(e.map(e=>fetch(`${this.linkAPIUrl}/events/${e.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(e=>console.error("Unabled to mark event as failed:",e))}async fetchUnseenEvents(){var e;let t=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(t.ok){let{events:i,error:r}=await t.json();if(r)throw Error(`Check unseen events failed: ${r}`);let s=null!=(e=null==i?void 0:i.filter(e=>"Web3Response"===e.event).map(e=>({type:"Event",sessionId:this.sessionId,eventId:e.id,event:e.event,data:e.data})))?e:[];return this.markUnseenEventsAsSeen(s),s}throw Error(`Check unseen events failed: ${t.status}`)}}(mH=mV||(mV={}))[mH.DISCONNECTED=0]="DISCONNECTED",mH[mH.CONNECTING=1]="CONNECTING",mH[mH.CONNECTED=2]="CONNECTED";class iL{setConnectionStateListener(e){this.connectionStateListener=e}setIncomingDataListener(e){this.incomingDataListener=e}constructor(e,t=WebSocket){this.WebSocketClass=t,this.webSocket=null,this.pendingData=[],this.url=e.replace(/^http/,"ws")}async connect(){if(this.webSocket)throw Error("webSocket object is not null");return new Promise((e,t)=>{var i;let r;try{this.webSocket=r=new this.WebSocketClass(this.url)}catch(e){t(e);return}null==(i=this.connectionStateListener)||i.call(this,mV.CONNECTING),r.onclose=e=>{var i;this.clearWebSocket(),t(Error(`websocket error ${e.code}: ${e.reason}`)),null==(i=this.connectionStateListener)||i.call(this,mV.DISCONNECTED)},r.onopen=t=>{var i;e(),null==(i=this.connectionStateListener)||i.call(this,mV.CONNECTED),this.pendingData.length>0&&([...this.pendingData].forEach(e=>this.sendData(e)),this.pendingData=[])},r.onmessage=e=>{var t,i;if("h"===e.data)null==(t=this.incomingDataListener)||t.call(this,{type:"Heartbeat"});else try{let t=JSON.parse(e.data);null==(i=this.incomingDataListener)||i.call(this,t)}catch(e){}}})}disconnect(){var e;let{webSocket:t}=this;if(t){this.clearWebSocket(),null==(e=this.connectionStateListener)||e.call(this,mV.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{t.close()}catch(e){}}}sendData(e){let{webSocket:t}=this;if(!t){this.pendingData.push(e),this.connect();return}t.send(e)}clearWebSocket(){let{webSocket:e}=this;e&&(this.webSocket=null,e.onclose=null,e.onerror=null,e.onmessage=null,e.onopen=null)}}class iq{constructor({session:e,linkAPIUrl:t,listener:i}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=t2(1),this._connected=!1,this._linked=!1,this.shouldFetchUnseenEventsOnConnect=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=e=>{e&&new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",t=>
3e.JsonRpcUrl&&this.handleChainUpdated(t,e.JsonRpcUrl)]]).forEach((t,i)=>{let r=e[i];void 0!==r&&t(r)})},this.handleDestroyed=e=>{var t;"1"===e&&(null==(t=this.listener)||t.resetAndReload())},this.handleAccountUpdated=async e=>{var t;let i=await this.cipher.decrypt(e);null==(t=this.listener)||t.accountUpdated(i)},this.handleMetadataUpdated=async(e,t)=>{var i;let r=await this.cipher.decrypt(t);null==(i=this.listener)||i.metadataUpdated(e,r)},this.handleWalletUsernameUpdated=async e=>{this.handleMetadataUpdated("walletUsername",e)},this.handleAppVersionUpdated=async e=>{this.handleMetadataUpdated("AppVersion",e)},this.handleChainUpdated=async(e,t)=>{var i;let r=await this.cipher.decrypt(e),s=await this.cipher.decrypt(t);null==(i=this.listener)||i.chainUpdated(r,s)},this.session=e,this.cipher=new iU(e.secret),this.listener=i;const r=new iL(`${t}/rpc`,WebSocket);r.setConnectionStateListener(async e=>{let t=!1;switch(e){case mV.DISCONNECTED:if(!this.destroyed){let e=async()=>{await new Promise(e=>setTimeout(e,5e3)),this.destroyed||r.connect().catch(()=>{e()})};e()}break;case mV.CONNECTED:t=await this.handleConnected(),this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},1e4),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();case mV.CONNECTING:}this.connected!==t&&(this.connected=t)}),r.setIncomingDataListener(e=>{var t;switch(e.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{let t="IsLinkedOK"===e.type?e.linked:void 0;this.linked=t||e.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":this.handleSessionMetadataUpdated(e.metadata);break;case"Event":this.handleIncomingEvent(e)}void 0!==e.id&&(null==(t=this.requestResolutions.get(e.id))||t(e))}),this.ws=r,this.http=new iB(t,e.id,e.key)}connect(){if(this.destroyed)throw Error("instance is destroyed");this.ws.connect()}async destroy(){this.destroyed||(await this.makeRequest({type:"SetSessionConfig",id:t2(this.nextReqId++),sessionId:this.session.id,metadata:{__destroyed:"1"}},{timeout:1e3}),this.destroyed=!0,this.ws.disconnect(),this.listener=void 0)}get connected(){return this._connected}set connected(e){this._connected=e}get linked(){return this._linked}set linked(e){var t,i;this._linked=e,e&&(null==(t=this.onceLinked)||t.call(this)),null==(i=this.listener)||i.linkedUpdated(e)}setOnceLinked(e){return new Promise(t=>{this.linked?e().then(t):this.onceLinked=()=>{e().then(t),this.onceLinked=void 0}})}async handleIncomingEvent(e){var t;if("Event"!==e.type||"Web3Response"!==e.event)return;let i=JSON.parse(await this.cipher.decrypt(e.data));if("WEB3_RESPONSE"!==i.type)return;let{id:r,response:s}=i;null==(t=this.listener)||t.handleWeb3ResponseMessage(r,s)}async checkUnseenEvents(){if(!this.connected){this.shouldFetchUnseenEventsOnConnect=!0;return}await new Promise(e=>setTimeout(e,250));try{await this.fetchUnseenEventsAPI()}catch(e){console.error("Unable to check for unseen events",e)}}async fetchUnseenEventsAPI(){this.shouldFetchUnseenEventsOnConnect=!1,(await this.http.fetchUnseenEvents()).forEach(e=>this.handleIncomingEvent(e))}async publishEvent(e,t,i=!1){let r=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},t),{origin:location.origin,location:location.href,relaySource:"coinbaseWalletExtension"in window&&window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),s={type:"PublishEvent",id:t2(this.nextReqId++),sessionId:this.session.id,event:e,data:r,callWebhook:i};return this.setOnceLinked(async()=>{let e=await this.makeRequest(s);if("Fail"===e.type)throw Error(e.error||"failed to publish event");return e.eventId})}sendData(e){this.ws.sendData(JSON.stringify(e))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>2e4)return void this.ws.disconnect();try{this.ws.sendData("h")}catch(e){}}async makeRequest(e,t={timeout:6e4}){let i,r=e.id;return this.sendData(e),Promise.race([new Promise((e,s)=>{i=window.setTimeout(()=>{s(Error(`request ${r} timed out`))},t.timeout)}),new Promise(e=>{this.requestResolutions.set(r,t=>{clearTimeout(i),e(t),this.requestResolutions.delete(r)})})])}
vendor: 6,543 bytes, line 3
3async handleConnected(){return"Fail"!==(await this.makeRequest({type:"HostSession",id:t2(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key})).type&&(this.sendData({type:"IsLinked",id:t2(this.nextReqId++),sessionId:this.session.id}),this.sendData({type:"GetSessionConfig",id:t2(this.nextReqId++),sessionId:this.session.id}),!0)}}class iK{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%0x7fffffff;let e=this._nextRequestId,t=is(e.toString(16));return this.callbacks.get(t)&&this.callbacks.delete(t),e}}var iH=e.i(280355),i$=e.i(470525);let iW="session:id",iz="session:secret",iF="session:linked";class iV{constructor(e,t,i,r=!1){this.storage=e,this.id=t,this.secret=i,this.key=(0,i$.bytesToHex)((0,iH.sha256)(`${t}, ${i} WalletLink`)),this._linked=!!r}static create(e){return new iV(e,t8(16),t8(32)).save()}static load(e){let t=e.getItem(iW),i=e.getItem(iF),r=e.getItem(iz);return t&&r?new iV(e,t,r,"1"===i):null}get linked(){return this._linked}set linked(e){this._linked=e,this.persistLinked()}save(){return this.storage.setItem(iW,this.id),this.storage.setItem(iz,this.secret),this.persistLinked(),this}persistLinked(){this.storage.setItem(iF,this._linked?"1":"0")}}function iJ(){var e,t;return null!=(t=null==(e=null==window?void 0:window.matchMedia)?void 0:e.call(window,"(prefers-color-scheme: dark)").matches)&&t}function iG(){let e=document.createElement("style");e.type="text/css",e.appendChild(document.createTextNode('@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}')),document.documentElement.appendChild(e)}var iY=e.i(102305),iZ=e.i(928020),iQ=e.i(698920);class iX{constructor(){this.items=new Map,this.nextItemKey=0,this.root=null,this.darkMode=iJ()}attach(e){this.root=document.createElement("div"),this.root.className="-cbwsdk-snackbar-root",e.appendChild(this.root),this.render()}presentItem(e){let t=this.nextItemKey++;return this.items.set(t,e),this.render(),()=>{this.items.delete(t),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&(0,iZ.render)((0,iZ.h)("div",null,(0,iZ.h)(i0,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([e,t])=>(0,iZ.h)(i1,Object.assign({},t,{key:e}))))),this.root)}}let i0=e=>(0,iZ.h)("div",{class:(0,iY.clsx)("-cbwsdk-snackbar-container")},(0,iZ.h)("style",null,".-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;
3cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}"),(0,iZ.h)("div",{class:"-cbwsdk-snackbar"},e.children)),i1=({autoExpand:e,message:t,menuItems:i})=>{let[r,s]=(0,iQ.useState)(!0),[n,a]=(0,iQ.useState)(null!=e&&e);return(0,iQ.useEffect)(()=>{let e=[window.setTimeout(()=>{s(!1)},1),window.setTimeout(()=>{a(!0)},1e4)];return()=>{e.forEach(window.clearTimeout)}}),(0,iZ.h)("div",{class:(0,iY.clsx)("-cbwsdk-snackbar-instance",r&&"-cbwsdk-snackbar-instance-hidden",n&&"-cbwsdk-snackbar-instance-expanded")},(0,iZ.h)("div",{class:"-cbwsdk-snackbar-instance-header",onClick:()=>{a(!n)}},(0,iZ.h)("img",{src:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+",class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",(0,iZ.h)("div",{class:"-cbwsdk-snackbar-instance-header-message"},t),(0,iZ.h)("div",{class:"-gear-container"},!n&&(0,iZ.h)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,iZ.h)("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),(0,iZ.h)("img",{src:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwu
3NTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=",class:"-gear-icon",title:"Expand"}))),i&&i.length>0&&(0,iZ.h)("div",{class:"-cbwsdk-snackbar-instance-menu"},i.map((e,t)=>(0,iZ.h)("div",{class:(0,iY.clsx)("-cbwsdk-snackbar-instance-menu-item",e.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:e.onClick,key:t},(0,iZ.h)("svg",{width:e.svgWidth,height:e.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,iZ.h)("path",{"fill-rule":e.defaultFillRule,"clip-rule":e.defaultClipRule,d:e.path,fill:"#AAAAAA"})),(0,iZ.h)("span",{class:(0,iY.clsx)("-cbwsdk-snackbar-instance-menu-item-info",e.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},e.info)))))},i2="M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z";class i5{constructor(){this.attached=!1,this.snackbar=new iX}attach(){if(this.attached)throw Error("Coinbase Wallet SDK UI is already attached");let e=document.documentElement,t=document.createElement("div");t.className="-cbwsdk-css-reset",e.appendChild(t),this.snackbar.attach(t),this.attached=!0,iG()}showConnecting(e){let t;return t=e.isUnlinkedErrorState?{autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]}:{message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:e.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:i2,defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]},this.snackbar.presentItem(t)}}class i3{constructor(){this.root=null,this.darkMode=iJ()}attach(){let e=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",e.appendChild(this.root),iG()}present(e){this.render(e)}clear(){this.render(null)}render(e){!this.root||((0,iZ.render)(null,this.root),e&&(0,iZ.render)((0,iZ.h)(i8,Object.assign({},e,{onDismiss:()=>{this.clear()},darkMode:this.darkMode})),this.root))}}let i8=({title:e,buttonText:t,darkMode:i,onButtonClick:r,onDismiss:s})=>(0,iZ.h)(i0,{darkMode:i},(0,iZ.h)("div",{class:"-cbwsdk-redirect-dialog"},(0,iZ.h)("style",null,".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}
3.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}"),(0,iZ.h)("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:s}),(0,iZ.h)("div",{class:(0,iY.clsx)("-cbwsdk-redirect-dialog-box",i?"dark":"light")},(0,iZ.h)("p",null,e),(0,iZ.h)("button",{onClick:r},t)))),i6="https://www.walletlink.org";class i4{constructor(){this.attached=!1,this.redirectDialog=new i3}attach(){if(this.attached)throw Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}redirectToCoinbaseWallet(e){let t=new URL("https://go.cb-w.com/walletlink");t.searchParams.append("redirect_url",function(){try{if(function(){try{return null!==window.frameElement}catch(e){return!1}}()&&window.top)return window.top.location;return window.location}catch(e){return window.location}}().href),e&&t.searchParams.append("wl_url",e);let i=document.createElement("a");i.target="cbw-opener",i.href=t.href,i.rel="noreferrer noopener",i.click()}openCoinbaseWalletDeeplink(e){this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",onButtonClick:()=>{this.redirectToCoinbaseWallet(e)}}),setTimeout(()=>{this.redirectToCoinbaseWallet(e)},99)}showConnecting(e){return()=>{this.redirectDialog.clear()}}}class i7{constructor(e){this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.isMobileWeb=function(){var e;return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(null==(e=null==window?void 0:window.navigator)?void 0:e.userAgent)}(),this.linkedUpdated=e=>{this.isLinked=e;let t=this.storage.getItem(iD);if(e&&(this._session.linked=e),this.isUnlinkedErrorState=!1,t){let i=t.split(" "),r="true"===this.storage.getItem("IsStandaloneSigning");""===i[0]||e||!this._session.linked||r||(this.isUnlinkedErrorState=!0)}},this.metadataUpdated=(e,t)=>{this.storage.setItem(e,t)},this.chainUpdated=(e,t)=>{(this.chainCallbackParams.chainId!==e||this.chainCallbackParams.jsonRpcUrl!==t)&&(this.chainCallbackParams={chainId:e,jsonRpcUrl:t},this.chainCallback&&this.chainCallback(t,Number.parseInt(e,10)))},this.accountUpdated=e=>{this.accountsCallback&&this.accountsCallback([e]),i7.accountRequestCallbackIds.size>0&&(Array.from(i7.accountRequestCallbackIds.values()).forEach(t=>{this.invokeCallback(t,{method:"requestEthereumAccounts",result:[e]})}),i7.accountRequestCallbackIds.clear())},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=e.linkAPIUrl,this.storage=e.storage,this.metadata=e.metadata,this.accountsCallback=e.accountsCallback,this.chainCallback=e.chainCallback;const{session:t,ui:i,connection:r}=this.subscribe();this._session=t,this.connection=r,this.relayEventManager=new iK,this.ui=i,this.ui.attach()}subscribe(){let e=iV.load(this.storage)||iV.create(this.storage),{linkAPIUrl:t}=this,i=new iq({session:e,linkAPIUrl:t,listener:this}),r=this.isMobileWeb?new i4:new i5;return i.connect(),{session:e,ui:r,connection:i}}resetAndReload(){this.connection.destroy().then(()=>{let e=iV.load(this.storage);(null==e?void 0:e.id)===this._session.id&&tO.clearAll(),document.location.reload()}).catch(e=>{})}signEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:ie(e.weiValue),data:t7(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?ie(e.gasPriceInWei):null,maxFeePerGas:e.gasPriceInWei?ie(e.gasPriceInWei):null,maxPriorityFeePerGas:e.gasPriceInWei?ie(e.gasPriceInWei):null,gasLimit:e.gasLim
vendor: 13,917 bytes, lines 3-5
3it?ie(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:ie(e.weiValue),data:t7(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?ie(e.gasPriceInWei):null,maxFeePerGas:e.maxFeePerGas?ie(e.maxFeePerGas):null,maxPriorityFeePerGas:e.maxPriorityFeePerGas?ie(e.maxPriorityFeePerGas):null,gasLimit:e.gasLimit?ie(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!0}})}submitEthereumTransaction(e,t){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:t7(e,!0),chainId:t}})}getWalletLinkSession(){return this._session}sendRequest(e){let t=null,i=t8(8),r=r=>{this.publishWeb3RequestCanceledEvent(i),this.handleErrorResponse(i,e.method,r),null==t||t()};return new Promise((s,n)=>{t=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:r,onResetConnection:this.resetAndReload}),this.relayEventManager.callbacks.set(i,e=>{if(null==t||t(),iM(e))return n(Error(e.errorMessage));s(e)}),this.publishWeb3RequestEvent(i,e)})}publishWeb3RequestEvent(e,t){let i={type:"WEB3_REQUEST",id:e,request:t};this.publishEvent("Web3Request",i,!0).then(e=>{}).catch(e=>{this.handleWeb3ResponseMessage(i.id,{method:t.method,errorMessage:e.message})}),this.isMobileWeb&&this.openCoinbaseWalletDeeplink(t.method)}openCoinbaseWalletDeeplink(e){if(this.ui instanceof i4)switch(e){case"requestEthereumAccounts":case"switchEthereumChain":return;default:window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0}),this.ui.openCoinbaseWalletDeeplink()}}publishWeb3RequestCanceledEvent(e){this.publishEvent("Web3RequestCanceled",{type:"WEB3_REQUEST_CANCELED",id:e},!1).then()}publishEvent(e,t,i){return this.connection.publishEvent(e,t,i)}handleWeb3ResponseMessage(e,t){if("requestEthereumAccounts"===t.method){i7.accountRequestCallbackIds.forEach(e=>this.invokeCallback(e,t)),i7.accountRequestCallbackIds.clear();return}this.invokeCallback(e,t)}handleErrorResponse(e,t,i){var r;let s=null!=(r=null==i?void 0:i.message)?r:"Unspecified error message.";this.handleWeb3ResponseMessage(e,{method:t,errorMessage:s})}invokeCallback(e,t){let i=this.relayEventManager.callbacks.get(e);i&&(i(t),this.relayEventManager.callbacks.delete(e))}requestEthereumAccounts(){let{appName:e,appLogoUrl:t}=this.metadata,i={method:"requestEthereumAccounts",params:{appName:e,appLogoUrl:t}},r=t8(8);return new Promise((e,t)=>{this.relayEventManager.callbacks.set(r,i=>{if(iM(i))return t(Error(i.errorMessage));e(i)}),i7.accountRequestCallbackIds.add(r),this.publishWeb3RequestEvent(r,i)})}watchAsset(e,t,i,r,s,n){let a={method:"watchAsset",params:{type:e,options:{address:t,symbol:i,decimals:r,image:s},chainId:n}},o=null,l=t8(8),c=e=>{this.publishWeb3RequestCanceledEvent(l),this.handleErrorResponse(l,a.method,e),null==o||o()};return o=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:c,onResetConnection:this.resetAndReload}),new Promise((e,t)=>{this.relayEventManager.callbacks.set(l,i=>{if(null==o||o(),iM(i))return t(Error(i.errorMessage));e(i)}),this.publishWeb3RequestEvent(l,a)})}addEthereumChain(e,t,i,r,s,n){let a={method:"addEthereumChain",params:{chainId:e,rpcUrls:t,blockExplorerUrls:r,chainName:s,iconUrls:i,nativeCurrency:n}},o=null,l=t8(8),c=e=>{this.publishWeb3RequestCanceledEvent(l),this.handleErrorResponse(l,a.method,e),null==o||o()};return o=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:c,onResetConnection:this.resetAndReload}),new Promise((e,t)=>{this.relayEventManager.callbacks.set(l,i=>{if(null==o||o(),iM(i))return t(Error(i.errorMessage));e(i)}),this.publishWeb3RequestEvent(l,a)})}switchEthereumChain(e,t){let i={method:"switchEthereumChain",params:Object.assign({chainId:e},{address:t})},r=null,s=t8(8),n=e=>{this.publishWeb3RequestCanceledEvent(s),this.handleErrorResponse(s,i.method,e),null==r||r()};return r=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:n,onResetConnection:this.resetAndReload}),new Promise((e,t)=>{this.relayEventManager.callbacks.set(s,i=>(null==r||r(),iM(i)&&i.errorCode)?t(tY({code:i.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."})):iM(i)?t(Error(i.errorMessage)):void e(i)),this.publishWeb3RequestEvent(s,i)})}}i7.accountRequestCallbackIds=new Set;let i9="DefaultChainId",re="DefaultJsonRpcUrl";class rt{constructor(e){this._relay=null,this._addresses=[],this.metadata=e.metadata,this._storage=new tO("walletlink",i6),this.callback=e.callback||null;const t=this._storage.getItem(iD);if(t){const e=t.split(" ");""!==e[0]&&(this._addresses=e.map(e=>il(e)))}this.initializeRelay()}getSession(){let{id:e,secret:t}=this.initializeRelay().getWalletLinkSession();return{id:e,secret:t}}async handshake(){await this._eth_requestAccounts()}get selectedAddress(){return this._addresses[0]||void 0}get jsonRpcUrl(){var e;return null!=(e=this._storage.getItem(re))?e:void 0}set jsonRpcUrl(e){this._storage.setItem(re,e)}updateProviderInfo(e,t){var i;this.jsonRpcUrl=e;let r=this.getChainId();this._storage.setItem(i9,t.toString(10)),ih(t)!==r&&(null==(i=this.callback)||i.call(this,"chainChanged",it(t)))}async watchAsset(e){let t=Array.isArray(e)?e[0]:e;if(!t.type)throw tW("Type is required");if((null==t?void 0:t.type)!=="ERC20")throw tW(`Asset of type '${t.type}' is not supported`);if(!(null==t?void 0:t.options))throw tW("Options are required");if(!(null==t?void 0:t.options.address))throw tW("Address is required");let i=this.getChainId(),{address:r,symbol:s,image:n,decimals:a}=t.options,o=this.initializeRelay(),l=await o.watchAsset(t.type,r,s,a,n,null==i?void 0:i.toString());return!iM(l)&&!!l.result}async addEthereumChain(e){var t,i;let r=e[0];if((null==(t=r.rpcUrls)?void 0:t.length)===0)throw tW("please pass in at least 1 rpcUrl");if(!r.chainName||""===r.chainName.trim())throw tW("chainName is a required field");if(!r.nativeCurrency)throw tW("nativeCurrency is a required field");let s=Number.parseInt(r.chainId,16);if(s===this.getChainId())return!1;let n=this.initializeRelay(),{rpcUrls:a=[],blockExplorerUrls:o=[],chainName:l,iconUrls:c=[],nativeCurrency:h}=r,d=await n.addEthereumChain(s.toString(),a,c,o,l,h);if(iM(d))return!1;if((null==(i=d.result)?void 0:i.isApproved)===!0)return this.updateProviderInfo(a[0],s),null;throw tz("unable to add ethereum chain")}async switchEthereumChain(e){let t=Number.parseInt(e[0].chainId,16),i=this.initializeRelay(),r=await i.switchEthereumChain(t.toString(10),this.selectedAddress||void 0);if(iM(r))throw r;let s=r.result;return s.isApproved&&s.rpcUrl.length>0&&this.updateProviderInfo(s.rpcUrl,t),null}async cleanup(){this.callback=null,this._relay&&this._relay.resetAndReload(),this._storage.clear()}_setAddresses(e,t){var i;if(!Array.isArray(e))throw Error("addresses is not an array");let r=e.map(e=>il(e));JSON.stringify(r)!==JSON.stringify(this._addresses)&&(this._addresses=r,null==(i=this.callback)||i.call(this,"accountsChanged",r),this._storage.setItem(iD,r.join(" ")))}async request(e){let t=e.params||[];switch(e.method){case"eth_accounts":return[...this._addresses];case"eth_coinbase":return this.selectedAddress||null;case"net_version":return this.getChainId().toString(10);case"eth_chainId":return it(this.getChainId());case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_ecRecover":case"personal_ecRecover":return this.ecRecover(e);case"personal_sign":return this.personalSign(e);case"eth_signTransaction":return this._eth_signTransaction(t);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(t);case"eth_sendTransaction":return this._eth_sendTransaction(t);case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":case"eth_signTypedData":return this.signTypedData(e);case"wallet_addEthereumChain":return this.addEthereumChain(t);case"wallet_switchEthereumChain":return this.switchEthereumChain(t);case"wallet_watchAsset":return this.watchAsset(t);default:if(!this.jsonRpcUrl)throw tz("No RPC URL set for chain");return i_(e,this.jsonRpcUrl)}}_ensureKnownAddress(e){let t=il(e);if(!this._addresses.map(e=>il(e)).includes(t))throw Error("Unknown Ethereum address")}_prepareTransactionParams(e){let t=e.from?il(e.from):this.selectedAddress;if(!t)throw Error("Ethereum address is unavailable");this._ensureKnownAddress(t);let i=e.to?il(e.to):null,r=null!=e.value?id(e.value):BigInt(0),s=e.data?ic(e.data):tT.Buffer.alloc(0),n=null!=e.nonce?ih(e.nonce):null,a=null!=e.gasPrice?id(e.gasPrice):null,o=null!=e.maxFeePerGas?id(e.maxFeePerGas):null,l=null!=e.maxPriorityFeePerGas?id(e.maxPriorityFeePerGas):null;return{fromAddress:t,toAddress:i,weiValue:r,data:s,nonce:n,gasPriceInWei:a,maxFeePerGas:o,maxPriorityFeePerGas:l,gasLimit:null!=e.gas?id(e.gas):null,chainId:e.chainId?ih(e.chainId):this.getChainId()}}async ecRecover(e){let{method:t,params:i}=e;if(!Array.isArray(i))throw tW();let r=this.initializeRelay(),s=await r.sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:t9(i[0]),signature:t9(i[1]),addPrefix:"personal_ecRecover"===t}});if(iM(s))throw s;return s.result}getChainId(){var e;return Number.parseInt(null!=(e=this._storage.getItem(i9))?e:"1",10)}async _eth_requestAccounts(){var e,t;if(this._addresses.length>0)return null==(e=this.callback)||e.call(this,"connect",{chainId:it(this.getChainId())}),this._addresses;let i=this.initializeRelay(),r=await i.requestEthereumAccounts();if(iM(r))throw r;if(!r.result)throw Error("accounts received is empty");return this._setAddresses(r.result),null==(t=this.callback)||t.call(this,"connect",{chainId:it(this.getChainId())}),this._addresses}async personalSign({params:e}){if(!Array.isArray(e))throw tW();let t=e[1],i=e[0];this._ensureKnownAddress(t);let r=this.initializeRelay(),s=await r.sendRequest({method:"signEthereumMessage",params:{address:il(t),message:t9(i),addPrefix:!0,typedDataJson:null}});if(iM(s))throw s;return s.result}async _eth_signTransaction(e){let t=this._prepareTransactionParams(e[0]||{}),i=this.initializeRelay(),r=await i.signEthereumTransaction(t);if(iM(r))throw r;return r.result}async _eth_sendRawTransaction(e){let t=ic(e[0]),i=this.initializeRelay(),r=await i.submitEthereumTransaction(t,this.getChainId());if(iM(r))throw r;return r.result}async _eth_sendTransaction(e){let t=this._prepareTransactionParams(e[0]||{}),i=this.initializeRelay(),r=await i.signAndSubmitEthereumTransaction(t);if(iM(r))throw r;return r.result}async signTypedData(e){let{method:t,params:i}=e;if(!Array.isArray(i))throw tW();let r=i[+("eth_signTypedData_v1"===t)],s=i[+("eth_signTypedData_v1"!==t)];this._ensureKnownAddress(r);let n=this.initializeRelay(),a=await n.sendRequest({method:"signEthereumMessage",params:{address:il(r),message:t7(({eth_signTypedData_v1:ij.default.hashForSignTypedDataLegacy,eth_signTypedData_v3:ij.default.hashForSignTypedData_v3,eth_signTypedData_v4:ij.default.hashForSignTypedData_v4,eth_signTypedData:ij.default.hashForSignTypedData_v4})[t]({data:function(e){if("string"==typeof e)return JSON.parse(e);if("object"==typeof e)return e;throw tW(`Not a JSON string or an object: ${String(e)}`)}(s)}),!0),typedDataJson:JSON.stringify(s,null,2),addPrefix:!1}});if(iM(a))throw a;return a.result}initializeRelay(){return this._relay||(this._relay=new i7({linkAPIUrl:i6,storage:this._storage,metadata:this.metadata,accountsCallback:this._setAddresses.bind(this),chainCallback:this.updateProviderInfo.bind(this)})),this._relay}}let ri="SignerType",rr=new tO("CBWSDK","SignerConfigurator");async function rs(e){let{communicator:t,metadata:i,handshakeRequest:r,callback:s}=e;rn(t,i,s).catch(()=>{});let n={id:crypto.randomUUID(),event:"selectSignerType",data:Object.assign(Object.assign({},e.preference),{handshakeRequest:r})},{data:a}=await t.postRequestAndWaitForResponse(n);return a}async function rn(e,t,i){await e.onMessage(({event:e})=>"WalletLinkSessionRequest"===e);let r=new rt({metadata:t,callback:i});e.postMessage({event:"WalletLinkUpdate",data:{session:r.getSession()}}),await r.handshake(),e.postMessage({event:"WalletLinkUpdate",data:{connected:!0}})}let ra=`Coinbase Wallet SDK requires the Cross-Origin-Opener-Policy header to not be set to 'same-origin'. This is to ensure that the SDK can communicate with the Coinbase Smart Wallet app.
4
5Please see https://www.smartwallet.dev/guides/tips/popup-tips#cross-origin-opener-policy for more information.`,{checkCrossOriginOpenerPolicy:ro,getCrossOriginOpenerPolicy:rl}={getCrossOriginOpenerPolicy:()=>void 0===a?"undefined":a,checkCrossOriginOpenerPolicy:async()=>{if("u"<typeof window){a="non-browser-env";return}try{let e=`${window.location.origin}${window.location.pathname}`,t=await fetch(e,{method:"HEAD"});if(!t.ok)throw Error(`HTTP error! status: ${t.status}`);let i=t.headers.get("Cross-Origin-Opener-Policy");a=null!=i?i:"null","same-origin"===a&&console.error(ra)}catch(e){console.error("Error checking Cross-Origin-Opener-Policy:",e.message),a="error"}}},rc={isRed:!1,info:"Retry",svgWidth:"10",svgHeight:"11",path:i2,defaultFillRule:"evenodd",defaultClipRule:"evenodd"},rh=null;class rd{constructor({url:e="https://keys.coinbase.com/connect",metadata:t,preference:i}){this.popup=null,this.listeners=new Map,this.postMessage=async e=>{(await this.waitForPopupLoaded()).postMessage(e,this.url.origin)},this.postRequestAndWaitForResponse=async e=>{let t=this.onMessage(({requestId:t})=>t===e.id);return this.postMessage(e),await t},this.onMessage=async e=>new Promise((t,i)=>{let r=i=>{if(i.origin!==this.url.origin)return;let s=i.data;e(s)&&(t(s),window.removeEventListener("message",r),this.listeners.delete(r))};window.addEventListener("message",r),this.listeners.set(r,{reject:i})}),this.disconnect=()=>{var e;(e=this.popup)&&!e.closed&&e.close(),this.popup=null,this.listeners.forEac
vendor: 4,218 bytes, line 5
5h(({reject:e},t)=>{e(tF("Request rejected")),window.removeEventListener("message",t)}),this.listeners.clear()},this.waitForPopupLoaded=async()=>this.popup&&!this.popup.closed?(this.popup.focus(),this.popup):(this.popup=await function(e){let t=(window.innerWidth-420)/2+window.screenX,i=(window.innerHeight-540)/2+window.screenY;function r(){let r=`wallet_${crypto.randomUUID()}`,s=window.open(e,r,`width=420, height=540, left=${t}, top=${i}`);return(null==s||s.focus(),s)?s:null}var s=e;for(let[e,t]of Object.entries({sdkName:iC,sdkVersion:iP,origin:window.location.origin,coop:rl()}))s.searchParams.append(e,t.toString());let n=r();if(!n){let e=function(){if(!rh){let e=document.createElement("div");e.className="-cbwsdk-css-reset",document.body.appendChild(e),(rh=new iX).attach(e)}return rh}();return new Promise((t,i)=>{e.presentItem({autoExpand:!0,message:"Popup was blocked. Try again.",menuItems:[Object.assign(Object.assign({},rc),{onClick:()=>{(n=r())?t(n):i(tz("Popup window was blocked")),e.clear()}})]})})}return Promise.resolve(n)}(this.url),this.onMessage(({event:e})=>"PopupUnload"===e).then(this.disconnect).catch(()=>{}),this.onMessage(({event:e})=>"PopupLoaded"===e).then(e=>{this.postMessage({requestId:e.id,data:{version:iP,metadata:this.metadata,preference:this.preference,location:window.location.toString()}})}).then(()=>{if(!this.popup)throw tz();return this.popup})),this.url=new URL(e),this.metadata=t,this.preference=i}}var ru=e.i(87246);class rp extends ru.EventEmitter{}var rf=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)0>t.indexOf(r[s])&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(i[r[s]]=e[r[s]]);return i};class rg extends rp{constructor(e){var{metadata:t}=e,i=e.preference,{keysUrl:r}=i,s=rf(i,["keysUrl"]);super(),this.signer=null,this.isCoinbaseWallet=!0,this.metadata=t,this.preference=s,this.communicator=new rd({url:r,metadata:t,preference:s});const n=rr.getItem(ri);n&&(this.signer=this.initSigner(n))}async request(e){try{if(!function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw tW({message:"Expected a single, non-array, object argument.",data:e});let{method:t,params:i}=e;if("string"!=typeof t||0===t.length)throw tW({message:"'args.method' must be a non-empty string.",data:e});if(void 0!==i&&!Array.isArray(i)&&("object"!=typeof i||null===i))throw tW({message:"'args.params' must be an object or array if provided.",data:e});switch(t){case"eth_sign":case"eth_signTypedData_v2":case"eth_subscribe":case"eth_unsubscribe":throw tJ()}}(e),!this.signer)switch(e.method){case"eth_requestAccounts":{let t=await this.requestSignerSelection(e),i=this.initSigner(t);await i.handshake(e),this.signer=i,rr.setItem(ri,t);break}case"wallet_sendCalls":{let t=this.initSigner("scw");await t.handshake({method:"handshake"});let i=await t.request(e);return await t.cleanup(),i}case"wallet_getCallsStatus":return i_(e,"https://rpc.wallet.coinbase.com");case"net_version":return 1;case"eth_chainId":return it(1);default:throw tV("Must call 'eth_requestAccounts' before other methods")}return await this.signer.request(e)}catch(r){let e,t,{code:i}=r;return i===tD&&this.disconnect(),Promise.reject((e=function(e,{shouldIncludeStack:t=!1}={}){var i,r;let s={};if(e&&"object"==typeof e&&!Array.isArray(e)&&tH(e,"code")&&Number.isInteger(i=e.code)&&(tB[i.toString()]||(r=i)>=-32099&&r<=-32e3))s.code=e.code,e.message&&"string"==typeof e.message?(s.message=e.message,tH(e,"data")&&(s.data=e.data)):(s.message=tq(s.code),s.data={originalError:tK(e)});else s.code=tN,s.message=t$(e,"message")?e.message:tL,s.data={originalError:tK(e)};return t&&(s.stack=t$(e,"stack")?e.stack:void 0),s}(function(e){var t;if("string"==typeof e)return{message:e,code:tN};if(iM(e)){let i=e.errorMessage,r=null!=(t=e.errorCode)?t:i.match(/(denied|rejected)/i)?tj:void 0;return Object.assign(Object.assign({},e),{message:i,code:r,data:{method:e.method}})}return e}(r),{shouldIncludeStack:!0}),(t=new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors")).searchParams.set("version",iP),t.searchParams.set("co
5de",e.code.toString()),t.searchParams.set("message",e.message),Object.assign(Object.assign({},e),{docUrl:t.href})))}}async enable(){return console.warn('.enable() has been deprecated. Please use .request({ method: "eth_requestAccounts" }) instead.'),await this.request({method:"eth_requestAccounts"})}async disconnect(){var e;await (null==(e=this.signer)?void 0:e.cleanup()),this.signer=null,tO.clearAll(),this.emit("disconnect",tG("User initiated disconnection"))}requestSignerSelection(e){return rs({communicator:this.communicator,preference:this.preference,metadata:this.metadata,handshakeRequest:e,callback:this.emit.bind(this)})}initSigner(e){return function(e){let{signerType:t,metadata:i,communicator:r,callback:s}=e;switch(t){case"scw":return new iN({metadata:i,callback:s,communicator:r});case"walletlink":return new rt({metadata:i,callback:s})}}({signerType:e,metadata:this.metadata,communicator:this.communicator,callback:this.emit.bind(this)})}}let ry={options:"all"};function rm(e){new tO("CBWSDK").setItem("VERSION",iP),ro();let t={metadata:{appName:e.appName||"Dapp",appLogoUrl:e.appLogoUrl||"",appChainIds:e.appChainIds||[]},preference:Object.assign(ry,null!=(i=e.preference)?i:{})};var i,r=t.preference;if(r){if(!["all","smartWalletOnly","eoaOnly"].includes(r.options))throw Error(`Invalid options: ${r.options}`);if(r.attribution&&void 0!==r.attribution.auto&&void 0!==r.attribution.dataSuffix)throw Error("Attribution cannot contain both auto and dataSuffix properties")}let s=null;return{getProvider:()=>{var e;let i;return s||(s=null!=(e=function({metadata:e,preference:t}){var i,r;let{appName:s,appLogoUrl:n,appChainIds:a}=e;if("smartWalletOnly"!==t.options){let e=globalThis.coinbaseWalletExtension;if(e)return null==(i=e.setAppInfo)||i.call(e,s,n,a,t),e}let o=function(){var e,t;try{let i=globalThis;return null!=(e=i.ethereum)?e:null==(t=i.top)?void 0:t.ethereum}catch(e){return}}();if(null==o?void 0:o.isCoinbaseBrowser)return null==(r=o.setAppInfo)||r.call(o,s,n,a,t),o}(i={metadata:t.metadata,preference:t.preference}))?e:new rg(i)),s}}}var rw=e.i(604677),rb=e.i(81039),rv=e.i(33750),rE=e.i(219298),rI=e.i(247167),rS=e.i(277945),rA=e.i(648512),rx=e.i(509217),rP=e.i(75063),rC=e.i(44314),r_=e.i(140965);let rk=BigInt(0),rO=BigInt(1);function rT(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function rR(e){if(!rT(e))throw Error("Uint8Array expected")}function rN(e,t){if("boolean"!=typeof t)throw Error(e+" boolean expected, got "+t)}function rj(e){let t=e.toString(16);return 1&t.length?"0"+t:t}function rD(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return""===e?rk:BigInt("0x"+e)}let rM="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,rU=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function rB(e){if(rR(e),rM)return e.toHex();let t="";for(let i=0;i<e.length;i++)t+=rU[e[i]];return t}function rL(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function rq(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(rM)return Uint8Array.fromHex(e);let t=e.length,i=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(i);for(let t=0,s=0;t<i;t++,s+=2){let i=rL(e.charCodeAt(s)),n=rL(e.charCodeAt(s+1));if(void 0===i||void 0===n)throw Error('hex string expected, got non-hex character "'+(e[s]+e[s+1])+'" at index '+s);r[t]=16*i+n}return r}function rK(e){return rD(rB(e))}function rH(e){return rR(e),rD(rB(Uint8Array.from(e).reverse()))}function r$(e,t){return rq(e.toString(16).padStart(2*t,"0"))}function rW(e,t){return r$(e,t).reverse()}function rz(e,t,i){let r;if("string"==typeof t)try{r=rq(t)}catch(t){throw Error(e+" must be hex string or Uint8Array, cause: "+t)}else if(rT(t))r=Uint8Array.from(t);else throw Error(e+" must be hex string or Uint8Array");let s=r.length;if("number"==typeof i&&s!==i)throw Error(e+" of length "+i+" expected, got "+s);return r}function rF(...e){let t=0;for(let i=0;i<e.length;i++){let r=e[i];rR(r),t+=r.length}let i=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let s=e[t];i.set(s,r),r+=s.length}return i}let rV=e=>"bigint"==typeof e&&rk<=e;function rJ(e,t,i){return rV(e)&&rV(t)&&rV(i)&&t<=e&&e<i}function rG(e,t,i,r){if(!rJ(t,i,r))throw Error("expected valid "+e+": "+i+" <= n < "+r+", got "+t)}let rY=e=>(rO<<BigInt(e))-rO,rZ=e=>new Uint8Array(e),rQ={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||rT(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function rX(e,t,i={}){let r=(t,i,r)=>{let s=rQ[i];if("function"!=typeof s)throw Error("invalid validator function");let n=e[t];if((!r||void 0!==n)&&!s(n,e))throw Error("param "+String(t)+" is invali
5d. Expected "+i+", got "+n)};for(let[e,i]of Object.entries(t))r(e,i,!1);for(let[e,t]of Object.entries(i))r(e,t,!0);return e}function r0(e){let t=new WeakMap;return(i,...r)=>{let s=t.get(i);if(void 0!==s)return s;let n=e(i,...r);return t.set(i,n),n}}let r1=BigInt(0),r2=BigInt(1),r5=BigInt(2),r3=BigInt(3),r8=BigInt(4),r6=BigInt(5),r4=BigInt(8);function r7(e,t){let i=e%t;return i>=r1?i:t+i}function r9(e,t,i){let r=e;for(;t-- >r1;)r*=r,r%=i;return r}function se(e,t){if(e===r1)throw Error("invert: expected non-zero number");if(t<=r1)throw Error("invert: expected positive modulus, got "+t);let i=r7(e,t),r=t,s=r1,n=r2,a=r2,o=r1;for(;i!==r1;){let e=r/i,t=r%i,l=s-a*e,c=n-o*e;r=i,i=t,s=a,n=o,a=l,o=c}if(r!==r2)throw Error("invert: does not exist");return r7(s,t)}function st(e,t){let i=(e.ORDER+r2)/r8,r=e.pow(t,i);if(!e.eql(e.sqr(r),t))throw Error("Cannot find square root");return r}function si(e,t){let i=(e.ORDER-r6)/r4,r=e.mul(t,r5),s=e.pow(r,i),n=e.mul(t,s),a=e.mul(e.mul(n,r5),s),o=e.mul(n,e.sub(a,e.ONE));if(!e.eql(e.sqr(o),t))throw Error("Cannot find square root");return o}let sr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ss(e){return rX(e,sr.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}))}function sn(e,t,i=!1){let r=Array(t.length).fill(i?e.ZERO:void 0),s=t.reduce((t,i,s)=>e.is0(i)?t:(r[s]=t,e.mul(t,i)),e.ONE),n=e.inv(s);return t.reduceRight((t,i,s)=>e.is0(i)?t:(r[s]=e.mul(t,r[s]),e.mul(t,i)),n),r}function sa(e,t){let i=(e.ORDER-r2)/r5,r=e.pow(t,i),s=e.eql(r,e.ONE),n=e.eql(r,e.ZERO),a=e.eql(r,e.neg(e.ONE));if(!s&&!n&&!a)throw Error("invalid Legendre symbol result");return s?1:n?0:-1}function so(e,t){void 0!==t&&(0,i$.anumber)(t);let i=void 0!==t?t:e.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function sl(e,t,i=!1,r={}){let s;if(e<=r1)throw Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:n,nByteLength:a}=so(e,t);if(a>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let o=Object.freeze({ORDER:e,isLE:i,BITS:n,BYTES:a,MASK:rY(n),ZERO:r1,ONE:r2,create:t=>r7(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error("invalid field element: expected bigint, got "+typeof t);return r1<=t&&t<e},is0:e=>e===r1,isOdd:e=>(e&r2)===r2,neg:t=>r7(-t,e),eql:(e,t)=>e===t,sqr:t=>r7(t*t,e),add:(t,i)=>r7(t+i,e),sub:(t,i)=>r7(t-i,e),mul:(t,i)=>r7(t*i,e),pow:(e,t)=>(function(e,t,i){if(i<r1)throw Error("invalid exponent, negatives unsupported");if(i===r1)return e.ONE;if(i===r2)return t;let r=e.ONE,s=t;for(;i>r1;)i&r2&&(r=e.mul(r,s)),s=e.sqr(s),i>>=r2;return r})(o,e,t),div:(t,i)=>r7(t*se(i,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>se(t,e),sqrt:r.sqrt||(t=>(s||(s=e%r8===r3?st:e%r4===r6?si:function(e){if(e<BigInt(3))throw Error("sqrt is not defined for small field");let t=e-r2,i=0;for(;t%r5===r1;)t/=r5,i++;let r=r5,s=sl(e);for(;1===sa(s,r);)if(r++>1e3)throw Error("Cannot find square root: probably non-prime P");if(1===i)return st;let n=s.pow(r,t),a=(t+r2)/r5;return function(e,r){if(e.is0(r))return r;if(1!==sa(e,r))throw Error("Cannot find square root");let s=i,o=e.mul(e.ONE,n),l=e.pow(r,t),c=e.pow(r,a);for(;!e.eql(l,e.ONE);){if(e.is0(l))return e.ZERO;let t=1,i=e.sqr(l);for(;!e.eql(i,e.ONE);)if(t++,i=e.sqr(i),t===s)throw Error("Cannot find square root");let r=r2<<BigInt(s-t-1),n=e.pow(o,r);s=t,o=e.sqr(n),l=e.mul(l,o),c=e.mul(c,n)}return c}}(e)),s(o,t))),toBytes:e=>i?rW(e,a):r$(e,a),fromBytes:e=>{if(e.length!==a)throw Error("Field.fromBytes: expected "+a+" bytes, got "+e.length);return i?rH(e):rK(e)},invertBatch:e=>sn(o,e),cmov:(e,t,i)=>i?t:e});return Object.freeze(o)}function sc(e){if("bigint"!=typeof e)throw Error("field order must be bigint");return Math.ceil(e.toString(2).length/8)}function sh(e){let t=sc(e);return t+Math.ceil(t/2)}let sd=BigInt(0),su=BigInt(1);function sp(e,t){let i=t.negate();return e?i:t}function sf(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function sg(e,t){sf(e,t);let i=Math.ceil(t/e)+1,r=2**(e-1),s=2**e;return{windows:i,windowSize:r,mask:rY(e),maxNumber:s,shiftBy:BigInt(e)}}function sy(e,t,i){let{windowSize:r,mask:s,maxNumber:n,shiftBy:a}=i,o=Number(e&s),l=e>>a;o>r&&(o-=n,l+=su);let c=t*r,h=c+Math.abs(o)-1,d=0===o;return{nextN:l,offset:h,isZero:d,isNeg:o<0,isNegF:t%2!=0,offsetF:c}}let sm=new WeakMap,sw=new WeakMap;
vendor: 15,986 bytes, line 5
5function sb(e){return sw.get(e)||1}function sv(e){return ss(e.Fp),rX(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...so(e.n,e.nBitLength),...e,...{p:e.Fp.ORDER}})}function sE(e){void 0!==e.lowS&&rN("lowS",e.lowS),void 0!==e.prehash&&rN("prehash",e.prehash)}let sI={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(e,t)=>{let{Err:i}=sI;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(1&t.length)throw new i("tlv.encode: unpadded data");let r=t.length/2,s=rj(r);if(s.length/2&128)throw new i("tlv.encode: long form length too big");let n=r>127?rj(s.length/2|128):"";return rj(e)+n+s+t},decode(e,t){let{Err:i}=sI,r=0;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new i("tlv.decode: wrong tlv");let s=t[r++],n=0;if(128&s){let e=127&s;if(!e)throw new i("tlv.decode(long): indefinite length not supported");if(e>4)throw new i("tlv.decode(long): byte length is too big");let a=t.subarray(r,r+e);if(a.length!==e)throw new i("tlv.decode: length bytes not complete");if(0===a[0])throw new i("tlv.decode(long): zero leftmost byte");for(let e of a)n=n<<8|e;if(r+=e,n<128)throw new i("tlv.decode(long): not minimal encoding")}else n=s;let a=t.subarray(r,r+n);if(a.length!==n)throw new i("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+n)}}},_int:{encode(e){let{Err:t}=sI;if(e<sS)throw new t("integer: negative integers are not allowed");let i=rj(e);if(8&Number.parseInt(i[0],16)&&(i="00"+i),1&i.length)throw new t("unexpected DER parsing assertion: unpadded hex");return i},decode(e){let{Err:t}=sI;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return rK(e)}},toSig(e){let{Err:t,_int:i,_tlv:r}=sI,s=rz("signature",e),{v:n,l:a}=r.decode(48,s);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:o,l:l}=r.decode(2,n),{v:c,l:h}=r.decode(2,l);if(h.length)throw new t("invalid signature: left bytes after parsing");return{r:i.decode(o),s:i.decode(c)}},hexFromSig(e){let{_tlv:t,_int:i}=sI,r=t.encode(2,i.encode(e.r)),s=t.encode(2,i.encode(e.s));return t.encode(48,r+s)}},sS=BigInt(0),sA=BigInt(1),sx=BigInt(2),sP=BigInt(3),sC=BigInt(4),s_=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),sk=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),sO=BigInt(0),sT=BigInt(1),sR=BigInt(2),sN=(e,t)=>(e+t/sR)/t,sj=sl(s_,void 0,void 0,{sqrt:function(e){let t=BigInt(3),i=BigInt(6),r=BigInt(11),s=BigInt(22),n=BigInt(23),a=BigInt(44),o=BigInt(88),l=e*e*e%s_,c=l*l*e%s_,h=r9(c,t,s_)*c%s_,d=r9(h,t,s_)*c%s_,u=r9(d,sR,s_)*l%s_,p=r9(u,r,s_)*u%s_,f=r9(p,s,s_)*p%s_,g=r9(f,a,s_)*f%s_,y=r9(g,o,s_)*g%s_,m=r9(y,a,s_)*f%s_,w=r9(m,t,s_)*c%s_,b=r9(w,n,s_)*p%s_,v=r9(b,i,s_)*l%s_,E=r9(v,sR,s_);if(!sj.eql(sj.sqr(E),e))throw Error("Cannot find square root");return E}}),sD=(m$={a:sO,b:BigInt(7),Fp:sj,n:sk,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),i=-sT*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=BigInt("0x100000000000000000000000000000000"),n=sN(t*e,sk),a=sN(-i*e,sk),o=r7(e-n*t-a*r,sk),l=r7(-n*i-a*t,sk),c=o>s,h=l>s;if(c&&(o=sk-o),h&&(l=sk-l),o>s||l>s)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:c,k1:o,k2neg:h,k2:l}}}},mW=rC.sha256,{...(o=e=>(function(e){let t,i=(rX(t=sv(e),{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})),{Fp:r,n:s,nByteLength:n,nBitLength:a}=i,o=r.BYTES+1,l=2*r.BYTES+1;function c(e){return r7(e,s)}let{ProjectivePoint:h,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:p}=function(e){var t;let i=function(e){let t=sv(e);rX(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:i,Fp:r,a:s}=t;if(i){if(!r.eql(s,r.ZERO))throw Error("invalid endo: CURVE.a must be 0");if("object"!=typeof i||"bigint"!=typeof i.beta||"function"!=typeof i.splitScalar)throw Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}(e),{Fp:r}=i,s=sl(i.n,i.nBitLength),n=i.toBytes||((e,t,i)=>{let s=t.toAffine();return rF(Uint8Array.from([4]),r.toBytes(s.x),r.toBytes(s.y))}),a=i.fromBytes||(e=>{let t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function o(e){let{a:t,b:s}=i,n=r.sqr(e),a=r.mul(n,e);return r.add(r.add(a,r.mul(e,t)),s)}function l(e,t){let i=r.sqr(t),s=o(e);return r.eql(i,s)}if(!l(i.Gx,i.Gy))throw Error("bad curve params: generator point");let c=r.mul(r.pow(i.a,sP),sC),h=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(c,h)))throw Error("bad curve params: a or b");function d(e){let t,{allowedPrivateKeyLengths:r,nByteLength:s,wrapPrivateKey:n,n:a}=i;if(r&&"bigint"!=typeof e){if(rT(e)&&(e=rB(e)),"string"!=typeof e||!r.includes(e.length))throw Error("invalid private key");e=e.padStart(2*s,"0")}try{t="bigint"==typeof e?e:rK(rz("private key",e,s))}catch(t){throw Error("invalid private key, expected hex or "+s+" bytes, got "+typeof e)}return n&&(t=r7(t,a)),rG("private key",t,sA,a),t}function u(e){if(!(e instanceof g))throw Error("ProjectivePoint expected")}let p=r0((e,t)=>{let{px:i,py:s,pz:n}=e;if(r.eql(n,r.ONE))return{x:i,y:s};let a=e.is0();null==t&&(t=a?r.ONE:r.inv(n));let o=r.mul(i,t),l=r.mul(s,t),c=r.mul(n,t);if(a)return{x:r.ZERO,y:r.ZERO};if(!r.eql(c,r.ONE))throw Error("invZ was invalid");return{x:o,y:l}}),f=r0(e=>{if(e.is0()){if(i.allowInfinityPoint&&!r.is0(e.py))return;throw Error("bad point: ZERO")}let{x:t,y:s}=e.toAffine();if(!r.isValid(t)||!r.isValid(s))throw Error("bad point: x or y not FE");if(!l(t,s))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class g{constructor(e,t,i){if(null==e||!r.isValid(e))throw Error("x required");if(null==t||!r.isValid(t)||r.is0(t))throw Error("y required");if(null==i||!r.isValid(i))throw Error("z required");this.px=e,this.py=t,this.pz=i,Object.freeze(this)}static fromAffine(e){let{x:t,y:i}=e||{};if(!e||!r.isValid(t)||!r.isValid(i))throw Error("invalid affine point");if(e instanceof g)throw Error("projective point not allowed");let s=e=>r.eql(e,r.ZERO);return s(t)&&s(i)?g.ZERO:new g(t,i,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){let t=sn(r,e.map(e=>e.pz));return e.map((e,i)=>e.toAffine(t[i])).map(g.fromAffine)}static fromHex(e){let t=g.fromAffine(a(rz("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return g.BASE.multiply(d(e))}static msm(e,t){return function(e,t,i,r){if(!Array.isArray(i))throw Error("array expected");i.forEach((t,i)=>{if(!(t instanceof e))throw Error("invalid point at index "+i)});if(!Array.isArray(r))throw Error("array of scalars expected");r.forEach((e,i)=>{if(!t.isValid(e))throw Error("invalid scalar at index "+i)});let s=i.length,n=r.length;if(s!==n)throw Error("arrays of points and scalars must have equal length");let a=e.ZERO,o=function(e){let t;for(t=0;e>rk;e>>=rO,t+=1);return t}(BigInt(s)),l=1;o>12?l=o-3:o>4?l=o-2:o>0&&(l=2);let c=rY(l),h=Array(Number(c)+1).fill(a),d=Math.floor((t.BITS-1)/l)*l,u=a;for(let e=d;e>=0;e-=l){h.fill(a);for(let t=0;t<n;t++){let s=Number(r[t]>>BigInt(e)&c);h[s]=h[s].add(i[t])}let t=a;for(let e=h.length-1,i=a;e>0;e--)i=i.add(h[e]),t=t.add(i);if(u=u.add(t),0!==e)for(let e=0;e<l;e++)u=u.double()}return u}(g,s,e,t)}_setWindowSize(e){w.setWindowSize(this,e)}assertValidity(){f(this)}hasEvenY(){let{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw Error("Field doesn't support isOdd")}equals(e){u(e);let{px:t,py:i,pz:s}=this,{px:n,py:a,pz:o}=e,l=r.eql(r.mul(t,o),r.mul(n,s)),c=r.eql(r.mul(i,o),r.mul(a,s));return l&&c}negate(){return new g(this.px,r.neg(this.py),this.pz)}double(){let{a:e,b:t}=i,s=r.mul(t,sP),{px:n,py:a,pz:o}=this,l=r.ZERO,c=r.ZERO,h=r.ZERO,d=r.mul(n,n),u=r.mul(a,a),p=r.mul(o,o),f=r.mul(n,a);return f=r.add(f,f),h=r.mul(n,o),h=r.add(h,h),l=r.mul(e,h),c=r.mul(s,p),c=r.add(l,c),l=r.sub(u,c),c=r.add(u,c),c=r.mul(l,c),l=r.mul(f,l),h=r.mul(s,h),p=r.mul(e,p),f=r.sub(d,p),f=r.mul(e,f),f=r.add(f,h),h=r.add(d,d),d=r.add(h,d),d=r.add(d,p),d=r.mul(d,f),c=r.add(c,d),p=r.mul(a,o),p=r.add(p,p),d=r.mul(p,f),l=r.sub(l,d),h=r.mul(p,u),h=r.add(h,h),new g(l,c,h=r.add(h,h))}add(e){u(e);let{px:t,py:s,pz:n}=this,{px:a,py:o,pz:l}=e,c=r.ZERO,h=r.ZERO,d=r.ZERO,p=i.a,f=r.mul(i.b,sP),y=r.mul(t,a),m=r.mul(s,o),w=r.mul(n,l),b=r.add(t,s),v=r.add(a,o);b=r.mul(b,v),v=r.add(y,m),b=r.sub(b,v),v=r.add(t,n);let E=r.add(a,l);return v=r.mul(v,E),E=r.add(y,w),v=r.sub(v,E),E=r.add(s,n),c=r.add(o,l),E=r.mul(E,c),c=r.add(m,w),E=r.sub(E,c),d=r.mul(p,v),c=r.mul(f,w),d=r.add(c,d),c=r.sub(m,d),d=r.add(m,d),h=r.mul(c,d),m=r.add(y,y),m=r.add(m,y),w=r.mul(p,w),v=r.mul(f,v),m=r.add(m,w),w=r.sub(y,w),w=r.mul(p,w),v=r.add(v,w),y=r.mul(m,v),h=r.add(h,y),y=r.mul(E,v),c=r.mul(b,c),c=r.sub(c,y),y=r.mul(b,m),d=r.mul(E,d),new g(c,h,d=r.add(d,y))}subtract(e){return this.add(e.negate())}is0(){return this.equals(g.ZERO)}wNAF(e){return w.wNAFCached(this,e,g.normalizeZ)}multiplyUnsafe(e){let{endo:t,n:s}=i;rG("scalar",e,sS,s);let n=g.ZERO;if(e===sS)return n;if(this.is0()||e===sA)return this;if(!t||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,e,g.normalizeZ);let{k1neg:a,k1:o,k2neg:l,k2:c}=t.splitScalar(e),h=n,d=n,u=this;for(;o>sS||c>sS;)o&sA&&(h=h.add(u)),c&sA&&(d=d.add(u)),u=u.double(),o>>=sA,c>>=sA;return a&&(h=h.negate()),l&&(d=d.negate()),d=new g(r.mul(d.px,t.beta),d.py,d.pz),h.add(d)}multiply(e){let t,s,{endo:n,n:a}=i;if(rG("scalar",e,sA,a),n){let{k1neg:i,k1:a,k2neg:o,k2:l}=n.splitScalar(e),{p:c,f:h}=this.wNAF(a),{p:d,f:u}=this.wNAF(l);c=w.constTimeNegate(i,c),d=w.constTimeNegate(o,d),d=new g(r.mul(d.px,n.beta),d.py,d.pz),t=c.add(d),s=h.add(u)}else{let{p:i,f:r}=this.wNAF(e);t=i,s=r}return g.normalizeZ([t,s])[0]}multiplyAndAddUnsafe(e,t,i){let r=g.BASE,s=(e,t)=>t!==sS&&t!==sA&&e.equals(r)?e.multiply(t):e.multiplyUnsafe(t),n=s(this,t).add(s(e,i));return n.is0()?void 0:n}toAffine(e){return p(this,e)}isTorsionFree(){let{h:e,isTorsionFree:t}=i;if(e===sA)return!0;if(t)return t(g,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:e,clearCofactor:t}=i;return e===sA?this:t?t(g,this):this.multiplyUnsafe(i.h)}toRawBytes(e=!0){return rN("isCompressed",e),this.assertValidity(),n(g,this,e)}toHex(e=!0){return rN("isCompressed",e),rB(this.toRawBytes(e))}}g.BASE=new g(i.Gx,i.Gy,r.ONE),g.ZERO=new g(r.ZERO,r.ONE,r.ZERO);let{endo:y,nBitLength:m}=i,w=(t=y?Math.ceil(m/2):m,{constTimeNegate:sp,hasPrecomputes:e=>1!==sb(e),unsafeLadder(e,t,i=g.ZERO){let r=e;for(;t>sd;)t&su&&(i=i.add(r)),r=r.double(),t>>=su;return i},precomputeWindow(e,i){let{windows:r,windowSize:s}=sg(i,t),n=[],a=e,o=a;for(let e=0;e<r;e++){o=a,n.push(o);for(let e=1;e<s;e++)o=o.add(a),n.push(o);a=o.double()}return n},wNAF(e,i,r){let s=g.ZERO,n=g.BASE,a=sg(e,t);for(let e=0;e<a.windows;e++){let{nextN:t,offset:o,isZero:l,isNeg:c,isNegF:h,offsetF:d}=sy(r,e,a);r=t,l?n=n.add(sp(h,i[d])):s=s.add(sp(c,i[o]))}return{p:s,f:n}},wNAFUnsafe(e,i,r,s=g.ZERO){let n=sg(e,t);for(let e=0;e<n.windows&&r!==sd;e++){let{nextN:t,offset:a,isZero:o,isNeg:l}=sy(r,e,n);if(r=t,!o){let e=i[a];s=s.add(l?e.negate():e)}}return s},getPrecomputes(e,t,i){let r=sm.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&sm.set(t,i(r))),r},wNAFCached(e,t,i){let r=sb(e);return this.wNAF(r,this.getPrecomputes(r,e,i),t)},wNAFCachedUnsafe(e,t,i,r){let s=sb(e);return 1===s?this.unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,i),t,r)},setWindowSize(e,i){sf(i,t),sw.set(e,i),sm.delete(e)}});return{CURVE:i,ProjectivePoint:g,normPrivateKeyToScalar:d,weierstrassEquation:o,isWithinCurveOrder:function(e){return rJ(e,sA,i.n)}}}({...i,toBytes(e,t,i){let s=t.toAffine(),n=r.toBytes(s.x);return(rN("isCompressed",i),i)?rF(Uint8Array.from([t.hasEvenY()?2:3]),n):rF(Uint8Array.from([4]),n,r.toBytes(s.y))},fromBytes(e){let t=e.length,i=e[0],s=e.subarray(1);if(t===o&&(2===i||3===i)){let e,t=rK(s);if(!rJ(t,sA,r.ORDER))throw Error("Point is not on curve");let n=u(t);try{e=r.sqrt(n)}catch(e){throw Error("Point is not on curve"+(e instanceof Error?": "+e.message:""))}return(1&i)==1!=((e&sA)===sA)&&(e=r.neg(e)),{x:t,y:e}}if(t===l&&4===i)return{x:r.fromBytes(s.subarray(0,r.BYTES)),y:r.fromBytes(s.subarray(r.BYTES,2*r.BYTES))};throw Error("invalid Point, expected length of "+o+", or uncompressed "+l+", got "+t)}}),f=(e,t,i)=>rK(e.slice(t,i));class g{constructor(e,t,i){rG("r",e,sA,s),rG("s",t,sA,s),this.r=e,this.s=t,null!=i&&(this.recovery=i),Object.freeze(this)}static fromCompact(e){return new g(f(e=rz("compactSignature",e,2*n),0,n),f(e,n,2*n))}static fromDER(e){let{r:t,s:i}=sI.toSig(rz("DER",e));return new g(t,i)}assertValidity(){}addRecoveryBit(e){return new g(this.r,this.s,e)}recoverPublicKey(e){let{r:t,s:n,recovery:a}=this,o=w(rz("msgHash",e));if(null==a||![0,1,2,3].includes(a))throw Error("recovery id invalid");let l=2===a||3===a?t+i.n:t;if(l>=r.ORDER)throw Error("recovery id 2 or 3 invalid");let d=(1&a)==0?"02":"03",u=h.fromHex(d+rB(r$(l,r.BYTES))),p=se(l,s),f=c(-o*p),g=c(n*p),y=h.BASE.multiplyAndAddUnsafe(u,f,g);if(!y)throw Error("point at infinify");return y.assertValidity(),y}hasHighS(){return this.s>s>>sA}normalizeS(){return this.hasHighS()?new g(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return rq(this.toDERHex())}toDERHex(){return sI.hexFromSig(this)}toCompactRawBytes(){return rq(this.toCompactHex())}toCompactHex(){return rB(r$(this.r,n))+rB(r$(this.s,n))}}function y(e){if("bigint"==typeof e)return!1;if(e instanceof h)return!0;let t=rz("key",e).length,s=r.BYTES,a=s+1;if(!i.allowedPrivateKeyLengths&&n!==a)return t===a||t===2*s+1}let m=i.bits2int||function(e){if(e.length>8192)throw Error("input is too large");let t=rK(e),i=8*e.length-a;return i>0?t>>BigInt(i):t},w=i.bits2int_modN||function(e){return c(m(e))},b=rY(a);function v(e){return rG("num < 2^"+a,e,sS,b),r$(e,n)}let E={lowS:i.lowS,prehash:!1},I={lowS:i.lowS,prehash:!1};return h.BASE._setWindowSize(8),{CURVE:i,getPublicKey:function(e,t=!0){return h.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,i=!0){if(!0===y(e))throw Error("first arg must be private key");if(!1===y(t))throw Error("second arg must be public key");return h.fromHex(t).multiply(d(e)).toRawBytes(i)},sign:function(e,t,n=E){let{seed:a,k2sig:o}=function(e,t,n=E){if(["recovered","canonical"].some(e=>e in n))throw Error("sign() legacy options not supported");let{hash:a,randomBytes:o}=i,{lowS:l,prehash:u,extraEntropy:f}=n;null==l&&(l=!0),e=rz("msgHash",e),sE(n),u&&(e=rz("prehashed msgHash",a(e)));let y=w(e),b=d(t),I=[v(b),v(y)];if(null!=f&&!1!==f){let e=!0===f?o(r.BYTES):f;I.push(rz("extraEntropy",e))}return{seed:rF(...I),k2sig:function(e){var t;let i=m(e);if(!p(i))return;let r=se(i,s),n=h.BASE.multiply(i).toAffine(),a=c(n.x);if(a===sS)return;let o=c(r*c(y+a*b));if(o===sS)return;let d=2*(n.x!==a)|Number(n.y&sA),u=o;return l&&o>s>>sA&&(u=(t=o)>s>>sA?c(-t):t,d^=1),new g(a,u,d)}}}(e,t,n);return(function(e,t,i){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof i)throw Error("hmacFn must be a function");let r=rZ(e),s=rZ(e),n=0,a=()=>{r.fill(1),s.fill(0),n=0},o=(...e)=>i(s,r,...e),l=(e=rZ(0))=>{let t;if(s=o((t=[0],Uint8Array.from(t)),e),r=o(),0!==e.length){let t;s=o((t=[1],Uint8Array.from(t)),e),r=o()}},c=()=>
5{if(n++>=1e3)throw Error("drbg: tried 1000 values");let e=0,i=[];for(;e<t;){let t=(r=o()).slice();i.push(t),e+=r.length}return rF(...i)};return(e,t)=>{let i;for(a(),l(e);!(i=t(c()));)l();return a(),i}})(i.hash.outputLen,i.nByteLength,i.hmac)(a,o)},verify:function(e,t,r,n=I){let a,o;t=rz("msgHash",t),r=rz("publicKey",r);let{lowS:l,prehash:d,format:u}=n;if(sE(n),"strict"in n)throw Error("options.strict was renamed to lowS");if(void 0!==u&&"compact"!==u&&"der"!==u)throw Error("format must be compact or der");let p="string"==typeof e||rT(e),f=!p&&!u&&"object"==typeof e&&null!==e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!p&&!f)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");try{if(f&&(o=new g(e.r,e.s)),p){try{"compact"!==u&&(o=g.fromDER(e))}catch(e){if(!(e instanceof sI.Err))throw e}o||"der"===u||(o=g.fromCompact(e))}a=h.fromHex(r)}catch(e){return!1}if(!o||l&&o.hasHighS())return!1;d&&(t=i.hash(t));let{r:y,s:m}=o,b=w(t),v=se(m,s),E=c(b*v),S=c(y*v),A=h.BASE.multiplyAndAddUnsafe(a,E,S)?.toAffine();return!!A&&c(A.x)===y},ProjectivePoint:h,Signature:g,utils:{isValidPrivateKey(e){try{return d(e),!0}catch(e){return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let e=sh(i.n);return function(e,t,i=!1){let r=e.length,s=sc(t),n=sh(t);if(r<16||r<n||r>1024)throw Error("expected "+n+"-1024 bytes of input, got "+r);let a=r7(i?rH(e):rK(e),t-r2)+r2;return i?rW(a,s):r$(a,s)}(i.randomBytes(e),i.n)},precompute:(e=8,t=h.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}})({...m$,...{hash:e,hmac:(t,...i)=>(0,r_.hmac)(e,t,(0,i$.concatBytes)(...i)),randomBytes:i$.randomBytes}}))(mW),create:o});sD.ProjectivePoint;let sM=(l=[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(e=>BigInt(e))).map(e=>Array.from(e).reverse()),(e,t)=>{let[i,r,s,n]=l.map(t=>t.reduce((t,i)=>sj.add(sj.mul(t,e),i))),[a,o]=sn(sj,[r,n],!0);return e=sj.mul(i,a),t=sj.mul(t,sj.mul(s,o)),{x:e,y:t}}),sU=function(e,t){if(ss(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw Error("mapToCurveSimpleSWU: invalid opts");let i=function(e,t){let i=e.ORDER,r=sS;for(let e=i-sA;e%sx===sS;e/=sx)r+=sA;let s=r,n=sx<<s-sA-sA,a=n*sx,o=(i-sA)/a,l=(o-sA)/sx,c=a-sA,h=e.pow(t,o),d=e.pow(t,(o+sA)/sx),u=(t,i)=>{let r=h,a=e.pow(i,c),o=e.sqr(a);o=e.mul(o,i);let u=e.mul(t,o);u=e.pow(u,l),u=e.mul(u,a),a=e.mul(u,i),o=e.mul(u,t);let p=e.mul(o,a);u=e.pow(p,n);let f=e.eql(u,e.ONE);a=e.mul(o,d),u=e.mul(p,r),o=e.cmov(a,o,f),p=e.cmov(u,p,f);for(let t=s;t>sA;t--){let i=t-sx;i=sx<<i-sA;let s=e.pow(p,i),n=e.eql(s,e.ONE);a=e.mul(o,r),r=e.mul(r,r),s=e.mul(p,r),o=e.cmov(a,o,n),p=e.cmov(s,p,n)}return{isValid:f,value:o}};if(e.ORDER%sC===sP){let i=(e.ORDER-sP)/sC,r=e.sqrt(e.neg(t));u=(t,s)=>{let n=e.sqr(s),a=e.mul(t,s);n=e.mul(n,a);let o=e.pow(n,i);o=e.mul(o,a);let l=e.mul(o,r),c=e.mul(e.sqr(o),s),h=e.eql(c,t),d=e.cmov(l,o,h);return{isValid:h,value:d}}}return u}(e,t.Z);if(!e.isOdd)throw Error("Fp.isOdd is not implemented!");return r=>{let s,n,a,o,l,c,h,d;s=e.sqr(r),s=e.mul(s,t.Z),n=e.sqr(s),n=e.add(n,s),a=e.add(n,e.ONE),a=e.mul(a,t.B),o=e.cmov(t.Z,e.neg(n),!e.eql(n,e.ZERO)),o=e.mul(o,t.A),n=e.sqr(a),c=e.sqr(o),l=e.mul(c,t.A),n=e.add(n,l),n=e.mul(n,a),c=e.mul(c,o),l=e.mul(c,t.B),n=e.add(n,l),h=e.mul(s,a);let{isValid:u,value:p}=i(n,c);d=e.mul(s,r),d=e.mul(d,p),h=e.cmov(h,a,u),d=e.cmov(d,p,u);let f=e.isOdd(r)===e.isOdd(d);d=e.cmov(e.neg(d),d,f);let g=sn(e,[o],!0)[0];return{x:h=e.mul(h,g),y:d}}}(sj,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:sj.create(BigInt("-11"))});!function(e,t,i){if("function"!=typeof t)throw Error("mapToCurve() must be defined")}(sD.ProjectivePoint,e=>{let{x:t,y:i}=sU(sj.create(e[0]));return sM(t,i)},(sj.ORDER,rC.sha256));
vendor: 4,183 bytes, line 5
5class sB extends Error{constructor(e,t={}){const i=(()=>{if(t.cause instanceof sB){if(t.cause.details)return t.cause.details;if(t.cause.shortMessage)return t.cause.shortMessage}return t.cause&&"details"in t.cause&&"string"==typeof t.cause.details?t.cause.details:t.cause?.message?t.cause.message:t.details})(),r=t.cause instanceof sB&&t.cause.docsPath||t.docsPath,s=`https://oxlib.sh${r??""}`;super([e||"An error occurred.",...t.metaMessages?["",...t.metaMessages]:[],...i||r?["",i?`Details: ${i}`:void 0,r?`See: ${s}`:void 0]:[]].filter(e=>"string"==typeof e).join("\n"),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:"[email protected]"}),this.cause=t.cause,this.details=i,this.docs=s,this.docsPath=r,this.shortMessage=e}walk(e){return function e(t,i){return i?.(t)?t:t&&"object"==typeof t&&"cause"in t&&t.cause?e(t.cause,i):i?null:t}(this,e)}}function sL(e,t){if(sG(e)>t)throw new s0({givenSize:sG(e),maxSize:t})}function sq(e,t={}){let{dir:i,size:r=32}=t;if(0===r)return e;let s=e.replace("0x","");if(s.length>2*r)throw new s2({size:Math.ceil(s.length/2),targetSize:r,type:"Hex"});return`0x${s["right"===i?"padEnd":"padStart"](2*r,"0")}`}function sK(e,t,i){return JSON.stringify(e,(e,i)=>"function"==typeof t?t(e,i):"bigint"==typeof i?i.toString()+"#__bigint":i,i)}let sH=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function s$(...e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}function sW(e){return e instanceof Uint8Array?sz(e):Array.isArray(e)?sz(new Uint8Array(e)):e}function sz(e,t={}){let i="";for(let t=0;t<e.length;t++)i+=sH[e[t]];let r=`0x${i}`;return"number"==typeof t.size?(sL(r,t.size),sV(r,t.size)):r}function sF(e,t={}){var i;let r,{signed:s,size:n}=t,a=BigInt(e);n?r=s?(1n<<8n*BigInt(n)-1n)-1n:2n**(8n*BigInt(n))-1n:"number"==typeof e&&(r=BigInt(Number.MAX_SAFE_INTEGER));let o="bigint"==typeof r&&s?-r-1n:0;if(r&&a>r||a<o){let t="bigint"==typeof e?"n":"";throw new sZ({max:r?`${r}${t}`:void 0,min:`${o}${t}`,signed:s,size:n,value:`${e}${t}`})}let l=(s&&a<0?(1n<<BigInt(8*n))+BigInt(a):a).toString(16),c=`0x${l}`;return n?(i=c,sq(i,{dir:"left",size:n})):c}function sV(e,t){return sq(e,{dir:"right",size:t})}function sJ(e,t,i,r={}){let{strict:s}=r;if("number"==typeof t&&t>0&&t>sG(e)-1)throw new s1({offset:t,position:"start",size:sG(e)});let n=`0x${e.replace("0x","").slice((t??0)*2,(i??e.length)*2)}`;return s&&function(e,t,i){if("number"==typeof t&&"number"==typeof i&&sG(e)!==i-t)throw new s1({offset:i,position:"end",size:sG(e)})}(n,t,i),n}function sG(e){return Math.ceil((e.length-2)/2)}function sY(e){return function(e,t={}){let{dir:i="left"}=t,r=e.replace("0x",""),s=0;for(let e=0;e<r.length-1;e++)if("0"===r["left"===i?e:r.length-e-1].toString())s++;else break;return"0"===(r="left"===i?r.slice(s):r.slice(0,r.length-s))?"0x":"right"===i&&r.length%2==1?`0x${r}0`:`0x${r}`}(e,{dir:"left"})}class sZ extends sB{constructor({max:e,min:t,signed:i,size:r,value:s}){super(`Number \`${s}\` is not in safe${r?` ${8*r}-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 sQ extends sB{constructor(e){super(`Value \`${"object"==typeof e?sK(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 sX extends sB{constructor(e){super(`Value \`${e}
5\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class s0 extends sB{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 s1 extends sB{constructor({offset:e,position:t,size:i}){super(`Slice ${"start"===t?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${i}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class s2 extends sB{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"})}}function s5(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}let s3=new TextEncoder;function s8(e){var t;return e instanceof Uint8Array?e:"string"==typeof e?s6(e):(t=e)instanceof Uint8Array?t:new Uint8Array(t)}function s6(e,t={}){let{size:i}=t,r=e;i&&(sL(e,i),r=sV(e,i));let s=r.slice(2);s.length%2&&(s=`0${s}`);let n=s.length/2,a=new Uint8Array(n);for(let e=0,t=0;e<n;e++){let i=s5(s.charCodeAt(t++)),r=s5(s.charCodeAt(t++));if(void 0===i||void 0===r)throw new sB(`Invalid byte sequence ("${s[t-2]}${s[t-1]}" in "${s}").`);a[e]=16*i+r}return a}class s4 extends sB{constructor(e){super(`Value \`${"object"==typeof e?sK(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 s7 extends sB{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 s9 extends sB{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"})}}let ne=2n**256n-1n;function nt(e,t={}){let{recovered:i}=t;if(void 0===e.r||void 0===e.s||i&&void 0===e.yParity)throw new nu({signature:e});if(e.r<0n||e.r>ne)throw new np({value:e.r});if(e.s<0n||e.s>ne)throw new nf({value:e.s});if("number"==typeof e.yParity&&0!==e.yParity&&1!==e.yParity)throw new ng({value:e.yParity})}function ni(e){return nr(sz(e))}function nr(e){if(130!==e.length&&132!==e.length)throw new nd({signature:e});let t=BigInt(sJ(e,0,32)),i=BigInt(sJ(e,32,64)),r=(()=>{let t=Number(`0x${e.slice(130)}`);if(!Number.isNaN(t))try{return nc(t)}catch{throw new ng({value:t})}})();return void 0===r?{r:t,s:i}:{r:t,s:i,yParity:r}}function ns(e){let t="string"==typeof e?nr(e):e instanceof Uint8Array?ni(e):"string"==typeof e.r?no(e):e.v?na(e):{r:e.r,s:e.s,...void 0!==e.yParity?{yParity:e.yParity}:{}};return nt(t),t}function nn(e){let{r:t,s:i}=sD.Signature.fromDER(sW(e).slice(2));return{r:t,s:i}}function na(e){return{r:e.r,s:e.s,yParity:nc(e.v)}}function no(e){let t=(()=>{let t=e.v?Number(e.v):void 0,i=e.yParity?Number(e.yParity):void 0;if("number"==typeof t&&"number"!=typeof i&&(i=nc(t)),"number"!=typeof i)throw new ng({value:e.yParity});return i})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function nl(e){nt(e);let t=e.r,i=e.s;return s$(sF(t,{size:32}),sF(i,{size:32}),"number"==typeof e.yParity?sF(nh(e.yParity),{size:1}):"0x")}function nc(e){if(0===e||27===e)return 0;if(1===e||28===e)return 1;if(e>=35)return+(e%2==0);throw new ny({value:e})}function nh(e){if(0===e)return 27;if(1===e)return 28;throw new ng({value:e})}class nd extends sB{constructor({signature:e}){super(`Value \`${e}
5\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${sG(sW(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class nu extends sB{constructor({signature:e}){super(`Signature \`${sK(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class np extends sB{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class nf extends sB{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class ng extends sB{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 ny extends sB{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"})}}e.s(["InvalidRError",0,np,"InvalidSError",0,nf,"InvalidSerializedSizeError",0,nd,"InvalidVError",0,ny,"InvalidYParityError",0,ng,"MissingPropertiesError",0,nu,"assert",0,nt,"extract",0,function(e){if(void 0!==e.r&&void 0!==e.s)return ns(e)},"from",0,ns,"fromBytes",0,ni,"fromDerBytes",0,function(e){return nn(sz(e))},"fromDerHex",0,nn,"fromHex",0,nr,"fromLegacy",0,na,"fromRpc",0,no,"fromTuple",0,function(e){let[t,i,r]=e;return ns({r:"0x"===i?0n:BigInt(i),s:"0x"===r?0n:BigInt(r),yParity:"0x"===t?0:Number(t)})},"toBytes",0,function(e){return s6(nl(e))},"toDerBytes",0,function(e){return new sD.Signature(e.r,e.s).toDERRawBytes()},"toDerHex",0,function(e){let t=new sD.Signature(e.r,e.s);return`0x${t.toDERHex()}`},"toHex",0,nl,"toLegacy",0,function(e){return{r:e.r,s:e.s,v:nh(e.yParity)}},"toRpc",0,function(e){let{r:t,s:i,yParity:r}=e;return{r:sF(t,{size:32}),s:sF(i,{size:32}),yParity:0===r?"0x0":"0x1"}},"toTuple",0,function(e){let{r:t,s:i,yParity:r}=e;return[r?"0x01":"0x",0n===t?"0x":sY(sF(t)),0n===i?"0x":sY(sF(i))]},"vToYParity",0,nc,"validate",0,function(e,t={}){try{return nt(e,t),!0}catch{return!1}},"yParityToV",0,nh],651255);var nm=e.i(651255),nm=nm;class nw extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let e=this.keys().next().value;e&&this.delete(e)}return this}}let nb={checksum:new nw(8192)}.checksum;var nv=e.i(145535);function nE(e,t={}){let{as:i="string"==typeof e?"Hex":"Bytes"}=t,r=(0,nv.keccak_256)(s8(e));return"Bytes"===i?r:sz(r)}function nI(e,t={}){let{compressed:i}=t,{prefix:r,x:s,y:n}=e;if(!1===i||"bigint"==typeof s&&"bigint"==typeof n){if(4!==r)throw new nC({prefix:r,cause:new nk});return}if(!0===i||"bigint"==typeof s&&void 0===n){if(3!==r&&2!==r)throw new nC({prefix:r,cause:new n_});return}throw new nP({publicKey:e})}function nS(e){let t=(()=>{if(function(e,t={}){let{strict:i=!1}=t;try{return!function(e,t={}){let{strict:i=!1}=t;if(!e||"string"!=typeof e)throw new sQ(e);if(i&&!/^0x[0-9a-fA-F]*$/.test(e)||!e.startsWith("0x"))throw new sX(e)}(e,{strict:i}),!0}catch{return!1}}(e))return nA(e);if(function(e){try{if(!(e instanceof Uint8Array)&&(!e||"object"!=typeof e||!("BYTES_PER_ELEMENT"in e)||1!==e.BYTES_PER_ELEMENT||"Uint8Array"!==e.constructor.name))throw new s4(e);return!0}catch{return!1}}(e))return nA(sz(e));let{prefix:t,x:i,y:r}=e;return"bigint"==typeof i&&"bigint"==typeof r?{prefix:t??4,x:i,y:r}:{prefix:t,x:i}})();return nI(t),t}function nA(e){if(132!==e.length&&130!==e.length&&68!==e.length)throw new nO({publicKey:e});if(130===e.length)return{prefix:4,x:BigInt(sJ(e,0,32)),y:BigInt(sJ(e,32,64))};if(132===e.length){let t=Number(sJ(e,0,1));return{prefix:t,x:BigInt(sJ(e,1,33)),y:BigInt(sJ(e,33,65))}}return{prefix:Number(sJ(e,0,1)),x:BigInt(sJ(e,1,33))}}function nx(e,t={}){nI(e);let{prefix:i,x:r,y:s}=e,{includePrefix:n=!0}=t;return s$(n?sF(i,{size:1}):"0x",sF(r,{size:32}),"bigint"==typeof s?sF(s,{size:32}):"0x")}class nP extends sB{constructor({publicKey:e}){super(`Value \`${sK(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 nC extends sB{constructor({prefix:e,cause:t}){super(`Prefix "${e}
5" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class n_ extends sB{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 nk extends sB{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class nO extends sB{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 ${sG(sW(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}let nT=/^0x[a-fA-F0-9]{40}$/;function nR(e,t={}){let{strict:i=!0}=t;if(!nT.test(e))throw new nj({address:e,cause:new nD});if(i){if(e.toLowerCase()===e)return;if(nN(e)!==e)throw new nj({address:e,cause:new nM})}}function nN(e){if(nb.has(e))return nb.get(e);nR(e,{strict:!1});let t=e.substring(2).toLowerCase(),i=nE(function(e,t={}){let{size:i}=t,r=s3.encode(e);if("number"==typeof i){var s;if(r.length>i)throw new s7({givenSize:r.length,maxSize:i});return s=r,function(e,t={}){let{dir:i,size:r=32}=t;if(0===r)return e;if(e.length>r)throw new s9({size:e.length,targetSize:r,type:"Bytes"});let s=new Uint8Array(r);for(let t=0;t<r;t++){let n="right"===i;s[n?t:r-t-1]=e[n?t:e.length-t-1]}return s}(s,{dir:"right",size:i})}return r}(t),{as:"Bytes"}),r=t.split("");for(let e=0;e<40;e+=2)i[e>>1]>>4>=8&&r[e]&&(r[e]=r[e].toUpperCase()),(15&i[e>>1])>=8&&r[e+1]&&(r[e+1]=r[e+1].toUpperCase());let s=`0x${r.join("")}`;return nb.set(e,s),s}class nj extends sB{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 nD extends sB{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 nM extends sB{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}function nU(e){let{privateKey:t}=e;return nS(sD.ProjectivePoint.fromPrivateKey(sW(t).slice(2)))}function nB(e={}){let{as:t="Hex"}=e,i=sD.utils.randomPrivateKey();return"Hex"===t?sz(i):i}function nL(e){return function(e,t={}){let i=nE(`0x${nx(e).slice(4)}`).substring(26);return function(e,t={}){let{checksum:i=!1}=t;return(nR(e),i)?nN(e):e}(`0x${i}`,t)}(nq(e))}function nq(e){let{payload:t,signature:i}=e,{r,s,yParity:n}=i;return nS(new sD.Signature(BigInt(r),BigInt(s)).addRecoveryBit(n).recoverPublicKey(sW(t).substring(2)))}e.s(["createKeyPair",0,function(e={}){let{as:t="Hex"}=e,i=nB({as:t}),r=nU({privateKey:i});return{privateKey:i,publicKey:r}},"getPublicKey",0,nU,"getSharedSecret",0,function(e){let{as:t="Hex",privateKey:i,publicKey:r}=e,s=sD.ProjectivePoint.fromHex(nx(r).slice(2)).multiply(sD.utils.normPrivateKeyToScalar(sW(i).slice(2))).toRawBytes(!0);return"Hex"===t?sz(s):s},"noble",0,sD,"randomPrivateKey",0,nB,"recoverAddress",0,nL,"recoverPublicKey",0,nq,"sign",0,function(e){let{extraEntropy:t=!1,hash:i,payload:r,privateKey:s}=e,{r:n,s:a,recovery:o}=sD.sign(s8(r),s8(s),{extraEntropy:"boolean"==typeof t?t:sW(t).slice(2),lowS:!0,...i?{prehash:!0}:{}});return{r:n,s:a,yParity:o}},"verify",0,function(e){let{address:t,hash:i,payload:r,publicKey:s,signature:n}=e;if(t){var a;return a=nL({payload:r,signature:n}),nR(t,{strict:!1}),nR(a,{strict:!1}),t.toLowerCase()===a.toLowerCase()}return sD.verify(n,s8(r),function(e,t={}){return s6(nx(e,t))}(s),...i?[{prehash:!0,lowS:!0}]:[])}],928770);var nK=e.i(928770),nK=nK,nH=e.i(103476),n$=e.i(131783),nW=e.i(726165),nz=e.i(166953),nF=e.i(121609);e.i(707720);var nV=e.i(966678),nJ=e.i(951828),nG=e.i(213223),nY=e.i(281223),nZ=e.i(5625),nQ=e.i(572206),nX=e.i(31794);let n0="custom_context";var n1=Object.defineProperty,n2=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?n1(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};
5class n5{constructor(e){n2(this,"nodeValue"),n2(this,"sizeInBytes"),n2(this,"next"),this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class n3{constructor(e){n2(this,"lengthInNodes"),n2(this,"sizeInBytes"),n2(this,"head"),n2(this,"tail"),n2(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){let t=new n5(e);if(t.size>this.maxSizeInBytes)throw Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?this.tail&&(this.tail.next=t):this.head=t,this.tail=t,this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;let e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){let e=[],t=this.head;for(;null!==t;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};let t=e.value;return e=e.next,{done:!1,value:t}}}}}var n8=Object.defineProperty,n6=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?n8(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class n4{constructor(e,t=1024e3){n6(this,"logs"),n6(this,"level"),n6(this,"levelValue"),n6(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=nQ.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new n3(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===nQ.levels.values.error?console.error(e):t===nQ.levels.values.warn?console.warn(e):t===nQ.levels.values.debug?console.debug(e):t===nQ.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append((0,nX.safeJsonStringify)({timestamp:new Date().toISOString(),log:e}));let t="string"==typeof e?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new n3(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){let t=this.getLogArray();return t.push((0,nX.safeJsonStringify)({extraMetadata:e})),new Blob(t,{type:"application/json"})}}var n7=Object.defineProperty;class n9{constructor(e,t=1024e3){((e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?n7(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(this,"baseChunkLogger"),this.baseChunkLogger=new n4(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){let t=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=t,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t)}}var ae=Object.defineProperty;class at{constructor(e,t=1024e3){((e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?ae(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(this,"baseChunkLogger"),this.baseChunkLogger=new n4(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var ai=Object.defineProperty,ar=Object.defineProperties,as=Object.getOwnPropertyDescriptors,an=Object.getOwnPropertySymbols,aa=Object.prototype.hasOwnProperty,ao=Object.prototype.propertyIsEnumerable,al=(e,t,i)=>t in e?ai(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,ac=(e,t)=>{for(var i in t||(t={}))aa.call(t,i)&&al(e,i,t[i]);if(an)for(var i of an(t))ao.call(t,i)&&al(e,i,t[i]);return e};function ah(e,t=n0){return e[t]||""}function ad(e,t,i=n0){let r=function(e,t,i=n0){let r=ah(e,i);return r.trim()?`${r}/${t}`:t}(e,t,i);return function(e,t,i=n0){return e[i]=t,e}(e.child({context:r}),r,i)}function au(e){var t,i,r,s;let n,a,o,l;return"u">typeof e.loggerOverride&&"string"!=typeof e.loggerOverride?{logger:e.loggerOverride,chunkLoggerController:null}:"u">typeof window?(l=new n9(null==(r=(i=e).opts)?void 0:r.level,i.maxSizeInBytes),{logger:(0,nQ.default)((a=ac({},i.opts),o={level:"trace",browser:ar(ac({},null==(s=i.opts)?void 0:s.browser),as({write:e=>l.write(e)}))},ar(a,as(o)))),chunkLoggerController:l}):(n=new at(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes),{logger:(0,nQ.default)(ar(ac({},e.opts),as({level:"trace"})),n),chunkLoggerController:n})}function ap(e){let[t,i]=e.split(":");return{namespace:t,reference:i}}function af(e,t=[]){let i=[];return Object.keys(e).forEach(r=>{if(t.length&&!t.includes(r))return;let s=e[r];i.push(...s.accounts)}),i}function ag(e,t){return e.includes(":")?[e]:t.chains||[]}var ay=Object.defineProperty,am=Object.defineProperties,aw=Object.getOwnPropertyDescriptors,ab=Object.getOwnPropertySymbols,av=Object.prototype.hasOwnProperty,aE=Object.prototype.propertyIsEnumerable,aI=(e,t,i)=>t in e?ay(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,aS=(e,t)=>{for(var i in t||(t={}))av.call(t,i)&&aI(e,i,t[i]);if(ab)for(var i of ab(t))aE.call(t,i)&&aI(e,i,t[i]);return e},aA=(e,t,i)=>aI(e,"symbol"!=typeof t?t+"":t,i);let ax="react-native",aP="node",aC="browser";function a_(){return"u">typeof rI.default&&"u">typeof rI.default.versions&&"u">typeof rI.default.versions.node}
5function ak(){return!(0,rx.getDocument)()&&!!(0,rx.getNavigator)()&&"ReactNative"===navigator.product}function aO(){return!a_()&&!!(0,rx.getNavigator)()&&!!(0,rx.getDocument)()}function aT(){return ak()?ax:a_()?aP:aO()?aC:"unknown"}function aR(){var t;try{return ak()&&"u">typeof(null==e.g?void 0:e.g.Application)?null==(t=e.g.Application)?void 0:t.applicationId:void 0}catch{return}}function aN(){return(0,rP.getWindowMetadata)()||{name:"",description:"",url:"",icons:[""]}}function aj(t,i,r){var s;let n,a=function(){if(aT()===ax&&"u">typeof(null==e.g?void 0:e.g.Platform)){let{OS:t,Version:i}=e.g.Platform;return[t,i].join("-")}let t=(0,rS.detect)();if(null===t)return"unknown";let i=t.os?t.os.replace(" ","").toLowerCase():"unknown";return"browser"===t.type?[i,t.name,t.version].join("-"):[i,t.version].join("-")}(),o=(n=aT())===aC?[n,(null==(s=(0,rx.getLocation)())?void 0:s.host)||"unknown"].join(":"):n;return[[t,i].join("-"),["js",r].join("-"),a,o].join("/")}function aD(e,t){return e.filter(e=>t.includes(e)).length===e.length}function aM(e){return Object.fromEntries(e.entries())}function aU(e){return new Map(Object.entries(e))}function aB(e=rA.FIVE_MINUTES,t){let i,r,s,n,a=(0,rA.toMiliseconds)(e||rA.FIVE_MINUTES);return{resolve:e=>{s&&i&&(clearTimeout(s),i(e),n=Promise.resolve(e))},reject:e=>{s&&r&&(clearTimeout(s),r(e))},done:()=>new Promise((e,o)=>{if(n)return e(n);s=setTimeout(()=>{let e=Error(t);n=Promise.reject(e),o(e)},a),i=e,r=o})}}function aL(e,t,i){return new Promise(async(r,s)=>{let n=setTimeout(()=>s(Error(i)),t);try{let t=await e;r(t)}catch(e){s(e)}clearTimeout(n)})}function aq(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw Error(`Unknown expirer target type: ${e}`)}function aK(e){let[t,i]=e.split(":"),r={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof i)r.topic=i;else if("id"===t&&Number.isInteger(Number(i)))r.id=Number(i);else throw Error(`Invalid target, expected id:number or topic:string, got ${t}:${i}`);return r}function aH(e,t){return(0,rA.fromMiliseconds)((t||Date.now())+(0,rA.toMiliseconds)(e))}function a$(e){return Date.now()>=(0,rA.toMiliseconds)(e)}function aW(e,t){return`${e}${t?`:${t}`:""}`}function az(e=[],t=[]){return[...new Set([...e,...t])]}async function aF({id:t,topic:i,wcDeepLink:r}){var s,n;try{if(!r)return;let a="string"==typeof r?JSON.parse(r):r,o=a?.href;if("string"!=typeof o)return;let l=function(e,t,i){let r=`requestId=${t}&sessionTopic=${i}`;e.endsWith("/")&&(e=e.slice(0,-1));let s=`${e}`;if(e.startsWith("https://t.me")){let t=e.includes("?")?"&startapp=":"?startapp=";s=`${s}${t}${function(e,t=!1){let i=tT.Buffer.from(e).toString("base64");return t?i.replace(/[=]/g,""):i}(r,!0)}`}else s=`${s}/wc?${r}`;return s}(o,t,i),c=aT();if(c===aC){let e;if(!(null!=(s=(0,rx.getDocument)())&&s.hasFocus()))return void console.warn("Document does not have focus, skipping deeplink.");n=l,e="_self",!function(){try{return window.self!==window.top}catch{return!1}}()?("u">typeof window&&(window.TelegramWebviewProxy||window.Telegram||window.TelegramWebviewProxyProto)||n.startsWith("https://")||n.startsWith("http://"))&&(e="_blank"):e="_top",window.open(n,e,"noreferrer noopener")}else c===ax&&"u">typeof(null==e.g?void 0:e.g.Linking)&&await e.g.Linking.openURL(l)}catch(e){console.error(e)}}async function aV(e,t){let i="";try{if(aO()&&(i=localStorage.getItem(t)))return i;i=await e.getItem(t)}catch(e){console.error(e)}return i}function aJ(e,t){if(!e.includes(t))return null;let i=e.split(/([&,?,=])/),r=i.indexOf(t);return i[r+2]}function aG(){return"u">typeof crypto&&null!=crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function aY(){return"u">typeof rI.default&&"true"===rI.default.env.IS_VITEST}function aZ(e){return tT.Buffer.from(e,"base64").toString("utf-8")}class aQ{constructor({limit:e}){aA(this,"limit"),aA(this,"set"),this.limit=e,this.set=new Set}
5add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){let e=this.set.values().next().value;e&&this.set.delete(e)}this.set.add(e)}}has(e){return this.set.has(e)}}let aX=BigInt(0x100000000-1),a0=BigInt(32);function a1(e,t=!1){return t?{h:Number(e&aX),l:Number(e>>a0&aX)}:{h:0|Number(e>>a0&aX),l:0|Number(e&aX)}}function a2(e,t=!1){let i=e.length,r=new Uint32Array(i),s=new Uint32Array(i);for(let n=0;n<i;n++){let{h:i,l:a}=a1(e[n],t);[r[n],s[n]]=[i,a]}return[r,s]}let a5=(e,t,i)=>e>>>i,a3=(e,t,i)=>e<<32-i|t>>>i,a8=(e,t,i)=>e>>>i|t<<32-i,a6=(e,t,i)=>e<<32-i|t>>>i,a4=(e,t,i)=>e<<64-i|t>>>i-32,a7=(e,t,i)=>e>>>i-32|t<<64-i;function a9(e,t,i,r){let s=(t>>>0)+(r>>>0);return{h:e+i+(s/0x100000000|0)|0,l:0|s}}let oe=(e,t,i)=>(e>>>0)+(t>>>0)+(i>>>0),ot=(e,t,i,r)=>t+i+r+(e/0x100000000|0)|0,oi=(e,t,i,r)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0),or=(e,t,i,r,s)=>t+i+r+s+(e/0x100000000|0)|0,os=(e,t,i,r,s)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0)+(s>>>0),on=(e,t,i,r,s,n)=>t+i+r+s+n+(e/0x100000000|0)|0,oa="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function oo(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ol(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function oc(e,...t){if(!oo(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function oh(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.createHasher");ol(e.outputLen),ol(e.blockLen)}function od(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function ou(e,t){oc(e);let i=t.outputLen;if(e.length<i)throw Error("digestInto() expects output buffer of length at least "+i)}function op(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function of(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function og(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function oy(e,t){return e<<32-t|e>>>t}let om=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0];function ow(e){return e<<24&0xff000000|e<<8&0xff0000|e>>>8&65280|e>>>24&255}let ob=om?e=>e:e=>ow(e),ov=om?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=ow(e[t]);return e},oE="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,oI=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function oS(e){if(oc(e),oE)return e.toHex();let t="";for(let i=0;i<e.length;i++)t+=oI[e[i]];return t}function oA(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function ox(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(oE)return Uint8Array.fromHex(e);let t=e.length,i=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(i);for(let t=0,s=0;t<i;t++,s+=2){let i=oA(e.charCodeAt(s)),n=oA(e.charCodeAt(s+1));if(void 0===i||void 0===n)throw Error('hex string expected, got non-hex character "'+(e[s]+e[s+1])+'" at index '+s);r[t]=16*i+n}return r}function oP(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function oC(e){return"string"==typeof e&&(e=oP(e)),oc(e),e}function o_(...e){let t=0;for(let i=0;i<e.length;i++){let r=e[i];oc(r),t+=r.length}let i=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let s=e[t];i.set(s,r),r+=s.length}return i}class ok{}function oO(e){let t=t=>e().update(oC(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}function oT(e=32){if(oa&&"function"==typeof oa.getRandomValues)return oa.getRandomValues(new Uint8Array(e));if(oa&&"function"==typeof oa.randomBytes)return Uint8Array.from(oa.randomBytes(e));throw Error("crypto.getRandomValues must be defined")}let oR=BigInt(0),oN=BigInt(1),oj=BigInt(2),oD=BigInt(7),oM=BigInt(256),oU=BigInt(113),oB=[],oL=[],oq=[];for(let e=0,t=oN,i=1,r=0;e<24;e++){[i,r]=[r,(2*i+3*r)%5],oB.push(2*(5*r+i)),oL.push((e+1)*(e+2)/2%64);let s=oR;for(let e=0;e<7;e++)(t=(t<<oN^(t>>oD)*oU)%oM)&oj&&(s^=oN<<(oN<<BigInt(e))-oN);
5oq.push(s)}let oK=a2(oq,!0),oH=oK[0],o$=oK[1],oW=(e,t,i)=>i>32?t<<i-32|e>>>64-i:e<<i|t>>>32-i,oz=(e,t,i)=>i>32?e<<i-32|t>>>64-i:t<<i|e>>>32-i;class oF extends ok{constructor(e,t,i,r=!1,s=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=r,this.rounds=s,ol(i),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=op(this.state)}clone(){return this._cloneInto()}keccak(){ov(this.state32),function(e,t=24){let i=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)i[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let r=(t+8)%10,s=(t+2)%10,n=i[s],a=i[s+1],o=oW(n,a,1)^i[r],l=oz(n,a,1)^i[r+1];for(let i=0;i<50;i+=10)e[t+i]^=o,e[t+i+1]^=l}let t=e[2],s=e[3];for(let i=0;i<24;i++){let r=oL[i],n=oW(t,s,r),a=oz(t,s,r),o=oB[i];t=e[o],s=e[o+1],e[o]=n,e[o+1]=a}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)i[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~i[(r+2)%10]&i[(r+4)%10]}e[0]^=oH[r],e[1]^=o$[r]}
5of(i)}(this.state32,this.rounds),ov(this.state32),this.posOut=0,this.pos=0}update(e){od(this),oc(e=oC(e));let{blockLen:t,state:i}=this,r=e.length;for(let s=0;s<r;){let n=Math.min(t-this.pos,r-s);for(let t=0;t<n;t++)i[this.pos++]^=e[s++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,(128&t)!=0&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){od(this,!1),oc(e),this.finish();let t=this.state,{blockLen:i}=this;for(let r=0,s=e.length;r<s;){this.posOut>=i&&this.keccak();let n=Math.min(i-this.posOut,s-r);e.set(t.subarray(this.posOut,this.posOut+n),r),this.posOut+=n,r+=n}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ol(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ou(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,of(this.state)}_cloneInto(e){let{blockLen:t,suffix:i,outputLen:r,rounds:s,enableXOF:n}=this;return e||(e=new oF(t,i,r,n,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=i,e.outputLen=r,e.enableXOF=n,e.destroyed=this.destroyed,e}}let oV=oO(()=>new oF(136,1,32));class oJ extends ok{constructor(e,t,i,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.buffer=new Uint8Array(e),this.view=og(this.buffer)}update(e){od(this),oc(e=oC(e));let{view:t,buffer:i,blockLen:r}=this,s=e.length;for(let n=0;n<s;){let a=Math.min(r-this.pos,s-n);if(a===r){let t=og(e);for(;r<=s-n;n+=r)this.process(t,n);continue}i.set(e.subarray(n,n+a),this.pos),this.pos+=a,n+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){od(this),ou(e,this),this.finished=!0;let{buffer:t,view:i,blockLen:r,isLE:s}=this,{pos:n}=this;t[n++]=128,of(this.buffer.subarray(n)),this.padOffset>r-n&&(this.process(i,0),n=0);for(let e=n;e<r;e++)t[e]=0;(function(e,t,i,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,r);let s=BigInt(32),n=BigInt(0xffffffff),a=Number(i>>s&n),o=Number(i&n),l=4*!!r,c=4*!r;e.setUint32(t+l,a,r),e.setUint32(t+c,o,r)})(i,r-8,BigInt(8*this.length),s),this.process(i,0);let a=og(e),o=this.outputLen;if(o%4)throw Error("_sha2: outputLen should be aligned to 32bit");let l=o/4,c=this.get();if(l>c.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<l;e++)a.setUint32(4*e,c[e],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:i,length:r,finished:s,destroyed:n,pos:a}=this;return e.destroyed=n,e.finished=s,e.length=r,e.pos=a,r%t&&e.buffer.set(i),e}clone(){return this._cloneInto()}}let oG=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),oY=Uint32Array.from([0xcbbb9d5d,0xc1059ed8,0x629a292a,0x367cd507,0x9159015a,0x3070dd17,0x152fecd8,0xf70e5939,0x67332667,0xffc00b31,0x8eb44a87,0x68581511,0xdb0c2e0d,0x64f98fa7,0x47b5481d,0xbefa4fa4]),oZ=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),oQ=Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),oX=new Uint32Array(64);class o0 extends oJ{constructor(e=32){super(64,e,8,!1),this.A=0|oG[0],this.B=0|oG[1],this.C=0|oG[2],this.D=0|oG[3],this.E=0|oG[4],this.F=0|oG[5],this.G=0|oG[6],this.H=0|oG[7]}get(){let{A:e,B:t,C:i,D:r,E:s,F:n,G:a,H:o}=this;return[e,t,i,r,s,n,a,o]}set(e,t,i,r,s,n,a,o){this.A=0|e,this.B=0|t,this.C=0|i,this.D=0|r,this.E=0|s,this.F=0|n,this.G=0|a,this.H=0|o}process(e,t){for(let i=0;i<16;i++,t+=4)oX[i]=e.getUint32(t,!1);for(let e=16;e<64;
5e++){let t=oX[e-15],i=oX[e-2],r=oy(t,7)^oy(t,18)^t>>>3,s=oy(i,17)^oy(i,19)^i>>>10;oX[e]=s+oX[e-7]+r+oX[e-16]|0}let{A:i,B:r,C:s,D:n,E:a,F:o,G:l,H:c}=this;for(let e=0;e<64;e++){var h,d,u,p;let t=c+(oy(a,6)^oy(a,11)^oy(a,25))+((h=a)&o^~h&l)+oQ[e]+oX[e]|0,f=(oy(i,2)^oy(i,13)^oy(i,22))+((d=i)&(u=r)^d&(p=s)^u&p)|0;c=l,l=o,o=a,a=n+t|0,n=s,s=r,r=i,i=t+f|0}i=i+this.A|0,r=r+this.B|0,s=s+this.C|0,n=n+this.D|0,a=a+this.E|0,o=o+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(i,r,s,n,a,o,l,c)}roundClean(){of(oX)}destroy(){this.set(0,0,0,0,0,0,0,0),of(this.buffer)}}let o1=a2(["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
55771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),o2=o1[0],o5=o1[1],o3=new Uint32Array(80),o8=new Uint32Array(80);class o6 extends oJ{constructor(e=64){super(128,e,16,!1),this.Ah=0|oZ[0],this.Al=0|oZ[1],this.Bh=0|oZ[2],this.Bl=0|oZ[3],this.Ch=0|oZ[4],this.Cl=0|oZ[5],this.Dh=0|oZ[6],this.Dl=0|oZ[7],this.Eh=0|oZ[8],this.El=0|oZ[9],this.Fh=0|oZ[10],this.Fl=0|oZ[11],this.Gh=0|oZ[12],this.Gl=0|oZ[13],this.Hh=0|oZ[14],this.Hl=0|oZ[15]}get(){let{Ah:e,Al:t,Bh:i,Bl:r,Ch:s,Cl:n,Dh:a,Dl:o,Eh:l,El:c,Fh:h,Fl:d,Gh:u,Gl:p,Hh:f,Hl:g}=this;return[e,t,i,r,s,n,a,o,l,c,h,d,u,p,f,g]}set(e,t,i,r,s,n,a,o,l,c,h,d,u,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|i,this.Bl=0|r,this.Ch=0|s,this.Cl=0|n,this.Dh=0|a,this.Dl=0|o,this.Eh=0|l,this.El=0|c,this.Fh=0|h,this.Fl=0|d,this.Gh=0|u,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let i=0;i<16;i++,t+=4)o3[i]=e.getUint32(t),o8[i]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=0|o3[e-15],i=0|o8[e-15],r=a8(t,i,1)^a8(t,i,8)^a5(t,i,7),s=a6(t,i,1)^a6(t,i,8)^a3(t,i,7),n=0|o3[e-2],a=0|o8[e-2],o=a8(n,a,19)^a4(n,a,61)^a5(n,a,6),l=oi(s,a6(n,a,19)^a7(n,a,61)^a3(n,a,6),o8[e-7],o8[e-16]),c=or(l,r,o,o3[e-7],o3[e-16]);o3[e]=0|c,o8[e]=0|l}let{Ah:i,Al:r,Bh:s,Bl:n,Ch:a,Cl:o,Dh:l,Dl:c,Eh:h,El:d,Fh:u,Fl:p,Gh:f,Gl:g,Hh:y,Hl:m}=this;for(let e=0;e<80;e++){let t=a8(h,d,14)^a8(h,d,18)^a4(h,d,41),w=a6(h,d,14)^a6(h,d,18)^a7(h,d,41),b=h&u^~h&f,v=os(m,w,d&p^~d&g,o5[e],o8[e]),E=on(v,y,t,b,o2[e],o3[e]),I=0|v,S=a8(i,r,28)^a4(i,r,34)^a4(i,r,39),A=a6(i,r,28)^a7(i,r,34)^a7(i,r,39),x=i&s^i&a^s&a,P=r&n^r&o^n&o;y=0|f,m=0|g,f=0|u,g=0|p,u=0|h,p=0|d,({h:h,l:d}=a9(0|l,0|c,0|E,0|I)),l=0|a,c=0|o,a=0|s,o=0|n,s=0|i,n=0|r;let C=oe(I,A,P);i=ot(C,E,S,x),r=0|C}({h:i,l:r}=a9(0|this.Ah,0|this.Al,0|i,0|r)),({h:s,l:n}=a9(0|this.Bh,0|this.Bl,0|s,0|n)),({h:a,l:o}=a9(0|this.Ch,0|this.Cl,0|a,0|o)),({h:l,l:c}=a9(0|this.Dh,0|this.Dl,0|l,0|c)),({h:h,l:d}=a9(0|this.Eh,0|this.El,0|h,0|d)),({h:u,l:p}=a9(0|this.Fh,0|this.Fl,0|u,0|p)),({h:f,l:g}=a9(0|this.Gh,0|this.Gl,0|f,0|g)),({h:y,l:m}=a9(0|this.Hh,0|this.Hl,0|y,0|m)),this.set(i,r,s,n,a,o,l,c,h,d,u,p,f,g,y,m)}roundClean(){of(o3,o8)}destroy(){of(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class o4 extends o6{constructor(){super(48),this.Ah=0|oY[0],this.Al=0|oY[1],this.Bh=0|oY[2],this.Bl=0|oY[3],this.Ch=0|oY[4],this.Cl=0|oY[5],this.Dh=0|oY[6],this.Dl=0|oY[7],this.Eh=0|oY[8],this.El=0|oY[9],this.Fh=0|oY[10],this.Fl=0|oY[11],this.Gh=0|oY[12],this.Gl=0|oY[13],this.Hh=0|oY[14],this.Hl=0|oY[15]}}let o7=Uint32Array.from([0x22312194,0xfc2bf72c,0x9f555fa3,0xc84c64c2,0x2393b86b,0x6f53b151,0x96387719,0x5940eabd,0x96283ee2,0xa88effe3,0xbe5e1e25,0x53863992,0x2b0199fc,0x2c85b8aa,0xeb72ddc,0x81c52ca2]);class o9 extends o6{constructor(){super(32),this.Ah=0|o7[0],this.Al=0|o7[1],this.Bh=0|o7[2],this.Bl=0|o7[3],this.Ch=0|o7[4],this.Cl=0|o7[5],this.Dh=0|o7[6],this.Dl=0|o7[7],this.Eh=0|o7[8],this.El=0|o7[9],this.Fh=0|o7[10],this.Fl=0|o7[11],this.Gh=0|o7[12],this.Gl=0|o7[13],this.Hh=0|o7[14],this.Hl=0|o7[15]}}let le=oO(()=>new o0),lt=oO(()=>new o6),li=oO(()=>new o4),lr=oO(()=>new o9),ls=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]),ln=Uint32Array.from([0xf3bcc908,0x6a09e66
57,0x84caa73b,0xbb67ae85,0xfe94f82b,0x3c6ef372,0x5f1d36f1,0xa54ff53a,0xade682d1,0x510e527f,0x2b3e6c1f,0x9b05688c,0xfb41bd6b,0x1f83d9ab,0x137e2179,0x5be0cd19]),la=new Uint32Array(32);function lo(e,t,i,r,s,n){let a=s[n],o=s[n+1],l=la[2*e],c=la[2*e+1],h=la[2*t],d=la[2*t+1],u=la[2*i],p=la[2*i+1],f=la[2*r],g=la[2*r+1],y=oe(l,h,a);c=ot(y,c,d,o),l=0|y,({Dh:g,Dl:f}={Dh:g^c,Dl:f^l}),({Dh:g,Dl:f}={Dh:f,Dl:g}),({h:p,l:u}=a9(p,u,g,f)),({Bh:d,Bl:h}={Bh:d^p,Bl:h^u}),({Bh:d,Bl:h}={Bh:a8(d,h,24),Bl:a6(d,h,24)}),la[2*e]=l,la[2*e+1]=c,la[2*t]=h,la[2*t+1]=d,la[2*i]=u,la[2*i+1]=p,la[2*r]=f,la[2*r+1]=g}function ll(e,t,i,r,s,n){let a=s[n],o=s[n+1],l=la[2*e],c=la[2*e+1],h=la[2*t],d=la[2*t+1],u=la[2*i],p=la[2*i+1],f=la[2*r],g=la[2*r+1],y=oe(l,h,a);c=ot(y,c,d,o),l=0|y,({Dh:g,Dl:f}={Dh:g^c,Dl:f^l}),({Dh:g,Dl:f}={Dh:a8(g,f,16),Dl:a6(g,f,16)}),({h:p,l:u}=a9(p,u,g,f)),({Bh:d,Bl:h}={Bh:d^p,Bl:h^u}),({Bh:d,Bl:h}={Bh:a4(d,h,63),Bl:a7(d,h,63)}),la[2*e]=l,la[2*e+1]=c,la[2*t]=h,la[2*t+1]=d,la[2*i]=u,la[2*i+1]=p,la[2*r]=f,la[2*r+1]=g}class lc extends ok{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ol(e),ol(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=op(this.buffer)}update(e){od(this),oc(e=oC(e));let{blockLen:t,buffer:i,buffer32:r}=this,s=e.length,n=e.byteOffset,a=e.buffer;for(let o=0;o<s;){this.pos===t&&(ov(r),this.compress(r,0,!1),ov(r),this.pos=0);let l=Math.min(t-this.pos,s-o),c=n+o;if(l===t&&!(c%4)&&o+l<s){let e=new Uint32Array(a,c,Math.floor((s-o)/4));ov(e);for(let i=0;o+t<s;i+=r.length,o+=t)this.length+=t,this.compress(e,i,!1);ov(e);continue}i.set(e.subarray(o,o+l),this.pos),this.pos+=l,this.length+=l,o+=l}return this}digestInto(e){od(this),ou(e,this);let{pos:t,buffer32:i}=this;this.finished=!0,of(this.buffer.subarray(t)),ov(i),this.compress(i,0,!0),ov(i);let r=op(e);this.get().forEach((e,t)=>r[t]=ob(e))}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){let{buffer:t,length:i,finished:r,destroyed:s,outputLen:n,pos:a}=this;return e||(e=new this.constructor({dkLen:n})),e.set(...this.get()),e.buffer.set(t),e.destroyed=s,e.finished=r,e.length=i,e.pos=a,e.outputLen=n,e}clone(){return this._cloneInto()}}class lh extends lc{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|ln[0],this.v0h=0|ln[1],this.v1l=0|ln[2],this.v1h=0|ln[3],this.v2l=0|ln[4],this.v2h=0|ln[5],this.v3l=0|ln[6],this.v3h=0|ln[7],this.v4l=0|ln[8],this.v4h=0|ln[9],this.v5l=0|ln[10],this.v5h=0|ln[11],this.v6l=0|ln[12],this.v6h=0|ln[13],this.v7l=0|ln[14],this.v7h=0|ln[15],function(e,t={}){if(ol(64),e<0||e>64)throw Error("outputLen bigger than keyLen");let{key:i,salt:r,personalization:s}=t;if(void 0!==i&&(i.length<1||i.length>64))throw Error("key length must be undefined or 1..64");if(void 0!==r&&16!==r.length)throw Error("salt must be undefined or 16");if(void 0!==s&&16!==s.length)throw Error("personalization must be undefined or 16")}(t,e);let{key:i,personalization:r,salt:s}=e,n=0;if(void 0!==i&&(n=(i=oC(i)).length),this.v0l^=this.outputLen|n<<8|0x1010000,void 0!==s){const e=op(s=oC(s));this.v4l^=ob(e[0]),this.v4h^=ob(e[1]),this.v5l^=ob(e[2]),this.v5h^=ob(e[3])}if(void 0!==r){const e=op(r=oC(r));this.v6l^=ob(e[0]),this.v6h^=ob(e[1]),this.v7l^=ob(e[2]),this.v7h^=ob(e[3])}if(void 0!==i){const e=new Uint8Array(this.blockLen);e.set(i),this.update(e)}}get(){let{v0l:e,v0h:t,v1l:i,v1h:r,v2l:s,v2h:n,v3l:a,v3h:o,v4l:l,v4h:c,v5l:h,v5h:d,v6l:u,v6h:p,v7l:f,v7h:g}=this;return[e,t,i,r,s,n,a,o,l,c,h,d,u,p,f,g]}set(e,t,i,r,s,n,a,o,l,c,h,d,u,p,f,g){this.v0l=0|e,this.v0h=0|t,this.v1l=0|i,this.v1h=0|r,this.v2l=0|s,this.v2h=0|n,this.v3l=0|a,this.v3h=0|o,this.v4l=0|l,this.v4h=0|c,this.v5l=0|h,this.v5h=0|d,this.v6l=0|u,this.v6h=0|p,this.v7l=0|f,this.v7h=0|g}compress(e,t,i){this.get().forEach((e,t)=>la[t]=e),la.set(ln,16);let{h:r,l:s}=a1(BigInt(this.length));la[24]=ln[8]^s,la[25]=ln[9]^r,i&&(la[28]=~la[28],la[29]=~la[29]);let n=0;for(let i=0;i<12;i++)lo(0,4,8,12,e,t+2*ls[n++]),ll(0,4,8,12,e,t+2*ls[n++]),lo(1,5,9,13,e,t+2*ls[n++]),ll(1,5,9,13,e,t+2*ls[n++]),lo(2,6,10,14,e,t+2*ls[n++]),ll(2,6,10,14,e,t+2*ls[n++]),lo(3,7,
511,15,e,t+2*ls[n++]),ll(3,7,11,15,e,t+2*ls[n++]),lo(0,5,10,15,e,t+2*ls[n++]),ll(0,5,10,15,e,t+2*ls[n++]),lo(1,6,11,12,e,t+2*ls[n++]),ll(1,6,11,12,e,t+2*ls[n++]),lo(2,7,8,13,e,t+2*ls[n++]),ll(2,7,8,13,e,t+2*ls[n++]),lo(3,4,9,14,e,t+2*ls[n++]),ll(3,4,9,14,e,t+2*ls[n++]);this.v0l^=la[0]^la[16],this.v0h^=la[1]^la[17],this.v1l^=la[2]^la[18],this.v1h^=la[3]^la[19],this.v2l^=la[4]^la[20],this.v2h^=la[5]^la[21],this.v3l^=la[6]^la[22],this.v3h^=la[7]^la[23],this.v4l^=la[8]^la[24],this.v4h^=la[9]^la[25],this.v5l^=la[10]^la[26],this.v5h^=la[11]^la[27],this.v6l^=la[12]^la[28],this.v6h^=la[13]^la[29],this.v7l^=la[14]^la[30],this.v7h^=la[15]^la[31],of(la)}destroy(){this.destroyed=!0,of(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}let ld=(mz=e=>new lh(e),(c=(e,t)=>mz(t).update(oC(e)).digest()).outputLen=(h=mz({})).outputLen,c.blockLen=h.blockLen,c.create=e=>mz(e),c);function lu(e){let t=`�Ethereum Signed Message:
6${e.length}`,i=new TextEncoder().encode(t+e);return"0x"+tT.Buffer.from(oV(i)).toString("hex")}async function lp(e,t,i,r,s,n){switch(i.t){case"eip191":var a,o,l;let c;return await (a=e,o=t,l=i.s,c=nm.fromHex(l),nK.recoverAddress({payload:lu(o),signature:c}).toLowerCase()===a.toLowerCase());case"eip1271":return await lf(e,t,i.s,r,s,n);default:throw Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${i.t}`)}}async function lf(e,t,i,r,s,n){let a=ap(r);if(!a.namespace||!a.reference)throw Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{let a="0x1626ba7e",o=i.substring(2),l=(o.length/2).toString(16).padStart(64,"0"),c=(t.startsWith("0x")?t:lu(t)).substring(2),h=a+c+"0000000000000000000000000000000000000000000000000000000000000040"+l+o,d=await fetch(`${n||"https://rpc.walletconnect.org/v1"}/?chainId=${r}&projectId=${s}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:Date.now()+Math.floor(1e3*Math.random()),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:h},"latest"]})}),{result:u}=await d.json();return!!u&&u.slice(0,a.length).toLowerCase()===a.toLowerCase()}catch(e){return console.error("isValidEip1271Signature: ",e),!1}}function lg(e){let t=new Uint8Array(le(function(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if("object"==typeof e&&null!=e&&e.data)return new Uint8Array(Object.values(e.data));if("object"==typeof e&&e)return new Uint8Array(Object.values(e));throw Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}(e)));return nH.default.encode(t)}function ly(e){let t=tT.Buffer.from(e,"base64"),i=(0,n$.decode)(t).txn;if(!i)throw Error("Invalid signed transaction: missing 'txn' field");let r=(0,nW.encode)(i),s=tT.Buffer.from("TX"),n=lr(tT.Buffer.concat([s,tT.Buffer.from(r)]));return nz.base32.encode(n).replace(/=+$/,"")}function lm(e){let t=[],i=BigInt(e);for(;i>=BigInt(128);)t.push(Number(i&BigInt(127)|BigInt(128))),i>>=BigInt(7);return t.push(Number(i)),tT.Buffer.from(t)}var lw=Object.defineProperty,lb=Object.defineProperties,lv=Object.getOwnPropertyDescriptors,lE=Object.getOwnPropertySymbols,lI=Object.prototype.hasOwnProperty,lS=Object.prototype.propertyIsEnumerable,lA=(e,t,i)=>t in e?lw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;let lx=e=>e?.split(":"),lP=e=>{let t=e&&lx(e);if(t)return t[2]+":"+t[3]},lC=e=>{let t=e&&lx(e);if(t)return t.pop()};async function l_(e){let{cacao:t,projectId:i}=e,{s:r,p:s}=t,n=lk(s,s.iss),a=lC(s.iss);return await lp(a,n,r,lP(s.iss),i)}let lk=(e,t)=>{let i=`${e.domain} wants you to sign in with your Ethereum account:`,r=lC(t);if(!e.aud&&!e.uri)throw Error("Either `aud` or `uri` is required to construct the message");let s=e.statement||void 0,n=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,o=`Chain ID: ${(e=>{let t=e&&lx(e);if(t)return e.includes("did:pkh:")?t[3]:t[1]})(t)}`,l=`Nonce: ${e.nonce}`,c=`Issued At: ${e.iat}`,h=e.exp?`Expiration Time: ${e.exp}`:void 0,d=e.nbf?`Not Before: ${e.nbf}`:void 0,u=e.requestId?`Request ID: ${e.requestId}`:void 0,p=e.resources?`Resources:${e.resources.map(e=>`
7- ${e}`).join("")}`:void 0,f=lD(e.resources);return f&&(s=function(e="",t){lO(t);let i="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(i))return e;let r=[],s=0;
7Object.keys(t.att).forEach(e=>{let i=Object.keys(t.att[e]).map(e=>({ability:e.split("/")[0],action:e.split("/")[1]}));i.sort((e,t)=>e.action.localeCompare(t.action));let n={};i.forEach(e=>{n[e.ability]||(n[e.ability]=[]),n[e.ability].push(e.action)});let a=Object.keys(n).map(t=>(s++,`(${s}) '${t}': '${n[t].join("', '")}' for '${e}'.`));r.push(a.join(", ").replace(".,","."))});let n=r.join(" "),a=`${i}${n}`;return`${e?e+" ":""}${a}`}(s,lR(f))),[i,r,"",s,"",n,a,o,l,c,h,d,u,p].filter(e=>null!=e).join(`
8`)};function lO(e){if(!e)throw Error("No recap provided, value is undefined");if(!e.att)throw Error("No `att` property found");let t=Object.keys(e.att);if(!(null!=t&&t.length))throw Error("No resources found in `att` property");t.forEach(t=>{let i=e.att[t];if(Array.isArray(i)||"object"!=typeof i)throw Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(e=>{let t=i[e];if(!Array.isArray(t))throw Error(`Ability limits ${e} must be an array of objects, found: ${t}`);if(!t.length)throw Error(`Value of ${e} is empty array, must be an array with objects`);t.forEach(t=>{if("object"!=typeof t)throw Error(`Ability limits (${e}) must be an array of objects, found: ${t}`)})})})}function lT(e){return lO(e),`urn:recap:${tT.Buffer.from(JSON.stringify(e)).toString("base64").replace(/=/g,"")}`}function lR(e){var t;let i=(t=e.replace("urn:recap:",""),JSON.parse(tT.Buffer.from(t,"base64").toString("utf-8")));return lO(i),i}function lN(e){var t;let i=lR(e);lO(i);let r=null==(t=i.att)?void 0:t.eip155;return r?Object.keys(r).map(e=>e.split("/")[1]):[]}function lj(e){let t=lR(e);lO(t);let i=[];return Object.values(t.att).forEach(e=>{Object.values(e).forEach(e=>{var t;null!=(t=e?.[0])&&t.chains&&i.push(e[0].chains)})}),[...new Set(i.flat())]}function lD(e){if(!e)return;let t=e?.[e.length-1];return t&&t.includes("urn:recap:")?t:void 0}function lM(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function lU(e){if("boolean"!=typeof e)throw Error(`boolean expected, not ${e}`)}function lB(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function lL(e,...t){if(!lM(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function lq(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function lK(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function lH(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}let l$=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0];function lW(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}(e);else if(lM(e))e=lV(e);else throw Error("Uint8Array expected, got "+typeof e);return e}function lz(e,t,i=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw Error("invalid output length, expected "+e+", got: "+t.length);if(i&&t.byteOffset%4!=0)throw Error("invalid output, must be aligned");return t}function lF(e,t,i,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,r);let s=BigInt(32),n=BigInt(0xffffffff),a=Number(i>>s&n),o=Number(i&n),l=4*!!r,c=4*!r;e.setUint32(t+l,a,r),e.setUint32(t+c,o,r)}function lV(e){return Uint8Array.from(e)}let lJ=e=>Uint8Array.from(e.split("").map(e=>e.charCodeAt(0))),lG=lJ("expand 16-byte k"),lY=lJ("expand 32-byte k"),lZ=lK(lG),lQ=lK(lY);function lX(e,t){return e<<t|e>>>32-t}function l0(e){return e.byteOffset%4==0}let l1=0x100000000-1,l2=new Uint32Array,l5=(e,t)=>255&e[t++]|(255&e[t++])<<8;class l3{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,lL(e=lW(e),32);const t=l5(e,0),i=l5(e,2),r=l5(e,4),s=l5(e,6),n=l5(e,8),a=l5(e,10),o=l5(e,12),l=l5(e,14);this.r[0]=8191&t,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|r<<6)&7939,this.r[3]=(r>>>7|s<<9)&8191,this.r[4]=(s>>>4|n<<12)&255,this.r[5]=n>>>1&8190,this.r[6]=(n>>>14|a<<2)&8191,this.r[7]=(a>>>11|o<<5)&8065,this.r[8]=(o>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let t=0;t<8;t++)this.pad[t]=l5(e,16+2*t)}process(e,t,i=!1){let{h:r,r:s}=this,n=s[0],a=s[1],o=s[2],l=s[3],c=s[4],h=s[5],d=s[6],u=s[7],p=s[8],f=s[9],g=l5(e,t+0),y=l5(e,t+2),m=l5(e,t+4),w=l5(e,t+6),b=l5(e,t+8),v=l5(e,t+10),E=l5(e,t+12),I=l5(e,t+14),S=r[0]+(8191&g),A=r[1]+((g>>>13|y<<3)&8191),x=r[2]+((y>>>10|m<<6)&8191),P=r[3]+((m>>>7|w<<9)&8191),C=r[4]+((w>>>4|b<<12)&8191),_=r[5]+(b>>>1&8191),k=r[6]+((b>>>14|v<<2)&8191),O=r[7]+((v>>>11|E<<5)&8191),T=r[8]+((E>>>8|I<<8)&8191),R=r[9]+(I>>>5|2048*!i),N=0,j=0+S*n+5*f*A+5*p*x+5*u*P+5*d*C;N=j>>>13,j&=8191,j+=5*h*_+5*c*k+5*l*O+5*o*T+5*a*R,N+=j>>>13,j&=8191;let D=N+S*a+A*n+5*f*x+5*p*P+5*u*C;N=D>>>13,D&=8191,D+=5*d*_+5*h*k+5*c*O+5*l*T+5*o*R,N+=D>>>13,D&=8191;let M=N+S*o+A*a+x*n+5*f*P+5*p*C;N=M>>>13,M&=8191,M+=5*u*_+5*d*k+5*h*O+5*c*T+5*l*R,N+=M>>>13,M&=8191;let U=N+S*l+A*o+x*a+P*n+5*f*C;N=U>>>13,U&=8191,U+=5*p*_+5*u*k+5*d*O+5*h*T+5*c*R,N+=U>>>13,U&=8191;let B=N+S*c+A*l+x*o+P*a+C*n;N=B>>>13,B&=8191,B+=5*f*_+5*p*k+5*u*O+5*d*T+5*h*R,N+=B>>>13,B&=8191;let L=N+S*h+A*c+x*l+P*o+C*a;N=L>>>
813,L&=8191,L+=_*n+5*f*k+5*p*O+5*u*T+5*d*R,N+=L>>>13,L&=8191;let q=N+S*d+A*h+x*c+P*l+C*o;N=q>>>13,q&=8191,q+=_*a+k*n+5*f*O+5*p*T+5*u*R,N+=q>>>13,q&=8191;let K=N+S*u+A*d+x*h+P*c+C*l;N=K>>>13,K&=8191,K+=_*o+k*a+O*n+5*f*T+5*p*R,N+=K>>>13,K&=8191;let H=N+S*p+A*u+x*d+P*h+C*c;N=H>>>13,H&=8191,H+=_*l+k*o+O*a+T*n+5*f*R,N+=H>>>13,H&=8191;let $=N+S*f+A*p+x*u+P*d+C*h;N=$>>>13,$&=8191,$+=_*c+k*l+O*o+T*a+R*n,N+=$>>>13,$&=8191,j=8191&(N=(N=(N<<2)+N|0)+j|0),N>>>=13,D+=N,r[0]=j,r[1]=D,r[2]=M,r[3]=U,r[4]=B,r[5]=L,r[6]=q,r[7]=K,r[8]=H,r[9]=$}finalize(){let{h:e,pad:t}=this,i=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=5*r,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,i[0]=e[0]+5,r=i[0]>>>13,i[0]&=8191;for(let t=1;t<10;t++)i[t]=e[t]+r,r=i[t]>>>13,i[t]&=8191;i[9]-=8192;let s=(1^r)-1;for(let e=0;e<10;e++)i[e]&=s;s=~s;for(let t=0;t<10;t++)e[t]=e[t]&s|i[t];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 n=e[0]+t[0];e[0]=65535&n;for(let i=1;i<8;i++)n=(e[i]+t[i]|0)+(n>>>16)|0,e[i]=65535&n;lH(i)}update(e){lq(this),lL(e=lW(e));let{buffer:t,blockLen:i}=this,r=e.length;for(let s=0;s<r;){let n=Math.min(i-this.pos,r-s);if(n===i){for(;i<=r-s;s+=i)this.process(e,s);continue}t.set(e.subarray(s,s+n),this.pos),this.pos+=n,s+=n,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){lH(this.h,this.r,this.buffer,this.pad)}digestInto(e){lq(this),function(e,t){lL(e);let i=t.outputLen;if(e.length<i)throw Error("digestInto() expects output buffer of length at least "+i)}(e,this),this.finished=!0;let{buffer:t,h:i}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let t=0;t<8;t++)e[s++]=i[t]>>>0,e[s++]=i[t]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}}let l8=(mF=e=>new l3(e),(d=(e,t)=>mF(t).update(lW(e)).digest()).outputLen=(u=mF(new Uint8Array(32))).outputLen,d.blockLen=u.blockLen,d.create=e=>mF(e),d),l6=function(e,t){let{allowShortKeys:i,extendNonceFn:r,counterLength:s,counterRight:n,rounds:a}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw Error("core must be a function");return lB(s),lB(a),lU(n),lU(i),(t,o,l,c,h=0)=>{lL(t),lL(o),lL(l);let d=l.length;if(void 0===c&&(c=new Uint8Array(d)),lL(c),lB(h),h<0||h>=l1)throw Error("arx: counter overflow");if(c.length<d)throw Error(`arx: output (${c.length}) is shorter than data (${d})`);let u=[],p=t.length,f,g;if(32===p)u.push(f=lV(t)),g=lQ;else if(16===p&&i)(f=new Uint8Array(32)).set(t),f.set(t,16),g=lZ,u.push(f);else throw Error(`arx: invalid 32-byte key, got length=${p}`);l0(o)||u.push(o=lV(o));let y=lK(f);if(r){if(24!==o.length)throw Error("arx: extended nonce must be 24 bytes");r(g,y,lK(o.subarray(0,16)),y),o=o.subarray(16)}let m=16-s;if(m!==o.length)throw Error(`arx: nonce must be ${m} or 16 bytes`);if(12!==m){let e=new Uint8Array(12);e.set(o,n?0:12-o.length),o=e,u.push(o)}return function(e,t,i,r,s,n,a,o){let l=s.length,c=new Uint8Array(64),h=lK(c),d=l0(s)&&l0(n),u=d?lK(s):l2,p=d?lK(n):l2;for(let f=0;f<l;a++){if(e(t,i,r,h,a,o),a>=l1)throw Error("arx: counter overflow");let g=Math.min(64,l-f);if(d&&64===g){let e=f/4;if(f%4!=0)throw Error("arx: invalid block position");for(let t=0,i;t<16;t++)p[i=e+t]=u[i]^h[t];f+=64;continue}for(let e=0,t;e<g;e++)n[t=f+e]=s[t]^c[e];f+=g}}(e,g,y,lK(o),l,c,h,a),lH(...u),c}}(function(e,t,i,r,s,n=20){let a=e[0],o=e[1],l=e[2],c=e[3],h=t[0],d=t[1],u=t[2],p=t[3],f=t[4],g=t[5],y=t[6],m=t[7],w=i[0],b=i[1],v=i[2],E=a,I=o,S=l,A=c,x=h,P=d,C=u,_=p,k=f,O=g,T=y,R=m,N=s,j=w,D=b,M=v;for(let e=0;e<n;e+=2)k=k+(N=lX(N^(E=E+x|0),16))|0,E=E+(x=lX(x^k,12))|0,k=k+(N=lX(N^E,8))|0,x=lX(x^k,7),O=O+(j=lX(j^(I=I+P|0),16))|0,I=I+(P=lX(P^O,12))|0,O=O+(j=lX(j^I,8))|0,P=lX(P^O,7),T=T+(D=lX(D^(S=S+C|0),16))|0,S=S+(C=lX(C^T,12))|0,T=T+(D=lX(D^S,8))|0,C=lX(C^T,7),R=R+(M=lX(M^(A=A+_|0),16))|0,A=A+(_=lX(_^R,12))|0,R=R+(M=lX(M^A,8))|0,_=lX(_^R,7),T=T+(M=lX(M^(E=E+P|0),16))|0,E=E+(P=lX(P^T,12))|0,T=T+(M=lX(M^E,8))|0,P=lX(P^T,7),R=R+(N=lX(N^(I=I+C|0),16))|0,I=I+(C=lX(C^R,12))|0,R=R+(N=lX(N^I,8))|0,C=lX(C^R,7),k=k+(j=lX(j^(S=S+_|0),16))|0,S=S+(_=lX(_^k,12))|0,k=k+(j=lX(j^S,8))|0,_=lX(_^k,7),O=O+(D=lX(D^(A=A+x|0),16))|0,A=A+(x=lX(x^O,12))|0,O=O+(D=lX(D^A,8))|0,x=lX(x^O,7);let U=0;r[U++]=a+E|0,r[U++]=o+I|0,r[U++]=l+S|0,r[U++]=c+A|0,r[U++]=h+x|0,r[U++]=d+P|0,r[U++]=u+C|0,r[U++]=p+_|0,r[U++]=f+k|0,r[U++]=g+O|0,r[U++]=y+T|0,r[U++]=m+R|0,r[U++]=s+N|0,r[U++]=w+j|0,r[U++]=b+D|0,r[U++]=v+M|0},{counterRight:!1,counterLength:4,allowShortKeys:!1}),l4=new Uint8Array(16),l7=(e,t)=>{e.update(t);let i=t.length%16;i&&e.update(l4.subarray(i))},l9=new Uint8Array(32);function ce(e,t,i,r,s){var n,a;let o,l,c=e(t,i,l9),h=l8.create(c);s&&l7(h,s),l7(h,r);let d=(n=r.length,a=s?s.length:0,lU(!0),lF(l=new DataView((o=new Uint8Array(16)).buffer,o.byteOffset,o.byteLength),0,BigInt(a),!0),lF(l,8,BigInt(n),!0),o);h.update(d);let u=h.digest();return lH(c,d),u}let ct=((e,t)=>{function i(r,...s){if(lL(r),!l$)throw Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){let t=s[0];if(!t)throw Error("nonce / iv required");e.varSizeNonce?lL(t):lL(t,e.nonceLength)}let n=e.tagLength;n&&void 0!==s[1]&&lL(s[1]);let a=t(r,...s),o=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");lL(t)}},l=!1;
8return{encrypt(e,t){if(l)throw Error("cannot encrypt() twice with same key + nonce");return l=!0,lL(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(lL(e),n&&e.length<n)throw Error("invalid ciphertext length: smaller than tagLength="+n);return o(a.decrypt.length,t),a.decrypt(e,t)}}}return Object.assign(i,e),i})({blockSize:64,nonceLength:12,tagLength:16},(e,t,i)=>({encrypt(r,s){let n=r.length;(s=lz(n+16,s,!1)).set(r);let a=s.subarray(0,-16);l6(e,t,a,a,1);let o=ce(l6,e,t,a,i);return s.set(o,n),lH(o),s},decrypt(r,s){s=lz(r.length-16,s,!1);let n=r.subarray(0,-16),a=r.subarray(-16),o=ce(l6,e,t,n,i);if(!function(e,t){if(e.length!==t.length)return!1;let i=0;for(let r=0;r<e.length;r++)i|=e[r]^t[r];return 0===i}(a,o))throw Error("invalid tag");return s.set(r.subarray(0,-16)),l6(e,t,s,s,1),lH(o),s}}));class ci extends ok{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,oh(e);const i=oC(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(i.length>r?e.create().update(i).digest():i);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),of(s)}update(e){return od(this),this.iHash.update(e),this}digestInto(e){od(this),oc(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:i,finished:r,destroyed:s,blockLen:n,outputLen:a}=this;return e.finished=r,e.destroyed=s,e.blockLen=n,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()}}let cr=(e,t,i)=>new ci(e,t).update(i).digest();cr.create=(e,t)=>new ci(e,t);let cs=Uint8Array.from([0]),cn=Uint8Array.of(),ca=BigInt(0),co=BigInt(1);function cl(e,t=""){if("boolean"!=typeof e)throw Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function cc(e,t,i=""){let r=oo(e),s=e?.length,n=void 0!==t;if(!r||n&&s!==t)throw Error((i&&`"${i}" `)+"expected Uint8Array"+(n?` of length ${t}`:"")+", got "+(r?`length=${s}`:`type=${typeof e}`));return e}function ch(e){let t=e.toString(16);return 1&t.length?"0"+t:t}function cd(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return""===e?ca:BigInt("0x"+e)}function cu(e){return oc(e),cd(oS(Uint8Array.from(e).reverse()))}function cp(e,t){return ox(e.toString(16).padStart(2*t,"0"))}function cf(e,t){return cp(e,t).reverse()}function cg(e,t,i){let r;if("string"==typeof t)try{r=ox(t)}catch(t){throw Error(e+" must be hex string or Uint8Array, cause: "+t)}else if(oo(t))r=Uint8Array.from(t);else throw Error(e+" must be hex string or Uint8Array");let s=r.length;if("number"==typeof i&&s!==i)throw Error(e+" of length "+i+" expected, got "+s);return r}let cy=e=>"bigint"==typeof e&&ca<=e;function cm(e,t,i,r){if(!(cy(t)&&cy(i)&&cy(r))||!(i<=t)||!(t<r))throw Error("expected valid "+e+": "+i+" <= n < "+r+", got "+t)}function cw(e){let t;for(t=0;e>ca;e>>=co,t+=1);return t}let cb=e=>(co<<BigInt(e))-co;function cv(e,t,i={}){if(!e||"object"!=typeof e)throw Error("expected valid options object");function r(t,i,r){let s=e[t];if(r&&void 0===s)return;let n=typeof s;if(n!==i||null===s)throw Error(`param "${t}" is invalid: expected ${i}, got ${n}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(i).forEach(([e,t])=>r(e,t,!0))}function cE(e){let t=new WeakMap;return(i,...r)=>{let s=t.get(i);if(void 0!==s)return s;let n=e(i,...r);return t.set(i,n),n}}let cI=BigInt(0),cS=BigInt(1),cA=BigInt(2),cx=BigInt(3),cP=BigInt(4),cC=BigInt(5),c_=BigInt(7),ck=BigInt(8),cO=BigInt(9),cT=BigInt(16);function cR(e,t){let i=e%t;return i>=cI?i:t+i}function cN(e,t,i){let r=e;for(;t-- >cI;)r*=r,r%=i;return r}function cj(e,t){if(e===cI)throw Error("invert: expected non-zero number");if(t<=cI)throw Error("invert: expected positive modulus, got "+t);let i=cR(e,t),r=t,s=cI,n=cS;for(;i!==cI;){let e=r/i,t=r%i,a=s-n*e;r=i,i=t,s=n,n=a}if(r!==cS)throw Error("invert: does not exist");return cR(s,t)}function cD(e,t,i){if(!e.eql(e.sqr(t),i))throw Error("Cannot find square root")}function cM(e,t){let i=(e.ORDER+cS)/cP,r=e.pow(t,i);return cD(e,r,t),r}function cU(e,t){let i=(e.ORDER-cC)/ck,r=e.mul(t,cA),s=e.pow(r,i),n=e.mul(t,s),a=e.mul(e.mul(n,cA),s),o=e.mul(n,e.sub(a,e.ONE));return cD(e,o,t),o}function cB(e){if(e<cx)throw Error("sqrt is not defined for small field");let t=e-cS,i=0;for(;t%cA===cI;)t/=cA,i++;let r=cA,s=c$(e);for(;1===cK(s,r);)if(r++>1e3)throw Error("Cannot find square root: probably non-prime P");if(1===i)return cM;let n=s.pow(r,t),a=(t+cS)/cA;return function(e,r){if(e.is0(r))return r;if(1!==cK(e,r))throw Error("Cannot find square root");let s=i,o=e.mul(e.ONE,n),l=e.pow(r,t),c=e.pow(r,a);for(;!e.eql(l,e.ONE);){if(e.is0(l))return e.ZERO;let t=1,i=e.sqr(l);for(;!e.eql(i,e.ONE);)if(t++,i=e.sqr(i),t===s)throw Error("Cannot find square root");let r=cS<<BigInt(s-t-1),n=e.pow(o,r);s=t,o=e.sqr(n),l=e.mul(l,o),c=e.mul(c,n)}return c}}let cL=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function cq(e,t,i=!1){let r=Array(t.length).fill(i?e.ZERO:void 0),s=t.reduce((t,i,s)=>e.is0(i)?t:(r[s]=t,e.mul(t,i)),e.ONE),n=e.inv(s);return t.reduceRight((t,i,s)=>e.is0(i)?t:(r[s]=e.mul(t,r[s]),e.mul(t,i)),n),r}function cK(e,t){let i=(e.ORDER-cS)/cA,r=e.pow(t,i),s=e.eql(r,e.ONE),n=e.eql(r,e.ZERO),a=e.eql(r,e.neg(e.ONE));if(!s&&!n&&!a)throw Error("invalid Legendre symbol result");return s?1:n?0:-1}function cH(e,t){void 0!==t&&ol(t);let i=void 0!==t?t:e.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function c$(e,t,i=!1,r={}){let s;if(e<=cI)throw Error("invalid field: expected ORDER > 0, got "+e);let n,a,o=!1,l;if("object"==typeof t&&null!=t){if(r.sqrt||i)throw Error("cannot specify opts in two arguments");
vendor: 3,847 bytes, line 8
8t.BITS&&(n=t.BITS),t.sqrt&&(a=t.sqrt),"boolean"==typeof t.isLE&&(i=t.isLE),"boolean"==typeof t.modFromBytes&&(o=t.modFromBytes),l=t.allowedLengths}else"number"==typeof t&&(n=t),r.sqrt&&(a=r.sqrt);let{nBitLength:c,nByteLength:h}=cH(e,n);if(h>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let d=Object.freeze({ORDER:e,isLE:i,BITS:c,BYTES:h,MASK:cb(c),ZERO:cI,ONE:cS,allowedLengths:l,create:t=>cR(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error("invalid field element: expected bigint, got "+typeof t);return cI<=t&&t<e},is0:e=>e===cI,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&cS)===cS,neg:t=>cR(-t,e),eql:(e,t)=>e===t,sqr:t=>cR(t*t,e),add:(t,i)=>cR(t+i,e),sub:(t,i)=>cR(t-i,e),mul:(t,i)=>cR(t*i,e),pow:(e,t)=>(function(e,t,i){if(i<cI)throw Error("invalid exponent, negatives unsupported");if(i===cI)return e.ONE;if(i===cS)return t;let r=e.ONE,s=t;for(;i>cI;)i&cS&&(r=e.mul(r,s)),s=e.sqr(s),i>>=cS;return r})(d,e,t),div:(t,i)=>cR(t*cj(i,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>cj(t,e),sqrt:a||(t=>{let i,r,n,a,o,l;return s||(s=e%cP===cx?cM:e%ck===cC?cU:e%cT===cO?(i=c$(e),n=(r=cB(e))(i,i.neg(i.ONE)),a=r(i,n),o=r(i,i.neg(n)),l=(e+c_)/cT,(e,t)=>{let i=e.pow(t,l),r=e.mul(i,n),s=e.mul(i,a),c=e.mul(i,o),h=e.eql(e.sqr(r),t),d=e.eql(e.sqr(s),t);i=e.cmov(i,r,h),r=e.cmov(c,s,d);let u=e.eql(e.sqr(r),t),p=e.cmov(i,r,u);return cD(e,p,t),p}):cB(e)),s(d,t)}),toBytes:e=>i?cf(e,h):cp(e,h),fromBytes:(t,r=!0)=>{if(l){if(!l.includes(t.length)||t.length>h)throw Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let e=new Uint8Array(h);e.set(t,i?0:e.length-t.length),t=e}if(t.length!==h)throw Error("Field.fromBytes: expected "+h+" bytes, got "+t.length);let s=i?cu(t):cd(oS(t));if(o&&(s=cR(s,e)),!r&&!d.isValid(s))throw Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>cq(d,e),cmov:(e,t,i)=>i?t:e});return Object.freeze(d)}function cW(e){if("bigint"!=typeof e)throw Error("field order must be bigint");return Math.ceil(e.toString(2).length/8)}function cz(e){let t=cW(e);return t+Math.ceil(t/2)}let cF=BigInt(0),cV=BigInt(1);function cJ(e,t){let i=t.negate();return e?i:t}function cG(e,t){let i=cq(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(i[r])))}function cY(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function cZ(e,t){cY(e,t);let i=Math.ceil(t/e)+1,r=2**(e-1),s=2**e;return{windows:i,windowSize:r,mask:cb(e),maxNumber:s,shiftBy:BigInt(e)}}function cQ(e,t,i){let{windowSize:r,mask:s,maxNumber:n,shiftBy:a}=i,o=Number(e&s),l=e>>a;o>r&&(o-=n,l+=cV);let c=t*r;return{nextN:l,offset:c+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:t%2!=0,offsetF:c}}let cX=new WeakMap,c0=new WeakMap;function c1(e){return c0.get(e)||1}function c2(e){if(e!==cF)throw Error("invalid wNAF")}class c5{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 r=e;for(;t>cF;)t&cV&&(i=i.add(r)),r=r.double(),t>>=cV;return i}precomputeWindow(e,t){let{windows:i,windowSize:r}=cZ(t,this.bits),s=[],n=e,a=n;for(let e=0;e<i;e++){a=n,s.push(a);for(let e=1;e<r;e++)a=a.add(n),s.push(a);n=a.double()}return s}wNAF(e,t,i){if(!this.Fn.isValid(i))throw Error("invalid scalar");let r=this.ZERO,s=this.BASE,n=cZ(e,this.bits);for(let e=0;e<n.windows;e++){let{nextN:a,offset:o,isZero:l,isNeg:c,isNegF:h,offsetF:d}=cQ(i,e,n);i=a,l?s=s.add(cJ(h,t[d])):r=r.add(cJ(c,t[o]))}return c2(i),{p:r,f:s}}wNAFUnsafe(e,t,i,r=this.ZERO){let s=cZ(e,this.bits);for(let e=0;e<s.windows&&i!==cF;e++){let{nextN:n,offset:a,isZero:o,isNeg:l}=cQ(i,e,s);if(i=n,!o){let e=t[a];r=r.add(l?e.negate():e)}}return c2(i),r}getPrecomputes(e,t,i){let r=cX.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof i&&(r=i(r)),cX.set(t,r))),r}cached(e,t,i){let r=c1(e);
8return this.wNAF(r,this.getPrecomputes(r,e,i),t)}unsafe(e,t,i,r){let s=c1(e);return 1===s?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,i),t,r)}createCache(e,t){cY(t,this.bits),c0.set(e,t),cX.delete(e)}hasCache(e){return 1!==c1(e)}}function c3(e,t,i){if(!t)return c$(e,{isLE:i});if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return cv(t,cL.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"})),t}BigInt(0),BigInt(1),BigInt(2),BigInt(8),oP("HashToScalar-");let c8=BigInt(0),c6=BigInt(1),c4=BigInt(2),c7=BigInt(1),c9=BigInt(2),he=BigInt(3),ht=BigInt(5),hi=BigInt(8),hr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),hs={p:hr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:hi,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")},hn=function(e){let{P:t,type:i,adjustScalarBytes:r,powPminus2:s,randomBytes:n}=(cv(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})),a="x25519"===i;if(!a&&"x448"!==i)throw Error("invalid type");let o=n||oT,l=a?255:448,c=a?32:56,h=BigInt(a?9:5),d=BigInt(a?121665:39081),u=a?c4**BigInt(254):c4**BigInt(447),p=u+(a?BigInt(8)*c4**BigInt(251)-c6:BigInt(4)*c4**BigInt(445)-c6)+c6,f=e=>cR(e,t),g=cf(f(h),c);function y(e,i){let n,o=function(e,i){cm("u",e,c8,t),cm("scalar",i,u,p);let r=c6,n=c8,a=e,o=c6,c=c8;for(let t=BigInt(l-1);t>=c8;t--){let s=i>>t&c6;c^=s,({x_2:r,x_3:a}=w(c,r,a)),({x_2:n,x_3:o}=w(c,n,o)),c=s;let l=r+n,h=f(l*l),u=r-n,p=f(u*u),g=h-p,y=a+o,m=f((a-o)*l),b=f(y*u),v=m+b,E=m-b;a=f(v*v),o=f(e*f(E*E)),r=f(h*p),n=f(g*(h+f(d*g)))}return{x_2:r,x_3:a}=w(c,r,a),{x_2:n,x_3:o}=w(c,n,o),f(r*s(n))}((n=cg("u coordinate",i,c),a&&(n[31]&=127),f(cu(n))),cu(r(cg("scalar",e,c))));if(o===c8)throw Error("invalid private or public key received");return cf(f(o),c)}function m(e){return y(e,g)}function w(e,t,i){let r=f(e*(t-i));return{x_2:t=f(t-r),x_3:i=f(i+r)}}let b={secretKey:c,publicKey:c,seed:c},v=(e=o(c))=>(oc(e,b.seed),e);return{keygen:function(e){let t=v(e);return{secretKey:t,publicKey:m(t)}},getSharedSecret:(e,t)=>y(e,t),getPublicKey:e=>m(e),scalarMult:y,scalarMultBase:m,utils:{randomSecretKey:v,randomPrivateKey:v},GuBytes:g.slice(),lengths:b}}({P:p=c$(hs.p,{isLE:!0}).ORDER,type:"x25519",powPminus2:e=>{let t,i,r,s,n,a,o,l,c,h,d,u,f,g,{pow_p_5_8:y,b2:m}=(t=BigInt(10),i=BigInt(20),r=BigInt(40),s=BigInt(80),a=cN(n=e*e%hr*e%hr,c9,hr)*n%hr,o=cN(a,c7,hr)*e%hr,l=cN(o,ht,hr)*o%hr,c=cN(l,t,hr)*l%hr,h=cN(c,i,hr)*c%hr,d=cN(h,r,hr)*h%hr,u=cN(d,s,hr)*d%hr,f=cN(u,s,hr)*d%hr,g=cN(f,t,hr)*l%hr,{pow_p_5_8:cN(g,c9,hr)*e%hr,b2:n});return cR(cN(y,he,p)*m,p)},adjustScalarBytes:function(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}}),ha=(e,t)=>(e+(e>=0?t:-t)/hu)/t;function ho(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function hl(e,t){let i={};for(let r of Object.keys(t))i[r]=void 0===e[r]?t[r]:e[r];return cl(i.lowS,"lowS"),cl(i.prehash,"prehash"),void 0!==i.format&&ho(i.format),i}let hc={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(e,t)=>{let{Err:i}=hc;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(1&t.length)throw new i("tlv.encode: unpadded data");let r=t.length/2,s=ch(r);if(s.length/2&128)throw new i("tlv.encode: long form length too big");let n=r>127?ch(s.length/2|128):"";return ch(e)+n+s+t},decode(e,t){let{Err:i}=hc,r=0;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new i("tlv.decode: wrong tlv");let s=t[r++],n=0;if(128&s){let e=127&s;if(!e)throw new i("tlv.decode(long): indefinite length not supported");if(e>4)throw new i("tlv.decode(long): byte length is too big");let a=t.subarray(r,r+e);if(a.length!==e)throw new i("tlv.decode: length bytes not complete");if(0===a[0])throw new i("tlv.decode(long): zero leftmost byte");for(let e of a)n=n<<8|e;if(r+=e,n<128)throw new i("tlv.decode(long): not minimal encoding")}else n=s;let a=t.subarray(r,r+n);if(a.length!==n)throw new i("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+n)}}},_int:{encode(e){let{Err:t}=hc;if(e<hh)throw new t("integer: negative integers are not allowed");let i=ch(e);if(8&Number.parseInt(i[0],16)&&(i="00"+i),1&i.length)throw new t("unexpected DER parsing assertion: unpadded hex");return i},decode(e){let{Err:t}=hc;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return cd(oS(e))}},toSig(e){let{Err:t,_int:i,_tlv:r}=hc,s=cg("signature",e),{v:n,l:a}=r.decode(48,s);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:o,l:l}=r.decode(2,n),{v:c,l:h}=r.decode(2,l);if(h.length)throw new t("invalid signature: left bytes after parsing");return{r:i.decode(o),s:i.decode(c)}},hexFromSig(e){let{_tlv:t,_int:i}=hc,r=t.encode(2,i.encode(e.r)),s=t.encode(2,i.encode(e.s));return t.encode(48,r+s)}},hh=BigInt(0),hd=BigInt(1),hu=BigInt(2),hp=BigInt(3),hf=BigInt(4);function hg(e,t){let i,{BYTES:r}=e;if("bigint"==typeof t)i=t;else{let s=cg("private key",t);try{i=e.fromBytes(s)}catch{throw Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(i))throw Error("invalid private key: out of range [1..N-1]");return i}function hy(e){return Uint8Array.of(e?2:3)}function hm(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function hw(e,t){let i=t=>(function(e){let t,{CURVE:i,curveOpts:r,hash:s,ecdsaOpts:n}=function(e){let t,i,r,s,{CURVE:n,curveOpts:a}=(t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},i=e.Fp,r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0,s={Fp:i,Fn:c$(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes},{CURVE:t,curveOpts:s}),o={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:n,curveOpts:a,hash:e.hash,ecdsaOpts:o}}(e),a=function(e,t,i={}){oh(t),cv(i,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=i.randomBytes||oT,s=i.hmac||((e,...i)=>cr(t,e,o_(...i))),{Fp:n,Fn:a}=e,{ORDER:o,BITS:l}=a,{keygen:c,getPublicKey:h,getSharedSecret:d,utils:u,lengths:p}=function(e,t={}){let{Fn:i}=e,r=t.randomBytes||oT,s=Object.assign(hm(e.Fp,i),{seed:cz(i.ORDER)});function n(e){try{return!!hg(i,e)}catch{return!1}}function a(e=r(s.seed)){return function(e,t,i=!1){let r=e.length,s=cW(t),n=cz(t);if(r<16||r<n||r>1024)throw Error("expected "+n+"-1024 bytes of input, got "+r);let a=cR(i?cu(e):cd(oS(e)),t-cS)+cS;return i?cf(a,s):cp(a,s)}(cc(e,s.seed,"seed"),i.ORDER)}function o(t,r=!0){return e.BASE.multiply(hg(i,t)).toBytes(r)}function l(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;let{secretKey:r,publicKey:n,publicKeyUncompressed:a}=s;if(i.allowedLengths||r===n)return;let o=cg("key",t).length;return o===n||o===a}return Object.freeze({getPublicKey:o,getSharedSecret:function(t,r,s=!0){if(!0===l(t))throw Error("first arg must be private key");if(!1===l(r))throw Error("second arg must be public key");let n=hg(i,t);return e.fromHex(r).multiply(n).toBytes(s)},keygen:function(e){let t=a(e);return{secretKey:t,publicKey:o(t)}},Point:e,utils:{isValidSecretKey:n,isValidPublicKey:function(t,i){let{publicKey:r,publicKeyUncompressed:n}=s;try{let s=t.length;return(!0!==i||s===r)&&(!1!==i||s===n)&&!!e.fromBytes(t)}catch{return!1}},randomSecretKey:a,isValidPrivateKey:n,randomPrivateKey:a,normPrivateKeyToScalar:e=>hg(i,e),precompute:(t=8,i=e.BASE)=>i.precompute(t,!1)},lengths:s})}(e,i),f={prehash:!1,lowS:"boolean"==typeof i.lowS&&i.lowS,format:void 0,extraEntropy:!1},g="compact";function y(e,t){if(!a.isValidNot0(t))throw Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class m{constructor(e,t,i){this.r=y("r",e),this.s=y("s",t),null!=i&&(this.recovery=i),Object.freeze(this)}static fromBytes(e,t=g){var i,r;let s,n;if(i=e,ho(r=t),n=p.signature,cc(i,"compact"===r?n:"recovered"===r?n+1:void 0,`${r}
8 signature`),"der"===t){let{r:t,s:i}=hc.toSig(cc(e));return new m(t,i)}"recovered"===t&&(s=e[0],t="compact",e=e.subarray(1));let o=a.BYTES,l=e.subarray(0,o),c=e.subarray(o,2*o);return new m(a.fromBytes(l),a.fromBytes(c),s)}static fromHex(e,t){return this.fromBytes(ox(e),t)}addRecoveryBit(e){return new m(this.r,this.s,e)}recoverPublicKey(t){let i=n.ORDER,{r:r,s:s,recovery:l}=this;if(null==l||![0,1,2,3].includes(l))throw Error("recovery id invalid");if(o*hu<i&&l>1)throw Error("recovery id is ambiguous for h>1 curve");let c=2===l||3===l?r+o:r;if(!n.isValid(c))throw Error("recovery id 2 or 3 invalid");let h=n.toBytes(c),d=e.fromBytes(o_(hy((1&l)==0),h)),u=a.inv(c),p=b(cg("msgHash",t)),f=a.create(-p*u),g=a.create(s*u),y=e.BASE.multiplyUnsafe(f).add(d.multiplyUnsafe(g));if(y.is0())throw Error("point at infinify");return y.assertValidity(),y}hasHighS(){return this.s>o>>hd}toBytes(e=g){if(ho(e),"der"===e)return ox(hc.hexFromSig(this));let t=a.toBytes(this.r),i=a.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw Error("recovery bit must be present");return o_(Uint8Array.of(this.recovery),t,i)}return o_(t,i)}toHex(e){return oS(this.toBytes(e))}assertValidity(){}static fromCompact(e){return m.fromBytes(cg("sig",e),"compact")}static fromDER(e){return m.fromBytes(cg("sig",e),"der")}normalizeS(){return this.hasHighS()?new m(this.r,a.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return oS(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return oS(this.toBytes("compact"))}}let w=i.bits2int||function(e){if(e.length>8192)throw Error("input is too large");let t=cd(oS(e)),i=8*e.length-l;return i>0?t>>BigInt(i):t},b=i.bits2int_modN||function(e){return a.create(w(e))},v=cb(l);function E(e){return cm("num < 2^"+l,e,hh,v),a.toBytes(e)}function I(e,i){return cc(e,void 0,"message"),i?cc(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:c,getPublicKey:h,getSharedSecret:d,utils:u,lengths:p,Point:e,sign:function(i,n,l={}){let{seed:c,k2sig:h}=function(t,i,s){if(["recovered","canonical"].some(e=>e in s))throw Error("sign() legacy options not supported");let{lowS:n,prehash:l,extraEntropy:c}=hl(s,f),h=b(t=I(t,l)),d=hg(a,i),u=[E(d),E(h)];if(null!=c&&!1!==c){let e=!0===c?r(p.secretKey):c;u.push(cg("extraEntropy",e))}return{seed:o_(...u),k2sig:function(t){let i=w(t);if(!a.isValidNot0(i))return;let r=a.inv(i),s=e.BASE.multiply(i).toAffine(),l=a.create(s.x);if(l===hh)return;let c=a.create(r*a.create(h+l*d));if(c===hh)return;let u=2*(s.x!==l)|Number(s.y&hd),p=c;return n&&c>o>>hd&&(p=a.neg(c),u^=1),new m(l,p,u)}}}(i=cg("message",i),n,l);return(function(e,t,i){if("number"!=typeof e||e<2)throw Error("hashLen must be a number");if("number"!=typeof t||t<2)throw Error("qByteLen must be a number");if("function"!=typeof i)throw Error("hmacFn must be a function");let r=e=>new Uint8Array(e),s=r(e),n=r(e),a=0,o=()=>{s.fill(1),n.fill(0),a=0},l=(...e)=>i(n,s,...e),c=(e=r(0))=>{n=l(Uint8Array.of(0),e),s=l(),0!==e.length&&(n=l(Uint8Array.of(1),e),s=l())},h=()=>{if(a++>=1e3)throw Error("drbg: tried 1000 values");let e=0,i=[];for(;e<t;){let t=(s=l()).slice();i.push(t),e+=s.length}return o_(...i)};return(e,t)=>{let i;for(o(),c(e);!(i=t(h()));)c();return o(),i}})(t.outputLen,a.BYTES,s)(c,h)},verify:function(t,i,r,s={}){let{lowS:n,prehash:o,format:l}=hl(s,f);if(r=cg("publicKey",r),i=I(cg("message",i),o),"strict"in s)throw Error("options.strict was renamed to lowS");let c=void 0===l?function(e){let t,i="string"==typeof e||oo(e),r=!i&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!i&&!r)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(r)t=new m(e.r,e.s);else if(i){try{t=m.fromBytes(cg("sig",e),"der")}catch(e){if(!(e instanceof hc.Err))throw e}if(!t)try{t=m.fromBytes(cg("sig",e),"compact")}catch{return!1}}return t||!1}(t):m.fromBytes(cg("sig",t),l);if(!1===c)return!1;try{let t=e.fromBytes(r);if(n&&c.hasHighS())return!1;let{r:s,s:o}=c,l=b(i),h=a.inv(o),d=a.create(l*h),u=a.create(s*h),p=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(u));return!p.is0()&&a.create(p.x)===s}catch{return!1}},recoverPublicKey:function(e,t,i={}){let{prehash:r}
vendor: 4,575 bytes, line 8
8=hl(i,f);return t=I(t,r),m.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:m,hash:t})}(function(e,t={}){let i=function(e,t,i={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw Error(`expected valid ${e} CURVE object`);for(let e of["p","n","h"]){let i=t[e];if(!("bigint"==typeof i&&i>cF))throw Error(`CURVE.${e} must be positive bigint`)}let s=c3(t.p,i.Fp,r),n=c3(t.n,i.Fn,r);for(let i of["Gx","Gy","a","weierstrass"===e?"b":"d"])if(!s.isValid(t[i]))throw Error(`CURVE.${i} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:s,Fn:n}}("weierstrass",e,t),{Fp:r,Fn:s}=i,n=i.CURVE,{h:a,n:o}=n;cv(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:l}=t;if(l&&(!r.is0(n.a)||"bigint"!=typeof l.beta||!Array.isArray(l.basises)))throw Error('invalid endo: expected "beta": bigint and "basises": array');let c=hm(r,s);function h(){if(!r.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}let d=t.toBytes||function(e,t,i){let{x:s,y:n}=t.toAffine(),a=r.toBytes(s);return(cl(i,"isCompressed"),i)?(h(),o_(hy(!r.isOdd(n)),a)):o_(Uint8Array.of(4),a,r.toBytes(n))},u=t.fromBytes||function(e){cc(e,void 0,"Point");let{publicKey:t,publicKeyUncompressed:i}=c,s=e.length,n=e[0],a=e.subarray(1);if(s===t&&(2===n||3===n)){let e,t=r.fromBytes(a);if(!r.isValid(t))throw Error("bad point: is not on curve, wrong x");let i=p(t);try{e=r.sqrt(i)}catch(e){throw Error("bad point: is not on curve, sqrt error"+(e instanceof Error?": "+e.message:""))}return h(),(1&n)==1!==r.isOdd(e)&&(e=r.neg(e)),{x:t,y:e}}if(s===i&&4===n){let e=r.BYTES,t=r.fromBytes(a.subarray(0,e)),i=r.fromBytes(a.subarray(e,2*e));if(!f(t,i))throw Error("bad point: is not on curve");return{x:t,y:i}}throw Error(`bad point: got length ${s}, expected compressed=${t} or uncompressed=${i}`)};function p(e){let t=r.sqr(e),i=r.mul(t,e);return r.add(r.add(i,r.mul(e,n.a)),n.b)}function f(e,t){let i=r.sqr(t),s=p(e);return r.eql(i,s)}if(!f(n.Gx,n.Gy))throw Error("bad curve params: generator point");let g=r.mul(r.pow(n.a,hp),hf),y=r.mul(r.sqr(n.b),BigInt(27));if(r.is0(r.add(g,y)))throw Error("bad curve params: a or b");function m(e,t,i=!1){if(!r.isValid(t)||i&&r.is0(t))throw Error(`bad point coordinate ${e}`);return t}function w(e){if(!(e instanceof S))throw Error("ProjectivePoint expected")}function b(e){if(!l||!l.basises)throw Error("no endo");return function(e,t,i){let[[r,s],[n,a]]=t,o=ha(a*e,i),l=ha(-s*e,i),c=e-o*r-l*n,h=-o*s-l*a,d=c<hh,u=h<hh;d&&(c=-c),u&&(h=-h);let p=cb(Math.ceil(cw(i)/2))+hd;if(c<hh||c>=p||h<hh||h>=p)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:c,k2neg:u,k2:h}}(e,l.basises,s.ORDER)}let v=cE((e,t)=>{let{X:i,Y:s,Z:n}=e;if(r.eql(n,r.ONE))return{x:i,y:s};let a=e.is0();null==t&&(t=a?r.ONE:r.inv(n));let o=r.mul(i,t),l=r.mul(s,t),c=r.mul(n,t);if(a)return{x:r.ZERO,y:r.ZERO};if(!r.eql(c,r.ONE))throw Error("invZ was invalid");return{x:o,y:l}}),E=cE(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw Error("bad point: ZERO")}let{x:i,y:s}=e.toAffine();if(!r.isValid(i)||!r.isValid(s))throw Error("bad point: x or y not field elements");if(!f(i,s))throw Error("bad point: equation left != right");if(!e.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});function I(e,t,i,s,n){return i=new S(r.mul(i.X,e),i.Y,i.Z),t=cJ(s,t),i=cJ(n,i),t.add(i)}class S{constructor(e,t,i){this.X=m("x",e),this.Y=m("y",t,!0),this.Z=m("z",i),Object.freeze(this)}static CURVE(){return n}static fromAffine(e){let{x:t,y:i}=e||{};if(!e||!r.isValid(t)||!r.isValid(i))throw Error("invalid affine point");if(e instanceof S)throw Error("projective point not allowed");return r.is0(t)&&r.is0(i)?S.ZERO:new S(t,i,r.ONE)}static fromBytes(e){let t=S.fromAffine(u(cc(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return S.fromBytes(cg("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return x.createCache(this,e),t||this.multiply(hp),this}assertValidity(){E(this)}hasEvenY(){let{y:e}=this.toAffine();if(!r.isOdd)throw Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){w(e);let{X:t,Y:i,Z:s}=this,{X:n,Y:a,Z:o}=e,l=r.eql(r.mul(t,o),r.mul(n,s)),c=r.eql(r.mul(i,o),r.mul(a,s));return l&&c}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){let{a:e,b:t}=n,i=r.mul(t,hp),{X:s,Y:a,Z:o}=this,l=r.ZERO,c=r.ZERO,h=r.ZERO,d=r.mul(s,s),u=r.mul(a,a),p=r.mul(
vendor: 4,210 bytes, line 8
8o,o),f=r.mul(s,a);return f=r.add(f,f),h=r.mul(s,o),h=r.add(h,h),l=r.mul(e,h),c=r.mul(i,p),c=r.add(l,c),l=r.sub(u,c),c=r.add(u,c),c=r.mul(l,c),l=r.mul(f,l),h=r.mul(i,h),p=r.mul(e,p),f=r.sub(d,p),f=r.mul(e,f),f=r.add(f,h),h=r.add(d,d),d=r.add(h,d),d=r.add(d,p),d=r.mul(d,f),c=r.add(c,d),p=r.mul(a,o),p=r.add(p,p),d=r.mul(p,f),l=r.sub(l,d),h=r.mul(p,u),h=r.add(h,h),new S(l,c,h=r.add(h,h))}add(e){w(e);let{X:t,Y:i,Z:s}=this,{X:a,Y:o,Z:l}=e,c=r.ZERO,h=r.ZERO,d=r.ZERO,u=n.a,p=r.mul(n.b,hp),f=r.mul(t,a),g=r.mul(i,o),y=r.mul(s,l),m=r.add(t,i),b=r.add(a,o);m=r.mul(m,b),b=r.add(f,g),m=r.sub(m,b),b=r.add(t,s);let v=r.add(a,l);return b=r.mul(b,v),v=r.add(f,y),b=r.sub(b,v),v=r.add(i,s),c=r.add(o,l),v=r.mul(v,c),c=r.add(g,y),v=r.sub(v,c),d=r.mul(u,b),c=r.mul(p,y),d=r.add(c,d),c=r.sub(g,d),d=r.add(g,d),h=r.mul(c,d),g=r.add(f,f),g=r.add(g,f),y=r.mul(u,y),b=r.mul(p,b),g=r.add(g,y),y=r.sub(f,y),y=r.mul(u,y),b=r.add(b,y),f=r.mul(g,b),h=r.add(h,f),f=r.mul(v,b),c=r.mul(m,c),c=r.sub(c,f),f=r.mul(m,g),d=r.mul(v,d),new S(c,h,d=r.add(d,f))}subtract(e){return this.add(e.negate())}is0(){return this.equals(S.ZERO)}multiply(e){let i,r,{endo:n}=t;if(!s.isValidNot0(e))throw Error("invalid scalar: out of range");let a=e=>x.cached(this,e,e=>cG(S,e));if(n){let{k1neg:t,k1:s,k2neg:o,k2:l}=b(e),{p:c,f:h}=a(s),{p:d,f:u}=a(l);r=h.add(u),i=I(n.beta,c,d,t,o)}else{let{p:t,f:s}=a(e);i=t,r=s}return cG(S,[i,r])[0]}multiplyUnsafe(e){let{endo:i}=t;if(!s.isValid(e))throw Error("invalid scalar: out of range");if(e===hh||this.is0())return S.ZERO;if(e===hd)return this;if(x.hasCache(this))return this.multiply(e);if(!i)return x.unsafe(this,e);{let{k1neg:t,k1:r,k2neg:s,k2:n}=b(e),{p1:a,p2:o}=function(e,t,i,r){let s=t,n=e.ZERO,a=e.ZERO;for(;i>cF||r>cF;)i&cV&&(n=n.add(s)),r&cV&&(a=a.add(s)),s=s.double(),i>>=cV,r>>=cV;return{p1:n,p2:a}}(S,this,r,n);return I(i.beta,a,o,t,s)}}multiplyAndAddUnsafe(e,t,i){let r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(i));return r.is0()?void 0:r}toAffine(e){return v(this,e)}isTorsionFree(){let{isTorsionFree:e}=t;return a===hd||(e?e(S,this):x.unsafe(this,o).is0())}clearCofactor(){let{clearCofactor:e}=t;return a===hd?this:e?e(S,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(e=!0){return cl(e,"isCompressed"),this.assertValidity(),d(S,this,e)}toHex(e=!0){return oS(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return cG(S,e)}static msm(e,t){return function(e,t,i,r){(function(e,t){if(!Array.isArray(e))throw Error("array expected");e.forEach((e,i)=>{if(!(e instanceof t))throw Error("invalid point at index "+i)})})(i,e),function(e,t){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach((e,i)=>{if(!t.isValid(e))throw Error("invalid scalar at index "+i)})}(r,t);let s=i.length,n=r.length;if(s!==n)throw Error("arrays of points and scalars must have equal length");let a=e.ZERO,o=cw(BigInt(s)),l=1;o>12?l=o-3:o>4?l=o-2:o>0&&(l=2);let c=cb(l),h=Array(Number(c)+1).fill(a),d=Math.floor((t.BITS-1)/l)*l,u=a;for(let e=d;e>=0;e-=l){h.fill(a);for(let t=0;t<n;t++){let s=Number(r[t]>>BigInt(e)&c);h[s]=h[s].add(i[t])}let t=a;for(let e=h.length-1,i=a;e>0;e--)i=i.add(h[e]),t=t.add(i);if(u=u.add(t),0!==e)for(let e=0;e<l;e++)u=u.double()}return u}(S,s,e,t)}static fromPrivateKey(e){return S.BASE.multiply(hg(s,e))}}S.BASE=new S(n.Gx,n.Gy,r.ONE),S.ZERO=new S(r.ZERO,r.ONE,r.ZERO),S.Fp=r,S.Fn=s;let A=s.BITS,x=new c5(S,t.endo?Math.ceil(A/2):A);return S.BASE.precompute(8),S}(i,r),s,n);return t=a.Point,Object.assign({},a,{ProjectivePoint:t,CURVE:Object.assign({},e,cH(t.Fn.ORDER,t.Fn.BITS))})})({...e,hash:t});return{...i(t),create:i}}let hb={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),G
8y:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},hv={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},hE={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},hI=c$(hb.p),hS=c$(hv.p),hA=c$(hE.p),hx=hw({...hb,Fp:hI,lowS:!1},le);hw({...hv,Fp:hS,lowS:!1},li),hw({...hE,Fp:hA,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},lt);let hP="base10",hC="base16",h_="base64pad",hk="base64url",hO="utf8";function hT(){let e=oT(32);return(0,nV.toString)(e,hC)}function hR(e){let t=le((0,nJ.fromString)(e,hC));return(0,nV.toString)(t,hC)}function hN(e){let t=le((0,nJ.fromString)(e,hO));return(0,nV.toString)(t,hC)}function hj(e){return(0,nJ.fromString)(`${e}`,hP)}function hD(e){return Number((0,nV.toString)(e,hP))}function hM(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hU(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4;return t+"=".repeat(i)}function hB(e){if(2===hD(e.type))return(0,nV.toString)((0,nG.concat)([e.type,e.sealed]),h_);if(1===hD(e.type)){if(typeof e.senderPublicKey>"u")throw Error("Missing sender public key for type 1 envelope");return(0,nV.toString)((0,nG.concat)([e.type,e.senderPublicKey,e.iv,e.sealed]),h_)}return(0,nV.toString)((0,nG.concat)([e.type,e.iv,e.sealed]),h_)}function hL(e){let t=(e.encoding||h_)===hk?hU(e.encoded):e.encoded,i=(0,nJ.fromString)(t,h_),r=i.slice(0,1);if(1===hD(r)){let e=i.slice(1,33),t=i.slice(33,45);return{type:r,sealed:i.slice(45),iv:t,senderPublicKey:e}}if(2===hD(r))return{type:r,sealed:i.slice(1),iv:oT(12)};let s=i.slice(1,13);return{type:r,sealed:i.slice(13),iv:s}}function hq(e){let t=e?.type||0;if(1===t){if(typeof e?.senderPublicKey>"u")throw Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function hK(e){return 1===e.type&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function hH(e){return e?.relay||{protocol:"irn"}}function h$(e){let t=nY.RELAY_JSONRPC[e];if(typeof t>"u")throw Error(`Relay Protocol not supported: ${e}`);return t}var hW=Object.defineProperty,hz=Object.defineProperties,hF=Object.getOwnPropertyDescriptors,hV=Object.getOwnPropertySymbols,hJ=Object.prototype.hasOwnProperty,hG=Object.prototype.propertyIsEnumerable,hY=(e,t,i)=>t in e?hW(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,hZ=(e,t)=>{for(var i in t||(t={}))hJ.call(t,i)&&hY(e,i,t[i]);if(hV)for(var i of hV(t))hG.call(t,i)&&hY(e,i,t[i]);return e};function hQ(e){var t;if(!e.includes("wc:")){let t=aZ(e);null!=t&&t.includes("wc:")&&(e=t)}let i=(e=(e=e.includes("wc://")?e.replace("wc://",""):e).includes("wc:")?e.replace("wc:",""):e).indexOf(":"),r=-1!==e.indexOf("?")?e.indexOf("?"):void 0,s=e.substring(0,i),n=e.substring(i+1,r).split("@"),a=Object.fromEntries(new URLSearchParams("u">typeof r?e.substring(r):"").entries()),o="string"==typeof a.methods?a.methods.split(","):void 0;return{protocol:s,topic:(t=n[0]).startsWith("//")?t.substring(2):t,version:parseInt(n[1],10),symKey:a.symKey,relay:function(e,t="-"){let i={},r="relay"+t;return Object.keys(e).forEach(t=>{if(t.startsWith(r)){let s=t.replace(r,""),n=e[t];i[s]=n}}),i}(a),methods:o,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function hX(e){let t=new URLSearchParams;return Object.entries(hZ(hZ(hz(hZ({},function(e,t="-"){let i={};return Object.keys(e).forEach(r=>{e[r]&&(i["relay"+t+r]=e[r])}),i}(e.relay)),hF({symKey:e.symKey})),e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()}),e.methods&&{methods:e.methods.join(",")})).sort(([e],[t])=>
8e.localeCompare(t)).forEach(([e,i])=>{void 0!==i&&t.append(e,String(i))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function h0(e,t,i){return`${e}?wc_ev=${i}&topic=${t}`}var h1=Object.defineProperty,h2=Object.defineProperties,h5=Object.getOwnPropertyDescriptors,h3=Object.getOwnPropertySymbols,h8=Object.prototype.hasOwnProperty,h6=Object.prototype.propertyIsEnumerable,h4=(e,t,i)=>t in e?h1(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,h7=(e,t)=>{for(var i in t||(t={}))h8.call(t,i)&&h4(e,i,t[i]);if(h3)for(var i of h3(t))h6.call(t,i)&&h4(e,i,t[i]);return e},h9=(e,t)=>h2(e,h5(t));function de(e){let t=[];return e.forEach(e=>{let[i,r]=e.split(":");t.push(`${i}:${r}`)}),t}function dt(e){return e.includes(":")}function di(e){return dt(e)?e.split(":")[0]:e}function dr(e){var t,i,r;let s={};if(!dd(e))return s;for(let[n,a]of Object.entries(e)){let e=dt(n)?[n]:a.chains,o=a.methods||[],l=a.events||[],c=di(n);s[c]=h9(h7({},s[c]),{chains:az(e,null==(t=s[c])?void 0:t.chains),methods:az(o,null==(i=s[c])?void 0:i.methods),events:az(l,null==(r=s[c])?void 0:r.events)})}return s}function ds(e,t){var i;let r,s=(i=t=t.map(e=>e.replace("did:pkh:","")),r={},i?.forEach(e=>{var t;let[i,s]=e.split(":");r[i]||(r[i]={accounts:[],chains:[],events:[],methods:[]}),r[i].accounts.push(e),null==(t=r[i].chains)||t.push(`${i}:${s}`)}),r);for(let[t,i]of Object.entries(s))i.methods?i.methods=az(i.methods,e):i.methods=e,i.events=["chainChanged","accountsChanged"];return s}let dn={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}},da={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 dl(e,t){let{message:i,code:r}=da[e];return{message:t?`${i} ${t}`:i,code:r}}function dc(e,t){let{message:i,code:r}=dn[e];return{message:t?`${i} ${t}`:i,code:r}}function dh(e,t){return!!Array.isArray(e)&&(!("u">typeof t)||!e.length||e.every(t))}function dd(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function du(e){return typeof e>"u"}function dp(e,t){return!!(t&&du(e))||"string"==typeof e&&!!e.trim().length}function df(e,t){return!!(t&&du(e))||"number"==typeof e&&!isNaN(e)}function dg(e){return!!(dp(e,!1)&&e.includes(":"))&&2===e.split(":").length}function dy(e){let t=!0;return dh(e)?e.length&&(t=e.every(e=>dp(e,!1))):t=!1,t}function dm(e,t){let i=null;return Object.values(e).forEach(e=>{var r;let s;if(i)return;let n=(r=`${t}, namespace`,s=null,dy(e?.methods)?dy(e?.events)||(s=dc("UNSUPPORTED_EVENTS",`${r}
8, events should be an array of strings or empty array for no events`)):s=dc("UNSUPPORTED_METHODS",`${r}, methods should be an array of strings or empty array for no methods`),s);n&&(i=n)}),i}function dw(e,t){let i=null;if(e&&dd(e)){let r,s=dm(e,t);s&&(i=s);let n=(r=null,Object.values(e).forEach(e=>{var i,s;let n;if(r)return;let a=(i=e?.accounts,s=`${t} namespace`,n=null,dh(i)?i.forEach(e=>{n||function(e){if(dp(e,!1)&&e.includes(":")){let t=e.split(":");if(3===t.length){let e=t[0]+":"+t[1];return!!t[2]&&dg(e)}}return!1}(e)||(n=dc("UNSUPPORTED_ACCOUNTS",`${s}, account ${e} should be a string and conform to "namespace:chainId:address" format`))}):n=dc("UNSUPPORTED_ACCOUNTS",`${s}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n);a&&(r=a)}),r);n&&(i=n)}else i=dl("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return i}function db(e){return dp(e.protocol,!0)}function dv(e){return"u">typeof e}function dE(e,t){let i;return!(!dg(t)||!(i=[],Object.values(e).forEach(e=>{i.push(...de(e.accounts))}),i).includes(t))}function dI(e,t,i){var r,s;let n,a,o=null,l=(n={},Object.keys(r=e).forEach(e=>{var t;e.includes(":")?n[e]=r[e]:null==(t=r[e].chains)||t.forEach(t=>{n[t]={methods:r[e].methods,events:r[e].events}})}),n),c=(a={},Object.keys(s=t).forEach(e=>{if(e.includes(":"))a[e]=s[e];else{let t=de(s[e].accounts);t?.forEach(t=>{a[t]={accounts:s[e].accounts.filter(e=>e.includes(`${t}:`)),methods:s[e].methods,events:s[e].events}})}}),a),h=Object.keys(l),d=Object.keys(c),u=dS(Object.keys(e)),p=dS(Object.keys(t)),f=u.filter(e=>!p.includes(e));return f.length&&(o=dl("NON_CONFORMING_NAMESPACES",`${i} namespaces keys don't satisfy requiredNamespaces.
9      Required: ${f.toString()}
10      Received: ${Object.keys(t).toString()}`)),aD(h,d)||(o=dl("NON_CONFORMING_NAMESPACES",`${i} namespaces chains don't satisfy required namespaces.
11      Required: ${h.toString()}
12      Approved: ${d.toString()}`)),Object.keys(t).forEach(e=>{if(!e.includes(":")||o)return;let r=de(t[e].accounts);r.includes(e)||(o=dl("NON_CONFORMING_NAMESPACES",`${i} namespaces accounts don't satisfy namespace accounts for ${e}
13        Required: ${e}
14        Approved: ${r.toString()}`))}),h.forEach(e=>{o||(aD(l[e].methods,c[e].methods)?aD(l[e].events,c[e].events)||(o=dl("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${e}`)):o=dl("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${e}`))}),o}function dS(e){return[...new Set(e.map(e=>e.includes(":")?e.split(":")[0]:e))]}function dA(){let e=aT();return new Promise(t=>{switch(e){case aC:t(aO()&&navigator?.onLine);break;case ax:t(dx());break;default:t(!0)}})}async function dx(){if(ak()&&null!=e.g&&e.g.NetInfo){let t=await (null==e.g?void 0:e.g.NetInfo.fetch());return t?.isConnected}return!0}let dP={};class dC{static get(e){return dP[e]}static set(e,t){dP[e]=t}static delete(e){delete dP[e]}}function d_(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function dk({logger:e,name:t}){let i="string"==typeof e?au({opts:{level:e,name:t}}).logger:e;return i.level="string"==typeof e?e:e.level,i}var dO=e.i(180476),dT=e.i(499276),dR=e.i(81775),dN=Object.defineProperty,dj=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?dN(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class dD extends dR.IEvents{constructor(e){super(),this.opts=e,dj(this,"protocol","wc"),dj(this,"version",2)}}var dM=Object.defineProperty;class dU extends dR.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,((e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?dM(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(this,"records",new Map)}}class dB{constructor(e,t){this.logger=e,this.core=t}}class dL extends dR.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}class dq extends dR.IEvents{constructor(e){super()}}class dK{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}}class dH extends dR.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}class d$ extends dR.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}}class dW{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}}class dz{constructor(e,t){this.projectId=e,this.logger=t}}class dF{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}}var dV=Object.defineProperty,dJ=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?dV(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};rE.default;class dG{constructor(e){this.opts=e,dJ(this,"protocol","wc"),dJ(this,"version",2)}}rE.EventEmitter;
14class dY{constructor(e){this.client=e}}var dZ=e.i(501365);e.i(424047);var dQ=e.i(329193),dX=e.i(850967),d0=e.i(112324);let d1="core",d2=`wc@2:${d1}:`,d5={database:":memory:"},d3="client_ed25519_seed",d8=rA.ONE_DAY,d6=rA.SIX_HOURS,d4="wss://relay.walletconnect.org",d7="relayer_message",d9="relayer_message_ack",ue="relayer_connection_stalled",ut="relayer_publish",ui="payload",ur="connect",us="disconnect",un="error",ua="2.22.4",uo="link_mode",ul="relay",uc="inbound",uh="WALLETCONNECT_LINK_MODE_APPS",ud="subscription_created",uu="subscription_deleted",up=(rA.THIRTY_DAYS,rA.FIVE_SECONDS,rA.THIRTY_DAYS,{wc_pairingDelete:{req:{ttl:rA.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:rA.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:rA.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:rA.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:rA.ONE_DAY,prompt:!1,tag:0},res:{ttl:rA.ONE_DAY,prompt:!1,tag:0}}}),uf="pairing_create",ug="pairing_delete",uy="history_created",um="history_updated",uw="history_deleted",ub="expirer_created",uv="expirer_deleted",uE="expirer_expired",uI=(rA.ONE_DAY,"https://verify.walletconnect.org"),uS=`${uI}/v3`,uA=["https://verify.walletconnect.com",uI],ux="malformed_pairing_uri",uP="session_approve_started";var uC=function(e,t){if(e.length>=255)throw TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var s=0;s<e.length;s++){var n=e.charAt(s),a=n.charCodeAt(0);if(255!==i[a])throw TypeError(n+" is ambiguous");i[a]=s}var o=e.length,l=e.charAt(0),c=Math.log(o)/Math.log(256),h=Math.log(256)/Math.log(o);function d(e){if("string"!=typeof e)throw TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[0]){for(var r=0,s=0;e[t]===l;)r++,t++;for(var n=(e.length-t)*c+1>>>0,a=new Uint8Array(n);e[t];){var h=i[e.charCodeAt(t)];if(255===h)return;for(var d=0,u=n-1;(0!==h||d<s)&&-1!==u;u--,d++)h+=o*a[u]>>>0,a[u]=h%256>>>0,h=h/256>>>0;if(0!==h)throw Error("Non-zero carry");s=d,t++}if(" "!==e[t]){for(var p=n-s;p!==n&&0===a[p];)p++;for(var f=new Uint8Array(r+(n-p)),g=r;p!==n;)f[g++]=a[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,r=0,s=0,n=t.length;s!==n&&0===t[s];)s++,i++;for(var a=(n-s)*h+1>>>0,c=new Uint8Array(a);s!==n;){for(var d=t[s],u=0,p=a-1;(0!==d||u<r)&&-1!==p;p--,u++)d+=256*c[p]>>>0,c[p]=d%o>>>0,d=d/o>>>0;if(0!==d)throw Error("Non-zero carry");r=u,s++}for(var f=a-r;f!==a&&0===c[f];)f++;for(var g=l.repeat(i);f<a;++f)g+=e.charAt(c[f]);return g},decodeUnsafe:d,decode:function(e){var i=d(e);if(i)return i;throw Error(`Non-${t} character`)}}};let u_=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unknown type, must be binary type")};class uk{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class uO{constructor(e,t,i){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return uR(this,e)}}class uT{constructor(e){this.decoders=e}or(e){return uR(this,e)}decode(e){let t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}let uR=(e,t)=>new uT({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class uN{constructor(e,t,i,r){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=r,this.encoder=new uk(e,t,i),this.decoder=new uO(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}let uj=({name:e,prefix:t,encode:i,decode:r})=>new uN(e,t,i,r),uD=({prefix:e,name:t,alphabet:i})=>{let{encode:r,decode:s}=uC(i,t);return uj({prefix:e,name:t,encode:r,decode:e=>u_(s(e))})}
14,uM=({name:e,prefix:t,bitsPerChar:i,alphabet:r})=>uj({prefix:t,name:e,encode:e=>((e,t,i)=>{let r="="===t[t.length-1],s=(1<<i)-1,n="",a=0,o=0;for(let r=0;r<e.length;++r)for(o=o<<8|e[r],a+=8;a>i;)a-=i,n+=t[s&o>>a];if(a&&(n+=t[s&o<<i-a]),r)for(;n.length*i&7;)n+="=";return n})(e,r,i),decode:t=>((e,t,i,r)=>{let s={};for(let e=0;e<t.length;++e)s[t[e]]=e;let n=e.length;for(;"="===e[n-1];)--n;let a=new Uint8Array(n*i/8|0),o=0,l=0,c=0;for(let t=0;t<n;++t){let n=s[e[t]];if(void 0===n)throw SyntaxError(`Non-${r} character`);l=l<<i|n,(o+=i)>=8&&(o-=8,a[c++]=255&l>>o)}if(o>=i||255&l<<8-o)throw SyntaxError("Unexpected end of data");return a})(t,r,i,e)});var uU=Object.freeze({__proto__:null,identity:uj({prefix:"\0",name:"identity",encode:e=>new TextDecoder().decode(e),decode:e=>new TextEncoder().encode(e)})}),uB=Object.freeze({__proto__:null,base2:uM({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})}),uL=Object.freeze({__proto__:null,base8:uM({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})}),uq=Object.freeze({__proto__:null,base10:uD({prefix:"9",name:"base10",alphabet:"0123456789"})}),uK=Object.freeze({__proto__:null,base16:uM({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper:uM({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})}),uH=Object.freeze({__proto__:null,base32:uM({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper:uM({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad:uM({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper:uM({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex:uM({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper:uM({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad:uM({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper:uM({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z:uM({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})}),u$=Object.freeze({__proto__:null,base36:uD({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper:uD({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})}),uW=Object.freeze({__proto__:null,base58btc:uD({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr:uD({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})}),uz=Object.freeze({__proto__:null,base64:uM({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad:uM({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url:uM({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad:uM({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});let uF=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),uV=uF.reduce((e,t,i)=>(e[i]=t,e),[]),uJ=uF.reduce((e,t,i)=>(e[t.codePointAt(0)]=i,e),[]);var uG=Object.freeze({__proto__:null,base256emoji:uj({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>
14e+=uV[t],"")},decode:function(e){let t=[];for(let i of e){let e=uJ[i.codePointAt(0)];if(void 0===e)throw Error(`Non-base256emoji character: ${i}`);t.push(e)}return new Uint8Array(t)}})});function uY(e,t,i){t=t||[],i=i||0;for(var r=i;e>=0x80000000;)t[i++]=255&e|128,e/=128;for(;-128&e;)t[i++]=255&e|128,e>>>=7;return t[i]=0|e,uY.bytes=i-r+1,t}var uZ=function(e){return e<128?1:e<16384?2:e<2097152?3:e<0x10000000?4:e<0x800000000?5:e<0x40000000000?6:e<0x2000000000000?7:e<0x100000000000000?8:e<0x8000000000000000?9:10};let uQ=(e,t,i=0)=>(uY(e,t,i),t),uX=(e,t)=>{let i=t.byteLength,r=uZ(e),s=r+uZ(i),n=new Uint8Array(s+i);return uQ(e,n,0),uQ(i,n,r),n.set(t,s),new u0(e,i,t,n)};class u0{constructor(e,t,i,r){this.code=e,this.size=t,this.digest=i,this.bytes=r}}let u1=({name:e,code:t,encode:i})=>new u2(e,t,i);class u2{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?uX(this.code,t):t.then(e=>uX(this.code,e))}throw Error("Unknown type, must be binary type")}}let u5=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t));var u3=Object.freeze({__proto__:null,sha256:u1({name:"sha2-256",code:18,encode:u5("SHA-256")}),sha512:u1({name:"sha2-512",code:19,encode:u5("SHA-512")})}),u8=Object.freeze({__proto__:null,identity:{code:0,name:"identity",encode:u_,digest:e=>uX(0,u_(e))}});new TextEncoder,new TextDecoder;let u6={...uU,...uB,...uL,...uq,...uK,...uH,...u$,...uW,...uz,...uG};function u4(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function u7(e,t,i,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:i},decoder:{decode:r}}}({...u3,...u8});let u9=u7("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),pe=u7("ascii","a",e=>{let t="a";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t},e=>{let t=function(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?u4(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}((e=e.substring(1)).length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}),pt={utf8:u9,"utf-8":u9,hex:u6.base16,latin1:pe,ascii:pe,binary:pe,...u6};var pi=Object.defineProperty,pr=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?pi(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class ps{constructor(e,t){this.core=e,this.logger=t,pr(this,"keychain",new Map),pr(this,"name","keychain"),pr(this,"version","0.3"),pr(this,"initialized",!1),pr(this,"storagePrefix",d2),pr(this,"init",async()=>{if(!this.initialized){let e=await this.getKeyChain();"u">typeof e&&(this.keychain=e),this.initialized=!0}}),pr(this,"has",e=>(this.isInitialized(),this.keychain.has(e))),pr(this,"set",async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()}),pr(this,"get",e=>{this.isInitialized();let t=this.keychain.get(e);if(typeof t>"u"){let{message:t}=dl("NO_MATCHING_KEY",`${this.name}: ${e}`);throw Error(t)}return t}),pr(this,"del",async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()}),this.core=e,this.logger=ad(t,this.name)}get context(){return ah(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,aM(e))}async getKeyChain(){let e=await this.core.storage.getItem(this.storageKey);return"u">typeof e?aU(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:e}=dl("NOT_INITIALIZED",this.name);throw Error(e)}}}var pn=Object.defineProperty,pa=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?pn(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class po{constructor(e,t,i){this.core=e,this.logger=t,pa(this,"name","crypto"),pa(this,"keychain"),pa(this,"randomSessionIdentifier",hT()),pa(this,"initialized",!1),pa(this,"clientId"),pa(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),pa(this,"hasKeys",e=>(this.isInitialized(),this.keychain.has(e))),pa(this,"getClientId",async()=>
14{if(this.isInitialized(),this.clientId)return this.clientId;let e=await this.getClientSeed(),t=nF.generateKeyPair(e),i=nF.encodeIss(t.publicKey);return this.clientId=i,i}),pa(this,"generateKeyPair",()=>{let e,t;this.isInitialized();let i=(e=hn.utils.randomPrivateKey(),t=hn.getPublicKey(e),{privateKey:(0,nV.toString)(e,hC),publicKey:(0,nV.toString)(t,hC)});return this.setPrivateKey(i.publicKey,i.privateKey)}),pa(this,"signJWT",async e=>{this.isInitialized();let t=await this.getClientSeed(),i=nF.generateKeyPair(t),r=this.randomSessionIdentifier;return await nF.signJWT(r,e,d8,i)}),pa(this,"generateSharedKey",(e,t,i)=>{var r,s,n;let a,o;this.isInitialized();let l=(r=this.getPrivateKey(e),a=hn.getSharedSecret((0,nJ.fromString)(r,hC),(0,nJ.fromString)(t,hC)),s=void 0,o=function(e,t,i,r=32){oh(e),ol(r);let s=e.outputLen;if(r>255*s)throw Error("Length should be <= 255*HashLen");let n=Math.ceil(r/s);void 0===i&&(i=cn);let a=new Uint8Array(n*s),o=cr.create(e,t),l=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let e=0;e<n;e++)cs[0]=e+1,l.update(0===e?cn:c).update(i).update(cs).digestInto(c),a.set(c,s*e),o._cloneInto(l);return o.destroy(),l.destroy(),of(c,cs),a.slice(0,r)}(le,(n=void 0,oh(le),void 0===n&&(n=new Uint8Array(le.outputLen)),cr(le,oC(n),oC(a))),s,32),(0,nV.toString)(o,hC));return this.setSymKey(l,i)}),pa(this,"setSymKey",async(e,t)=>{this.isInitialized();let i=t||hR(e);return await this.keychain.set(i,e),i}),pa(this,"deleteKeyPair",async e=>{this.isInitialized(),await this.keychain.del(e)}),pa(this,"deleteSymKey",async e=>{this.isInitialized(),await this.keychain.del(e)}),pa(this,"encode",async(e,t,i)=>{this.isInitialized();let r=hq(i),s=(0,nX.safeJsonStringify)(t);if(2===r.type){var n;let e,t,r;return n=i?.encoding,e=hj(2),t=oT(12),r=hB({type:e,sealed:(0,nJ.fromString)(s,hO),iv:t}),n===hk?hM(r):r}if(hK(r)){let t=r.senderPublicKey,i=r.receiverPublicKey;e=await this.generateSharedKey(t,i)}let a=this.getSymKey(e),{type:o,senderPublicKey:l}=r;return function(e){let t=hj("u">typeof e.type?e.type:0);if(1===hD(t)&&typeof e.senderPublicKey>"u")throw Error("Missing sender public key for type 1 envelope");let i="u">typeof e.senderPublicKey?(0,nJ.fromString)(e.senderPublicKey,hC):void 0,r="u">typeof e.iv?(0,nJ.fromString)(e.iv,hC):oT(12),s=hB({type:t,sealed:ct((0,nJ.fromString)(e.symKey,hC),r).encrypt((0,nJ.fromString)(e.message,hO)),iv:r,senderPublicKey:i});return e.encoding===hk?hM(s):s}({type:o,symKey:a,message:s,senderPublicKey:l,encoding:i?.encoding})}),pa(this,"decode",async(e,t,i)=>{let r;this.isInitialized();let s=hq({type:hD((r=hL({encoded:t,encoding:i?.encoding})).type),senderPublicKey:"u">typeof r.senderPublicKey?(0,nV.toString)(r.senderPublicKey,hC):void 0,receiverPublicKey:i?.receiverPublicKey});if(2===s.type){let e=function(e,t){let{sealed:i}=hL({encoded:e,encoding:t});return(0,nV.toString)(i,hO)}(t,i?.encoding);return(0,nX.safeJsonParse)(e)}if(hK(s)){let t=s.receiverPublicKey,i=s.senderPublicKey;e=await this.generateSharedKey(t,i)}try{let r=this.getSymKey(e),s=function(e){let t=(0,nJ.fromString)(e.symKey,hC),{sealed:i,iv:r}=hL({encoded:e.encoded,encoding:e.encoding}),s=ct(t,r).decrypt(i);if(null===s)throw Error("Failed to decrypt");return(0,nV.toString)(s,hO)}({symKey:r,encoded:t,encoding:i?.encoding});return(0,nX.safeJsonParse)(s)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}}),pa(this,"getPayloadType",(e,t=h_)=>hD(hL({encoded:e,encoding:t}).type)),pa(this,"getPayloadSenderPublicKey",(e,t=h_)=>{let i=hL({encoded:e,encoding:t});return i.senderPublicKey?(0,nV.toString)(i.senderPublicKey,hC):void 0}),this.core=e,this.logger=ad(t,this.name),this.keychain=i||new ps(this.core,this.logger)}get context(){return ah(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(d3)}catch{e=hT(),await this.keychain.set(d3,e)}return function(e,t="utf8"){let i=pt[t];if(!i)throw Error(`Unsupported encoding "${t}"`);return("utf8"===t||"utf-8"===t)&&null!=globalThis.Buffer&&null!=globalThis.Buffer.from?u4(globalThis.Buffer.from(e,"utf-8")):i.decoder.decode(`${i.prefix}${e}`)}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){let{message:e}=dl("NOT_INITIALIZED",this.name);throw Error(e)}}}var pl=Object.defineProperty,pc=Object.defineProperties,ph=Object.getOwnPropertyDescriptors,pd=Object.getOwnPropertySymbols,pu=Object.prototype.hasOwnProperty,pp=Object.prototype.propertyIsEnumerable,pf=(e,t,i)=>t in e?pl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,pg=(e,t,i)=>pf(e,"symbol"!=typeof t?t+"":t,i);class py extends dB{constructor(e,t){super(e,t),this.logger=e,this.core=t,pg(this,"messages",new Map),pg(this,"messagesWithoutClientAck",new Map),pg(this,"name","messages"),pg(this,"version","0.3"),pg(this,"initialized",!1),pg(this,"storagePrefix",d2),pg(this,"init",async()=>
14{if(!this.initialized){this.logger.trace("Initialized");try{let e=await this.getRelayerMessages();"u">typeof e&&(this.messages=e);let t=await this.getRelayerMessagesWithoutClientAck();"u">typeof t&&(this.messagesWithoutClientAck=t),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}}),pg(this,"set",async(e,t,i)=>{this.isInitialized();let r=hN(t),s=this.messages.get(e);if(typeof s>"u"&&(s={}),"u">typeof s[r])return r;if(s[r]=t,this.messages.set(e,s),i===uc){let i=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,pc(((e,t)=>{for(var i in t||(t={}))pu.call(t,i)&&pf(e,i,t[i]);if(pd)for(var i of pd(t))pp.call(t,i)&&pf(e,i,t[i]);return e})({},i),ph({[r]:t})))}return await this.persist(),r}),pg(this,"get",e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t}),pg(this,"getWithoutAck",e=>{this.isInitialized();let t={};for(let i of e){let e=this.messagesWithoutClientAck.get(i)||{};t[i]=Object.values(e)}return t}),pg(this,"has",(e,t)=>(this.isInitialized(),"u">typeof this.get(e)[hN(t)])),pg(this,"ack",async(e,t)=>{this.isInitialized();let i=this.messagesWithoutClientAck.get(e);if(typeof i>"u")return;let r=hN(t);delete i[r],0===Object.keys(i).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,i),await this.persist()}),pg(this,"del",async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()}),this.logger=ad(e,this.name),this.core=t}get context(){return ah(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,aM(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,aM(e))}async getRelayerMessages(){let e=await this.core.storage.getItem(this.storageKey);return"u">typeof e?aU(e):void 0}async getRelayerMessagesWithoutClientAck(){let e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return"u">typeof e?aU(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){let{message:e}=dl("NOT_INITIALIZED",this.name);throw Error(e)}}}var pm=Object.defineProperty,pw=Object.defineProperties,pb=Object.getOwnPropertyDescriptors,pv=Object.getOwnPropertySymbols,pE=Object.prototype.hasOwnProperty,pI=Object.prototype.propertyIsEnumerable,pS=(e,t,i)=>t in e?pm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,pA=(e,t)=>{for(var i in t||(t={}))pE.call(t,i)&&pS(e,i,t[i]);if(pv)for(var i of pv(t))pI.call(t,i)&&pS(e,i,t[i]);return e},px=(e,t,i)=>pS(e,"symbol"!=typeof t?t+"":t,i);class pP extends dL{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,px(this,"events",new rE.EventEmitter),px(this,"name","publisher"),px(this,"queue",new Map),px(this,"publishTimeout",(0,rA.toMiliseconds)(rA.ONE_MINUTE)),px(this,"initialPublishTimeout",(0,rA.toMiliseconds)(15*rA.ONE_SECOND)),px(this,"needsTransportRestart",!1),px(this,"publish",async(e,t,i)=>{var r,s,n,a,o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:i}});let l=i?.ttl||d6,c=i?.prompt||!1,h=i?.tag||0,d=i?.id||(0,dQ.getBigIntRpcId)().toString(),u=h$(hH().protocol),p={id:d,method:i?.publishMethod||u.publish,params:pA({topic:e,message:t,ttl:l,prompt:c,tag:h,attestation:i?.attestation},i?.tvf)},f=`Failed to publish payload, please try again. id:${d} tag:${h}`;try{du(null==(r=p.params)?void 0:r.prompt)&&(null==(s=p.params)||delete s.prompt),du(null==(n=p.params)?void 0:n.tag)&&(null==(a=p.params)||delete a.tag);let o=new Promise(async e=>{let t=({id:i})=>{var r;(null==(r=p.id)?void 0:r.toString())===i.toString()&&(this.removeRequestFromQueue(i),this.relayer.events.removeListener(ut,t),e())};this.relayer.events.on(ut,t);let r=aL(new Promise((e,t)=>
14{this.rpcPublish(p,i).then(e).catch(e=>{this.logger.warn(e,e?.message),t(e)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${h}`);try{await r,this.events.removeListener(ut,t)}catch(e){this.queue.set(d,{request:p,opts:i,attempt:1}),this.logger.warn(e,e?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:e,message:t,opts:i}}),await aL(o,this.publishTimeout,f)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),null!=(o=i?.internal)&&o.throwOnFailedPublish)throw e}finally{this.queue.delete(d)}}),px(this,"publishCustom",async e=>{var t,i,r,s,n;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:e});let{payload:a,opts:o={}}=e,{attestation:l,tvf:c,publishMethod:h,prompt:d,tag:u,ttl:p=rA.FIVE_MINUTES}=o,f=o.id||(0,dQ.getBigIntRpcId)().toString(),g=h$(hH().protocol),y=h||g.publish,m={id:f,method:y,params:pA(pw(pA({},a),pb({ttl:p,prompt:d,tag:u,attestation:l})),c)},w=`Failed to publish custom payload, please try again. id:${f} tag:${u}`;try{du(null==(t=m.params)?void 0:t.prompt)&&(null==(i=m.params)||delete i.prompt),du(null==(r=m.params)?void 0:r.tag)&&(null==(s=m.params)||delete s.tag);let e=new Promise(async e=>{let t=({id:i})=>{var r;(null==(r=m.id)?void 0:r.toString())===i.toString()&&(this.removeRequestFromQueue(i),this.relayer.events.removeListener(ut,t),e())};this.relayer.events.on(ut,t);let i=aL(new Promise((e,t)=>{this.rpcPublish(m,o).then(e).catch(e=>{this.logger.warn(e,e?.message),t(e)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${y} id:${f} tag:${u}`);try{await i,this.events.removeListener(ut,t)}catch(e){this.queue.set(f,{request:m,opts:o,attempt:1}),this.logger.warn(e,e?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:f,payload:a,opts:o}}),await aL(e,this.publishTimeout,w)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),null!=(n=o?.internal)&&n.throwOnFailedPublish)throw e}finally{this.queue.delete(f)}}),px(this,"on",(e,t)=>{this.events.on(e,t)}),px(this,"once",(e,t)=>{this.events.once(e,t)}),px(this,"off",(e,t)=>{this.events.off(e,t)}),px(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.relayer=e,this.logger=ad(t,this.name),this.registerEventListeners()}get context(){return ah(this.logger)}async rpcPublish(e,t){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});let i=await this.relayer.request(e);return this.relayer.events.emit(ut,pA(pA({},e),t)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{var i;let r=e.attempt+1;this.queue.set(t,pw(pA({},e),pb({attempt:r}))),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${null==(i=e.request.params)?void 0:i.tag}, attempt: ${r}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(dO.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ue);return}this.checkQueue()}),this.relayer.on(d9,e=>{this.removeRequestFromQueue(e.id.toString())})}}var pC=Object.defineProperty,p_=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?pC(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class pk{constructor(){p_(this,"map",new Map),p_(this,"set",(e,t)=>{let i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),p_(this,"get",e=>this.map.get(e)||[]),p_(this,"exists",(e,t)=>this.get(e).includes(t)),p_(this,"delete",(e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;let i=this.get(e);if(!this.exists(e,t))return;let r=i.filter(e=>e!==t);r.length?this.map.set(e,r):this.map.delete(e)}),p_(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var pO=Object.defineProperty,pT=Object.defineProperties,pR=Object.getOwnPropertyDescriptors,pN=Object.getOwnPropertySymbols,pj=Object.prototype.hasOwnProperty,pD=Object.prototype.propertyIsEnumerable,pM=(e,t,i)=>t in e?pO(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,pU=(e,t)=>{for(var i in t||(t={}))pj.call(t,i)&&pM(e,i,t[i]);if(pN)for(var i of pN(t))pD.call(t,i)&&pM(e,i,t[i]);return e},pB=(e,t,i)=>pM(e,"symbol"!=typeof t?t+"":t,i);class pL extends dH{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,pB(this,"subscriptions",new Map),pB(this,"topicMap",new pk),pB(this,"events",new rE.EventEmitter),pB(this,"name","subscription"),pB(this,"version","0.3"),pB(this,"pending",new Map),pB(this,"cac
14hed",[]),pB(this,"initialized",!1),pB(this,"storagePrefix",d2),pB(this,"subscribeTimeout",(0,rA.toMiliseconds)(rA.ONE_MINUTE)),pB(this,"initialSubscribeTimeout",(0,rA.toMiliseconds)(15*rA.ONE_SECOND)),pB(this,"clientId"),pB(this,"batchSubscribeTopicsLimit",500),pB(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),pB(this,"subscribe",async(e,t)=>{var i;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{let r=hH(t),s={topic:e,relay:r,transportType:t?.transportType};null!=(i=t?.internal)&&i.skipSubscribe||this.pending.set(e,s);let n=await this.rpcSubscribe(e,r,t);return"string"==typeof n&&(this.onSubscribe(n,s),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}})),n}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}}),pB(this,"unsubscribe",async(e,t)=>{this.isInitialized(),"u">typeof t?.id?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)}),pB(this,"isSubscribed",e=>new Promise(t=>{t(this.topicMap.topics.includes(e))})),pB(this,"isKnownTopic",e=>new Promise(t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some(t=>t.topic===e))})),pB(this,"on",(e,t)=>{this.events.on(e,t)}),pB(this,"once",(e,t)=>{this.events.once(e,t)}),pB(this,"off",(e,t)=>{this.events.off(e,t)}),pB(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),pB(this,"start",async()=>{await this.onConnect()}),pB(this,"stop",async()=>{await this.onDisconnect()}),pB(this,"restart",async()=>{await this.restore(),await this.onRestart()}),pB(this,"checkPending",async()=>{if(0===this.pending.size&&(!this.initialized||!this.relayer.connected))return;let e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e)}),pB(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(dO.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.events.on(ud,async e=>{this.logger.info(`Emitting ${ud}`),this.logger.debug({type:"event",event:ud,data:e}),await this.persist()}),this.events.on(uu,async e=>{this.logger.info(`Emitting ${uu}`),this.logger.debug({type:"event",event:uu,data:e}),await this.persist()})}),this.relayer=e,this.logger=ad(t,this.name),this.clientId=""}get context(){return ah(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){let i=this.topicMap.get(e);await Promise.all(i.map(async i=>await this.unsubscribeById(e,i,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{let r=hH(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);let s=dc("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t,i){var r,s;
14let n=await this.getSubscriptionId(e);if(null!=(r=i?.internal)&&r.skipSubscribe)return n;i&&i?.transportType!==ul||await this.restartToComplete({topic:e,id:e,relay:t});let a={method:h$(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});let o=null==(s=i?.internal)?void 0:s.throwOnFailedPublish;try{if(i?.transportType===uo)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(e=>this.logger.warn(e))},(0,rA.toMiliseconds)(rA.ONE_SECOND)),n;let t=new Promise(async t=>{let i=r=>{r.topic===e&&(this.events.removeListener(ud,i),t(r.id))};this.events.on(ud,i);try{let r=await aL(new Promise((e,t)=>{this.relayer.request(a).catch(e=>{this.logger.warn(e,e?.message),t(e)}).then(e)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(ud,i),t(r)}catch{}}),r=await aL(t,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!r&&o)throw Error(`Subscribing to ${e} failed, please try again`);return r?n:null}catch(e){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ue),o)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return;let t={method:h$(e[0].relay.protocol).batchSubscribe,params:{topics:e.map(e=>e.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{await await aL(new Promise(e=>{this.relayer.request(t).catch(e=>this.logger.warn(e)).then(e)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(ue)}}async rpcBatchFetchMessages(e){let t;if(!e.length)return;let i={method:h$(e[0].relay.protocol).batchFetchMessages,params:{topics:e.map(e=>e.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{t=await await aL(new Promise((e,t)=>{this.relayer.request(i).catch(e=>{this.logger.warn(e),t(e)}).then(e)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(ue)}return t}rpcUnsubscribe(e,t,i){let r={method:h$(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,pT(pU({},t),pR({id:e}))),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(e=>{this.setSubscription(e.id,pU({},e)),this.pending.delete(e.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,pU({},t)),this.topicMap.set(t.topic,e),this.events.emit(ud,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});let t=this.subscriptions.get(e);if(!t){let{message:t}=dl("NO_MATCHING_KEY",`${this.name}: ${e}`);throw Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});let i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(uu,pT(pU({},i),pR({reason:t})))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit("subscription_sync")}async onRestart(){if(this.cached.length){let e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){let t=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(t)}}this.events.emit("subscription_resubscribed")}
14async restore(){try{let e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(e=>{var t;return e.topic===(null==(t=this.subscriptions.get(e.id))?void 0:t.topic)})){let{message:e}=dl("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),Error(e)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async e=>pT(pU({},e),pR({id:await this.getSubscriptionId(e.topic)}))))))}async batchFetchMessages(e){var t;if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);let i=await this.rpcBatchFetchMessages(e);i&&i.messages&&(await (t=(0,rA.toMiliseconds)(rA.ONE_SECOND),new Promise(e=>setTimeout(e,t))),await this.relayer.handleBatchMessageEvents(i.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){let{message:e}=dl("NOT_INITIALIZED",this.name);throw 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 hN(e+await this.getClientId())}}var pq=Object.defineProperty,pK=Object.getOwnPropertySymbols,pH=Object.prototype.hasOwnProperty,p$=Object.prototype.propertyIsEnumerable,pW=(e,t,i)=>t in e?pq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,pz=(e,t)=>{for(var i in t||(t={}))pH.call(t,i)&&pW(e,i,t[i]);if(pK)for(var i of pK(t))p$.call(t,i)&&pW(e,i,t[i]);return e},pF=(e,t,i)=>pW(e,"symbol"!=typeof t?t+"":t,i);class pV extends dq{constructor(t){var i;super(t),pF(this,"protocol","wc"),pF(this,"version",2),pF(this,"core"),pF(this,"logger"),pF(this,"events",new rE.EventEmitter),pF(this,"provider"),pF(this,"messages"),pF(this,"subscriber"),pF(this,"publisher"),pF(this,"name","relayer"),pF(this,"transportExplicitlyClosed",!1),pF(this,"initialized",!1),pF(this,"connectionAttemptInProgress",!1),pF(this,"relayUrl"),pF(this,"projectId"),pF(this,"packageName"),pF(this,"bundleId"),pF(this,"hasExperiencedNetworkDisruption",!1),pF(this,"pingTimeout"),pF(this,"heartBeatTimeout",(0,rA.toMiliseconds)(rA.THIRTY_SECONDS+rA.FIVE_SECONDS)),pF(this,"reconnectTimeout"),pF(this,"connectPromise"),pF(this,"reconnectInProgress",!1),pF(this,"requestsInFlight",[]),pF(this,"connectTimeout",(0,rA.toMiliseconds)(15*rA.ONE_SECOND)),pF(this,"request",async e=>{var t,i;this.logger.debug("Publishing Request Payload");let r=e.id||(0,dQ.getBigIntRpcId)().toString();await this.toEstablishConnection();try{this.logger.trace({id:r,method:e.method,topic:null==(t=e.params)?void 0:t.topic},"relayer.request - publishing...");let s=`${r}:${(null==(i=e.params)?void 0:i.tag)||""}`;this.requestsInFlight.push(s);let n=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter(e=>e!==s),n}catch(e){throw this.logger.debug(`Failed to Publish Request: ${r}`),e}}),pF(this,"resetPingTimeout",()=>{a_()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var e,t,i,r;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),null==(r=null==(i=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:i.terminate)||r.call(i)}catch(e){this.logger.warn(e,e?.message)}},this.heartBeatTimeout))}),pF(this,"onPayloadHandler",e=>{this.onProviderPayload(e),this.resetPingTimeout()}),pF(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit("relayer_connect")}),pF(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),pF(this,"onProviderErrorHandler",e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit("relayer_error",e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),pF(this,"registerProviderListeners",()=>{this.provider.on(ui,this.onPayloadHandler),this.provider.on(ur,this.onConnectHandler),this.provider.on(us,this.onDisconnectHandler),this.provider.on(un,this.onProviderErrorHandler)}
14),this.core=t.core,this.logger=dk({logger:null!=(i=t.logger)?i:"error",name:this.name}),this.messages=new py(this.logger,t.core),this.subscriber=new pL(this,this.logger),this.publisher=new pP(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||d4,ak()&&"u">typeof(null==e.g?void 0:e.g.Platform)&&(null==e.g?void 0:e.g.Platform.OS)==="android"?this.packageName=aR():ak()&&"u">typeof(null==e.g?void 0:e.g.Platform)&&(null==e.g?void 0:e.g.Platform.OS)==="ios"&&(this.bundleId=aR()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return ah(this.logger)}get connected(){var e,t,i;return(null==(i=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:i.readyState)===1}get connecting(){var e,t,i;return(null==(i=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:i.readyState)===0||void 0!==this.connectPromise}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:ul},"outbound")}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,t){var i,r,s;this.isInitialized(),null!=t&&t.transportType&&t?.transportType!=="relay"||await this.toEstablishConnection();let n=typeof(null==(i=t?.internal)?void 0:i.throwOnFailedPublish)>"u"||(null==(r=t?.internal)?void 0:r.throwOnFailedPublish),a=(null==(s=this.subscriber.topicMap.get(e))?void 0:s[0])||"",o,l=t=>{t.topic===e&&(this.subscriber.off(ud,l),o())};return await Promise.all([new Promise(e=>{o=e,this.subscriber.on(ud,l)}),new Promise(async(i,r)=>{a=await this.subscriber.subscribe(e,pz({internal:{throwOnFailedPublish:n}},t)).catch(e=>{n&&r(e)})||a,i()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await aL(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics)return void this.logger.info("Starting WS connection skipped because the client has no topics to work with.");if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,i)=>{await this.connect(e).then(t).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await dA())throw Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0)return void this.logger.trace("Batch message events is empty. Ignoring...");let t=e.sort((e,t)=>e.publishedAt-t.publishedAt);for(let e of(this.logger.debug(`Batch of ${t.length} message events sorted`),t))try{await this.onMessageEvent(e)}catch(e){this.logger.warn(e,"Error while processing batch message event: "+e?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){let{topic:i}=e;if(!t.sessionExists){let e=aH(rA.FIVE_MINUTES);await this.core.pairing.pairings.set(i,{topic:i,expiry:e,relay:{protocol:"irn"},active:!1})}this.events.emit(d7,e),await this.recordMessageEvent(e,uc)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(e,t)=>{let i=()=>
14{t(Error("Connection interrupted while trying to connect"))};this.provider.once(us,i),await aL(new Promise((e,t)=>{this.provider.connect().then(e).catch(t)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(e=>{t(e)}).finally(()=>{this.provider.off(us,i),clearTimeout(this.reconnectTimeout)}),await new Promise(async(e,i)=>{let r=()=>{t(Error("Connection interrupted while trying to subscribe"))};this.provider.once(us,r),await this.subscriber.start().then(e).catch(i).finally(()=>{this.provider.off(us,r)})}),this.hasExperiencedNetworkDisruption=!1,e()})}catch(e){await this.subscriber.stop(),this.logger.warn({},e.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(e=>setTimeout(e,(0,rA.toMiliseconds)(+t))),t++}}startPingTimeout(){var e,t,i,r,s;if(a_())try{null!=(t=null==(e=this.provider)?void 0:e.connection)&&t.socket&&(null==(s=null==(r=null==(i=this.provider)?void 0:i.connection)?void 0:r.socket)||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new dZ.JsonRpcProvider(new d0.default(function({protocol:e,version:t,relayUrl:i,sdkVersion:r,auth:s,projectId:n,useOnCloseEvent:a,bundleId:o,packageName:l}){var c,h;let d,u=i.split("?"),p=aj(e,t,r),f=(c=u[1]||"",h={auth:s,ua:p,projectId:n,useOnCloseEvent:a||void 0,packageName:l||void 0,bundleId:o||void 0},d=new URLSearchParams(c),Object.entries(h).sort(([e],[t])=>e.localeCompare(t)).forEach(([e,t])=>{null!=t&&d.set(e,String(t))}),d.toString());return u[0]+"?"+f}({sdkVersion:ua,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){let{topic:i,message:r}=e;await this.messages.set(i,r,t)}async shouldIgnoreMessageEvent(e){let{topic:t,message:i}=e;if(!i||0===i.length)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;let r=this.messages.has(t,i);return r&&this.logger.warn(`Ignoring duplicate message: ${i}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),(0,dX.isJsonRpcRequest)(e)){if(!e.method.endsWith("_subscription"))return;let t=e.params,{topic:i,message:r,publishedAt:s,attestation:n}=t.data,a={topic:i,message:r,publishedAt:s,transportType:ul,attestation:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(pz({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else(0,dX.isJsonRpcResponse)(e)&&this.events.emit(d9,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,uc),this.events.emit(d7,e))}async acknowledgePayload(e){let t=(0,dQ.formatJsonRpcResult)(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(ui,this.onPayloadHandler),this.provider.off(ur,this.onConnectHandler),this.provider.off(us,this.onDisconnectHandler),this.provider.off(un,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await dA();(function(t){var i,r;switch(aT()){case aC:i=t,!ak()&&aO()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)));break;case ax:r=t,ak()&&null!=e.g&&e.g.NetInfo&&e.g?.NetInfo.addEventListener(e=>r(e?.isConnected))}})(async e=>{t!==e&&(t=e,e?await this.transportOpen().catch(e=>this.logger.error(e,e?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(dO.HEARTBEAT_EVENTS.pulse,async()=>{var e;if(!this.transportExplicitlyClosed&&!this.connected&&(!(aO()&&(0,rx.getDocument)())||
14(null==(e=(0,rx.getDocument)())?void 0:e.visibilityState)==="visible"))try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit("relayer_disconnect"),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},(0,rA.toMiliseconds)(.1)))))}isInitialized(){if(!this.initialized){let{message:e}=dl("NOT_INITIALIZED",this.name);throw Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise)return void await this.connectPromise;await this.connect()}}}function pJ(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function pG(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}let pY="[object Arguments]",pZ="[object Object]";function pQ(){}function pX(e){if(!e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&"[object Object]"===Object.prototype.toString.call(e)}var p0=Object.defineProperty,p1=Object.getOwnPropertySymbols,p2=Object.prototype.hasOwnProperty,p5=Object.prototype.propertyIsEnumerable,p3=(e,t,i)=>t in e?p0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,p8=(e,t)=>{for(var i in t||(t={}))p2.call(t,i)&&p3(e,i,t[i]);if(p1)for(var i of p1(t))p5.call(t,i)&&p3(e,i,t[i]);return e},p6=(e,t,i)=>p3(e,"symbol"!=typeof t?t+"":t,i);class p4 extends dK{constructor(e,t,i,r=d2,s){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,p6(this,"map",new Map),p6(this,"version","0.3"),p6(this,"cached",[]),p6(this,"initialized",!1),p6(this,"getKey"),p6(this,"storagePrefix",d2),p6(this,"recentlyDeleted",[]),p6(this,"recentlyDeletedLimit",200),p6(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>{var t;this.getKey&&null!==e&&!du(e)?this.map.set(this.getKey(e),e):(null==(t=e?.proposer)?void 0:t.publicKey)?this.map.set(e.id,e):e?.topic&&this.map.set(e.topic,e)}),this.cached=[],this.initialized=!0)}),p6(this,"set",async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())}),p6(this,"get",e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e))),p6(this,"getAll",e=>(this.isInitialized(),e?this.values.filter(t=>Object.keys(e).every(i=>{var r;return r=t[i],function e(t,i,r,s,n,a,o){let l=o(t,i,r,s,n,a);if(void 0!==l)return l;if(typeof t==typeof i)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":case"function":return t===i;case"number":return t===i||Object.is(t,i)}return function t(i,r,s,n){if(Object.is(i,r))return!0;let a=pG(i),o=pG(r);if(a===pY&&(a=pZ),o===pY&&(o=pZ),a!==o)return!1;switch(a){case"[object String]":return i.toString()===r.toString();case"[object Number]":{let e=i.valueOf(),t=r.valueOf();return e===t||Number.isNaN(e)&&Number.isNaN(t)}case"[object Boolean]":case"[object Date]":case"[object Symbol]":return Object.is(i.valueOf(),r.valueOf());case"[object RegExp]":return i.source===r.source&&i.flags===r.flags;case"[object Function]":return i===r}let l=(s=s??new Map).get(i),c=s.get(r);if(null!=l&&null!=c)return l===r;s.set(i,r),s.set(r,i);try{switch(a){case"[object Map]":if(i.size!==r.size)return!1;for(let[t,a]of i.entries())if(!r.has(t)||!e(a,r.get(t),t,i,r,s,n))return!1;return!0;case"[object Set]":{if(i.size!==r.size)return!1;let t=Array.from(i.values()),a=Array.from(r.values());for(let o=0;o<t.length;o++){let l=t[o],c=a.findIndex(t=>e(l,t,void 0,i,r,s,n));if(-1===c)return!1;a.splice(c,1)}return!0}case"[object Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":case"[object BigUint64Array
14]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object BigInt64Array]":case"[object Float32Array]":case"[object Float64Array]":if("u">typeof tT.Buffer&&tT.Buffer.isBuffer(i)!==tT.Buffer.isBuffer(r)||i.length!==r.length)return!1;for(let t=0;t<i.length;t++)if(!e(i[t],r[t],t,i,r,s,n))return!1;return!0;case"[object ArrayBuffer]":return i.byteLength===r.byteLength&&t(new Uint8Array(i),new Uint8Array(r),s,n);case"[object DataView]":return i.byteLength===r.byteLength&&i.byteOffset===r.byteOffset&&t(new Uint8Array(i),new Uint8Array(r),s,n);case"[object Error]":return i.name===r.name&&i.message===r.message;case pZ:{if(!(t(i.constructor,r.constructor,s,n)||pX(i)&&pX(r)))return!1;let a=[...Object.keys(i),...pJ(i)],o=[...Object.keys(r),...pJ(r)];if(a.length!==o.length)return!1;for(let t=0;t<a.length;t++){let o=a[t],l=i[o];if(!Object.hasOwn(r,o))return!1;let c=r[o];if(!e(l,c,o,i,r,s,n))return!1}return!0}default:return!1}}finally{s.delete(i),s.delete(r)}}(t,i,a,o)}(r,e[i],void 0,void 0,void 0,void 0,pQ)})):this.values)),p6(this,"update",async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});let i=p8(p8({},this.getData(e)),t);this.map.set(e,i),await this.persist()}),p6(this,"delete",async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())}),this.logger=ad(t,this.name),this.storagePrefix=r,this.getKey=s}get context(){return ah(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){let t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){let{message:t}=dl("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),Error(t)}let{message:t}=dl("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),Error(t)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{let e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){let{message:e}=dl("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),Error(e)}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){let{message:e}=dl("NOT_INITIALIZED",this.name);throw Error(e)}}}var p7=Object.defineProperty,p9=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?p7(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class fe{constructor(e,t){this.core=e,this.logger=t,p9(this,"name","pairing"),p9(this,"version","0.3"),p9(this,"events",new rE.default),p9(this,"pairings"),p9(this,"initialized",!1),p9(this,"storagePrefix",d2),p9(this,"ignoredPayloadTypes",[1]),p9(this,"registeredMethods",[]),p9(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),p9(this,"register",({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]}),p9(this,"create",async e=>{this.isInitialized();let t=hT(),i=await this.core.crypto.setSymKey(t),r=aH(rA.FIVE_MINUTES),s={protocol:"irn"},n={topic:i,expiry:r,relay:s,active:!1,methods:e?.methods},a=hX({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:t,relay:s,expiryTimestamp:r,methods:e?.methods});return this.events.emit(uf,n),this.core.expirer.set(i,r),await this.pairings.set(i,n),await this.core.relayer.subscribe(i,{transportType:e?.transportType,internal:e?.internal}),{topic:i,uri:a}}),p9(this,"pair",async e=>{let t;this.isInitialized();let i=this.core.eventClient.createEvent({properties:{topic:e?.uri,trace:["pairing_started"]}});this.isValidPair(e,i);let{topic:r,symKey:s,relay:n,expiryTimestamp:a,methods:o}=hQ(e.uri);if(i.props.properties.topic=r,i.addTrace("pairing_uri_validation_success"),i.addTrace("pairing_uri_not_expired"),this.pairings.keys.includes(r)){if(t=this.pairings.get(r),i.addTrace("existing_pairing"),t.active)throw i.setError("active_pairing_already_exists"),Error(`Pairing already exists: ${r}. Please try again with a new connection URI.`);
14i.addTrace("pairing_not_expired")}let l=a||aH(rA.FIVE_MINUTES),c={topic:r,relay:n,expiry:l,active:!1,methods:o};this.core.expirer.set(r,l),await this.pairings.set(r,c),i.addTrace("store_new_pairing"),e.activatePairing&&await this.activate({topic:r}),this.events.emit(uf,c),i.addTrace("emit_inactive_pairing"),this.core.crypto.keychain.has(r)||await this.core.crypto.setSymKey(s,r),i.addTrace("subscribing_pairing_topic");try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError("no_internet_connection")}try{await this.core.relayer.subscribe(r,{relay:n})}catch(e){throw i.setError("subscribe_pairing_topic_failure"),e}return i.addTrace("subscribe_pairing_topic_success"),c}),p9(this,"activate",async({topic:e})=>{this.isInitialized();let t=aH(rA.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})}),p9(this,"ping",async e=>{this.isInitialized(),await this.isValidPing(e),this.logger.warn("ping() is deprecated and will be removed in the next major release.");let{topic:t}=e;if(this.pairings.keys.includes(t)){let e=await this.sendRequest(t,"wc_pairingPing",{}),{done:i,resolve:r,reject:s}=aB();this.events.once(aW("pairing_ping",e),({error:e})=>{e?s(e):r()}),await i()}}),p9(this,"updateExpiry",async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})}),p9(this,"updateMetadata",async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})}),p9(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),p9(this,"disconnect",async e=>{this.isInitialized(),await this.isValidDisconnect(e);let{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",dc("USER_DISCONNECTED")),await this.deletePairing(t))}),p9(this,"formatUriFromPairing",e=>{this.isInitialized();let{topic:t,relay:i,expiry:r,methods:s}=e,n=this.core.crypto.keychain.get(t);return hX({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:n,relay:i,expiryTimestamp:r,methods:s})}),p9(this,"sendRequest",async(e,t,i)=>{let r=(0,dQ.formatJsonRpcRequest)(t,i),s=await this.core.crypto.encode(e,r),n=up[t].req;return this.core.history.set(e,r),this.core.relayer.publish(e,s,n),r.id}),p9(this,"sendResult",async(e,t,i)=>{let r=(0,dQ.formatJsonRpcResult)(e,i),s=await this.core.crypto.encode(t,r),n=up[(await this.core.history.get(t,e)).request.method].res;await this.core.relayer.publish(t,s,n),await this.core.history.resolve(r)}),p9(this,"sendError",async(e,t,i)=>{let r=(0,dQ.formatJsonRpcError)(e,i),s=await this.core.crypto.encode(t,r),n=(await this.core.history.get(t,e)).request.method,a=up[n]?up[n].res:up.unregistered_method.res;await this.core.relayer.publish(t,s,a),await this.core.history.resolve(r)}),p9(this,"deletePairing",async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,dc("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])}),p9(this,"cleanup",async()=>{let e=this.pairings.getAll().filter(e=>a$(e.expiry));await Promise.all(e.map(e=>this.deletePairing(e.topic)))}),p9(this,"onRelayEventRequest",async e=>{let{topic:t,payload:i}=e;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(t,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(t,i);default:return await this.onUnknownRpcMethodRequest(t,i)}}),p9(this,"onRelayEventResponse",async e=>{let{topic:t,payload:i}=e,r=(await this.core.history.get(t,i.id)).request.method;return"wc_pairingPing"===r?this.onPairingPingResponse(t,i):this.onUnknownRpcMethodResponse(r)}),p9(this,"onPairingPingRequest",async(e,t)=>{let{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult(i,e,!0),this.events.emit("pairing_ping",{id:i,topic:e})}catch(t){await this.sendError(i,e,t),this.logger.error(t)}}),p9(this,"onPairingPingResponse",(e,t)=>{let{id:i}=t;setTimeout(()=>{(0,dX.isJsonRpcResult)(t)?this.events.emit(aW("pairing_ping",i),{}):(0,dX.isJsonRpcError)(t)&&this.events.emit(aW("pairing_ping",i),{error:t.error})},500)}),p9(this,"onPairingDeleteRequest",async(e,t)=>{let{id:i}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(ug,{id:i,topic:e})}catch(t){await this.sendError(i,e,t),this.logger.error(t)}}),p9(this,"onUnknownRpcMethodRequest",async(e,t)=>{let{id:i,method:r}=t;try{if(this.registeredMethods.includes(r))return;let t=dc("WC_METHOD_UNSUPPORTED",r);await this.sendError(i,e,t),this.logger.error(t)}catch(t){await this.sendError(i,e,t),this.logger.error(t)}}),p9(this,"onUnknownRpcMethodResponse",e=>{this.registeredMethods.includes(e)||this.logger.error(dc("WC_METHOD_UNSUPPORTED",e))}),p9(this,"isValidPair",(e,t)=>{var i;if(!dv(e)){let{message:i}=dl("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(ux),Error(i)}if(!function(e){function t(e){try{return"u">typeof new URL(e)}catch{return!1}}try{if(dp(e,!1)){if(t(e))return!0;let i=aZ(e);return t(i)}}catch{}return!1}(e.uri)){let{message:i}=dl("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(ux),Error(i)}let r=hQ(e?.uri);if(!(null!=(i=r?.relay)&&i.protocol)){let{message:e}=dl("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(ux),Error(e)}if(!(null!=r&&r.symKey)){let{message:e}=dl("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(ux),Error(e)}if(null!=r&&r.expiryTimestamp&&(0,rA.toMiliseconds)(r?.expiryTimestamp)<Date.now()){t.setError("pairing_expired");let{message:e}=dl("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw Error(e)}}),p9(this,"isValidPing",async e=>{if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`ping() params: ${e}`);throw Error(t)}let{topic:t}=e;await this.isValidPairingTopic(t)}),p9(this,"isValidDisconnect",async e=>{if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw Error(t)}let{topic:t}=e;await this.isValidPairingTopic(t)}),p9(this,"isValidPairingTopic",async e=>{if(!dp(e,!1)){let{message:t}=dl("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw Error(t)}if(!this.pairings.keys.includes(e)){let{message:t}=dl("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw Error(t)}if(a$(this.pairings.get(e).expiry)){await this.deletePairing(e);let{message:t}=dl("EXPIRED",`pairing topic: ${e}`);throw Error(t)}}),this.core=e,this.logger=ad(t,this.name),this.pairings=new p4(this.core,this.logger,this.name,this.storagePrefix)}get context(){return ah(this.logger)}isInitialized(){if(!this.initialized){let{message:e}=dl("NOT_INITIALIZED",this.name);throw Error(e)}}registerRelayerEvents(){this.core.relayer.on(d7,async e=>{let{topic:t,message:i,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==uo&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{let e=await this.core.crypto.decode(t,i);(0,dX.isJsonRpcRequest)(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):(0,dX.isJsonRpcResponse)(e)&&(await this.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e}),this.core.history.delete(t,e.id)),await this.core.relayer.messages.ack(t,i)}catch(e){this.logger.error(e)}})}registerExpirerEvents(){this.core.expirer.on(uE,async e=>{let{topic:t}=aK(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit("pairing_expire",{topic:t}))})}}var ft=Object.defineProperty,fi=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?ft(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class fr extends dU{constructor(e,t){super(e,t),this.core=e,this.logger=t,fi(this,"records",new Map),fi(this,"events",new rE.EventEmitter),fi(this,"name","history"),fi(this,"version","0.3"),fi(this,"cac
14hed",[]),fi(this,"initialized",!1),fi(this,"storagePrefix",d2),fi(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.records.set(e.id,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),fi(this,"set",(e,t,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:i}),this.records.has(t.id))return;let r={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:i,expiry:aH(rA.THIRTY_DAYS)};this.records.set(r.id,r),this.persist(),this.events.emit(uy,r)}),fi(this,"resolve",async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;let t=await this.getRecord(e.id);typeof t.response>"u"&&(t.response=(0,dX.isJsonRpcError)(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit(um,t))}),fi(this,"get",async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t))),fi(this,"delete",(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach(i=>{i.topic===e&&("u">typeof t&&i.id!==t||(this.records.delete(i.id),this.events.emit(uw,i)))}),this.persist()}),fi(this,"exists",async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e)),fi(this,"on",(e,t)=>{this.events.on(e,t)}),fi(this,"once",(e,t)=>{this.events.once(e,t)}),fi(this,"off",(e,t)=>{this.events.off(e,t)}),fi(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=ad(t,this.name)}get context(){return ah(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(){let e=[];return this.values.forEach(t=>{if("u">typeof t.response)return;let i={topic:t.topic,request:(0,dQ.formatJsonRpcRequest)(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();let t=this.records.get(e);if(!t){let{message:t}=dl("NO_MATCHING_KEY",`${this.name}: ${e}`);throw Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit("history_sync")}async restore(){try{let e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){let{message:e}=dl("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),Error(e)}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(uy,e=>{this.logger.info(`Emitting ${uy}`),this.logger.debug({type:"event",event:uy,record:e})}),this.events.on(um,e=>{this.logger.info(`Emitting ${um}`),this.logger.debug({type:"event",event:um,record:e})}),this.events.on(uw,e=>{this.logger.info(`Emitting ${uw}`),this.logger.debug({type:"event",event:uw,record:e})}),this.core.heartbeat.on(dO.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{(0,rA.toMiliseconds)(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(uw,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){let{message:e}=dl("NOT_INITIALIZED",this.name);throw Error(e)}}}var fs=Object.defineProperty,fn=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?fs(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class fa extends d${constructor(e,t){super(e,t),this.core=e,this.logger=t,fn(this,"expirations",new Map),fn(this,"events",new rE.EventEmitter),fn(this,"name","expirer"),fn(this,"version","0.3"),fn(this,"cac
14hed",[]),fn(this,"initialized",!1),fn(this,"storagePrefix",d2),fn(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.expirations.set(e.target,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),fn(this,"has",e=>{try{let t=this.formatTarget(e);return"u">typeof this.getExpiration(t)}catch{return!1}}),fn(this,"set",(e,t)=>{this.isInitialized();let i=this.formatTarget(e),r={target:i,expiry:t};this.expirations.set(i,r),this.checkExpiry(i,r),this.events.emit(ub,{target:i,expiration:r})}),fn(this,"get",e=>{this.isInitialized();let t=this.formatTarget(e);return this.getExpiration(t)}),fn(this,"del",e=>{if(this.isInitialized(),this.has(e)){let t=this.formatTarget(e),i=this.getExpiration(t);this.expirations.delete(t),this.events.emit(uv,{target:t,expiration:i})}}),fn(this,"on",(e,t)=>{this.events.on(e,t)}),fn(this,"once",(e,t)=>{this.events.once(e,t)}),fn(this,"off",(e,t)=>{this.events.off(e,t)}),fn(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=ad(t,this.name)}get context(){return ah(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("string"==typeof e)return aq("topic",e);if("number"==typeof e)return aq("id",e);let{message:t}=dl("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw 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("expirer_sync")}async restore(){try{let e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){let{message:e}=dl("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),Error(e)}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){let t=this.expirations.get(e);if(!t){let{message:t}=dl("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),Error(t)}return t}checkExpiry(e,t){let{expiry:i}=t;(0,rA.toMiliseconds)(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(uE,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(dO.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(ub,e=>{this.logger.info(`Emitting ${ub}`),this.logger.debug({type:"event",event:ub,data:e}),this.persist()}),this.events.on(uE,e=>{this.logger.info(`Emitting ${uE}`),this.logger.debug({type:"event",event:uE,data:e}),this.persist()}),this.events.on(uv,e=>{this.logger.info(`Emitting ${uv}`),this.logger.debug({type:"event",event:uv,data:e}),this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=dl("NOT_INITIALIZED",this.name);throw Error(e)}}}var fo=Object.defineProperty,fl=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?fo(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class fc extends dW{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,fl(this,"name","verify-api"),fl(this,"abortController"),fl(this,"isDevEnv"),fl(this,"verifyUrlV3",uS),fl(this,"storagePrefix",d2),fl(this,"version",2),fl(this,"publicKey"),fl(this,"fetchPromise"),fl(this,"init",async()=>{var e;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,rA.toMiliseconds)(null==(e=this.publicKey)?void 0:e.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),fl(this,"register",async e=>{if(!aO()||this.isDevEnv)return;let t=window.location.origin,{id:i,decryptedId:r}=e,s=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${t}&id=${i}&decryptedId=${r}`;try{let e=(0,rx.getDocument)(),t=this.startAbortTimer(5*rA.ONE_SECOND),r=await new Promise((r,n)=>{let a=()=>{window.removeEventListener("message",l),e.body.removeChild(o),n("attestation aborted")};this.abortController.signal.addEventListener("abort",a);let o=e.createElement("iframe");o.src=s,o.style.display="none",o.addEventListener("error",a,{signal:this.abortController.signal});let l=s=>{if(s.data&&"string"==typeof s.data)try{let n=JSON.parse(s.data);if("verify_attestation"===n.type){if((0,nF.decodeJWT)(n.attestation).payload.id!==i)return;clearInterval(t),e.body.removeChild(o),this.abortController.signal.removeEventListener("abort",a),window.removeEventListener("message",l),r(null===n.attestation?"":n.attestation)}}catch(e){this.logger.warn(e)}};e.body.appendChild(o),window.addEventListener("message",l,{signal:this.abortController.signal})});
14return this.logger.debug(r,"jwt attestation"),r}catch(e){this.logger.warn(e)}return""}),fl(this,"resolve",async e=>{if(this.isDevEnv)return"";let{attestationId:t,hash:i,encryptedId:r}=e;if(""===t)return void this.logger.debug("resolve: attestationId is empty, skipping");if(t){if((0,nF.decodeJWT)(t).payload.id!==r)return;let e=await this.isValidJwtAttestation(t);if(e)return e.isVerified?e:void this.logger.warn("resolve: jwt attestation: origin url not verified")}if(!i)return;let s=this.getVerifyUrl(e?.verifyUrl);return this.fetchAttestation(i,s)}),fl(this,"fetchAttestation",async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);let i=this.startAbortTimer(5*rA.ONE_SECOND),r=await fetch(`${t}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(i),200===r.status?await r.json():void 0}),fl(this,"getVerifyUrl",e=>{let t=e||uI;return uA.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${uI}`),t=uI),t}),fl(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);let e=this.startAbortTimer(rA.FIVE_SECONDS),t=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await t.json()}catch(e){this.logger.warn(e)}}),fl(this,"persistPublicKey",async e=>{this.logger.debug(e,"persisting public key to local storage"),await this.store.setItem(this.storeKey,e),this.publicKey=e}),fl(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),fl(this,"isValidJwtAttestation",async e=>{let t=await this.getPublicKey();try{if(t)return this.validateAttestation(e,t)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}let i=await this.fetchAndPersistPublicKey();try{if(i)return this.validateAttestation(e,i)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}}),fl(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),fl(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async e=>{let t=await this.fetchPublicKey();t&&(await this.persistPublicKey(t),e(t))});let e=await this.fetchPromise;return this.fetchPromise=void 0,e}),fl(this,"validateAttestation",(e,t)=>{let i=function(e,t){let i,r,[s,n,a]=e.split("."),o=tT.Buffer.from(hU(a),"base64");if(64!==o.length)throw Error("Invalid signature length");let l=o.slice(0,32),c=o.slice(32,64),h=le(`${s}.${n}`),d=(i=tT.Buffer.from(t.x,"base64"),r=tT.Buffer.from(t.y,"base64"),(0,nG.concat)([new Uint8Array([4]),i,r]));if(!hx.verify((0,nG.concat)([l,c]),h,d))throw Error("Invalid signature");return(0,nF.decodeJWT)(e).payload}(e,t.publicKey),r={hasExpired:(0,rA.toMiliseconds)(i.exp)<Date.now(),payload:i};if(r.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),Error("JWT attestation expired");return{origin:r.payload.origin,isScam:r.payload.isScam,isVerified:r.payload.isVerified}}),this.logger=ad(t,this.name),this.abortController=new AbortController,this.isDevEnv=aY(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return ah(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),(0,rA.toMiliseconds)(e))}}var fh=Object.defineProperty,fd=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?fh(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class fu extends dz{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,fd(this,"context","echo"),fd(this,"registerDeviceToken",async e=>{let{clientId:t,token:i,notificationType:r,enableEncrypted:s=!1}=e,n=`https://echo.walletconnect.com/${this.projectId}/clients`;await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t,type:r,token:i,always_raw:s})})}),this.logger=ad(t,this.context)}}var fp=Object.defineProperty,ff=Object.getOwnPropertySymbols,fg=Object.prototype.hasOwnProperty,fy=Object.prototype.propertyIsEnumerable,fm=(e,t,i)=>t in e?fp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,fw=(e,t)=>{for(var i in t||(t={}))fg.call(t,i)&&fm(e,i,t[i]);if(ff)for(var i of ff(t))fy.call(t,i)&&fm(e,i,t[i]);return e},fb=(e,t,i)=>fm(e,"symbol"!=typeof t?t+"":t,i);class fv extends dF{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,fb(this,"context","event-client"),fb(this,"storagePrefix",d2),fb(this,"storageVersion",.1),fb(this,"events",new Map),fb(this,"shouldPersist",!1),fb(this,"init",async()=>
14{if(!aY())try{let e={eventId:aG(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:aj(this.core.relayer.protocol,this.core.relayer.version,ua)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}}),fb(this,"createEvent",e=>{let{event:t="ERROR",type:i="",properties:{topic:r,trace:s}}=e,n=aG(),a=this.core.projectId||"",o=fw({eventId:n,timestamp:Date.now(),props:{event:t,type:i,properties:{topic:r,trace:s}},bundleId:a,domain:this.getAppDomain()},this.setMethods(n));return this.telemetryEnabled&&(this.events.set(n,o),this.shouldPersist=!0),o}),fb(this,"getEvent",e=>{let{eventId:t,topic:i}=e;if(t)return this.events.get(t);let r=Array.from(this.events.values()).find(e=>e.props.properties.topic===i);if(r)return fw(fw({},r),this.setMethods(r.eventId))}),fb(this,"deleteEvent",e=>{let{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0}),fb(this,"setEventListeners",()=>{this.core.heartbeat.on(dO.HEARTBEAT_EVENTS.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(e=>{(0,rA.fromMiliseconds)(Date.now())-(0,rA.fromMiliseconds)(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)})})}),fb(this,"setMethods",e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)})),fb(this,"addTrace",(e,t)=>{let i=this.events.get(e);i&&(i.props.properties.trace.push(t),this.events.set(e,i),this.shouldPersist=!0)}),fb(this,"setError",(e,t)=>{let i=this.events.get(e);i&&(i.props.type=t,i.timestamp=Date.now(),this.events.set(e,i),this.shouldPersist=!0)}),fb(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),fb(this,"restore",async()=>{try{let e=await this.core.storage.getItem(this.storageKey)||[];if(!e.length)return;e.forEach(e=>{this.events.set(e.eventId,fw(fw({},e),this.setMethods(e.eventId)))})}catch(e){this.logger.warn(e)}}),fb(this,"submit",async()=>{if(!this.telemetryEnabled||0===this.events.size)return;let e=[];for(let[t,i]of this.events)i.props.type&&e.push(i);if(0!==e.length)try{if((await this.sendEvent(e)).ok)for(let t of e)this.events.delete(t.eventId),this.shouldPersist=!0}catch(e){this.logger.warn(e)}}),fb(this,"sendEvent",async e=>{let t=this.getAppDomain()?"":"&sp=desktop";return await fetch(`https://pulse.walletconnect.org/batch?projectId=${this.core.projectId}&st=events_sdk&sv=js-${ua}${t}`,{method:"POST",body:JSON.stringify(e)})}),fb(this,"getAppDomain",()=>aN().url),this.logger=ad(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}}var fE=Object.defineProperty,fI=Object.getOwnPropertySymbols,fS=Object.prototype.hasOwnProperty,fA=Object.prototype.propertyIsEnumerable,fx=(e,t,i)=>t in e?fE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,fP=(e,t)=>{for(var i in t||(t={}))fS.call(t,i)&&fx(e,i,t[i]);if(fI)for(var i of fI(t))fA.call(t,i)&&fx(e,i,t[i]);return e},fC=(e,t,i)=>fx(e,"symbol"!=typeof t?t+"":t,i);class f_ extends dD{constructor(e){var t;super(e),fC(this,"protocol","wc"),fC(this,"version",2),fC(this,"name",d1),fC(this,"relayUrl"),fC(this,"projectId"),fC(this,"customStoragePrefix"),fC(this,"events",new rE.EventEmitter),fC(this,"logger"),fC(this,"heartbeat"),fC(this,"relayer"),fC(this,"crypto"),fC(this,"storage"),fC(this,"history"),fC(this,"expirer"),fC(this,"pairing"),fC(this,"verify"),fC(this,"echoClient"),fC(this,"linkModeSupportedApps"),fC(this,"eventClient"),fC(this,"initialized",!1),fC(this,"logChunkController"),fC(this,"on",(e,t)=>this.events.on(e,t)),fC(this,"once",(e,t)=>this.events.once(e,t)),fC(this,"off",(e,t)=>this.events.off(e,t)),fC(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),fC(this,"dispatchEnvelope",({topic:e,message:t,sessionExists:i})=>{if(!e||!t)return;let r={topic:e,message:t,publishedAt:Date.now(),transportType:uo};this.relayer.onLinkMessageEvent(r,{sessionExists:i})});const i=this.getGlobalCore(e?.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}catch(e){console.warn("Failed to copy global core",e)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||d4,this.customStoragePrefix=null!=e&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const{logger:r,chunkLoggerController:s}=au({opts:function(e){return ar(ac({},e),as({level:e?.level||"info"}))}({level:"string"==typeof e?.logger&&e.logger?e.logger:"error",name:d1}),maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,null!=(t=this.logChunkController)&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var e,t;null!=(e=this.logChunkController)&&e.downloadLogsBlobInBrowser&&(null==(t=this.logChunkController)||t.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=ad(r,this.name),this.heartbeat=new dO.HeartBeat,this.crypto=new po(this,this.logger,e?.keychain),this.history=new fr(this,this.logger),this.expirer=new fa(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new dT.default(fP(fP({},d5),e?.storageOptions)),this.relayer=new pV({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new fe(this,this.logger),this.verify=new fc(this,this.logger,this.storage),this.echoClient=new fu(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new fv(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){let t=new f_(e);await t.initialize();let i=await t.crypto.getClientId();return await t.storage.setItem("WALLETCONNECT_CLIENT_ID",i),t}get context(){return ah(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return null==(e=this.logChunkController)?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(uh,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(
14),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(uh)||[],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;let 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(e){console.warn("Failed to get global WalletConnect core",e);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;let i=`_walletConnectCore_${(null==(t=e.opts)?void 0:t.customStoragePrefix)||""}`;globalThis[i]=e}catch(e){console.warn("Failed to set global WalletConnect core",e)}}isGlobalCoreDisabled(){try{return"u">typeof rI.default&&"true"===rI.default.env.DISABLE_GLOBAL_CORE}catch{return!0}}}let fk="client",fO=`wc@2:${fk}:`,fT="WALLETCONNECT_DEEPLINK_CHOICE",fR=(rA.THIRTY_DAYS,"Proposal expired"),fN=rA.SEVEN_DAYS,fj={wc_sessionPropose:{req:{ttl:rA.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:rA.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:rA.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:rA.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:rA.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:rA.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:rA.ONE_DAY,prompt:!1,tag:1104},res:{ttl:rA.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:rA.ONE_DAY,prompt:!1,tag:1106},res:{ttl:rA.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:rA.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:rA.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:rA.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:rA.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:rA.ONE_DAY,prompt:!1,tag:1112},res:{ttl:rA.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:rA.ONE_DAY,prompt:!1,tag:1114},res:{ttl:rA.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:rA.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:rA.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:rA.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:rA.FIVE_MINUTES,prompt:!1,tag:1119}}},fD={min:rA.FIVE_MINUTES,max:rA.SEVEN_DAYS},fM="IDLE",fU="ACTIVE",fB={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:""}},fL=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],fq="[email protected]:auth:",fK=`${fq}:PUB_KEY`;var fH=Object.defineProperty,f$=Object.defineProperties,fW=Object.getOwnPropertyDescriptors,fz=Object.getOwnPropertySymbols,fF=Object.prototype.hasOwnProperty,fV=Object.prototype.propertyIsEnumerable,fJ=(e,t,i)=>t in e?fH(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,fG=(e,t)=>{for(var i in t||(t={}))fF.call(t,i)&&fJ(e,i,t[i]);if(fz)for(var i of fz(t))fV.call(t,i)&&fJ(e,i,t[i]);return e},fY=(e,t,i)=>fJ(e,"symbol"!=typeof t?t+"":t,i);class fZ extends dY{constructor(t){super(t),fY(this,"name","engine"),fY(this,"events",new rE.default),fY(this,"initialized",!1),fY(this,"requestQueue",{state:fM,queue:[]}),fY(this,"sessionRequestQueue",{state:fM,queue:[]}),fY(this,"emittedSessionRequests",new aQ({limit:500})),fY(this,"requestQueueDelay",rA.ONE_SECOND),fY(this,"expectedPairingMethodMap",new Map),fY(this,"recentlyDeletedMap",new Map),fY(this,"recentlyDeletedLimit",200),fY(this,"relayMessageCache",[]),fY(this,"pendingSessions",new Map),fY(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(fj)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,rA.toMiliseconds)(this.requestQueueDelay)))}),fY(this,"connect",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();let t=f$(fG({},e),fW({requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}}));await this.isValidConnect(t),t.optionalNamespaces=function(e,t){var i,r,s,n,a,o;let l=dr(e),c=dr(t),h={};for(let e of Object.keys(l).concat(Object.keys(c)))h[e]={chains:az(null==(i=l[e])?void 0:i.chains,null==(r=c[e])?void 0:r.chains),methods:az(null==(s=l[e])?void 0:s.methods,null==(n=c[e])?void 0:n.methods),events:az(null==(a=l[e])?void 0:a.events,null==(o=c[e])?void 0:o.events)};return h}(t.requiredNamespaces,t.optionalNamespaces),t.requiredNamespaces={};let{pairingTopic:i,requiredNamespaces:r,optionalNamespaces:s,sessionProperties:n,scopedProperties:a,relays:o}
14=t,l=i,c,h=!1;try{if(l){let e=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=e.active}}catch(e){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),e}if(!l||!h){let{topic:e,uri:t}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});l=e,c=t}if(!l){let{message:e}=dl("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw Error(e)}let d=await this.client.core.crypto.generateKeyPair(),u=fj.wc_sessionPropose.req.ttl||rA.FIVE_MINUTES,p=aH(u),f=f$(fG(fG({requiredNamespaces:r,optionalNamespaces:s,relays:o??[{protocol:"irn"}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:p,pairingTopic:l},n&&{sessionProperties:n}),a&&{scopedProperties:a}),fW({id:(0,dQ.payloadId)()})),g=aW("session_connect",f.id),{reject:y,resolve:m,done:w}=aB(u,fR),b=({id:e})=>{e===f.id&&(this.client.events.off("proposal_expire",b),this.pendingSessions.delete(f.id),this.events.emit(g,{error:{message:fR,code:0}}))};return this.client.events.on("proposal_expire",b),this.events.once(g,({error:e,session:t})=>{this.client.events.off("proposal_expire",b),e?y(e):t&&m(t)}),await this.sendProposeSession({proposal:f,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:f.id}}}),await this.setProposal(f.id,f),{uri:c,approval:w}}),fY(this,"pair",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(e){throw this.client.logger.error("pair() failed"),e}}),fY(this,"approve",async e=>{var t,i,r;let s=this.client.core.eventClient.createEvent({properties:{topic:null==(t=e?.id)?void 0:t.toString(),trace:[uP]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(e){throw s.setError("no_internet_connection"),e}try{await this.isValidProposalId(e?.id)}catch(t){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),s.setError("proposal_not_found"),t}try{await this.isValidApprove(e)}catch(e){throw this.client.logger.error("approve() -> isValidApprove() failed"),s.setError("session_approve_namespace_validation_failure"),e}let{id:n,relayProtocol:a,namespaces:o,sessionProperties:l,scopedProperties:c,sessionConfig:h}=e,d=this.client.proposal.get(n);this.client.core.eventClient.deleteEvent({eventId:s.eventId});let{pairingTopic:u,proposer:p,requiredNamespaces:f,optionalNamespaces:g}=d,y=null==(i=this.client.core.eventClient)?void 0:i.getEvent({topic:u});y||(y=null==(r=this.client.core.eventClient)?void 0:r.createEvent({type:uP,properties:{topic:u,trace:[uP,"session_namespaces_validation_success"]}}));let m=await this.client.core.crypto.generateKeyPair(),w=p.publicKey,b=await this.client.core.crypto.generateSharedKey(m,w),v=fG(fG(fG({relay:{protocol:a??"irn"},namespaces:o,controller:{publicKey:m,metadata:this.client.metadata},expiry:aH(fN)},l&&{sessionProperties:l}),c&&{scopedProperties:c}),h&&{sessionConfig:h});y.addTrace("subscribing_session_topic");try{await this.client.core.relayer.subscribe(b,{transportType:ul,internal:{skipSubscribe:!0}})}catch(e){throw y.setError("subscribe_session_topic_failure"),e}y.addTrace("subscribe_session_topic_success");let E=f$(fG({},v),fW({topic:b,requiredNamespaces:f,optionalNamespaces:g,pairingTopic:u,acknowledged:!1,self:v.controller,peer:{publicKey:p.publicKey,metadata:p.metadata},controller:m,transportType:ul}));await this.client.session.set(b,E),y.addTrace("store_session");try{await this.sendApproveSession({sessionTopic:b,proposal:d,pairingProposalResponse:{relay:{protocol:a??"irn"},responderPublicKey:m},sessionSettleRequest:v,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:n}}}),y.addTrace("session_approve_publish_success")}catch(e){throw this.client.logger.error(e),this.client.session.delete(b,dc("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(b),e}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:u,metadata:p.metadata}),await this.deleteProposal(n),await this.client.core.pairing.activate({topic:u}),await this.setExpiry(b,aH(fN)),{topic:b,acknowledged:()=>Promise.resolve(this.client.session.get(b))}}),fY(this,"reject",async e=>{let t;this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(e){throw this.client.logger.error("reject() -> isValidReject() failed"),e}let{id:i,reason:r}=e;try{t=this.client.proposal.get(i).pairingTopic}catch(e){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),e}
14t&&await this.sendError({id:i,topic:t,error:r,rpcOpts:fj.wc_sessionPropose.reject}),await this.deleteProposal(i)}),fY(this,"update",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(e){throw this.client.logger.error("update() -> isValidUpdate() failed"),e}let{topic:t,namespaces:i}=e,{done:r,resolve:s,reject:n}=aB(),a=(0,dQ.payloadId)(),o=(0,dQ.getBigIntRpcId)().toString(),l=this.client.session.get(t).namespaces;return this.events.once(aW("session_update",a),({error:e})=>{e?n(e):s()}),await this.client.session.update(t,{namespaces:i}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:o}).catch(e=>{this.client.logger.error(e),this.client.session.update(t,{namespaces:l}),n(e)}),{acknowledged:r}}),fY(this,"extend",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(e){throw this.client.logger.error("extend() -> isValidExtend() failed"),e}let{topic:t}=e,i=(0,dQ.payloadId)(),{done:r,resolve:s,reject:n}=aB();return this.events.once(aW("session_extend",i),({error:e})=>{e?n(e):s()}),await this.setExpiry(t,aH(fN)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(e=>{n(e)}),{acknowledged:r}}),fY(this,"request",async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(e){throw this.client.logger.error("request() -> isValidRequest() failed"),e}let{chainId:t,request:i,topic:r,expiry:s=fj.wc_sessionRequest.req.ttl}=e,n=this.client.session.get(r);n?.transportType===ul&&await this.confirmOnlineStateOrThrow();let a=(0,dQ.payloadId)(),o=(0,dQ.getBigIntRpcId)().toString(),{done:l,resolve:c,reject:h}=aB(s,"Request expired. Please try again.");this.events.once(aW("session_request",a),({error:e,result:t})=>{e?h(e):c(t)});let d="wc_sessionRequest",u=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);if(u)return await this.sendRequest({clientRpcId:a,relayRpcId:o,topic:r,method:d,params:{request:f$(fG({},i),fW({expiryTimestamp:aH(s)})),chainId:t},expiry:s,throwOnFailedPublish:!0,appLink:u}).catch(e=>h(e)),this.client.events.emit("session_request_sent",{topic:r,request:i,chainId:t,id:a}),await l();let p={request:f$(fG({},i),fW({expiryTimestamp:aH(s)})),chainId:t};return await Promise.all([new Promise(async e=>{await this.sendRequest({clientRpcId:a,relayRpcId:o,topic:r,method:d,params:p,expiry:s,throwOnFailedPublish:!0,tvf:this.getTVFParams(a,p)}).catch(e=>h(e)),this.client.events.emit("session_request_sent",{topic:r,request:i,chainId:t,id:a}),e()}),new Promise(async e=>{var t;if(!(null!=(t=n.sessionConfig)&&t.disableDeepLink)){let e=await aV(this.client.core.storage,fT);await aF({id:a,topic:r,wcDeepLink:e})}e()}),l()]).then(e=>e[2])}),fY(this,"respond",async e=>{var t,i;this.isInitialized();let r=this.client.core.eventClient.createEvent({properties:{topic:e?.topic||(null==(i=null==(t=e?.response)?void 0:t.id)?void 0:i.toString()),trace:["session_request_response_started"]}});try{await this.isValidRespond(e)}catch(e){throw r.addTrace(e?.message),r.setError("session_request_response_validation_failure"),e}r.addTrace("session_request_response_validation_success");let{topic:s,response:n}=e,{id:a}=n,o=this.client.session.get(s);o.transportType===ul&&await this.confirmOnlineStateOrThrow();let l=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);try{r.addTrace("session_request_response_publish_started"),(0,dX.isJsonRpcResult)(n)?await this.sendResult({id:a,topic:s,result:n.result,throwOnFailedPublish:!0,appLink:l}):(0,dX.isJsonRpcError)(n)&&await this.sendError({id:a,topic:s,error:n.error,appLink:l}),this.cleanupAfterResponse(e)}catch(e){throw r.addTrace(e?.message),r.setError("session_request_response_publish_failure"),e}}),fY(this,"ping",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(e){throw this.client.logger.error("ping() -> isValidPing() failed"),e}let{topic:t}=e;if(this.client.session.keys.includes(t)){let e=(0,dQ.payloadId)(),i=(0,dQ.getBigIntRpcId)().toString(),{done:r,resolve:s,reject:n}=aB();this.events.once(aW("session_ping",e),({error:e})=>{e?n(e):s()}),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:e,relayRpcId:i}),r()])}else this.client.core.pairing.pairings.keys.includes(t)&&(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:t}))}),fY(this,"emit",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);
14let{topic:t,event:i,chainId:r}=e,s=(0,dQ.getBigIntRpcId)().toString(),n=(0,dQ.payloadId)();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:i,chainId:r},throwOnFailedPublish:!0,relayRpcId:s,clientRpcId:n})}),fY(this,"disconnect",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);let{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:dc("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(t))await this.client.core.pairing.disconnect({topic:t});else{let{message:e}=dl("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw Error(e)}}),fY(this,"find",e=>(this.isInitialized(),this.client.session.getAll().filter(t=>(function(e,t){let{requiredNamespaces:i}=t,r=Object.keys(e.namespaces),s=Object.keys(i),n=!0;return!!aD(s,r)&&(r.forEach(t=>{let{accounts:r,methods:s,events:a}=e.namespaces[t],o=de(r),l=i[t];aD(ag(t,l),o)&&aD(l.methods,s)&&aD(l.events,a)||(n=!1)}),n)})(t,e)))),fY(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),fY(this,"authenticate",async(e,t)=>{var i,r,s,n,a;let o;this.isInitialized(),this.isValidAuthenticate(e);let l=t&&this.client.core.linkModeSupportedApps.includes(t)&&(null==(i=this.client.metadata.redirect)?void 0:i.linkMode),c=l?uo:ul;c===ul&&await this.confirmOnlineStateOrThrow();let{chains:h,statement:d="",uri:u,domain:p,nonce:f,type:g,exp:y,nbf:m,methods:w=[],expiry:b}=e,v=[...e.resources||[]],{topic:E,uri:I}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:c});this.client.logger.info({message:"Generated new pairing",pairing:{topic:E,uri:I}});let S=await this.client.core.crypto.generateKeyPair(),A=hR(S);if(await Promise.all([this.client.auth.authKeys.set(fK,{responseTopic:A,publicKey:S}),this.client.auth.pairingTopics.set(A,{topic:A,pairingTopic:E})]),await this.client.core.relayer.subscribe(A,{transportType:c}),this.client.logger.info(`sending request to new pairing topic: ${E}`),w.length>0){let e,t,{namespace:i}=ap(h[0]),o=lT(function(e,t,i,r={}){return i?.sort((e,t)=>e.localeCompare(t)),{att:{[e]:function(e,t,i={}){return Object.assign({},...(t=t?.sort((e,t)=>e.localeCompare(t))).map(t=>({[`${e}/${t}`]:[i]})))}(t,i,r)}}}(i,"request",w));lD(v)&&(r=o,s=v.pop(),o=lT((n=lR(r),a=lR(s),lO(n),lO(a),e=Object.keys(n.att).concat(Object.keys(a.att)).sort((e,t)=>e.localeCompare(t)),t={att:{}},e.forEach(e=>{var i,r;Object.keys((null==(i=n.att)?void 0:i[e])||{}).concat(Object.keys((null==(r=a.att)?void 0:r[e])||{})).sort((e,t)=>e.localeCompare(t)).forEach(i=>{var r,s;t.att[e]=lb(((e,t)=>{for(var i in t||(t={}))lI.call(t,i)&&lA(e,i,t[i]);if(lE)for(var i of lE(t))lS.call(t,i)&&lA(e,i,t[i]);return e})({},t.att[e]),lv({[i]:(null==(r=n.att[e])?void 0:r[i])||(null==(s=a.att[e])?void 0:s[i])}))})}),t))),v.push(o)}let x=b&&b>fj.wc_sessionAuthenticate.req.ttl?b:fj.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:g??"caip122",chains:h,statement:d,aud:u,domain:p,version:"1",nonce:f,iat:new Date().toISOString(),exp:y,nbf:m,resources:v},requester:{publicKey:S,metadata:this.client.metadata},expiryTimestamp:aH(x)},C={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:h,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:E,proposer:{publicKey:S,metadata:this.client.metadata},expiryTimestamp:aH(fj.wc_sessionPropose.req.ttl),id:(0,dQ.payloadId)()},{done:_,resolve:k,reject:O}=aB(x,"Request expired"),T=(0,dQ.payloadId)(),R=aW("session_connect",C.id),N=aW("session_request",T),j=async({error:e,session:t})=>{this.events.off(N,D),e?O(e):t&&k({session:t})},D=async e=>{var i,r,s;let n;if(await this.deletePendingAuthRequest(T,{message:"fulfilled",code:0}),e.error){let t=dc("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(R,j),O(e.error.message))}
14await this.deleteProposal(C.id),this.events.off(R,j);let{cacaos:a,responder:o}=e.result,l=[],h=[];for(let e of a){await l_({cacao:e,projectId:this.client.core.projectId})||(this.client.logger.error(e,"Signature verification failed"),O(dc("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:t}=e,i=lD(t.resources),r=[lP(t.iss)],s=lC(t.iss);if(i){let e=lN(i),t=lj(i);l.push(...e),r.push(...t)}for(let e of r)h.push(`${e}:${s}`)}let d=await this.client.core.crypto.generateSharedKey(S,o.publicKey);l.length>0&&(n={topic:d,acknowledged:!0,self:{publicKey:S,metadata:this.client.metadata},peer:o,controller:o.publicKey,expiry:aH(fN),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:E,namespaces:ds([...new Set(l)],[...new Set(h)]),transportType:c},await this.client.core.relayer.subscribe(d,{transportType:c}),await this.client.session.set(d,n),E&&await this.client.core.pairing.updateMetadata({topic:E,metadata:o.metadata}),n=this.client.session.get(d)),null!=(i=this.client.metadata.redirect)&&i.linkMode&&null!=(r=o.metadata.redirect)&&r.linkMode&&null!=(s=o.metadata.redirect)&&s.universal&&t&&(this.client.core.addLinkModeSupportedApp(o.metadata.redirect.universal),this.client.session.update(d,{transportType:uo})),k({auths:a,session:n})};this.events.once(R,j),this.events.once(N,D);try{if(l){let e=(0,dQ.formatJsonRpcRequest)("wc_sessionAuthenticate",P,T);this.client.core.history.set(E,e);let i=await this.client.core.crypto.encode("",e,{type:2,encoding:hk});o=h0(t,E,i)}else await Promise.all([this.sendRequest({topic:E,method:"wc_sessionAuthenticate",params:P,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:T}),this.sendRequest({topic:E,method:"wc_sessionPropose",params:C,expiry:fj.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:C.id})])}catch(e){throw this.events.off(R,j),this.events.off(N,D),e}return await this.setProposal(C.id,C),await this.setAuthRequest(T,{request:f$(fG({},P),fW({verifyContext:{}})),pairingTopic:E,transportType:c}),{uri:o??I,response:_}}),fY(this,"approveSessionAuthenticate",async e=>{let t,{id:i,auths:r}=e,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:["authenticated_session_approve_started"]}});try{this.isInitialized()}catch(e){throw s.setError("no_internet_connection"),e}let n=this.getPendingAuthRequest(i);if(!n)throw s.setError("authenticated_session_pending_request_not_found"),Error(`Could not find pending auth request with id ${i}`);let a=n.transportType||ul;a===ul&&await this.confirmOnlineStateOrThrow();let o=n.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),c=hR(o),h={type:1,receiverPublicKey:o,senderPublicKey:l},d=[],u=[];for(let e of r){if(!await l_({cacao:e,projectId:this.client.core.projectId})){s.setError("invalid_cacao");let e=dc("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:c,error:e,encodeOpts:h}),Error(e.message)}s.addTrace("cacaos_verified");let{p:t}=e,r=lD(t.resources),n=[lP(t.iss)],a=lC(t.iss);if(r){let e=lN(r),t=lj(r);d.push(...e),n.push(...t)}for(let e of n)u.push(`${e}:${a}`)}let p=await this.client.core.crypto.generateSharedKey(l,o);if(s.addTrace("create_authenticated_session_topic"),d?.length>0){t={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:o,metadata:n.requester.metadata},controller:o,expiry:aH(fN),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:n.pairingTopic,namespaces:ds([...new Set(d)],[...new Set(u)]),transportType:a},s.addTrace("subscribing_authenticated_session_topic");try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(e){throw s.setError("subscribe_authenticated_session_topic_failure"),e}s.addTrace("subscribe_authenticated_session_topic_success"),await this.client.session.set(p,t),s.addTrace("store_authenticated_session"),await this.client.core.pairing.updateMetadata({topic:n.pairingTopic,metadata:n.requester.metadata})}s.addTrace("publishing_authenticated_session_approve");
14try{await this.sendResult({topic:c,id:i,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(n.requester.metadata,a)})}catch(e){throw s.setError("authenticated_session_approve_publish_failure"),e}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:n.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:t}}),fY(this,"rejectSessionAuthenticate",async e=>{this.isInitialized();let{id:t,reason:i}=e,r=this.getPendingAuthRequest(t);if(!r)throw Error(`Could not find pending auth request with id ${t}`);r.transportType===ul&&await this.confirmOnlineStateOrThrow();let s=r.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),a=hR(s);await this.sendError({id:t,topic:a,error:i,encodeOpts:{type:1,receiverPublicKey:s,senderPublicKey:n},rpcOpts:fj.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(r.requester.metadata,r.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.deleteProposal(t)}),fY(this,"formatAuthMessage",e=>{this.isInitialized();let{request:t,iss:i}=e;return lk(t,i)}),fY(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(0!==this.relayMessageCache.length)for(;this.relayMessageCache.length>0;)try{let e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}},50)}),fY(this,"cleanupDuplicatePairings",async e=>{if(e.pairingTopic)try{let t=this.client.core.pairing.pairings.get(e.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(i=>{var r,s;return(null==(r=i.peerMetadata)?void 0:r.url)&&(null==(s=i.peerMetadata)?void 0:s.url)===e.peer.metadata.url&&i.topic&&i.topic!==t.topic});if(0===i.length)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(e=>this.client.core.pairing.disconnect({topic:e.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}}),fY(this,"deleteSession",async e=>{var t;let{topic:i,expirerHasDeleted:r=!1,emitEvent:s=!0,id:n=0}=e,{self:a}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,dc("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),r||this.client.core.expirer.del(i),this.client.core.storage.removeItem(fT).catch(e=>this.client.logger.warn(e)),this.getPendingSessionRequests().forEach(e=>{e.topic===i&&this.deletePendingSessionRequest(e.id,dc("USER_DISCONNECTED"))}),i===(null==(t=this.sessionRequestQueue.queue[0])?void 0:t.topic)&&(this.sessionRequestQueue.state=fM),s&&this.client.events.emit("session_delete",{id:n,topic:i})}),fY(this,"deleteProposal",async(e,t)=>{if(t)try{let t=this.client.proposal.get(e),i=this.client.core.eventClient.getEvent({topic:t.pairingTopic});i?.setError("proposal_expired")}catch{}await Promise.all([this.client.proposal.delete(e,dc("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")}),fY(this,"deletePendingSessionRequest",async(e,t,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),i?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(t=>t.id!==e),i&&(this.sessionRequestQueue.state=fM,this.client.events.emit("session_request_expire",{id:e}))}),fY(this,"deletePendingAuthRequest",async(e,t,i=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),i?Promise.resolve():this.client.core.expirer.del(e)])}),fY(this,"setExpiry",async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))}),fY(this,"setProposal",async(e,t)=>{this.client.core.expirer.set(e,aH(fj.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)}),fY(this,"setAuthRequest",async(e,t)=>{let{request:i,pairingTopic:r,transportType:s=ul}=t;this.client.core.expirer.set(e,i.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:e,pairingTopic:r,verifyContext:i.verifyContext,transportType:s})}),fY(this,"setPendingSessionRequest",async e=>{let{id:t,topic:i,params:r,verifyContext:s}=e,n=r.request.expiryTimestamp||aH(fj.wc_sessionRequest.req.ttl);
14this.client.core.expirer.set(t,n),await this.client.pendingRequest.set(t,{id:t,topic:i,params:r,verifyContext:s})}),fY(this,"sendRequest",async t=>{let i,r,{topic:s,method:n,params:a,expiry:o,relayRpcId:l,clientRpcId:c,throwOnFailedPublish:h,appLink:d,tvf:u,publishOpts:p={}}=t,f=(0,dQ.formatJsonRpcRequest)(n,a,c),g=!!d;try{let e=g?hk:h_;i=await this.client.core.crypto.encode(s,f,{encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),e}if(fL.includes(n)){let e=hN(JSON.stringify(f)),t=hN(i);r=await this.client.core.verify.register({id:t,decryptedId:e})}let y=fG(fG({},fj[n].req),p);if(y.attestation=r,o&&(y.ttl=o),l&&(y.id=l),this.client.core.history.set(s,f),g){let t=h0(d,s,i);await e.g.Linking.openURL(t,this.client.name)}else{let e;y.tvf=f$(fG({},u),fW({correlationId:f.id})),h?(e=fG({},y.internal),y.internal=f$(e,fW({throwOnFailedPublish:!0})),await this.client.core.relayer.publish(s,i,y)):this.client.core.relayer.publish(s,i,y).catch(e=>this.client.logger.error(e))}return f.id}),fY(this,"sendProposeSession",async e=>{let{proposal:t,publishOpts:i}=e,r=(0,dQ.formatJsonRpcRequest)("wc_sessionPropose",t,t.id);this.client.core.history.set(t.pairingTopic,r);let s=await this.client.core.crypto.encode(t.pairingTopic,r,{encoding:h_}),n=hN(JSON.stringify(r)),a=hN(s),o=await this.client.core.verify.register({id:a,decryptedId:n});await this.client.core.relayer.publishCustom({payload:{pairingTopic:t.pairingTopic,sessionProposal:s},opts:f$(fG({},i),fW({publishMethod:"wc_proposeSession",attestation:o}))})}),fY(this,"sendApproveSession",async e=>{let{sessionTopic:t,pairingProposalResponse:i,proposal:r,sessionSettleRequest:s,publishOpts:n}=e,a=(0,dQ.formatJsonRpcResult)(r.id,i),o=await this.client.core.crypto.encode(r.pairingTopic,a,{encoding:h_}),l=(0,dQ.formatJsonRpcRequest)("wc_sessionSettle",s,n?.id),c=await this.client.core.crypto.encode(t,l,{encoding:h_});this.client.core.history.set(t,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:t,pairingTopic:r.pairingTopic,sessionProposalResponse:o,sessionSettlementRequest:c},opts:f$(fG({},n),fW({publishMethod:"wc_approveSession"}))})}),fY(this,"sendResult",async t=>{let i,r,s,{id:n,topic:a,result:o,throwOnFailedPublish:l,encodeOpts:c,appLink:h}=t,d=(0,dQ.formatJsonRpcResult)(n,o),u=h&&"u">typeof(null==e.g?void 0:e.g.Linking);try{let e,t,r=u?hk:h_;i=await this.client.core.crypto.encode(a,d,(e=fG({},c||{}),t={encoding:r},f$(e,fW(t))))}catch(e){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${a} failed`),e}try{let e=(r=await this.client.core.history.get(a,n)).request;try{s=this.getTVFParams(n,e.params,o)}catch(e){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${e?.message}`)}}catch(e){throw this.client.logger.error(`sendResult() -> history.get(${a}, ${n}) failed`),e}if(u){let t=h0(h,a,i);await e.g.Linking.openURL(t,this.client.name)}else{let e,t=fj[r.request.method].res;t.tvf=f$(fG({},s),fW({correlationId:n})),l?(e=fG({},t.internal),t.internal=f$(e,fW({throwOnFailedPublish:!0})),await this.client.core.relayer.publish(a,i,t)):this.client.core.relayer.publish(a,i,t).catch(e=>this.client.logger.error(e))}await this.client.core.history.resolve(d)}),fY(this,"sendError",async t=>{let i,r,{id:s,topic:n,error:a,encodeOpts:o,rpcOpts:l,appLink:c}=t,h=(0,dQ.formatJsonRpcError)(s,a),d=c&&"u">typeof(null==e.g?void 0:e.g.Linking);try{let e,t,r=d?hk:h_;i=await this.client.core.crypto.encode(n,h,(e=fG({},o||{}),t={encoding:r},f$(e,fW(t))))}catch(e){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),e}try{r=await this.client.core.history.get(n,s)}catch(e){throw this.client.logger.error(`sendError() -> history.get(${n}, ${s}) failed`),e}if(d){let t=h0(c,n,i);await e.g.Linking.openURL(t,this.client.name)}else{let e=r.request.method,t=l||fj[e].res;this.client.core.relayer.publish(n,i,t)}await this.client.core.history.resolve(h)}),fY(this,"cleanup",async()=>{let e=[],t=[];
14this.client.session.getAll().forEach(t=>{let i=!1;a$(t.expiry)&&(i=!0),this.client.core.crypto.keychain.has(t.topic)||(i=!0),i&&e.push(t.topic)}),this.client.proposal.getAll().forEach(e=>{a$(e.expiryTimestamp)&&t.push(e.id)}),await Promise.all([...e.map(e=>this.deleteSession({topic:e})),...t.map(e=>this.deleteProposal(e))])}),fY(this,"onProviderMessageEvent",async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)}),fY(this,"onRelayEventRequest",async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()}),fY(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===fU)return void this.client.logger.info("Request queue already active, skipping...");for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=fU;let e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=fM}),fY(this,"processRequest",async e=>{let{topic:t,payload:i,attestation:r,transportType:s,encryptedId:n}=e,a=i.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:a}))switch(a){case"wc_sessionPropose":return await this.onSessionProposeRequest
14({topic:t,payload:i,attestation:r,encryptedId:n});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,i);case"wc_sessionPing":return await this.onSessionPingRequest(t,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:i,attestation:r,encryptedId:n,transportType:s});case"wc_sessionEvent":return await this.onSessionEventRequest(t,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:i,attestation:r,encryptedId:n,transportType:s});default:return this.client.logger.info(`Unsupported request method ${a}`)}}),fY(this,"onRelayEventResponse",async e=>{let{topic:t,payload:i,transportType:r}=e,s=(await this.client.core.history.get(t,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(t,i,r);case"wc_sessionSettle":return this.onSessionSettleResponse(t,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,i);case"wc_sessionExtend":return this.onSessionExtendResponse(t,i);case"wc_sessionPing":return this.onSessionPingResponse(t,i);case"wc_sessionRequest":return this.onSessionRequestResponse(t,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}}),fY(this,"onRelayEventUnknownPayload",e=>{let{topic:t}=e,{message:i}=dl("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw Error(i)}),fY(this,"shouldIgnorePairingRequest",e=>{let{topic:t,requestMethod:i}=e,r=this.expectedPairingMethodMap.get(t);return!(!r||r.includes(i))&&!!(r.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),fY(this,"onSessionProposeRequest",async e=>{let{topic:t,payload:i,attestation:r,encryptedId:s}=e,{params:n,id:a}=i;try{let e=this.client.core.eventClient.getEvent({topic:t});0===this.client.events.listenerCount("session_proposal")&&(console.warn("No listener for session_proposal event"),e?.setError("proposal_listener_not_found")),this.isValidConnect(fG({},i.params));let o=n.expiryTimestamp||aH(fj.wc_sessionPropose.req.ttl),l=fG({id:a,pairingTopic:t,expiryTimestamp:o,attestation:r,encryptedId:s},n);await this.setProposal(a,l);let c=await this.getVerifyContext({attestationId:r,hash:hN(JSON.stringify(i)),encryptedId:s,metadata:l.proposer.metadata});e?.addTrace("emit_session_proposal"),this.client.events.emit("session_proposal",{id:a,params:l,verifyContext:c})}catch(e){await this.sendError({id:a,topic:t,error:e,rpcOpts:fj.wc_sessionPropose.autoReject}),this.client.logger.error(e)}}),fY(this,"onSessionProposeResponse",async(e,t,i)=>{let{id:r}=t;if((0,dX.isJsonRpcResult)(t)){let{result:s}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});let n=this.client.proposal.get(r);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});let a=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});let o=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:o});let l=await this.client.core.crypto.generateSharedKey(a,o);this.pendingSessions.set(r,{sessionTopic:l,pairingTopic:e,proposalId:r,publicKey:a});let c=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:c}),await this.client.core.pairing.activate({topic:e})}else if((0,dX.isJsonRpcError)(t)){await this.deleteProposal(r);let e=aW("session_connect",r);if(0===this.events.listenerCount(e))throw Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:t.error})}}),fY(this,"onSessionSettleRequest",async(e,t)=>{let{id:i,params:r}=t;try{let i,s;this.isValidSessionSettleRequest(r);let{relay:n,controller:a,expiry:o,namespaces:l,sessionProperties:c,scopedProperties:h,sessionConfig:d}=t.params,u=[...this.pendingSessions.values()].find(t=>t.sessionTopic===e);if(!u)return this.client.logger.error(`Pending session not found for topic ${e}`);
14let p=this.client.proposal.get(u.proposalId),f=(i=fG(fG(fG({topic:e,relay:n,expiry:o,namespaces:l,acknowledged:!0,pairingTopic:u.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:u.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},c&&{sessionProperties:c}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),s={transportType:ul},f$(i,fW(s)));await this.client.session.set(f.topic,f),await this.setExpiry(f.topic,f.expiry),await this.client.core.pairing.updateMetadata({topic:u.pairingTopic,metadata:f.peer.metadata}),this.client.events.emit("session_connect",{session:f}),this.events.emit(aW("session_connect",u.proposalId),{session:f}),this.pendingSessions.delete(u.proposalId),this.deleteProposal(u.proposalId,!1),this.cleanupDuplicatePairings(f),await this.sendResult({id:t.id,topic:e,result:!0})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}}),fY(this,"onSessionSettleResponse",async(e,t)=>{let{id:i}=t;(0,dX.isJsonRpcResult)(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(aW("session_approve",i),{})):(0,dX.isJsonRpcError)(t)&&(await this.client.session.delete(e,dc("USER_DISCONNECTED")),this.events.emit(aW("session_approve",i),{error:t.error}))}),fY(this,"onSessionUpdateRequest",async(e,t)=>{let{params:i,id:r}=t;try{let t=`${e}_session_update`,s=dC.get(t);if(s&&this.isRequestOutOfSync(s,r)){this.client.logger.warn(`Discarding out of sync request - ${r}`),this.sendError({id:r,topic:e,error:dc("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(fG({topic:e},i));try{dC.set(t,r),await this.client.session.update(e,{namespaces:i.namespaces}),await this.sendResult({id:r,topic:e,result:!0})}catch(e){throw dC.delete(t),e}this.client.events.emit("session_update",{id:r,topic:e,params:i})}catch(t){await this.sendError({id:r,topic:e,error:t}),this.client.logger.error(t)}}),fY(this,"isRequestOutOfSync",(e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3)),fY(this,"onSessionUpdateResponse",(e,t)=>{let{id:i}=t,r=aW("session_update",i);if(0===this.events.listenerCount(r))throw Error(`emitting ${r} without any listeners`);(0,dX.isJsonRpcResult)(t)?this.events.emit(aW("session_update",i),{}):(0,dX.isJsonRpcError)(t)&&this.events.emit(aW("session_update",i),{error:t.error})}),fY(this,"onSessionExtendRequest",async(e,t)=>{let{id:i}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,aH(fN)),await this.sendResult({id:i,topic:e,result:!0}),this.client.events.emit("session_extend",{id:i,topic:e})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}}),fY(this,"onSessionExtendResponse",(e,t)=>{let{id:i}=t,r=aW("session_extend",i);if(0===this.events.listenerCount(r))throw Error(`emitting ${r} without any listeners`);(0,dX.isJsonRpcResult)(t)?this.events.emit(aW("session_extend",i),{}):(0,dX.isJsonRpcError)(t)&&this.events.emit(aW("session_extend",i),{error:t.error})}),fY(this,"onSessionPingRequest",async(e,t)=>{let{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:i,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:e})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}}),fY(this,"onSessionPingResponse",(e,t)=>{let{id:i}=t,r=aW("session_ping",i);setTimeout(()=>{if(0===this.events.listenerCount(r))throw Error(`emitting ${r} without any listeners 2176`);(0,dX.isJsonRpcResult)(t)?this.events.emit(aW("session_ping",i),{}):(0,dX.isJsonRpcError)(t)&&this.events.emit(aW("session_ping",i),{error:t.error})},500)}),fY(this,"onSessionDeleteRequest",async(e,t)=>{let{id:i}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await Promise.all([new Promise(t=>{this.client.core.relayer.once(ut,async()=>{t(await this.deleteSession({topic:e,id:i}))})}),this.sendResult({id:i,topic:e,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:e,error:dc("USER_DISCONNECTED")})]).catch(e=>this.client.logger.error(e))}catch(e){this.client.logger.error(e)}}),fY(this,"onSessionRequest",async e=>{var t,i,r;let{topic:s,payload:n,attestation:a,encryptedId:o,transportType:l}=e,{id:c,params:h}=n;try{await this.isValidRequest(fG({topic:s},h));let e=this.client.session.get(s),n=await this.getVerifyContext({attestationId:a,hash:hN(JSON.stringify((0,dQ.formatJsonRpcRequest)("wc_sessionRequest",h,c))),encryptedId:o,metadata:e.peer.metadata,transportType:l}),d={id:c,topic:s,params:h,verifyContext:n};await this.setPendingSessionRequest(d),l===uo&&null!=(t=e.peer.metadata.redirect)&&t.universal&&this.client.core.addLinkModeSupportedApp(null==(i=e.peer.metadata.redirect)?void 0:i.universal),null!=(r=this.client.signConfig)&&r.disableRequestQueue?this.emitSessionRequest(d):(this.addSessionRequestToSessionRequestQueue(d),this.processSessionRequestQueue())}
14catch(e){await this.sendError({id:c,topic:s,error:e}),this.client.logger.error(e)}}),fY(this,"onSessionRequestResponse",(e,t)=>{let{id:i}=t,r=aW("session_request",i);if(0===this.events.listenerCount(r))throw Error(`emitting ${r} without any listeners`);(0,dX.isJsonRpcResult)(t)?this.events.emit(aW("session_request",i),{result:t.result}):(0,dX.isJsonRpcError)(t)&&this.events.emit(aW("session_request",i),{error:t.error})}),fY(this,"onSessionEventRequest",async(e,t)=>{let{id:i,params:r}=t;try{let t=`${e}_session_event_${r.event.name}`,s=dC.get(t);if(s&&this.isRequestOutOfSync(s,i))return void this.client.logger.info(`Discarding out of sync request - ${i}`);this.isValidEmit(fG({topic:e},r)),this.client.events.emit("session_event",{id:i,topic:e,params:r}),dC.set(t,i)}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}}),fY(this,"onSessionAuthenticateResponse",(e,t)=>{let{id:i}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),(0,dX.isJsonRpcResult)(t)?this.events.emit(aW("session_request",i),{result:t.result}):(0,dX.isJsonRpcError)(t)&&this.events.emit(aW("session_request",i),{error:t.error})}),fY(this,"onSessionAuthenticateRequest",async e=>{var t;let{topic:i,payload:r,attestation:s,encryptedId:n,transportType:a}=e;try{let{requester:e,authPayload:o,expiryTimestamp:l}=r.params,c=await this.getVerifyContext({attestationId:s,hash:hN(JSON.stringify(r)),encryptedId:n,metadata:e.metadata,transportType:a}),h={requester:e,pairingTopic:i,id:r.id,authPayload:o,verifyContext:c,expiryTimestamp:l};await this.setAuthRequest(r.id,{request:h,pairingTopic:i,transportType:a}),a===uo&&null!=(t=e.metadata.redirect)&&t.universal&&this.client.core.addLinkModeSupportedApp(e.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:r.params,id:r.id,verifyContext:c})}catch(n){this.client.logger.error(n);let e=r.params.requester.publicKey,t=await this.client.core.crypto.generateKeyPair(),s=this.getAppLinkIfEnabled(r.params.requester.metadata,a);await this.sendError({id:r.id,topic:i,error:n,encodeOpts:{type:1,receiverPublicKey:e,senderPublicKey:t},rpcOpts:fj.wc_sessionAuthenticate.autoReject,appLink:s})}}),fY(this,"addSessionRequestToSessionRequestQueue",e=>{this.sessionRequestQueue.queue.push(e)}),fY(this,"cleanupAfterResponse",e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=fM,this.processSessionRequestQueue()},(0,rA.toMiliseconds)(this.requestQueueDelay))}),fY(this,"cleanupPendingSentRequestsForTopic",({topic:e,error:t})=>{let i=this.client.core.history.pending;i.length>0&&i.filter(t=>t.topic===e&&"wc_sessionRequest"===t.request.method).forEach(e=>{let i=aW("session_request",e.request.id);if(0===this.events.listenerCount(i))throw Error(`emitting ${i} without any listeners`);this.events.emit(aW("session_request",e.request.id),{error:t})})}),fY(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===fU)return void this.client.logger.info("session request queue is already active.");let e=this.sessionRequestQueue.queue[0];if(!e)return void this.client.logger.info("session request queue is empty.");try{this.emitSessionRequest(e)}catch(e){this.client.logger.error(e)}}),fY(this,"emitSessionRequest",e=>{this.emittedSessionRequests.has(e.id)?this.client.logger.warn({id:e.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${e.id}`):(this.sessionRequestQueue.state=fU,this.emittedSessionRequests.add(e.id),this.client.events.emit("session_request",e))}),fY(this,"onPairingCreated",e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;let t=this.client.proposal.getAll().find(t=>t.pairingTopic===e.topic);
14t&&this.onSessionProposeRequest({topic:e.topic,payload:(0,dQ.formatJsonRpcRequest)("wc_sessionPropose",f$(fG({},t),fW({requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties,scopedProperties:t.scopedProperties})),t.id),attestation:t.attestation,encryptedId:t.encryptedId})}),fY(this,"isValidConnect",async e=>{let t;if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw Error(t)}let{pairingTopic:i,requiredNamespaces:r,optionalNamespaces:s,sessionProperties:n,scopedProperties:a,relays:o}=e;if(du(i)||await this.isValidPairingTopic(i),t=!1,o?o&&dh(o)&&o.length&&o.forEach(e=>{t=db(e)}):t=!0,!t){let{message:e}=dl("MISSING_OR_INVALID",`connect() relays: ${o}`);throw Error(e)}if(r&&!du(r)&&0!==dd(r)){let e="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(e):this.client.logger.warn(e),this.validateNamespaces(r,"requiredNamespaces")}if(s&&!du(s)&&0!==dd(s)&&this.validateNamespaces(s,"optionalNamespaces"),n&&!du(n)&&this.validateSessionProps(n,"sessionProperties"),a&&!du(a)){this.validateSessionProps(a,"scopedProperties");let e=Object.keys(r||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(t=>e.includes(t.split(":")[0])))throw Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(e)}`)}}),fY(this,"validateNamespaces",(e,t)=>{let i=function(e,t,i){let r=null;if(e&&dd(e)){let s,n=dm(e,t);n&&(r=n);let a=(s=null,Object.entries(e).forEach(([e,r])=>{var n,a;let o;if(s)return;let l=(n=ag(e,r),a=`${t} ${i}`,o=null,dh(n)&&n.length?n.forEach(e=>{o||dg(e)||(o=dc("UNSUPPORTED_CHAINS",`${a}, chain ${e} should be a string and conform to "namespace:chainId" format`))}):dg(e)||(o=dc("UNSUPPORTED_CHAINS",`${a}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),o);l&&(s=l)}),s);a&&(r=a)}else r=dl("MISSING_OR_INVALID",`${t}, ${i} should be an object with data`);return r}(e,"connect()",t);if(i)throw Error(i.message)}),fY(this,"isValidApprove",async e=>{if(!dv(e))throw Error(dl("MISSING_OR_INVALID",`approve() params: ${e}`).message);let{id:t,namespaces:i,relayProtocol:r,sessionProperties:s,scopedProperties:n}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);let a=this.client.proposal.get(t),o=dw(i,"approve()");if(o)throw Error(o.message);let l=dI(a.requiredNamespaces,i,"approve()");if(l)throw Error(l.message);if(!dp(r,!0)){let{message:e}=dl("MISSING_OR_INVALID",`approve() relayProtocol: ${r}`);throw Error(e)}if(s&&!du(s)&&this.validateSessionProps(s,"sessionProperties"),n&&!du(n)){this.validateSessionProps(n,"scopedProperties");let e=new Set(Object.keys(i));if(!Object.keys(n).every(t=>e.has(t.split(":")[0])))throw Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(n)}, approved namespaces: ${Array.from(e).join(", ")}`)}}),fY(this,"isValidReject",async e=>{if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`reject() params: ${e}`);throw Error(t)}let{id:t,reason:i}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!i||"object"!=typeof i||!i.code||!df(i.code,!1)||!i.message||!dp(i.message,!1)){let{message:e}=dl("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw Error(e)}}),fY(this,"isValidSessionSettleRequest",e=>{let t;if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw Error(t)}
14let{relay:i,controller:r,namespaces:s,expiry:n}=e;if(!db(i)){let{message:e}=dl("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw Error(e)}let a=(t=null,dp(r?.publicKey,!1)||(t=dl("MISSING_OR_INVALID","onSessionSettleRequest() controller public key should be a string")),t);if(a)throw Error(a.message);let o=dw(s,"onSessionSettleRequest()");if(o)throw Error(o.message);if(a$(n)){let{message:e}=dl("EXPIRED","onSessionSettleRequest()");throw Error(e)}}),fY(this,"isValidUpdate",async e=>{if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`update() params: ${e}`);throw Error(t)}let{topic:t,namespaces:i}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);let r=this.client.session.get(t),s=dw(i,"update()");if(s)throw Error(s.message);let n=dI(r.requiredNamespaces,i,"update()");if(n)throw Error(n.message)}),fY(this,"isValidExtend",async e=>{if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`extend() params: ${e}`);throw Error(t)}let{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)}),fY(this,"isValidRequest",async e=>{var t;let i;if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`request() params: ${e}`);throw Error(t)}let{topic:r,request:s,chainId:n,expiry:a}=e;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);let{namespaces:o}=this.client.session.get(r);if(!dE(o,n)){let{message:e}=dl("MISSING_OR_INVALID",`request() chainId: ${n}`);throw Error(e)}if(du(s)||!dp(s.method,!1)){let{message:e}=dl("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw Error(e)}if(!(dp(t=s.method,!1)&&(i=[],Object.values(o).forEach(e=>{de(e.accounts).includes(n)&&i.push(...e.methods)}),i).includes(t))){let{message:e}=dl("MISSING_OR_INVALID",`request() method: ${s.method}`);throw Error(e)}if(a&&(!df(a,!1)||!(a<=fD.max)||!(a>=fD.min))){let{message:e}=dl("MISSING_OR_INVALID",`request() expiry: ${a}. Expiry must be a number (in seconds) between ${fD.min} and ${fD.max}`);throw Error(e)}}),fY(this,"isValidRespond",async e=>{var t;if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`respond() params: ${e}`);throw Error(t)}let{topic:i,response:r}=e;try{await this.isValidSessionTopic(i)}catch(i){throw null!=(t=e?.response)&&t.id&&this.cleanupAfterResponse(e),i}if(du(r)||du(r.result)&&du(r.error)||!df(r.id,!1)||!dp(r.jsonrpc,!1)){let{message:e}=dl("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(r)}`);throw Error(e)}let s=this.client.pendingRequest.get(r.id);if(s.topic!==i){let{message:e}=dl("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${r.id}, expected topic: ${s.topic}, received topic: ${i}`);throw Error(e)}}),fY(this,"isValidPing",async e=>{if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`ping() params: ${e}`);throw Error(t)}let{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),fY(this,"isValidEmit",async e=>{var t;let i;if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`emit() params: ${e}`);throw Error(t)}let{topic:r,event:s,chainId:n}=e;await this.isValidSessionTopic(r);let{namespaces:a}=this.client.session.get(r);if(!dE(a,n)){let{message:e}=dl("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw Error(e)}if(du(s)||!dp(s.name,!1)||!(dp(t=s.name,!1)&&(i=[],Object.values(a).forEach(e=>{de(e.accounts).includes(n)&&i.push(...e.events)}),i).includes(t))){let{message:e}=dl("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw Error(e)}}),fY(this,"isValidDisconnect",async e=>{if(!dv(e)){let{message:t}=dl("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw Error(t)}let{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),fY(this,"isValidAuthenticate",e=>{let{chains:t,uri:i,domain:r,nonce:s}=e;if(!Array.isArray(t)||0===t.length)throw Error("chains is required and must be a non-empty array");if(!dp(i,!1))throw Error("uri is required parameter");if(!dp(r,!1))throw Error("domain is required parameter");if(!dp(s,!1))throw Error("nonce is required parameter");if([...new Set(t.map(e=>ap(e).namespace))].length>1)throw Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:n}=ap(t[0]);if("eip155"!==n)throw Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),fY(this,"getVerifyContext",async e=>{let{attestationId:t,hash:i,encryptedId:r,metadata:s,transportType:n}=e,a={verified:{verifyUrl:s.verifyUrl||uI,validation:"UNKNOWN",origin:s.url||""}};try{if(n===uo){let e=this.getAppLinkIfEnabled(s,n);return a.verified.validation=e&&new URL(e).origin===new URL(s.url).origin?"VALID":"INVALID",a}let e=await this.client.core.verify.resolve({attestationId:t,hash:i,encryptedId:r,verifyUrl:s.verifyUrl});e&&(a.verified.origin=e.origin,a.verified.isScam=e.isScam,a.verified.validation=e.origin===new URL(s.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.warn(e)}return this.client.logger.debug(`Verify context: ${JSON.stringify(a)}`),a}),fY(this,"validateSessionProps",(e,t)=>{Object.values(e).forEach((i,r)=>{if(null==i){let{message:s}=dl("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${i} for key ${Object.keys(e)[r]}`);throw Error(s)}})}),fY(this,"getPendingAuthRequest",e=>{let t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0}),fY(this,"addToRecentlyDeleted",(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0,t=this.recentlyDeletedLimit/2;
14for(let i of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(i)}}}),fY(this,"checkRecentlyDeleted",e=>{let t=this.recentlyDeletedMap.get(e);if(t){let{message:i}=dl("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw Error(i)}}),fY(this,"isLinkModeEnabled",(t,i)=>{var r,s,n,a,o,l,c,h,d;return!!t&&i===uo&&(null==(s=null==(r=this.client.metadata)?void 0:r.redirect)?void 0:s.linkMode)===!0&&(null==(a=null==(n=this.client.metadata)?void 0:n.redirect)?void 0:a.universal)!==void 0&&(null==(l=null==(o=this.client.metadata)?void 0:o.redirect)?void 0:l.universal)!==""&&(null==(c=t?.redirect)?void 0:c.universal)!==void 0&&(null==(h=t?.redirect)?void 0:h.universal)!==""&&(null==(d=t?.redirect)?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&"u">typeof(null==e.g?void 0:e.g.Linking)}),fY(this,"getAppLinkIfEnabled",(e,t)=>{var i;return this.isLinkModeEnabled(e,t)?null==(i=e?.redirect)?void 0:i.universal:void 0}),fY(this,"handleLinkModeMessage",({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;let t=aJ(e,"topic")||"",i=decodeURIComponent(aJ(e,"wc_ev")||""),r=this.client.session.keys.includes(t);r&&this.client.session.update(t,{transportType:uo}),this.client.core.dispatchEnvelope({topic:t,message:i,sessionExists:r})}),fY(this,"registerLinkModeListeners",async()=>{var t;if(aY()||ak()&&null!=(t=this.client.metadata.redirect)&&t.linkMode){let t=null==e.g?void 0:e.g.Linking;if("u">typeof t){t.addEventListener("url",this.handleLinkModeMessage,this.client.name);let e=await t.getInitialURL();e&&setTimeout(()=>{this.handleLinkModeMessage({url:e})},50)}}}),fY(this,"getTVFParams",(e,t,i)=>{var r,s,n;if(!(null!=(r=t.request)&&r.method))return{};let a={correlationId:e,rpcMethods:[t.request.method],chainId:t.chainId};try{a.txHashes=this.extractTxHashesFromResult(t.request,i),a.contractAddresses=this.isValidContractData(t.request.params)?[null==(n=null==(s=t.request.params)?void 0:s[0])?void 0:n.to]:[]}catch(e){this.client.logger.warn(e,"Error getting TVF params")}return a}),fY(this,"isValidContractData",e=>{var t;if(!e)return!1;try{let i=e?.data||(null==(t=e?.[0])?void 0:t.data);if(!i.startsWith("0x"))return!1;let r=i.slice(2);return!!/^[0-9a-fA-F]*$/.test(r)&&r.length%2==0}catch{}return!1}),fY(this,"extractTxHashesFromResult",(e,t)=>{var i,r,s,n,a;try{if(!t)return[];let o=e.method,l=fB[o];if("sui_signTransaction"===o){let e,i,r,n;return[(s=t.transactionBytes,e=new Uint8Array(tT.Buffer.from(s,"base64")),i=Array.from("TransactionData::").map(e=>e.charCodeAt(0)),(r=new Uint8Array(i.length+e.length)).set(i),r.set(e,i.length),n=ld(r,{dkLen:32}),nH.default.encode(n))]}if("near_signTransaction"===o)return[lg(t)];if("near_signTransactions"===o)return t.map(e=>lg(e));if("xrpl_signTransactionFor"===o||"xrpl_signTransaction"===o)return[null==(i=t.tx_json)?void 0:i.hash];if("polkadot_signTransaction"===o){let i,s,n,a;return[(r={transaction:e.params.transactionPayload,signature:t.signature},n=Uint8Array.from(tT.Buffer.from(r.signature,"hex")),a=function({publicKey:e,signature:t,payload:i}){var r,s,n;let a,o=d_(i.method),l=128|parseInt((null==(r=i.version)?void 0:r.toString())||"4"),c=(s=i.address,a=nH.default.decode(s)[0],42===a?0:60===a?2:1),h="00"===i.era?new Uint8Array([0]):d_(i.era);if(1!==h.length&&2!==h.length)throw Error("Invalid era length");let d=parseInt(i.nonce,16),u=new Uint8Array([255&d,d>>8&255]),p=new Uint8Array([0,...e,c,...t,...h,...u,...function(e){if(e<BigInt(1)<<BigInt(6))return new Uint8Array([Number(e<<BigInt(2))]);if(e<BigInt(1)<<BigInt(14)){let t=e<<BigInt(2)|BigInt(1);return new Uint8Array([Number(t&BigInt(255)),Number(t>>BigInt(8)&BigInt(255))])}if(e<BigInt(1)<<BigInt(30)){let t=e<<BigInt(2)|BigInt(2);return new Uint8Array([Number(t&BigInt(255)),Number(t>>BigInt(8)&BigInt(255)),Number(t>>BigInt(16)&BigInt(255)),Number(t>>BigInt(24)&BigInt(255))])}throw Error("BigInt compact encoding not supported > 2^30")}(BigInt(`0x${(n=i.tip).startsWith("0x")?n.slice(2):n}`)),...o]);return new Uint8Array([...function(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){let t=e<<2|1;return new Uint8Array([255&t,t>>8&255])}if(e<0x40000000){let t=e<<2|2;return new Uint8Array([255&t,t>>8&255,t>>16&255,t>>24&255])}throw Error("Compact encoding > 2^30 not supported")}(p.length+1),l,...p])}({publicKey:function(e){let t=nH.default.decode(e);if(t.length<33)throw Error("Too short to contain a public key");return t.slice(1,33)}(r.transaction.address),signature:n,payload:r.transaction}),i=d_(tT.Buffer.from(a).toString("hex")),s=(0,nZ.blake2b)(i,void 0,32),"0x"+tT.Buffer.from(s).toString("hex"))]}if("algo_signTxn"===o)return dh(t)?t.map(e=>ly(e)):[ly(t)];
14if("cosmos_signDirect"===o){let e,i,r,s,n;return[(e=tT.Buffer.from(t.signed.bodyBytes,"base64"),i=tT.Buffer.from(t.signed.authInfoBytes,"base64"),r=tT.Buffer.from(t.signature.signature,"base64"),(s=[]).push(tT.Buffer.from([10])),s.push(lm(e.length)),s.push(e),s.push(tT.Buffer.from([18])),s.push(lm(i.length)),s.push(i),s.push(tT.Buffer.from([26])),s.push(lm(r.length)),s.push(r),n=le(tT.Buffer.concat(s)),tT.Buffer.from(n).toString("hex").toUpperCase())]}if("wallet_sendCalls"===o){let e=[];try{if("string"==typeof t)return e.push(t),e;if("object"!=typeof t)return e;null!=t&&t.id&&e.push(t.id);let i=null==(a=null==(n=t?.capabilities)?void 0:n.caip345)?void 0:a.transactionHashes;i&&e.push(...i)}catch(e){console.warn("getWalletSendCallsHashes failed: ",e)}return e}if("string"==typeof t)return[t];let c=t[l.key];if(dh(c))return"solana_signAllTransactions"===o?c.map(e=>(function(e){let t=atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e);let r=i[0];if(0===r)throw Error("No signatures found");if(i.length<1+64*r)throw Error("Transaction data too short for claimed signature count");if(i.length<100)throw Error("Transaction too short");let s=tT.Buffer.from(e,"base64").slice(1,65);return nH.default.encode(s)})(e)):c;if("string"==typeof c)return[c]}catch(e){this.client.logger.warn(e,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{let e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(let[e,i]of Object.entries(t))for(let t of i)try{await this.onProviderMessageEvent({topic:e,message:t,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${e}, message: ${t}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){let{message:e}=dl("NOT_INITIALIZED",this.name);throw Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(d7,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){let{topic:t,message:i,attestation:r,transportType:s}=e,{publicKey:n}=this.client.auth.authKeys.keys.includes(fK)?this.client.auth.authKeys.get(fK):{responseTopic:void 0,publicKey:void 0};try{let e=await this.client.core.crypto.decode(t,i,{receiverPublicKey:n,encoding:s===uo?hk:h_});(0,dX.isJsonRpcRequest)(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:r,transportType:s,encryptedId:hN(i)})):(0,dX.isJsonRpcResponse)(e)?(await this.client.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e,transportType:s}),this.client.core.history.delete(t,e.id)):await this.onRelayEventUnknownPayload({topic:t,payload:e,transportType:s}),await this.client.core.relayer.messages.ack(t,i)}catch(e){this.client.logger.error(e)}}registerExpirerEvents(){this.client.core.expirer.on(uE,async e=>{let{topic:t,id:i}=aK(e.target);return i&&this.client.pendingRequest.keys.includes(i)?await this.deletePendingSessionRequest(i,dl("EXPIRED"),!0):i&&this.client.auth.requests.keys.includes(i)?await this.deletePendingAuthRequest(i,dl("EXPIRED"),!0):void(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})))})}registerPairingEvents(){this.client.core.pairing.events.on(uf,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(ug,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!dp(e,!1)){let{message:t}=dl("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){let{message:t}=dl("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw Error(t)}if(a$(this.client.core.pairing.pairings.get(e).expiry)){let{message:t}=dl("EXPIRED",`pairing topic: ${e}`);throw Error(t)}}async isValidSessionTopic(e){if(!dp(e,!1)){let{message:t}=dl("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){let{message:t}=dl("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw Error(t)}if(a$(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});let{message:t}=dl("EXPIRED",`session topic: ${e}`);throw Error(t)}if(!this.client.core.crypto.keychain.has(e)){let{message:t}=dl("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),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(dp(e,!1)){let{message:t}=dl("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw Error(t)}else{let{message:t}=dl("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw Error(t)}}async isValidProposalId(e){if("number"!=typeof e){let{message:t}=dl("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw Error(t)}if(!this.client.proposal.keys.includes(e)){let{message:t}=dl("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw Error(t)}if(a$(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);let{message:t}=dl("EXPIRED",`proposal id: ${e}`);throw Error(t)}}}class fQ extends p4{constructor(e,t){super(e,t,"proposal",fO),this.core=e,this.logger=t}}class fX extends p4{constructor(e,t){super(e,t,"session",fO),this.core=e,this.logger=t}}class f0 extends p4{constructor(e,t){super(e,t,"request",fO,e=>e.id),this.core=e,this.logger=t}}class f1 extends p4{constructor(e,t){super(e,t,"authKeys",fq,()=>fK),this.core=e,this.logger=t}}class f2 extends p4{constructor(e,t){super(e,t,"pairingTopics",fq),this.core=e,this.logger=t}}class f5 extends p4{constructor(e,t){super(e,t,"requests",fq,e=>e.id),this.core=e,this.logger=t}}var f3=Object.defineProperty,f8=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?f3(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class f6{constructor(e,t){this.core=e,this.logger=t,f8(this,"authKeys"),f8(this,"pairingTopics"),f8(this,"requests"),this.authKeys=new f1(this.core,this.logger),this.pairingTopics=new f2(this.core,this.logger),this.requests=new f5(this.core,this.logger)}
14async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var f4=Object.defineProperty,f7=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?f4(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class f9 extends dG{constructor(e){super(e),f7(this,"protocol","wc"),f7(this,"version",2),f7(this,"name",fk),f7(this,"metadata"),f7(this,"core"),f7(this,"logger"),f7(this,"events",new rE.EventEmitter),f7(this,"engine"),f7(this,"session"),f7(this,"proposal"),f7(this,"pendingRequest"),f7(this,"auth"),f7(this,"signConfig"),f7(this,"on",(e,t)=>this.events.on(e,t)),f7(this,"once",(e,t)=>this.events.once(e,t)),f7(this,"off",(e,t)=>this.events.off(e,t)),f7(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),f7(this,"removeAllListeners",e=>this.events.removeAllListeners(e)),f7(this,"connect",async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"pair",async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"approve",async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"reject",async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"update",async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"extend",async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"request",async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"respond",async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"ping",async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"emit",async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"disconnect",async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"find",e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}}),f7(this,"authenticate",async(e,t)=>{try{return await this.engine.authenticate(e,t)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"formatAuthMessage",e=>{try{return this.engine.formatAuthMessage(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"approveSessionAuthenticate",async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}}),f7(this,"rejectSessionAuthenticate",async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}}),this.name=e?.name||fk,this.metadata=function(e){var t,i;let r=aN();try{let s,n;return null!=e&&e.url&&r.url&&new URL(e.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),e.url=r.url),null!=(t=e?.icons)&&t.length&&e.icons.length>0&&(e.icons=e.icons.filter(e=>""!==e)),s=aS(aS({},r),e),n={url:e?.url||r.url,name:e?.name||r.name,description:e?.description||r.description,icons:null!=(i=e?.icons)&&i.length&&e.icons.length>0?e.icons:r.icons},am(s,aw(n))}catch(t){return console.warn("Error populating app metadata",t),e||r}}(e?.metadata),this.signConfig=e?.signConfig;const t=dk({logger:e?.logger||"error",name:this.name});this.logger=t,this.core=e?.core||new f_(e),this.session=new fX(this.core,this.logger),this.proposal=new fQ(this.core,this.logger),this.pendingRequest=new f0(this.core,this.logger),this.engine=new fZ(this),this.auth=new f6(this.core,this.logger)}static async init(e){let t=new f9(e);return await t.initialize(),t}get context(){return ah(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}}}var ge=e.i(98418);function gt(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function gi(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}
14function gr(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}let gs="[object String]",gn="[object Number]",ga="[object Boolean]",go="[object Arguments]";function gl(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function gc(e,t,i,r=new Map,s){let n=s?.(e,t,i,r);if(null!=n)return n;if(gt(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){let t=Array(e.length);r.set(e,t);for(let n=0;n<e.length;n++)t[n]=gc(e[n],n,i,r,s);return Object.hasOwn(e,"index")&&(t.index=e.index),Object.hasOwn(e,"input")&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){let t=new Map;for(let[n,a]of(r.set(e,t),e))t.set(n,gc(a,n,i,r,s));return t}if(e instanceof Set){let t=new Set;for(let n of(r.set(e,t),e))t.add(gc(n,void 0,i,r,s));return t}if("u">typeof tT.Buffer&&tT.Buffer.isBuffer(e))return e.subarray();if(gl(e)){let t=new(Object.getPrototypeOf(e)).constructor(e.length);r.set(e,t);for(let n=0;n<e.length;n++)t[n]=gc(e[n],n,i,r,s);return t}if(e instanceof ArrayBuffer||"u">typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return r.set(e,t),gh(t,e,i,r,s),t}if("u">typeof File&&e instanceof File){let t=new File([e],e.name,{type:e.type});return r.set(e,t),gh(t,e,i,r,s),t}if(e instanceof Blob){let t=new Blob([e],{type:e.type});return r.set(e,t),gh(t,e,i,r,s),t}if(e instanceof Error){let t=new e.constructor;return r.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,gh(t,e,i,r,s),t}if("object"==typeof e&&function(e){switch(gr(e)){case go:case"[object Array]":case"[object ArrayBuffer]":case"[object DataView]":case ga:case"[object Date]":case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Map]":case gn:case"[object Object]":case"[object RegExp]":case"[object Set]":case gs:case"[object Symbol]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return!0;default:return!1}}(e)){let t=Object.create(Object.getPrototypeOf(e));return r.set(e,t),gh(t,e,i,r,s),t}return e}function gh(e,t,i=e,r,s){let n=[...Object.keys(t),...gi(t)];for(let a=0;a<n.length;a++){let o=n[a],l=Object.getOwnPropertyDescriptor(e,o);(null==l||l.writable)&&(e[o]=gc(t[o],o,i,r,s))}}function gd(e){var t;return t=(t,i,r,s)=>{let n;if(null!=n)return n;if("object"==typeof e)switch(Object.prototype.toString.call(e)){case gn:case gs:case ga:{let t=new e.constructor(e?.valueOf());return gh(t,e),t}case go:{let t={};return gh(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}},gc(e,void 0,e,new Map,t)}function gu(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===gr(e)}function gp(e){return"object"==typeof e&&null!==e}function gf(){}let gg="error",gy="universal_provider",gm=`wc@2:${gy}:`,gw="https://rpc.walletconnect.org/v1/",gb="generic",gv=`${gw}bundler`,gE="call_status",gI="default_chain_changed";var gS=Object.defineProperty,gA=Object.defineProperties,gx=Object.getOwnPropertyDescriptors,gP=Object.getOwnPropertySymbols,gC=Object.prototype.hasOwnProperty,g_=Object.prototype.propertyIsEnumerable,gk=(e,t,i)=>t in e?gS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,gO=(e,t)=>{for(var i in t||(t={}))gC.call(t,i)&&gk(e,i,t[i]);if(gP)for(var i of gP(t))g_.call(t,i)&&gk(e,i,t[i]);return e},gT=(e,t)=>gA(e,gx(t));function gR(e,t,i){var r;let s=ap(e);return(null==(r=t.rpcMap)?void 0:r[s.reference])||`${gw}?chainId=${s.namespace}:${s.reference}&projectId=${i}`}function gN(e){return e.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function gj(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>{var i,r;return(null==(i=t?.chains)?void 0:i.length)&&(null==(r=t?.chains)?void 0:r.length)>0}))}function gD(e={},t={}){return function(e,...t){return function(e,...t){let i=t.slice(0,-1),r=t[t.length-1],s=e;for(let e=0;e<i.length;e++)s=function e(t,i,r,s){if(gt(t)&&(t=Object(t)),null==i||"object"!=typeof i)return t;if(s.has(i))return function(e){if(gt(e))return e;if(Array.isArray(e)||gl(e)||e instanceof ArrayBuffer||"u">typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return e.slice(0);let t=Object.getPrototypeOf(e),i=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new i(e);if(e instanceof RegExp){let t=new i(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new i(e.buffer.slice(0));if(e instanceof Error){let t=new i(e.message);return t.stack=e.stack,t.name=e.name,t.cause=e.cause,t}return"u">typeof File&&e instanceof File?new i([e],e.name,{type:e.type,lastModified:e.lastModified}):"object"==typeof e?Object.assign(Object.create(t),e):e}(s.get(i));if(s.set(i,t),Array.isArray(i)){i=i.slice();for(let e=0;e<i.length;e++)i[e]=i[e]??void 0}let n=[...Object.keys(i),...gi(i)];for(let a=0;a<n.length;a++){let o=n[a],l=i[o],c=t[o];if(gu(l)&&(l={...l}),gu(c)&&(c={...c}),"u">typeof tT.Buffer&&tT.Buffer.isBuffer(l)&&(l=gd(l)),Array.isArray(l))if("object"==typeof c&&null!=c){let e=[],t=Reflect.ownKeys(c);for(let i=0;i<t.length;i++){let r=t[i];e[r]=c[r]}c=e}else c=[];let h=r(c,l,o,t,i,s);null!=h?t[o]=h:Array.isArray(l)||gp(c)&&gp(l)?t[o]=e(c,l,r,s):null==c&&function(e){if("object"!=typeof e||null==e)return!1;if(null===Object.getPrototypeOf(e))return!0;
14if("[object Object]"!==Object.prototype.toString.call(e)){let t=e[Symbol.toStringTag];return null!=t&&!!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable&&e.toString()===`[object ${t}]`}let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(l)?t[o]=e({},l,r,s):null==c&&gl(l)?t[o]=gd(l):(void 0===c||void 0!==l)&&(t[o]=l)}return t}(s,i[e],r,new Map);return s}(e,...t,gf)}(gj(gM(e)),gj(gM(t)))}function gM(e){var t,i,r,s,n;let a={};if(!dd(e))return a;for(let[o,l]of Object.entries(e)){let e=dt(o)?[o]:l.chains,c=l.methods||[],h=l.events||[],d=l.rpcMap||{},u=di(o);a[u]=gT(gO(gO({},a[u]),l),{chains:az(e,null==(t=a[u])?void 0:t.chains),methods:az(c,null==(i=a[u])?void 0:i.methods),events:az(h,null==(r=a[u])?void 0:r.events)}),(dd(d)||dd((null==(s=a[u])?void 0:s.rpcMap)||{}))&&(a[u].rpcMap=gO(gO({},d),null==(n=a[u])?void 0:n.rpcMap))}return a}function gU(e){return e.includes(":")?e.split(":")[2]:e}function gB(e){let t={};for(let[i,r]of Object.entries(e)){let e=r.methods||[],s=r.events||[],n=r.accounts||[],a=dt(i)?[i]:r.chains?r.chains:gN(r.accounts);t[i]={chains:a,methods:e,events:s,accounts:n}}return t}function gL(e){return"number"==typeof e?e:e.includes("0x")?parseInt(e,16):isNaN(Number(e=e.includes(":")?e.split(":")[1]:e))?e:Number(e)}let gq={},gK=e=>gq[e],gH=(e,t)=>{gq[e]=t};var g$=Object.defineProperty,gW=Object.getOwnPropertySymbols,gz=Object.prototype.hasOwnProperty,gF=Object.prototype.propertyIsEnumerable,gV=(e,t,i)=>t in e?g$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,gJ=(e,t)=>{for(var i in t||(t={}))gz.call(t,i)&&gV(e,i,t[i]);if(gW)for(var i of gW(t))gF.call(t,i)&&gV(e,i,t[i]);return e};let gG="eip155",gY=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],gZ=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,gQ=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,gX=e=>Object.keys(e).filter(e=>gY.includes(e)).reduce((t,i)=>(t[i]=g0(e[i]),t),{}),g0=e=>"string"==typeof e&&function(e){try{let t=JSON.parse(e);return"object"==typeof t&&null!==t&&!Array.isArray(t)}catch{return!1}}(e)?JSON.parse(e):e;var g1=Object.defineProperty;class g2{constructor(e){((e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?g1(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(this,"storage"),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 t||(t=new g2(e)),t}}var g5=Object.defineProperty,g3=Object.defineProperties,g8=Object.getOwnPropertyDescriptors,g6=Object.getOwnPropertySymbols,g4=Object.prototype.hasOwnProperty,g7=Object.prototype.propertyIsEnumerable,g9=(e,t,i)=>t in e?g5(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;async function ye(e,t){let i,r=ap(e.result.capabilities.caip345.caip2),s=e.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(s.map(e=>yt(r.reference,e,t))),a=n.filter(e=>"fulfilled"===e.status).map(e=>e.value).filter(e=>e);n.filter(e=>"rejected"===e.status).forEach(e=>console.warn("Failed to fetch transaction receipt:",e.reason));let o=!a.length||a.some(e=>!e),l=a.every(e=>e?.status==="0x1"),c=a.every(e=>e?.status==="0x0"),h=a.some(e=>e?.status==="0x0");return o?i=100:l?i=200:c?i=500:h&&(i=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:a,status:i}}async function yt(e,t,i){return await i(parseInt(e)).request((0,dQ.formatJsonRpcRequest)("eth_getTransactionReceipt",[t]))}async function yi({sendCalls:e,storage:t}){let i=await t.getItem(gE);await t.setItem(gE,g3(((e,t)=>{for(var i in t||(t={}))g4.call(t,i)&&g9(e,i,t[i]);if(g6)for(var i of g6(t))g7.call(t,i)&&g9(e,i,t[i]);return e})({},i),g8({[e.result.id]:{request:e.request,result:e.result,expiry:aH(86400)}})))}async function yr({resultId:e,storage:t}){let i=await t.getItem(gE);if(i){for(let r in delete i[e],await t.setItem(gE,i),i)a$(i[r].expiry)&&delete i[r];await t.setItem(gE,i)}}async function ys({resultId:e,storage:t}
14){let i=await t.getItem(gE),r=i?.[e];if(r&&!a$(r.expiry))return r;await yr({resultId:e,storage:t})}var yn=Object.defineProperty,ya=Object.defineProperties,yo=Object.getOwnPropertyDescriptors,yl=Object.getOwnPropertySymbols,yc=Object.prototype.hasOwnProperty,yh=Object.prototype.propertyIsEnumerable,yd=(e,t,i)=>t in e?yn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,yu=(e,t)=>{for(var i in t||(t={}))yc.call(t,i)&&yd(e,i,t[i]);if(yl)for(var i of yl(t))yh.call(t,i)&&yd(e,i,t[i]);return e},yp=(e,t,i)=>yd(e,"symbol"!=typeof t?t+"":t,i);class yf{constructor(e){yp(this,"name","eip155"),yp(this,"client"),yp(this,"chainId"),yp(this,"namespace"),yp(this,"httpProviders"),yp(this,"events"),yp(this,"storage"),this.namespace=e.namespace,this.events=gK("events"),this.client=gK("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=g2.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":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);let i=this.chainId;this.chainId=parseInt(e),this.events.emit(gI,{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;let e=this.namespace.chains[0];if(!e)throw Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){let i=t||gR(`${this.name}:${e}`,this.namespace,this.client.core.projectId);return new dZ.JsonRpcProvider(new ge.HttpConnection(i,gK("disableProviderPing")))}setHttpProvider(e,t){let i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){let e={};return this.namespace.chains.forEach(t=>{var i;let r=parseInt(t.includes(":")?t.split(":")[1]:t);e[r]=this.createHttpProvider(r,null==(i=this.namespace.rpcMap)?void 0:i[t])}),e}getAccounts(){let e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}getHttpProvider(e){let t=e||this.chainId;return this.httpProviders[t]||(this.httpProviders=ya(yu({},this.httpProviders),yo({[t]:this.createHttpProvider(t)})),this.httpProviders[t])}async handleSwitchChain(e){var t,i;let r=e.request.params?null==(t=e.request.params[0])?void 0:t.chainId:"0x0",s=parseInt(r=r.startsWith("0x")?r:`0x${r}`,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:null==(i=this.namespace.chains)?void 0:i[0]}),this.setDefaultChain(`${s}`);else throw Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,r,s,n;let a,o=null==(i=null==(t=e.request)?void 0:t.params)?void 0:i[0],l=(null==(s=null==(r=e.request)?void 0:r.params)?void 0:s[1])||[];if(!o)throw Error("Missing address parameter in `wallet_getCapabilities` request");let c=this.client.session.get(e.topic),h=(null==(n=c?.sessionProperties)?void 0:n.capabilities)||{},d=`${o}${l.join(",")}`,u=h?.[d];if(u)return u;try{a=((e,t,i)=>{let{sessionProperties:r={},scopedProperties:s={}}=e,n={};if(!dd(s)&&!dd(r))return;let a=gX(r);for(let e of i){let i=gZ(e);if(!i)continue;n[gQ(i)]=a;let r=s?.[`${gG}:${i}`];if(r){let e=r?.[`${gG}:${i}:${t}`];n[gQ(i)]=gJ(gJ({},n[gQ(i)]),gX(e||r))}}for(let[e,t]of Object.entries(n))0===Object.keys(t).length&&delete n[e];return Object.keys(n).length>0?n:void 0})(c,o,l)}catch(e){console.warn("Failed to extract capabilities from session",e)}if(a)return a;let p=await this.client.request(e);try{let t,i,r,s;await this.client.session.update(e.topic,{sessionProperties:(r=yu({},c.sessionProperties||{}),s={capabilities:(t=yu({},h||{}),i={[d]:p},ya(t,yo(i)))},ya(r,yo(s)))})}catch(e){console.warn("Failed to update session with capabilities",e)}return p}async getCallStatus(e){var t,i,r;let s=this.client.session.get(e.topic),n=null==(t=s.sessionProperties)?void 0:t.bundler_name;if(n){let t=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(t,e)}catch(e){console.warn("Failed to fetch call status from bundler",e,t)}}let a=null==(i=s.sessionProperties)?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(e){console.warn("Failed to fetch call status from custom bundler",e,a)}let o=await ys({resultId:null==(r=e.request.params)?void 0:r[0],storage:this.storage});if(o)try{return await ye(o,this.getHttpProvider.bind(this))}catch(e){console.warn("Failed to fetch call status from stored send calls",e,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;let r=new URL(e),s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify((0,dQ.formatJsonRpcRequest)("eth_getUserOperationReceipt",[null==(i=t.request.params)?void 0:i[0]]))});if(!s.ok)throw Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}
14getBundlerUrl(e,t){return`${gv}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}async sendCalls(e){var t,i,r;let s=await this.client.request(e),n=null==(t=e.request.params)?void 0:t[0],a=s?.id,o=s?.capabilities||{},l=null==(i=o?.caip345)?void 0:i.caip2,c=null==(r=o?.caip345)?void 0:r.transactionHashes;return a&&l&&null!=c&&c.length&&await yi({sendCalls:{request:n,result:s},storage:this.storage}),s}}var yg=Object.defineProperty,yy=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?yg(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class ym{constructor(e){yy(this,"name",gb),yy(this,"client"),yy(this,"httpProviders"),yy(this,"events"),yy(this,"namespace"),yy(this,"chainId"),this.namespace=e.namespace,this.events=gK("events"),this.client=gK("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);let i=this.chainId;this.chainId=e,this.events.emit(gI,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;let e=this.namespace.chains[0];if(!e)throw Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){let e=this.namespace.chains[0];if(!e)throw Error("ChainId not found");return ap(e).namespace}getAccounts(){let e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){var e,t;let i={};return null==(t=null==(e=this.namespace)?void 0:e.accounts)||t.forEach(e=>{var t,r;let s=ap(e),n=null==(r=null==(t=this.namespace)?void 0:t.rpcMap)?void 0:r[`${s.namespace}:${s.reference}`];i[s.reference]=this.createHttpProvider(e,n)}),i}getHttpProvider(e){let t=ap(e).reference,i=this.httpProviders[t];if(typeof i>"u")throw Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,t){let i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){let i=t||gR(e,this.namespace,this.client.core.projectId);return new dZ.JsonRpcProvider(new ge.default(i,gK("disableProviderPing")))}}var yw=Object.defineProperty,yb=Object.defineProperties,yv=Object.getOwnPropertyDescriptors,yE=Object.getOwnPropertySymbols,yI=Object.prototype.hasOwnProperty,yS=Object.prototype.propertyIsEnumerable,yA=(e,t,i)=>t in e?yw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,yx=(e,t)=>{for(var i in t||(t={}))yI.call(t,i)&&yA(e,i,t[i]);if(yE)for(var i of yE(t))yS.call(t,i)&&yA(e,i,t[i]);return e},yP=(e,t,i)=>yA(e,"symbol"!=typeof t?t+"":t,i);class yC{constructor(e){var t,i;yP(this,"client"),yP(this,"namespaces"),yP(this,"optionalNamespaces"),yP(this,"sessionProperties"),yP(this,"scopedProperties"),yP(this,"events",new rE.default),yP(this,"rpcProviders",{}),yP(this,"session"),yP(this,"providerOpts"),yP(this,"logger"),yP(this,"uri"),yP(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=dk({logger:null!=(t=e.logger)?t:gg,name:null!=(i=this.providerOpts.name)?i:gy}),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){let t=new yC(e);return await t.initialize(),t}async request(e,t,i){let[r,s]=this.validateChain(t);if(!this.session)throw Error("Please call connect() before request()");return await this.getProvider(r).request({request:yx({},e),chainId:`${r}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,r){let s=new Date().getTime();this.request(e,i,r).then(e=>t(null,(0,dQ.formatJsonRpcResult)(s,e))).catch(e=>t(e,void 0))}async enable(){if(!this.client)throw Error("Sign Client not initialized");
14return 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 Error("Please call connect() before enable()");await this.client.disconnect({topic:null==(e=this.session)?void 0:e.topic,reason:dc("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw Error("Sign Client not initialized");if(this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();let{uri:i,response:r}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));let s=await r();if(this.session=s.session,this.session){let e=gB(this.session.namespaces);this.namespaces=gD(this.namespaces,e),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}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){let{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));let r=await i();this.session=r;let s=gB(r.namespaces);return this.namespaces=gD(this.namespaces,s),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;let[i,r]=this.validateChain(e);this.getProvider(i).setDefaultChain(r,t)}catch(e){if(!/Please call connect/.test(e.message))throw e}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");let t=this.client.pairing.getAll();if(!dh(t))return;for(let 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(e){this.logger.warn(e,"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 f9.init({core:this.providerOpts.core,logger:this.providerOpts.logger||gg,relayUrl:this.providerOpts.relayUrl||"wss://relay.walletconnect.org",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"),Error(`The provided session: ${null==(t=null==(e=this.providerOpts)?void 0:e.session)?void 0:t.topic} doesn't exist in the Sign client`)}else{let e=this.client.session.getAll();this.session=e[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw Error("Sign Client not initialized");if(!this.session)throw Error("Session not initialized. Please call connect() before enable()");let e=[...new Set(Object.keys(this.session.namespaces).map(e=>di(e)))];gH("client",this.client),gH("events",this.events),gH("disableProviderPing",this.disableProviderPing),e.forEach(e=>{if(!this.session)return;let t=function(e,t){let i=Object.keys(t.namespaces).filter(t=>t.includes(e));if(!i.length)return[];let r=[];
14return i.forEach(e=>{let i=t.namespaces[e].accounts;r.push(...i)}),r}(e,this.session);if(t?.length===0)return;let i=gN(t),r=yb(yx({},gD(this.namespaces,this.optionalNamespaces)[e]),yv({accounts:t,chains:i}));"eip155"===e?this.rpcProviders[e]=new yf({namespace:r}):this.rpcProviders[e]=new ym({namespace:r})})}registerEventListeners(){if(typeof this.client>"u")throw Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;let{topic:i}=e;i===(null==(t=this.session)?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;let{params:i,topic:r}=e;if(r!==(null==(t=this.session)?void 0:t.topic))return;let{event:s}=i;if("accountsChanged"===s.name){let e=s.data;e&&dh(e)&&this.events.emit("accountsChanged",e.map(gU))}else if("chainChanged"===s.name){let e=i.chainId,t=i.event.data,r=di(e),s=gL(e)!==gL(t)?`${r}:${gL(t)}`:e;this.onChainChanged({currentCaipChainId:s})}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i,r;if(e!==(null==(i=this.session)?void 0:i.topic))return;let{namespaces:s}=t,n=null==(r=this.client)?void 0:r.session.get(e);this.session=yb(yx({},n),yv({namespaces:s})),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===(null==(t=this.session)?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",yb(yx({},dc("USER_DISCONNECTED")),yv({data:e.topic}))))}),this.on(gI,e=>{this.onChainChanged(yb(yx({},e),yv({internal:!0})))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[gb]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace(null==(t=this.session)?void 0:t.namespaces[e])})}setNamespaces(e){let{namespaces:t={},optionalNamespaces:i={},sessionProperties:r,scopedProperties:s}=e;this.optionalNamespaces=gD(t,i),this.sessionProperties=r,this.scopedProperties=s}validateChain(e){let[t,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(e=>di(e)).includes(t))throw Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];let r=di(Object.keys(this.namespaces)[0]),s=this.rpcProviders[r].getDefaultChain();return[r,s]}async requestAccounts(){let[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:t,internal:i=!1}){if(!this.namespaces)return;let[r,s]=this.validateChain(e);s&&(this.updateNamespaceChain(r,s),i?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:r,currentCaipChainId:e,previousCaipChainId:t})):this.getProvider(r).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:t,previousCaipChainId:i}){var r,s;try{if(i===t)return;let n=null==(s=null==(r=this.session)?void 0:r.namespaces[e])?void 0:s.accounts;if(!n)return;let a=n.filter(e=>e.includes(`${t}:`)).map(gU);if(!dh(a))return;this.events.emit("accountsChanged",a)}catch(e){this.logger.warn(e,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,t){if(!this.namespaces)return;let i=this.namespaces[e]?e:`${e}:${t}`;this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=t):this.namespaces[i]={chains:[],methods:[],events:[],defaultChain:t}}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){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 i;let r=(null==(i=this.session)?void 0:i.topic)||"";await this.client.core.storage.setItem(`${gm}/${e}${r}`,t)}async getFromStore(e){var t;let i=(null==(t=this.session)?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${gm}/${e}${i}`)}async deleteFromStore(e){var t;let i=(null==(t=this.session)?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${gm}/${e}${i}`)}async cleanupStorage(){var e;try{if((null==(e=this.client)?void 0:e.session.length)>0)return;for(let e of(await this.client.core.storage.getKeys()))e.startsWith(gm)&&await this.client.core.storage.removeItem(e)}catch(e){this.logger.warn(e,"Failed to cleanup storage")}}}let y_=["eth_sendTransaction","personal_sign"],yk=["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"],yO=["chainChanged","accountsChanged"],yT=["chainChanged","accountsChanged","message","disconnect","connect"],yR=async()=>{let{createAppKit:t}=await e.A(755823);return t};var yN=Object.defineProperty,yj=Object.defineProperties,yD=Object.getOwnPropertyDescriptors,yM=Object.getOwnPropertySymbols,yU=Object.prototype.hasOwnProperty,yB=Object.prototype.propertyIsEnumerable,yL=(e,t,i)=>t in e?yN(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,yq=(e,t)=>{for(var i in t||(t={}))yU.call(t,i)&&yL(e,i,t[i]);if(yM)for(var i of yM(t))yB.call(t,i)&&yL(e,i,t[i]);return e},yK=(e,t,i)=>yL(e,"symbol"!=typeof t?t+"":t,i);function yH(e){return Number(e[0].split(":")[1])}function y$(e){return`0x${e.toString(16)}`}class yW{constructor(){yK(this,"events",new rE.EventEmitter),yK(this,"namespace","eip155"),yK(this,"accounts",[]),yK(this,"signer"),yK(this,"chainId",1),yK(this,"modal"),yK(this,"rpc"),yK(this,"STORAGE_KEY","wc@2:ethereum_provider:"),yK(this,"on",(e,t)=>(this.events.on(e,t),this)),yK(this,"once",(e,t)=>(this.events.once(e,t),this)),yK(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),yK(this,"off",(e,t)=>(this.events.off(e,t),this)),yK(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){let t=new yW;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}get connecting(){return!!this.signer.client&&this.signer.client.core.relayer.connecting}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var t;if(!this.signer.client)throw Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);let{required:i,optional:r}=function(e){let{chains:t,optionalChains:i,methods:r,optionalMethods:s,events:n,optionalEvents:a,rpcMap:o}=e;if(!dh(t))throw Error("Invalid chains");let l={chains:t,methods:r||y_,events:n||yO,rpcMap:yq({},t.length?{[yH(t)]:o[yH(t)]}:{})},c=n?.filter(e=>!yO.includes(e)),h=r?.filter(e=>!y_.includes(e));if(!i&&!a&&!s&&!(null!=c&&c.length)&&!(null!=h&&h.length))return{required:t.length?l:void 0};let d={chains:[...new Set(c?.length&&h?.length||!i?l.chains.concat(i||[]):i)],methods:[...new Set(l.methods.concat(null!=s&&s.length?s:yk))],events:[...new Set(l.events.concat(null!=a&&a.length?a:yT))],rpcMap:o};return{required:t.length?l:void 0,optional:i.length?d:void 0}}(this.rpc);try{let t=await new Promise(async(t,s)=>{var n,a;let o,l;this.rpc.showQrModal&&(null==(n=this.modal)||n.open(),null==(a=this.modal)||a.subscribeState(e=>{e.open||this.signer.session||(this.signer.abortPairingAttempt(),s(Error("Connection request reset. Please try again.")))}));let c=null!=e&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect((o=yq({namespaces:yq({},i&&{[this.namespace]:i})},r&&{optionalNamespaces:{[this.namespace]:r}}),l={pairingTopic:e?.pairingTopic,scopedProperties:c},yj(o,yD(l)))).then(e=>{t(e)}).catch(e=>{var t;null==(t=this.modal)||t.showErrorMessage("Unable to connect"),s(Error(e.message))})});if(!t)return;let s=af(t.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:y$(this.chainId)})}catch(e){throw this.signer.logger.error(e),e}finally{null==(t=this.modal)||t.close()}}async authenticate(e,t){var i;if(!this.signer.client)throw Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{let i=await new Promise(async(i,r)=>{var s,n;let a,o;this.rpc.showQrModal&&(null==(s=this.modal)||s.open(),null==(n=this.modal)||n.subscribeState(e=>{e.open||this.signer.session||(this.signer.abortPairingAttempt(),r(Error("Connection request reset. Please try again.")))})),await this.signer.authenticate((a=yq({},e),o={chains:this.rpc.chains},yj(a,yD(o))),t).then(e=>{i(e)}).catch(e=>{var t;null==(t=this.modal)||t.showErrorMessage("Unable to connect"),r(Error(e.message))})}),r=i.session;if(r){let e=af(r.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:e),this.setAccounts(e),this.events.emit("connect",{chainId:y$(this.chainId)})}return i}catch(e){throw this.signer.logger.error(e),e}finally{null==(i=this.modal)||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=>{let{params:t}=e,{event:i}=t;"accountsChanged"===i.name?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):"chainChanged"===i.name?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=>{let t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",y$(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",yj(yq({},dc("USER_DISCONNECTED")),yD({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"string"==typeof e&&e.startsWith(`${this.namespace}:`)}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){let t=e.filter(e=>this.isCompatibleChainId(e)).map(e=>this.parseChainId(e));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",y$(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){let t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){let[t,i,r]=e.split(":");return{chainId:`${t}:${i}`,address:r}}setAccounts(e){this.accounts=e.filter(e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId).map(e=>this.parseAccountId(e).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,i;let r=null!=(t=e?.chains)?t:[],s=null!=(i=e?.optionalChains)?i:[],n=r.concat(s);if(!n.length)throw Error("No chains specified in either `chains` or `optionalChains`");let a=r.length?e?.methods||y_:[],o=r.length?e?.events||yO:[],l=e?.optionalMethods||[],c=e?.optionalEvents||[],h=e?.rpcMap||this.buildRpcMap(n,e.projectId),d=e?.qrModalOptions||void 0;return{chains:r?.map(e=>this.formatChainId(e)),optionalChains:s.map(e=>this.formatChainId(e)),methods:a,events:o,optionalMethods:l,optionalEvents:c,rpcMap:h,showQrModal:!!(null!=e&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){let i={};
14return e.forEach(e=>{i[e]=this.getRpcUrl(e,t)}),i}async initialize(e){var t;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?yH(this.rpc.chains):yH(this.rpc.optionalChains),this.signer=await yC.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 e;try{let i,r,s,n,a=await yR(),{convertWCMToAppKitOptions:o}=await Promise.resolve().then(function(){return y1}),l=o((i=yq({},this.rpc.qrModalOptions),r={chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId},yj(i,yD(r))));if(!l.networks.length)throw Error("No networks found for WalletConnect·");e=a((s=yq({},l),n={universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:(null==(t=this.rpc.qrModalOptions)?void 0:t.enableMobileFullScreen)===!0},yj(s,yD(n))))}catch(e){throw console.warn(e),Error("To use QR modal, please install @reown/appkit package")}if(e)try{this.modal=e}catch(e){throw this.signer.logger.error(e),Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;let{chains:t,optionalChains:i,rpcMap:r}=e;t&&dh(t)&&(this.rpc.chains=t.map(e=>this.formatChainId(e)),t.forEach(e=>{this.rpc.rpcMap[e]=r?.[e]||this.getRpcUrl(e)})),i&&dh(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(e=>this.formatChainId(e)),i.forEach(e=>{this.rpc.rpcMap[e]=r?.[e]||this.getRpcUrl(e)}))}getRpcUrl(e,t){var i;return(null==(i=this.rpc.rpcMap)?void 0:i[e])||`https://rpc.walletconnect.org/v1/?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{let 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?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(e=>this.signer.logger.warn(e))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return"string"==typeof e||e instanceof String?[this.parseAccount(e)]:e.map(e=>this.parseAccount(e))}}var yz=Object.defineProperty,yF=Object.defineProperties,yV=Object.getOwnPropertyDescriptors,yJ=Object.getOwnPropertySymbols,yG=Object.prototype.hasOwnProperty,yY=Object.prototype.propertyIsEnumerable,yZ=(e,t,i)=>t in e?yz(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,yQ=(e,t)=>{for(var i in t||(t={}))yG.call(t,i)&&yZ(e,i,t[i]);if(yJ)for(var i of yJ(t))yY.call(t,i)&&yZ(e,i,t[i]);return e};let yX=e=>{let[t,i]=e.split(":");return y0({id:i,caipNetworkId:e,chainNamespace:t,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function y0(e){return yQ({formatters:void 0,fees:void 0,serializers:void 0},e)}var y1=Object.freeze({__proto__:null,convertWCMToAppKitOptions:function(e){var t,i,r,s,n,a,o;let l=null==(t=e.chains)?void 0:t.map(yX).filter(Boolean);if(0===l.length)throw Error("At least one chain must be specified");let c=l.find(t=>{var i;return t.id===(null==(i=e.defaultChain)?void 0:i.id)}),h={projectId:e.projectId,networks:l,themeMode:e.themeMode,themeVariables:function(e){if(e)return{"--w3m-font-family":e["--wcm-font-family"],"--w3m-accent":e["--wcm-accent-color"],"--w3m-color-mix":e["--wcm-background-color"],"--w3m-z-index":e["--wcm-z-index"]?Number(e["--wcm-z-index"]):void 0,"--w3m-qr-color":e["--wcm-accent-color"],"--w3m-font-size-master":e["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":e["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}(e.themeVariables),chainImages:e.chainImages,connectorImages:e.walletImages,defaultNetwork:c,metadata:yF(yQ({},e.metadata),yV({name:(null==(i=e.metadata)?void 0:i.name)||"WalletConnect",description:(null==(r=e.metadata)?void 0:r.description)||"Connect to WalletConnect-compatible wallets",url:(null==(s=e.metadata)?void 0:s.url)||"https://walletconnect.org",icons:(null==(n=e.metadata)?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]})),showWallets:!0,featuredWalletIds:"NONE"===e.explorerRecommendedWalletIds?[]:Array.isArray(e.explorerRecommendedWalletIds)?e.explorerRecommendedWalletIds:[],excludeWalletIds:"ALL"===e.explorerExcludedWalletIds?[]:Array.isArray(e.explorerExcludedWalletIds)?e.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if(null!=(a=e.mobileWallets)&&a.length||null!=(o=e.desktopWallets)&&o.length){let t=[...(e.mobileWallets||[]).map(e=>({id:e.id,name:e.name,links:e.links})),...(e.desktopWallets||[]).map(e=>({id:e.id,name:e.name,links:{native:e.links.native,universal:e.links.universal}}))],i=[...h.featuredWalletIds||[],...h.excludeWalletIds||[]],r=t.filter(e=>!i.includes(e.id));r.length&&(h.customWallets=r)}return h},defineChain:y0}),y2=e.i(361724),y5=e.i(668223),y3=e.i(803959),y8=e.i(450223),y6=e.i(414930),y4=e.i(859654),y7=e.i(117595),y9=e.i(941164),me=e.i(189643),mt=e.i(608861),mi=e.i(796516);function mr(e){if("string"==typeof e){if(!(0,mi.isAddress)(e,{strict:!1}))throw new mt.InvalidAddressError({address:e});return{address:e,type:"json-rpc"}}if(!(0,mi.isAddress)(e.address,{strict:!1}))throw new mt.InvalidAddressError({address:e.address});return{address:e.address,nonceManager:e.nonceManager,sign:e.sign,signAuthorization:e.signAuthorization,signMessage:e.sign
14Message,signTransaction:e.signTransaction,signTypedData:e.signTypedData,source:"custom",type:"local"}}e.s(["toAccount",0,mr],992744);var ms=e.i(656450);class mn{static parse(e){try{return new mn(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return tm(e),e}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){return Date.now()>=1e3*(this.expiration-e)}constructor(e){this.value=e,this._decoded=tm(e)}}class ma extends mn{static parse(e){try{return new ma(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}let mo="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PScwIDAgMTAyNCAxMDI0JyBmaWxsPSdub25lJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHN0eWxlPSdoZWlnaHQ6MjhweDt3aWR0aDoyOHB4Jz48cmVjdCB3aWR0aD0nMTAyNCcgaGVpZ2h0PScxMDI0JyBmaWxsPScjMDA1MkZGJyByeD0nMTAwJyByeT0nMTAwJz48L3JlY3Q+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBjbGlwLXJ1bGU9J2V2ZW5vZGQnIGQ9J00xNTIgNTEyQzE1MiA3MTAuODIzIDMxMy4xNzcgODcyIDUxMiA4NzJDNzEwLjgyMyA4NzIgODcyIDcxMC44MjMgODcyIDUxMkM4NzIgMzEzLjE3NyA3MTAuODIzIDE1MiA1MTIgMTUyQzMxMy4xNzcgMTUyIDE1MiAzMTMuMTc3IDE1MiA1MTJaTTQyMCAzOTZDNDA2Ljc0NSAzOTYgMzk2IDQwNi43NDUgMzk2IDQyMFY2MDRDMzk2IDYxNy4yNTUgNDA2Ljc0NSA2MjggNDIwIDYyOEg2MDRDNjE3LjI1NSA2MjggNjI4IDYxNy4yNTUgNjI4IDYwNFY0MjBDNjI4IDQwNi43NDUgNjE3LjI1NSAzOTYgNjA0IDM5Nkg0MjBaJyBmaWxsPSd3aGl0ZSc+PC9wYXRoPjwvc3ZnPg==",ml="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAALZJREFUaEPtmjEOhDAMBNc/O14GvOzys3CAKK6eAlmaVGl2Zc+kTOU685vkc9/bnD2prZK5/TZY24z9P+g4F5hNh7/GdoG37WlAA5CATwgCxHENYISwQAMQII5rACOEBRqAAHFcAxghLNAABIjjGsAIYYEGIEAc1wBGCAs0AAHiuAYwQligAQgQxzWAEcICDUCAOK4BjBAWaAACxHENYISwQAMQII6fBjr+VHkW3+u+tfyxMpJaDgYzYxb/ALZVAAAAAElFTkSuQmCC";class mc extends tP.E{async initialize(){await this.importPromise,await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:ml,id:"com.coinbase.wallet"}}async promptConnection(){tC.c.debug("Prompting connection via Base Account",{wallet:this.walletClientType});try{await this.importPromise,tC.c.rpcRequest("eth_requestAccounts",this.walletClientType);let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(tC.c.rpcResponse("eth_requestAccounts",this.walletClientType),!e||0===e.length||!e[0])throw new t_.e("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw tC.c.connectionFailed(this.walletClientType,e,{method:"base_account"}),(0,tC.j)(e)}}constructor(t,r,s,n,a){super("base_account",t,r,s),this.connectorType="base_account",this.walletClientType="base_account",this.displayName="Base",this.setBaseAccountSdk=a,this.proxyProvider=new tP.P(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.baseAccountConfig={...n,appChainIds:[r.id].concat(t.map(e=>e.id))},i?(this.proxyProvider.setWalletProvider(i.getProvider()),this.setBaseAccountSdk(i)):this.importPromise=e.A(224814).then(({createBaseAccountSDK:e})=>{i=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider(i.getProvider()),this.setBaseAccountSdk(i)}).catch(console.error)}}let mh=[1,0xaa36a7,137,10,8453,84532,42161,7777777,43114,56];class md extends tP.E{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:mo,id:"com.coinbase.wallet"}}async promptConnection(){tC.c.debug("Prompting connection via Coinbase Wallet",{wallet:this.walletClientType});try{tC.c.rpcRequest("eth_requestAccounts",this.walletClientType);let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(tC.c.rpcResponse("eth_requestAccounts",this.walletClientType),!e||0===e.length||!e[0])throw new t_.e("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw tC.c.connectionFailed(this.walletClientType,e,{method:"coinbase_wallet"}),(0,tC.j)(e)}}updateConnectionPreference(e){this.coinbaseWalletConfig={...this.coinbaseWalletConfig,preference:{...this.coinbaseWalletConfig.preference,options:e}},this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",r=rm({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(r.getProvider())}constructor(e,t,i,s){if(super("coinbase_wallet",e,t,i),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new tP.P(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.coinbaseWalletConfig={...s,appChainIds:[t.id].concat(e.map(e=>e.id))},this.walletClientType="smartWalletOnly"===this.coinbaseWalletConfig.preference?.options?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!r){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter(e=>!mh.includes(e)):[];e.length>0&&!e.every(e=>rw.DEFAULT_SUPPORTED_CHAIN_IDS.has(e))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${e.join(", ")}`),r=rm(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(r.getProvider())}}let mu=({style:e,...t}={})=>(0,tk.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",stroke:"currentColor",strokeWidth:1.5,viewBox:"0 0 24 24",style:{...e},...t,children:(0,tk.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25m18 0A2.25 2.25 0 0018.75 3H5.25A2.25 2.25 0 003 5.25m18 0V12a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 12V5.25"})}),mp=({style:e,...t}={})=>(0,tk.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"108",height:"108",viewBox:"0 0 108 108",fill:"none",style:{height:"28px",width:"28px",...e},...t,children:[(0,tk.jsx)("rect",{width:"108",height:"108",rx:"23",fill:"#AB9FF2"}),(0,tk.jsx)("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M46.5267 69.9229C42.0054 76.8509 34.4292 85.6182 24.348 85.6182C19.5824 85.6182 15 83.6563 15 75.1342C15 53.4305 44.6326 19.8327 72.1268 19.8327C87.768 19.8327 94 30.6846 94 43.0079C94 58.8258 83.7355 76.9122 73.5321 76.9122C70.2939 76.9122 68.7053 75.1342 68.7053 72.314C68.7053 71.5783 68.8275 70.7812 69.0719 69.9229C65.5893 75.8699 58.8685 81.3878 52.5754 81.3878C47.993 81.3878 45.6713 78.5063 45.6713 74.4598C45.6713 72.9884 45.9768 71.4556 46.5267 69.9229ZM83.6761 42.5794C83.6761 46.1704 81.5575 47.9658 79.1875 47.9658C76.7816 47.9658 74.6989 46.1704 74.6989 42.5794C74.6989 38.9885 76.7816 37.1931 79.1875 37.1931C81.5575 37.1931 83.6761 38.9885 83.6761 42.5794ZM70.2103 42.5795C70.2103 46.1704 68.0916 47.9658 65.7216 47.9658C63.3157 47.9658 61.233 46.1704 61.233 42.5795C61.233 38.9885 63.3157 37.1931 65.7216 37.1931C68.0916 37.1931 70.2103 38.9885 70.2103 42.5795Z",fill:"#FFFDF8"})]});function mf(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var mg=0;async function my(e,t){try{tC.c.rpcRequest("eth_requestAccounts",t);let i=await e.request({method:"eth_requestAccounts"});return tC.c.rpcResponse("eth_requestAccounts",t),i}catch(i){if(-32002===i.code&&i.message?.includes("Already processing")){tC.c.debug("eth_requestAccounts already processing, retrying after delay",{wallet:t}),await new Promise(e=>setTimeout(e,500)),tC.c.rpcRequest("eth_requestAccounts",t);let i=await e.request({method:"eth_requestAccounts"});return tC.c.rpcResponse("eth_requestAccounts",t),i}throw i}}class mm extends tP.E{async initialize(){tC.c.debug("Initializing injected connector (EIP-6963)",{wallet:this.walletClientType}
14),await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){if(tC.c.connectionStart(this.walletClientType,"injected",{showPrompt:e.showPrompt}),e.showPrompt&&await this.promptConnection(),!await this.isConnected())return tC.c.debug("Not connected after prompt",{wallet:this.walletClientType}),null;let t=await this.getConnectedWallet();return t&&tC.c.connectionSuccess(this.walletClientType),t}get walletBranding(){return{name:this.providerDetail.info.name,icon:this.providerDetail.info.icon,id:this.providerDetail.info.rdns}}disconnect(){console.warn(`Programmatic disconnect with ${this.providerDetail.info.name} is not yet supported.`)}async promptConnection(){tC.c.debug("Prompting connection via eth_requestAccounts",{wallet:this.walletClientType});try{let e=await my(this.proxyProvider,this.walletClientType);if(!e||0===e.length||!e[0])throw new t_.e("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw tC.c.connectionFailed(this.walletClientType,e,{method:"injected"}),(0,tC.j)(e)}}constructor(e,t,i,r,s){super(s||"unknown",e,t,i),this.connectorType="injected",this.proxyProvider=new tP.P(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=r;let n=r.provider;this.proxyProvider.setWalletProvider(n)}}var mw="__private_"+mg+++"__walletBranding";class mb extends tP.E{async initialize(){tC.c.debug("Initializing legacy injected connector",{wallet:this.walletClientType}),await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){if(tC.c.connectionStart(this.walletClientType,"injected (legacy)",{showPrompt:e.showPrompt}),e.showPrompt&&await this.promptConnection(),!await this.isConnected())return tC.c.debug("Not connected after prompt",{wallet:this.walletClientType}),null;let t=await this.getConnectedWallet();return t&&tC.c.connectionSuccess(this.walletClientType),t}get walletBranding(){return mf(this,mw)[mw]??{name:"Browser Extension",icon:mu,id:"extension"}}disconnect(){tC.c.debug("Disconnect requested (not supported for legacy injected)",{wallet:this.walletClientType})}async promptConnection(){tC.c.debug("Prompting connection via eth_requestAccounts (legacy)",{wallet:this.walletClientType});try{let e=await my(this.proxyProvider,this.walletClientType);if(!e||0===e.length||!e[0])throw new t_.e("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw tC.c.connectionFailed(this.walletClientType,e,{method:"injected (legacy)"}),(0,tC.j)(e)}}constructor(e,t,i,r,s){super(s??"unknown",e,t,i),Object.defineProperty(this,mw,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new tP.P(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(r),"metamask"===s?mf(this,mw)[mw]={name:"MetaMask",icon:tP.M,id:"io.metamask"}:"phantom"===s&&(mf(this,mw)[mw]={name:"Phantom",icon:mp,id:"phantom"})}}class mv extends mm{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){tC.c.debug("Prompting connection via MetaMask",{wallet:this.walletClientType});try{rv.isMobile||(tC.c.rpcRequest("wallet_requestPermissions",this.walletClientType),await this.proxyProvider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),tC.c.rpcResponse("wallet_requestPermissions",this.walletClientType)),tC.c.rpcRequest("eth_requestAccounts",this.walletClientType);let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(tC.c.rpcResponse("eth_requestAccounts",this.walletClientType),!e||0===e.length||!e[0])throw new t_.e("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw tC.c.connectionFailed(this.walletClientType,e,{method:"metamask"}),(0,tC.j)(e)}}}class mE extends tP.E{async initialize(){tC.c.debug("Initializing WalletConnect V2 connector",{wallet:this.walletClientType});let e=await this.createProvider();if(this.provider=e,this.proxyProvider.setWalletProvider(e),this.subscribeListeners(),e.session){let e=this.walletProvider?.session?.peer.metadata;tC.c.debug("Restoring existing WalletConnect session",{peerName:e?.name,accountsCount:this.walletProvider?.accounts?.length}),this.walletProvider?.session?.peer.metadata.url&&(this.walletEntry=(0,tP.e)(this.walletProvider?.session?.peer.metadata.url),this.walletClientType=this.walletEntry?.slug||"unknown"),this.connected=!0,await this.syncAccounts()}
14this.initialized=!0,this.emit("initialized")}async connect(e){tC.c.connectionStart(this.walletClientType,"wallet_connect_v2",{showPrompt:e.showPrompt}),e.showPrompt&&await this.promptConnection();let t=await this.getConnectedWallet();return t&&tC.c.connectionSuccess(this.walletClientType),t}async isConnected(){return!!this.walletProvider?.connected}get walletBranding(){let e=this.walletProvider?.session?.peer.metadata.icons?.[0];return{name:(0,tC.k)(this.walletProvider?.session?.peer.metadata.name||"")||"WalletConnect",icon:"string"==typeof e?e:tC.h,id:this.walletProvider?.session?.peer.metadata.name.toLowerCase()||"wallet_connect_v2"}}async resetConnection(e){let t=this.walletClientType;tC.c.debug("Resetting WalletConnect connection for new wallet",{previousWallet:t,newWallet:e}),this.walletProvider&&this.walletProvider.connected&&(await this.walletProvider.disconnect(),this.walletProvider.signer.session=void 0,this.walletClientType=e,this.redirectUri=void 0,this.fallbackUniversalRedirectUri=void 0,(0,y2.e)(),this.onDisconnect())}async promptConnection(){if(this.provider)return tC.c.debug("Prompting WalletConnect connection",{wallet:this.walletClientType}),new Promise((e,t)=>{(async()=>{tC.c.debug("Enabling WalletConnect provider",{wallet:this.walletClientType,timeoutMs:this.proxyProvider.rpcTimeoutDuration});let t="",i=await Promise.race([this.walletProvider?.enable(),this.proxyProvider.walletTimeout().then(()=>{})]);if(i?.length&&(t=i[0],tC.c.debug("WalletConnect accounts received",{address:t,accountsCount:i.length})),!t||""===t)throw new t_.e("Unable to retrieve address");this.walletProvider?.session?.peer.metadata.url&&(this.walletEntry=(0,tP.e)(this.walletProvider?.session?.peer.metadata.url),this.walletClientType=this.walletEntry?.slug||"unknown",tC.c.debug("Identified wallet from session",{wallet:this.walletClientType}),this.proxyProvider.rpcTimeoutDuration=(0,tP.g)(this.rpcConfig,this.walletClientType)),this.connected=!0,await this.syncAccounts(i),e()})().catch(e=>{tC.c.connectionFailed(this.walletClientType,e,{method:"wallet_connect_v2"}),t(e?(0,tC.j)(e):new t_.e("Unknown error during connection"))})});tC.c.warn("WalletConnect provider not initialized")}disconnect(){this.walletProvider?.disconnect().then(()=>this.onDisconnect()).catch(()=>console.warn("Unable to disconnect WalletConnect provider"))}get walletProvider(){return this.proxyProvider.walletProvider}setWalletProvider(e){this.proxyProvider.setWalletProvider(e)}async createProvider(){tC.c.debug("Creating WalletConnect EthereumProvider",{chainsCount:this.chains.length,defaultChainId:this.defaultChain.id});let e={};for(let t of this.chains){let i=(0,tC.m)(t.id,this.chains,this.rpcConfig,this.privyAppId);i&&(e[t.id]=i)}let t=this.shouldEnforceDefaultChainOnConnect?[this.defaultChain.id]:[],i=this.chains.map(e=>e.id);tC.c.debug("Initializing WalletConnect EthereumProvider",{requiredChains:t.join(", ")||"none",optionalChainsCount:i.length});let r=await yW.init({projectId:this.walletConnectCloudProjectId,chains:t,optionalChains:i,optionalEvents:yT,optionalMethods:yk,rpcMap:e,showQrModal:!1,metadata:{description:this.privyAppName,name:this.privyAppName,url:window.location.origin,icons:[]}});return r.on("display_uri",e=>{if(tC.c.debug("WalletConnect URI generated",{wallet:this.walletClientType,isMobile:rv.isMobile,hasWalletEntry:!!this.walletEntry}),tC.c.debug("Aborting WalletConnect pairing attempt"),r.signer.abortPairingAttempt(),(0,y2.r)(),!this.showPrivyQrModal)throw new t_.e("WalletConnect modal not available - Privy handles wallet connections through its own UI");if(rv.isMobile&&this.walletEntry){let{redirect:t,href:i}=(0,y2.b)(e,this.walletEntry),r=t.startsWith("http");tC.c.debug("Opening mobile wallet via deep link",{wallet:this.walletEntry.name,redirectType:r?"universal":"native"}),(0,y2.o)(t,"_self"),(0,y2.s)({href:i,name:this.walletEntry.metadata?.shortName||this.walletEntry.name});let s=(0,y2.f)(e,this.walletEntry);return this.redirectUri=t,this.fallbackUniversalRedirectUri=s?.redirect,this.showPrivyQrModal({native:t,universal:t})}if(tC.c.debug("Displaying WalletConnect QR code",{wallet:this.walletEntry?.name||"generic"}),this.redirectUri=void 0,this.walletEntry){let t=(0,y2.f)(e,this.walletEntry);this.fallbackUniversalRedirectUri=t?.redirect}this.showPrivyQrModal({native:e,universal:void 0})}),r.on("connect",()=>{let e=r.session?.peer.metadata;tC.c.debug("WalletConnect session established",{peerName:e?.name,peerIcon:e?.icons?.[0]?"present":"none"}),r.session?.peer.metadata.url&&(this.walletEntry=(0,tP.e)(r.session?.peer.metadata.url),this.walletClientType=this.walletEntry?.slug||"unknown")}),r}async enableProvider(){return this.walletProvider?.connected?Promise.resolve(this.walletProvider.accounts):await this.walletProvider?.enable()}setWalletEntry(e,t){this.walletEntry=e,this.showPrivyQrModal=t}constructor({walletConnectCloudProjectId:e,rpcConfig:t,chains:i,defaultChain:r,shouldEnforceDefaultChainOnConnect:s,privyAppId:n,privyAppName:a,walletClientType:o}){super(o||"unknown",i,r,t),this.connectorType="wallet_connect_v2",this.privyAppId=n,this.privyAppName=a,this.walletConnectCloudProjectId=e,this.rpcConfig=t,this.shouldEnforceDefaultChainOnConnect=s,this.proxyProvider=new tP.P(void 0,this.rpcTimeoutDuration),o&&(this.walletEntry=(0,tP.f)(o),this.walletClientType=o)}}class mI extends tx.default{get wallets(){let e=new Set;return this.walletConnectors.flatMap(e=>e.wallets).sort((e,t)=>
14e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0).filter(t=>{let i=`${t.address}${t.walletClientType}${t.connectorType}${t.meta.id}`;return!e.has(i)&&(e.add(i),!0)})}async initialize(e){if(tC.c.info("Starting connector initialization",{reInit:e??!1}),this.initialized&&!e)return;if(e&&this.removeAllConnectors(),this.externalWalletConfig.disableAllExternalWallets)return void tC.c.info("All external wallets disabled, skipping initialization");let t=(0,tC.n)({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then(e=>{tC.c.info("Detected injected providers",{count:e.length,wallets:e.map(e=>e.type).join(", ")}),e.forEach(({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:i})=>{this.createEthereumWalletConnector({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:i}})})});for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),this.walletList.includes("base_account")&&this.createEthereumWalletConnector({connectorType:"base_account",walletClientType:"base_account"}),Object.values(tP.m)))!e.isInstalled&&this.walletList.includes(e.client)&&(["ethereum-only","ethereum-and-solana"].includes(this.walletChainType)&&e.chainTypes.includes("ethereum")&&this.createEthereumWalletConnector({connectorType:"null",walletClientType:e.client,walletConfig:e}),["ethereum-and-solana","solana-only"].includes(this.walletChainType)&&e.chainTypes.includes("solana")&&this.addSolanaWalletConnector(new tP.S({id:e.client,name:e.name})));let i=this.walletList.includes("wallet_connect_qr_solana")||(0,tP.s)(this.walletList)&&"ethereum-only"!==this.walletChainType,r=this.externalWalletConfig.walletConnect.enabled&&(this.walletList.includes("wallet_connect_qr")||(0,tP.s)(this.walletList))&&"solana-only"!==this.walletChainType,s=this.externalWalletConfig.solana.connectors?.get()||[],n=async e=>{await e.initializeProvider({walletConnectCloudProjectId:this.walletConnectCloudProjectId,privyAppName:this.privyAppName});let t=await e.hideSolanaSessionsFromSignClient();try{this.ethereumWalletConnectInitPromise||(this.ethereumWalletConnectInitPromise=this.initEthereumWalletConnect()),await this.ethereumWalletConnectInitPromise}finally{await e.unhideSolanaSessionsInSignClient(t)}await e.restoreSession()},a=async e=>{let t=e.find(e=>"walletconnect_solana"===e.walletBranding?.id),s=t?.wallet??null;!r||i&&s?i&&!r&&s?await s.initialize({walletConnectCloudProjectId:this.walletConnectCloudProjectId,privyAppName:this.privyAppName}):i&&r&&s&&await n(s):this.ethereumWalletConnectInitPromise||(this.ethereumWalletConnectInitPromise=this.initEthereumWalletConnect())};a(s),s.filter(e=>i||"walletconnect_solana"!==e.walletBranding?.id).forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.(e=>{a(e),e?.filter(e=>i||"walletconnect_solana"!==e.walletBranding?.id).forEach(this.addSolanaWalletConnector)}),await t,this.initialized=!0}findWalletConnector(e,t,i){return"wallet_connect_v2"===e?this.walletConnectors.filter(tP.h).find(t=>t.connectorType===e&&(!i||t.wallets.some(e=>e.address===i)))??null:this.walletConnectors.filter(tP.h).find(r=>r.connectorType===e&&r.walletClientType===t&&(!i||r.wallets.some(e=>e.address===i)))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(tP.d).find(t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e)??null}onInitialized(e){tC.c.connectorInit(e.connectorType,e.walletClientType,{walletsCount:e.wallets.length}),e.wallets.forEach(e=>{let t=this.storedConnections.find(t=>t.address===e.address&&t.connectorType===e.connectorType&&("solana"===e.type&&"unknown"===t.walletClientType&&"unknown"===e.walletClientType?e.meta.id===t.id:t.walletClientType===e.walletClientType));t&&(e.connectedAt=t.connectedAt)}),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&this.emit("walletsUpdated")}initEthereumWalletConnect(){return this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"unknown"}).then(e=>{if(e)return new Promise(t=>{if(e.initialized)return void t();let i=setTimeout(()=>t(),5e3);e.once("initialized",()=>{clearTimeout(i),t()})})})}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:i,walletConfig:r}){tC.c.debug("Creating Ethereum wallet connector",{connector:e,wallet:t});let s=this.findWalletConnector(e,t);if(s&&(0,tP.h)(s))return tC.c.debug("Found existing connector, reusing",{connector:e,wallet:t}),s instanceof mE&&s.resetConnection(t),s;let n="injected"!==e?"coinbase_wallet"===e?new md(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new mc(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new mE({w
14alletConnectCloudProjectId:this.walletConnectCloudProjectId,rpcConfig:this.rpcConfig,chains:this.chains,defaultChain:this.defaultChain,shouldEnforceDefaultChainOnConnect:this.shouldEnforceDefaultChainOnConnect,privyAppId:this.privyAppId,privyAppName:this.privyAppName,walletClientType:t}):r?new tP.j({id:r.client,name:r.name,defaultChain:this.defaultChain,walletClientType:r.client}):null:"metamask"===t&&i?.eip6963InjectedProvider?new mv(this.chains,this.defaultChain,this.rpcConfig,i?.eip6963InjectedProvider,"metamask"):"metamask"===t&&i?.legacyInjectedProvider?new mb(this.chains,this.defaultChain,this.rpcConfig,i?.legacyInjectedProvider,"metamask"):"phantom"===t&&i?.legacyInjectedProvider?new mb(this.chains,this.defaultChain,this.rpcConfig,i?.legacyInjectedProvider,"phantom"):i?.legacyInjectedProvider&&"unknown_browser_extension"===t?new mb(this.chains,this.defaultChain,this.rpcConfig,i?.legacyInjectedProvider):i?.eip6963InjectedProvider?new mm(this.chains,this.defaultChain,this.rpcConfig,i?.eip6963InjectedProvider,t):void 0;return n?(tC.c.connectorCreated(e,t),this.addWalletConnector(n)):tC.c.debug("No connector created",{connector:e,wallet:t}),n||null}addWalletConnector(e){tC.c.debug("Adding wallet connector",{connector:e.connectorType,wallet:e.walletClientType}),this.walletConnectors.push(e),e.on("initialized",()=>this.onInitialized(e)),e.on("walletsUpdated",()=>this.onWalletsUpdated(e)),e.initialize().catch(t=>{tC.c.error("Failed to initialize connector",t,{connector:e.connectorType,wallet:e.walletClientType})})}setWalletList(e){this.walletList=e,this.initialized&&this.initialize(!0).catch(console.error)}removeAllConnectors(){for(let e of this.walletConnectors)e.removeAllListeners();this.walletConnectors=[]}constructor(e,t,i,r,s,n,a,o,l,c,h,d,u){super(),this.ethereumWalletConnectInitPromise=null,this.addSolanaWalletConnector=async e=>{let t=this.findSolanaWalletConnector(e.walletClientType);if(!t||"null"===t.connectorType){if("null"===t?.connectorType){let e=this.walletConnectors.indexOf(t);this.walletConnectors.splice(e,1)}this.addWalletConnector(e)}},tC.c.setEnabled(u??!1),tC.c.info("ConnectorManager initializing",{walletChainType:d||void 0,walletListCount:a.length}),this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=i,this.chains=r,this.defaultChain=s,this.walletConnectors=[],this.initialized=!1,this.store=n,this.walletList=a,this.shouldEnforceDefaultChainOnConnect=o,this.externalWalletConfig=l,this.privyAppName=c,this.walletChainType=d||"ethereum-only",this.setBaseAccountSdk=h,this.storedConnections=(0,tC.l)()}}let mS=(0,y3.create)(()=>({identityToken:null})),mA=[y6.s,y6.m,y6.n];class mx{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw(0,t_.f)(e)}}async post(e,t,i){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...i})}catch(e){throw(0,t_.f)(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw(0,t_.f)(e)}}constructor({appId:e,appClientId:t,client:i,defaults:r}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=i.clientAnalyticsId,this.sdkVersion=y5.V,this.client=i,this.defaults=r,this.fallbackApiUrl=i.fallbackApiUrl,this.baseFetch=y8.ofetch.create({baseURL:this.defaults.baseURL,timeout:this.defaults.timeout,retry:3,retryDelay:500,retryStatusCodes:[408,409,425,500,502,503,504],credentials:"include",onRequest:async({request:e,options:t})=>{let i=new Headers(t.headers);i.set("privy-app-id",this.appId),this.appClientId&&i.set("privy-client-id",this.appClientId),i.set("privy-ca-id",this.clientAnalyticsId||""),i.set("privy-client",`react-auth:${this.sdkVersion}`);let r=mA.includes(e.toString());if(!i.has("authorization")){let e=await this.client.getAccessToken({disableAutoRefresh:r});null!==e&&i.set("authorization",`Bearer ${e}`)}t.headers=i,t.retryDelay&&"number"==typeof t.retryDelay&&(t.retryDelay=3*t.retryDelay)},onRequestError:({error:e})=>{if(e instanceof DOMException&&"AbortError"===e.name)throw new t_.g}})}}let mP=e=>({rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map(e=>({id:e.id,type:e.type,transports:e.transports}))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}),mC=Symbol("cross-tab-user-sync-plugin");class m_{async authenticate(){if(!this.api)throw new t_.P("Auth flow has no API instance");try{return await this.api.post(y6.q,{token:this.meta.token})}catch(e){throw(0,t_.f)(e)}}async link(){if(!this.api)throw new t_.P("Auth flow has no API instance");try{return await this.api.post(y6.r,{token:this.meta.token})}catch(e){throw(0,t_.f)(e)}}constructor(e){this.meta={token:e}}}function mk(e){return e?{"privy-ui":"t"}:void 0}class mO{async authenticate(){if(!this.api)throw new t_.P("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new t_.P("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(y6.u,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw(0,t_.f)(e)}}async link(){if(!this.api)throw new t_.P("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new t_.P("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(y6.v,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw(0,t_.f)(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:i}){if(!this.api)throw new t_.P("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new t_.P("Email must be set when initialzing authentication.");let r=mk(i);try{return await this.api.post(y6.w,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...r}})}catch(e){throw(0,t_.f)(e)}}constructor({email:e,captchaToken:t,disableSignup:i}){this.meta={email:e,captchaToken:t,disableSignup:i??!1}}}class mT{getOrCreateGuestCredential(e){let t=(0,y5.g)(e);
14if((0,tC.e)()){if(tC.s.get(t))return tC.s.get(t);{let e=tS.base64url.encode((0,y2.g)(32));return tC.s.put(t,e),e}}return tS.base64url.encode((0,y2.g)(32))}async authenticate(){if(!this.api)throw new t_.P("Auth flow has no API instance");try{return await this.api.post(y6.y,{guest_credential:this.meta.guestCredential})}catch(e){throw(0,t_.f)(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}function mR(){return"u">typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function mN(){if(!mR())return;let e=window.chrome;return e?.runtime?.id}function mj(){if(!mR())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function mD(e){return new Promise((t,i)=>{mj()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},async e=>{try{let i=function(){if(!mR())return;let e=window.chrome;return e?.runtime?.lastError?.message}();if(i||!e){let e=`WebAuthFlow failed: ${i||"Response URI missing"}`;throw Error(e)}let r=new URL(e),s=mN();if(!s)throw Error("Invalid extension context");if("chrome-extension:"===r.protocol){if(r.hostname!==s)throw Error("Invalid responseUri origin")}else{if("https:"!==r.protocol)throw Error("Invalid responseUri protocol");{let e=r.hostname.split(".");if(3!==e.length||"chromiumapp"!==e[1]||"org"!==e[2]||e[0]!==s)throw Error("Invalid responseUri origin")}}let n=r.searchParams.get("privy_oauth_state"),a=r.searchParams.get("privy_oauth_code");if(!n||!a)throw Error("Invalid responseUri - missing required parameters");t({privyOAuthState:n,privyOAuthCode:a})}catch(e){i(e)}}):i(Error("Chrome identity API not available"))})}class mM{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new t_.P("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new t_.P("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new t_.P("User denied confirmation during OAuth flow");let e=(0,y2.h)();try{let t=await this.api.post(y6.o,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});return tC.s.del(y5.f),tC.s.del(y5.H),tC.s.del(y5.O),t}catch(t){let e=(0,t_.f)(t);if(e.privyErrorCode)throw new t_.P(e.message||"Invalid code during OAuth flow.",void 0,e.privyErrorCode);if("User denied confirmation during OAuth flow"===e.message)throw new t_.P("Invalid code during oauth flow.",void 0,t_.a.OAUTH_USER_DENIED);throw new t_.P("Invalid code during OAuth flow.",void 0,t_.a.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new t_.P("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new t_.P("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new t_.P("User denied confirmation during OAuth flow");let e=tC.s.get(y5.f);if(!e)throw new t_.P("Authentication error.");try{let t=await this.api.post(y6.k,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return tC.s.del(y5.f),t}catch(e){throw(0,t_.f)(e)}}async getAuthorizationUrl(){if(!this.api)throw new t_.P("Auth flow has no API instance");if(!this.meta.provider)throw new t_.P("Provider must be set when initializing OAuth authentication.");let e=(0,y2.c)();tC.s.put(y5.f,e);let t=(0,y2.a)();tC.s.put(y5.S,t);let i=await (0,y2.d)(e);this.meta.withPrivyUi||tC.s.put(y5.H,!0),this.meta.disableSignup?tC.s.put(y5.O,!0):tC.s.del(y5.O);let r=mk(this.meta.withPrivyUi),s=window.location.href,n=function(){let e=mN();if(e)return`https://${e}.chromiumapp.org`}();n&&(s=n);try{return await this.api.post(y6.l,{provider:this.meta.provider,redirect_to:this.meta.customOAuthRedirectUrl||s,token:this.meta.captchaToken,code_challenge:i,state_code:t},{headers:{...r}})}catch(e){throw(0,t_.f)(e)}}constructor(e){this.meta=e}}class mU{execute(e){return null===this.promise&&(this.promise=(async()=>{try{return await this.fn(e)}finally{this.promise=null}})()),this.promise}constructor(e){this.promise=null,this.fn=e}}let mB=({address:e,chainId:t,nonce:i})=>`${window.location.host} wants you to sign in with your Ethereum account:
15${e}
16
17By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.
18
19URI: ${window.location.origin}
20Version: 1
21Chain ID: ${t}
22Nonce: ${i}
23Issued At: ${(new Date).toISOString()}
24Resources:
25- https://privy.io`;
25class mL{get meta(){return{connectorType:this.wallet?.connectorType,walletClientType:this.wallet?.walletClientType,chainId:this.wallet?.chainId,address:this.wallet?.address,disableSignup:this._meta.disableSignup}}async authenticate(){if(!this.client)throw new t_.P("SiweFlow has no client instance");try{if(this.preparedMessage&&this.signature)return await this.client.authenticateWithSiweInternal({message:this.preparedMessage,signature:this.signature,chainId:this.wallet?.chainId,walletClientType:this.walletClientType??this.wallet?.walletClientType,connectorType:this.connectorType??this.wallet?.connectorType,mode:this._meta.disableSignup?"no-signup":"login-or-sign-up"});if(!this.wallet)throw new t_.P("SiweFlow has no wallet instance");let{message:e,signature:t}=await this.sign();return await this.client.authenticateWithSiweInternal({message:e,signature:t,chainId:this.wallet.chainId,walletClientType:this.wallet.walletClientType,connectorType:this.wallet.connectorType,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw(0,t_.f)(e)}}async link(){if(!this.client)throw new t_.P("SiweFlow has no client instance");try{if(!this.wallet)throw new t_.P("SiweFlow has no wallet instance");let{message:e,signature:t}=await this.sign();return await this.client.linkWithSiweInternal({message:e,signature:t,chainId:this.wallet.chainId,walletClientType:this.wallet.walletClientType,connectorType:this.wallet.connectorType})}catch(e){throw(0,t_.f)(e)}}async sign(){if(!this.client)throw new t_.P("SiweFlow has no client instance");if(await this.buildMessage(),!this.preparedMessage)throw new t_.P("Could not prepare SIWE message");if(!this.wallet)throw new t_.P("SiweFlow has no wallet instance");let e=await this.wallet.sign(this.preparedMessage);return{message:this.preparedMessage,signature:e}}async _getNonceOnce(){if(!this.client)throw new t_.P("SiweFlow has no client instance");if(!this.wallet)throw new t_.P("UI SiweFlow has no wallet instance");return await this.client.generateSiweNonce({address:this.wallet.address,captchaToken:this.captchaToken})}async buildMessage(){if(!this.client)throw new t_.P("SiweFlow has no client instance");if(!this.wallet)throw new t_.P("SiweFlow has no wallet instance");let e=this.wallet.address,t=this.wallet.chainId.replace("eip155:","");return this.nonce||(this.nonce=await this.getNonceOnce.execute()),this.preparedMessage=mB({address:e,chainId:t,nonce:this.nonce}),this.preparedMessage}constructor(e,t,i,r=!1,s){this._meta={disableSignup:!1},this.getNonceOnce=new mU(this._getNonceOnce.bind(this)),this.wallet=t,this.captchaToken=i,this.client=e,this._meta.disableSignup=r,this.preparedMessage=s?.message,this.signature=s?.signature,this.walletClientType=s?.walletClientType,this.connectorType=s?.connectorType}}class mq{async authenticate(){if(!this.api)throw new t_.P("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new t_.P("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(y6.z,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw(0,t_.f)(e)}}async link(){if(!this.api)throw new t_.P("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new t_.P("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(y6.A,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw(0,t_.f)(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:i}){if(!this.api)throw new t_.P("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new t_.P("phone nNumber must be set when initialzing authentication.");let r=mk(i);try{return await this.api.post(y6.B,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...r}})}catch(e){throw(0,t_.f)(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:i}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:i??!1}}}function mK(){return!(rv.isSafari&&window.location.origin.startsWith("http://localhost"))}var mH,m$,mW,mz,mF,mV,mJ,mG=((mJ={}).PRIVY="privy_access_token",mJ.CUSTOMER="customer_access_token",mJ);class mY{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(y5.d)}get privyAccessToken(){return this._getToken(y5.h)}_getToken(e){try{let t=tC.s.get(e);return"string"==typeof t?mn.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=tC.s.get(y5.R);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=tC.s.get((0,y5.e)(e));if("string"!=typeof t)return null;{let i=new mn(t);return i.isExpired()?(tC.s.del((0,y5.e)(e)),null):i.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=y7.default.get(y5.i);return void 0!==e&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(e="privy_access_token"){let t="string"==typeof this.getToken(e),i="string"==typeof this.refreshToken&&this.refreshToken!==y5.j;return this.mightHaveServerCookies||t&&i}hasActiveAccessToken(e){let t=mn.parse(this.getToken(e));return null!==t&&!t.isExpired(30)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}destroy(){return this.destroyOnce.execute()}storeProviderAccessToken(e,t){"string"==typeof t?tC.s.put((0,y5.e)(e),t):tC.s.del((0,y5.e)(e))}updateIdentityToken(e){"string"==typeof e?this.storeIdentityToken(e):this.clearIdentityToken()}async _authenticate(e){try{let t=await e.authenticate(),{user:i,is_new_user:r,oauth_tokens:s}=t;this.handleTokenResponse(t);let n=s?{provider:s.provider,accessToken:s.access_token,accessTokenExpiresInSeconds:s.access_token_expires_in_seconds,refreshToken:s.refresh_token,refreshTokenExpiresInSeconds:s.refresh_token_expires_in_seconds,scopes:s.scopes}:void 0;return this._trackAuthenticateEvents(e,r),{user:(0,tA.j)(i),isNewUser:r,oAuthTokens:n}}catch(e){throw console.warn("Error authenticating session"),(0,t_.h)(e)}}_trackAuthenticateEvents(e,t){let i=e instanceof mO?"email":e instanceof mq?"sms":e instanceof mL?"siwe":e instanceof mT?"guest":e instanceof m_?"custom_auth":e instanceof mM?e.meta.provider:null;i&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:i,isNewUser:t}}),"siwe"===i&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate_siwe",payload:{connectorType:e.meta.connectorType,walletClientType:e.meta.walletClientType}})}async _link(e){try{let t=await e.link(),i=t.oauth_tokens,r=i?{provider:i.provider,accessToken:i.access_token,accessTokenExpiresInSeconds:i.access_token_expires_in_seconds,refreshToken:i.refresh_token,refreshTokenExpiresInSeconds:i.refresh_token_expires_in_seconds,scopes:i.scopes}:void 0;return{user:(0,tA.j)(t),oAuthTokens:r}}catch(e){throw console.warn("Error linking account"),(0,t_.h)(e)}}async _refresh(){if(!this.api)throw new t_.P("Session has no API instance");if(!this.client)throw new t_.P("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let e=this.token,t=this.refreshToken;if(this.client.useServerCookies&&!this.mightHaveServerCookies&&this.token&&window.location.origin===this.client.apiUrl)return this.destroyLocalState(),null;try{let i;if(!(e&&t||this.mightHaveServerCookies))return null;{let r={};e&&(r.authorization=`Bearer ${e}`),i=await this.api.post(y6.s,t?{refresh_token:t}:{},{headers:r})}return this.handleTokenResponse(i),(0,tA.j)(i.user)}catch(e){if(e instanceof t_.c&&e.privyErrorCode===t_.a.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw(0,t_.h)(e)}}handleTokenResponse(e){e.session_update_action&&"set"!==e.session_update_action?"clear"===e.session_update_action?this.destroyLocalState():"ignore"===e.session_update_action&&(e.token&&(this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token)),e.identity_token&&this.storeIdentityToken(e.identity_token)):this._storeAllTokens(e)}_storeAllTokens(e){this.storeRefreshToken(e.refresh_token),this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token),e.identity_token&&this.storeIdentityToken(e.identity_token)}async _destroy(){try{await this.api?.post(y6.m,{refresh_token:this.refreshToken})}catch(e){console.warn("Error destroying session")}this.destroyLocalState()}destroyLocalState(){this.storeRefreshToken(null),this.storeCustomerAccessToken(null),this.storePrivyAccessToken(null),this.clearIdentityToken()}storeCustomerAccessToken(e){if("string"==typeof e){let t=tC.s.get(y5.d);if(tC.s.put(y5.d,e),!this.client?.useServerCookies){let t=mn.parse(e)?.expiration;
25y7.default.set(y5.k,e,{sameSite:"Strict",secure:mK(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else tC.s.del(y5.d),y7.default.remove(y5.k),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(tC.s.put(y5.R,e),this.client?.useServerCookies||y7.default.set(y5.i,"t",{sameSite:"Strict",secure:mK(),expires:30})):(tC.s.del(y5.R),y7.default.remove(y5.l),y7.default.remove(y5.i))}storePrivyAccessToken(e){"string"==typeof e?tC.s.put(y5.h,e):tC.s.del(y5.h)}storeIdentityToken(e){if(mS.setState({identityToken:e}),this.client?.useServerCookies)return;tC.s.put(y5.I,e);let t=mn.parse(e)?.expiration;y7.default.set(y5.m,e,{sameSite:"Strict",secure:mK(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){tC.s.del(y5.I),mS.setState({identityToken:null}),y7.default.remove(y5.m)}constructor(){this.authenticateOnce=new mU(async e=>this._authenticate(e)),this.linkOnce=new mU(async e=>this._link(e)),this.refreshOnce=new mU(this._refresh.bind(this)),this.destroyOnce=new mU(this._destroy.bind(this))}}var mZ=0,mQ="__private_"+mZ+++"__getOrGenerateClientAnalyticsId";class mX{getAppId(){return this.appId}initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:i,defaultChain:r,store:s,walletList:n,shouldEnforceDefaultChainOnConnect:a,externalWalletConfig:o,appName:l,walletChainType:c,setBaseAccountSdk:h,connectorsDebugLogs:d}){this.connectors||(this.connectors=new mI(this.appId,e,t,i,r,s,n,a,o,l,h,c,d))}generateApi(){let e=new mx({appId:this.appId,appClientId:this.appClientId,client:this,defaults:{baseURL:this.apiUrl,timeout:this.timeout}});return this.session.api=e,e}updateApiUrl(e){this.apiUrl=e||this.fallbackApiUrl,this.api=this.generateApi(),e&&(this.useServerCookies=!0)}authenticate(){if(!this.authFlow)throw new t_.P("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new t_.P("No auth flow in progress.");let{oAuthTokens:e}=await this.session.link(this.authFlow);return{user:await this.getAuthenticatedUser(),oAuthTokens:e}}storeProviderAccessToken(e,t){this.session.storeProviderAccessToken(e,t)}getProviderAccessToken(e){return this.session.getProviderAccessToken(e)}async logout(){await this.session.destroy(),this.authFlow=void 0}clearProviderAcccessTokens(e){e.linkedAccounts.filter(e=>"cross_app"===e.type).forEach(e=>{this.storeProviderAccessToken(e.providerApp.id,null)})}startAuthFlow(e){return e.api=this.api,this.authFlow=e,this.authFlow}async initMfaSmsVerification(){try{await this.api.post(y6.D,{action:"verify"})}catch(e){throw(0,t_.f)(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(y6.E,{});return mP(e.options)}catch(e){throw(0,t_.f)(e)}}async getCrossAppProviderDetails(e){try{return this._cachedProviderAppDetails[e]||(this._cachedProviderAppDetails[e]=await this.api.get(`/api/v1/apps/${e}/cross-app/details`)),this._cachedProviderAppDetails[e]}catch(e){console.error("Error fetching cross app provider details",e)}}async acceptTerms(){try{let e=await this.api.post(y6.F,{});return(0,tA.j)(e)}catch(e){throw(0,t_.h)(e)}}async unlinkEmail(e){try{let t=await this.api.post(y6.G,{address:e});return await this.getAuthenticatedUser()??(0,tA.j)(t)}catch(e){throw(0,t_.h)(e)}}async unlinkPhone(e){try{let t=await this.api.post(y6.H,{phoneNumber:e});return await this.getAuthenticatedUser()??(0,tA.j)(t)}catch(e){throw(0,t_.h)(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(y6.I,{address:e});return await this.getAuthenticatedUser()??(0,tA.j)(t)}catch(e){throw(0,t_.h)(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(y6.J,{address:e});return await this.getAuthenticatedUser()??(0,tA.j)(t)}catch(e){throw(0,t_.h)(e)}}async unlinkOAuth(e,t){try{let i=await this.api.post(y6.K,{provider:e,subject:t});return await this.getAuthenticatedUser()??(0,tA.j)(i)}catch(e){throw(0,t_.h)(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(y6.L,{fid:e});return await this.getAuthenticatedUser()??(0,tA.j)(t)}catch(e){throw(0,t_.h)(e)}}async unlinkTelegram(e){try{let t=await this.api.post(y6.M,{telegram_user_id:e});return await this.getAuthenticatedUser()??(0,tA.j)(t)}catch(e){throw(0,t_.h)(e)}}async revokeDelegatedWallet(){try{await this.api.post(y6.N,{})}catch(e){throw(0,t_.h)(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:i,options:r}){if("u">typeof window)try{if(!this.clientAnalyticsId)return void console.warn("No client analytics id set, refusing to send analytics event");await this.api.post(y6.n,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:i?i.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:r?.keepAlive??!1})}catch{}}async signMoonpayOnRampUrl(e){try{return this.api.post(y6.O,e)}catch(e){throw(0,t_.h)(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(y6.P,e)}catch(e){throw(0,t_.h)(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${y6.Q}?partnerUserId=${e}`)}catch(e){throw(0,t_.h)(e)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(e){return await this.getPrivyAccessToken(e)||await this.getCustomerAccessToken(e)}async getCustomerAccessToken(e){return await this._getToken(mG.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(mG.PRIVY,e)}async _getToken(e,t){if(this.session.getToken(e)){if(this.session.hasActiveAccessToken(e))return this.session.hasRefreshCredentials(e)?ma.parse(this.session.getToken(e))?.appId!==this.appId?(await this.logout(),null):this.session.getToken(e):(this.session.destroyLocalState(),null);{if(t?.disableAutoRefresh||!this.session.hasRefreshCredentials(e))return null;let i=(0,y4.g)(mC);if(i){let t=async()=>(await this.session.refresh(),this.session.getToken(e));return await i.withRefreshLock({onLeader:t,onFollowerReleased:async()=>this.session.hasActiveAccessToken(e)?this.session.getToken(e):t()})}return await this.session.refresh(),this.session.getToken(e)}}return!t?.disableAutoRefresh&&this.useServerCookies&&this.session.mightHaveServerCookies?(await this.session.refresh(),this.session.getToken(e)):null}async getUsdTokenPrice(e){try{return(await this.api.get(`/api/v1/token_price?chainId=${e.id}&tokenSymbol=${e.nativeCurrency.symbol}`)).usd}catch(t){return void console.error(`Unable to fetch token price for chain with id ${e.id}`)}}async getUsdPriceForSol(){try{return(await this.api.get("/api/v1/token_price?chainId=0&tokenSymbol=SOL")).usd}catch(e){return void console.error("Unable to fetch token price for SOL")}}async getSplTokenMetadata({mintAddress:e,cluster:t}){try{return await this.api.get(`/api/v1/spl_token_info?mint_address=${e}
25&cluster=${t}`)}catch(i){return void console.error(`Unable to fetch token metadata for ${t}:${e}`)}}async requestFarcasterSignerStatus(e){try{return await this.api.post("/api/v1/farcaster/signer/status",{ed25519_public_key:e})}catch(e){throw console.error("Unable to fetch Farcaster signer status"),e}}async generateSiweNonce({address:e,captchaToken:t}){try{return(await this.api.post(y6.R,{address:e,token:t})).nonce}catch(e){throw(0,t_.h)(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:i,walletClientType:r,connectorType:s,mode:n}){return await this.api.post(y6.S,{message:e,signature:t,chainId:i,walletClientType:r,connectorType:s,mode:n})}async linkWithSiweInternal({message:e,signature:t,chainId:i,walletClientType:r,connectorType:s}){return await this.api.post(y6.T,{message:e,signature:t,chainId:i,walletClientType:r,connectorType:s})}async linkSmartWallet({message:e,signature:t,smartWalletType:i,smartWalletVersion:r}){try{let s=await this.api.post(y6.U,{message:e,signature:t,smart_wallet_type:i,smart_wallet_version:r});return(0,tA.j)(s)}catch(e){throw(0,t_.h)(e)}}async linkWithSiwe({message:e,signature:t,chainId:i,walletClientType:r,connectorType:s}){try{let n=await this.linkWithSiweInternal({message:e,signature:t,chainId:i,walletClientType:r,connectorType:s});return(0,tA.j)(n)}catch(e){throw(0,t_.h)(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(y6.V,{address:e,token:t})).nonce}catch(e){throw(0,t_.h)(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:i,connectorType:r,mode:s,messageType:n="plain"}){return await this.api.post(y6.W,{message:e,signature:t,walletClientType:i,connectorType:r,mode:s,message_type:n})}async authenticateWithSiws({message:e,signature:t,walletClientType:i,connectorType:r,mode:s,messageType:n="plain"}){let a=await this.authenticateWithSiwsInternal({message:e,signature:t,walletClientType:i,connectorType:r,mode:s,messageType:n});this.session.handleTokenResponse(a);let o=(0,tA.j)(a.user);if(!o)throw Error("Authentication failed - no user returned");return{user:o,isNewUser:a.is_new_user||!1}}async sendAccountTransferRequest({nonce:e,account:t,accountType:i,externalWalletMetadata:r,telegramAuthResult:s,telegramWebAppData:n,farcasterEmbeddedAddress:a,oAuthUserInfo:o}){try{let l,c;switch(i){case"email":l=y6.a1,c={nonce:e,email:t};break;case"sms":l=y6.a0,c={nonce:e,phoneNumber:t};break;case"siwe":if(l=y6.$,!r)throw Error("Wallet parameters must be defined");c={nonce:e,address:t,...r};break;case"farcaster":l=y6._,c={nonce:e,farcaster_id:t,farcaster_embedded_address:a};break;case"telegram":l=y6.Z,c={nonce:e,telegram_auth_result:s,telegram_web_app_data:n};break;case"siws":l=y6.Y,c={nonce:e,address:t,...r};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:l=y6.X,c={nonce:e,userInfo:o}}let h=await this.api.post(l,c);return await this.getAuthenticatedUser()??(0,tA.j)(h)}catch(e){throw(0,t_.h)(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:i,connectorType:r,messageType:s="plain"}){return await this.api.post(y6.a2,{message:e,signature:t,walletClientType:i,connectorType:r,message_type:s})}async linkWithSiws({message:e,signature:t,walletClientType:i,connectorType:r,messageType:s="plain"}){try{let n=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:i,connectorType:r,messageType:s});return(0,tA.j)(n)}catch(e){throw(0,t_.h)(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(y6.a3);return this.session.updateIdentityToken(e.identity_token),(0,tA.j)(e.user)}catch(e){throw(0,t_.h)(e)}}async scanTransaction(e){try{return await this.api.post(y6.a4,e)}catch(e){throw(0,t_.h)(e)}}constructor({apiUrl:e=y5.D,appId:t,appClientId:i,timeout:r=y5.n}){Object.defineProperty(this,mQ,{value:m0}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==y5.D&&e.startsWith("https://privy."),this.timeout=r,this.appId=t,this.appClientId=i,this.clientAnalyticsId=(function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e})(this,mQ)[mQ](),s||(s=new mY),this.session=s,this.api=this.generateApi(),this.session.client=this}}function m0(){if("u"<typeof window)return null;try{let e=tC.s.get(y5.c);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=crypto.randomUUID();try{return tC.s.put(y5.c,e),e}catch(t){return e}}
25function m1(){if(!n)throw new t_.P("No global PrivyClient instance found. Please ensure you have initialized the PrivyProvider.");return n}async function m2(){let e=m1();return e?e.getAccessToken():Promise.resolve(tC.s.get(y5.h)||tC.s.get(y5.d)||null)}async function m5(e,t,i,r){let s=(0,y9.toViemTransactionSerializable)(e),{chain:n,authorizationList:a,...o}=await (async()=>r?await r():await t.prepareTransactionRequest({...s,account:{address:i,type:"json-rpc"}}))();return{...o,type:y9.STRING_TO_NUMBER_TXN_TYPE[o.type],authorizationList:e.authorizationList}}let m3=["calls","feePayer","feePayerSignature","feeToken","keyAuthorization","nonceKey","signature","validBefore","validAfter"],m8=async({wallet:e,signatureOptions:t})=>{let i=await e.getEthereumProvider();return mr({address:e.address,sign:async({hash:t})=>{if("privy"!==e.walletClientType)throw new rb.PrivyClientError({error:"Unprefixed signing is not supported by external wallets.",code:"unsupported_wallet_type"});return await i.request({method:"secp256k1_sign",params:[t]})},signMessage:async({message:t})=>{let r;if("string"==typeof t)r=t;else{if("string"!=typeof t.raw)throw new rb.PrivyClientError({error:"signMessage only supports string messages or {raw: Hex} format",code:"invalid_input"});r=t.raw}return await i.request({method:"personal_sign",params:[r,e.address]})},signTypedData:async r=>{let s;if("erc1271"===t?.type){let e=r?.domain,i=e?.chainId;s={signatureOptions:t,...null!=i?{caip2:`eip155:${i}`}:{}}}return await i.request({method:"eth_signTypedData_v4",params:[e.address,r,s]})},signTransaction:async e=>await i.request({method:"eth_signTransaction",params:[e]}),signAuthorization:async t=>{if("privy"!==e.walletClientType)throw new rb.PrivyClientError({error:"EIP-7702 authorization signing is not supported by external wallets.",code:"unsupported_wallet_type"});let r={chainId:t.chainId,address:t.contractAddress??t.address,nonce:t.nonce},s=(0,ms.hashAuthorization)(r),n=(0,me.parseSignature)(await i.request({method:"secp256k1_sign",params:[s]}));return{...r,...n}}})};e.s(["B",0,mu,"C",0,m_,"E",0,mO,"G",0,mT,"O",0,mM,"R",0,mU,"S",0,mL,"T",0,mn,"U",0,class extends mq{async link(){if(!this.api)throw new t_.P("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new t_.P("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(y6.C,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw(0,t_.f)(e)}}constructor(e,t,i){super({phoneNumber:t,captchaToken:i}),this.meta={phoneNumber:t,captchaToken:i,oldPhoneNumber:e,disableSignup:!1}}},"W",0,mE,"a",0,m2,"b",0,mq,"c",0,class extends mO{async link(){if(!this.api)throw new t_.P("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new t_.P("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(y6.x,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw(0,t_.f)(e)}}constructor(e,t,i){super({email:t,captchaToken:i}),this.meta={email:t,captchaToken:i,oldAddress:e,disableSignup:!1}}},"d",0,m5,"e",0,function(e){n||(n=new mX({appId:e.appId,appClientId:e.clientId,apiUrl:e.apiUrl}))},"f",0,m1,"g",0,mk,"h",0,mj,"i",0,e=>{if(!e||"object"!=typeof e)return!1;if(e.type===y9.TEMPO_TXN_TYPE_NUMBER||"string"==typeof e.type&&e.type.toLowerCase()===y9.TEMPO_TXN_TYPE_STRING)return!0;let t=e.account;return!!t?.keyType&&"secp256k1"!==t.keyType||"accessKey"===t?.source||m3.some(t=>void 0!==e[t])},"j",0,mC,"k",0,mP,"l",0,mD,"m",0,m8,"p",0,mB,"t",0,e=>({type:y9.TEMPO_TXN_TYPE_NUMBER,from:e.from,chainId:e.chainId,nonce:e.nonce,gasLimit:e.gasLimit??e.gas,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,calls:(e=>{let t=e.calls&&e.calls.length>0?e.calls:e.to?[{to:e.to,data:e.data,value:e.value}]:[];if(0===t.length)throw Error("Tempo transactions require at least one call");return t.map(e=>{if(!e.to)throw Error("Tempo transaction calls require a `to` address");return{to:e.to,data:e.data,value:e.value}})})(e),feeToken:(e=>{if(void 0!==e)return"string"==typeof e?e:`0x20c0${e.toString(16).padStart(36,"0")}`})(e.feeToken),nonceKey:(e=>{if("expiring"!==e&&"random"!==e)return e})(e.nonceKey),validBefore:e.validBefore,validAfter:e.validAfter,feePayerSignature:e.feePayerSignature??void 0,accessList:e.accessList}),"u",0,function(){let{identityToken:e}=mS();return{identityToken:e}},"v",0,mo,"w",0,ml,"x",0,({style:e,...t})=>(0,tk.jsxs)("svg",{viewBox:"0 0 1024 1024",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"28px",width:"28px",...e},...t,children:[(0,tk.jsx)("rect",{width:"1024",height:"1024",fill:"#0052FF",rx:100,ry:100}),(0,tk.jsx)("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z",fill:"white"})]})],324607)}]);

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.