PageSourceSearch

https://terminallyonchain.xyz/_next/static/chunks/06.lkzb7zj-6b.js

js terminallyonchain.xyz collected 2026-10-09 22:40:54 UTC 579,472 bytes, 28 lines download raw bytes

1;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="bd2c9d0e-a766-7f5b-5492-41e18f706019")}catch(e){}}();
2(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,763162,e=>{"use strict";e.s(["default",0,function(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}])},33867,e=>{"use strict";class t 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)}}e.s(["JOSEAlgNotAllowed",0,class extends t{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},"JOSEError",0,t,"JOSENotSupported",0,class extends t{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},"JWEDecompressionFailed",0,class extends t{constructor(){super(...arguments),this.code="ERR_JWE_DECOMPRESSION_FAILED",this.message="decompression operation failed"}static get code(){return"ERR_JWE_DECOMPRESSION_FAILED"}},"JWEDecryptionFailed",0,class extends t{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}},"JWEInvalid",0,class extends t{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}},"JWKInvalid",0,class extends t{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},"JWKSInvalid",0,class extends t{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},"JWKSMultipleMatchingKeys",0,class extends t{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"}},"JWKSNoMatchingKey",0,class extends t{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"}},"JWKSTimeout",0,class extends t{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}},"JWSInvalid",0,class extends t{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},"JWSSignatureVerificationFailed",0,class extends t{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}},"JWTClaimValidationFailed",0,class extends t{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}},"JWTExpired",0,class extends t{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}},"JWTInvalid",0,class extends t{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}])},576951,e=>{"use strict";var t=e.i(840796),i=e.i(932763),r=e.i(763162),s=e.i(33867);e.s(["decodeJwt",0,function(e){let n,a;if("string"!=typeof e)throw new s.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");let{1:o,length:l}=e.split(".");if(5===l)throw new s.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(3!==l)throw new s.JWTInvalid("Invalid JWT");
2if(!o)throw new s.JWTInvalid("JWTs must contain a payload");try{n=(0,t.decode)(o)}catch(e){throw new s.JWTInvalid("Failed to base64url decode the payload")}try{a=JSON.parse(i.decoder.decode(n))}catch(e){throw new s.JWTInvalid("Failed to parse the decoded payload as JSON")}if(!(0,r.default)(a))throw new s.JWTInvalid("Invalid JWT Claims Set");return a}])},577906,740382,e=>{"use strict";var t=e.i(880841),i=e.i(675107);let r={0:"legacy",1:"eip2930",2:"eip1559",3:"eip4844",4:"eip7702"},s=e=>void 0!==e?BigInt(e):void 0;e.s(["STRING_TO_NUMBER_TXN_TYPE",0,{legacy:0,eip2930:1,eip1559:2,eip4844:3,eip7702:4},"toBigIntIfDefined",0,s,"toViemTransactionSerializable",0,function(e){let n,{type:a=2,...o}="string"==typeof e?JSON.parse(e):e;o.accessList&&Array.isArray(o.accessList)?n=o.accessList.map(e=>Array.isArray(e)?{address:e[0],storageKeys:e[1]}:e):o.accessList&&(n=Object.entries(o.accessList).map(e=>({address:e[0],storageKeys:e[1]})));let l=Number(o.chainId??1),c=(0,t.isHex)(o.data)?o.data:o.data?(0,i.toHex)(Uint8Array.from(o.data)):void 0,h=o.nonce?Number(o.nonce):void 0,d={chainId:l,data:c,nonce:h,value:s(o.value),gas:s(o.gas??o.gasLimit)},u=Number(a);if(0===u)return{...o,type:r[u],...d,gasPrice:s(o.gasPrice),accessList:void 0,maxFeePerGas:void 0,maxPriorityFeePerGas:void 0};if(1===u)return{...o,type:r[u],...d,gasPrice:s(o.gasPrice),accessList:n,maxFeePerGas:void 0,maxPriorityFeePerGas:void 0};if(2===u)return{...o,type:r[u],...d,nonce:h,accessList:n,maxFeePerGas:s(o.maxFeePerGas),maxPriorityFeePerGas:s(o.maxPriorityFeePerGas),gasPrice:void 0,maxFeePerBlobGas:void 0};throw Error(`Unsupported transaction type: ${a}`)}],740382);let n="tempo",a=(e,t)=>{if(void 0===e)return;let i=Number(e);if(!Number.isSafeInteger(i)||i<0)throw Error(`Invalid Tempo ${t}: ${String(e)}`);return i};e.s(["TEMPO_TXN_TYPE_NUMBER",0,118,"isTempoTransactionRequest",0,function(e){if(!e||"object"!=typeof e)return!1;let t=e.type;if(118!==t&&("string"!=typeof t||t.toLowerCase()!==n))return!1;let i=e.calls;return Array.isArray(i)&&i.length>0},"normalizeViemPreparedTempoTransaction",0,function(e,t){let{chain:i,gas:r,...s}=e;return{...s,...void 0!==r&&void 0===t?{gasLimit:r}:{}}},"toViemTempoTransactionSerializable",0,function(e){let t,i;if("string"==typeof e)try{t=JSON.parse(e)}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Invalid Tempo transaction JSON: ${e}`)}else t=e;if(t.accessList&&Array.isArray(t.accessList)?i=t.accessList.map(e=>Array.isArray(e)?{address:e[0],storageKeys:e[1]}:e):t.accessList&&(i=Object.entries(t.accessList).map(e=>({address:e[0],storageKeys:e[1]}))),void 0===t.chainId||null===t.chainId)throw Error("Tempo transactions require a chainId");let r=Number(t.chainId);if(!Number.isSafeInteger(r)||r<=0)throw Error(`Invalid Tempo chainId: ${String(t.chainId)}`);let o=a(t.nonce,"nonce");if(!Array.isArray(t.calls)||0===t.calls.length)throw Error("Tempo transactions require at least one call");let l=t.calls.map(e=>({to:e.to,data:e.data,value:s(e.value)}));return{type:n,chainId:r,from:t.from,nonce:o,gas:s(t.gasLimit),maxFeePerGas:s(t.maxFeePerGas),maxPriorityFeePerGas:s(t.maxPriorityFeePerGas),calls:l,feeToken:t.feeToken,nonceKey:s(t.nonceKey),validBefore:a(t.validBefore,"validBefore"),validAfter:a(t.validAfter,"validAfter"),accessList:i}}],577906)},964092,692560,216816,273055,781142,489986,477114,235613,303931,496928,11138,e=>{"use strict";var t=e.i(33867);e.i(840796),e.s([],964092);var i=e.i(932763),r=e.i(654544);let s=r.default.getRandomValues.bind(r.default);function n(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 t.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}e.s(["default",0,s],692560),e.s(["bitLength",0,n,"default",0,e=>s(new Uint8Array(n(e)>>3))],216816);let a=(e,i)=>{if(i.length<<3!==n(e))throw new t.JWEInvalid("Invalid Initialization Vector length")};e.s(["default",0,a],273055);let o=(e,i)=>{let r=e.byteLength<<3;if(r!==i)throw new t.JWEInvalid(`Invalid Content Encryption Key length. Expected ${i}
2 bits, got ${r} bits`)};function l(e,t="algorithm.name"){return TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function c(e,t){return e.name===t}function h(e){return parseInt(e.name.slice(4),10)}function d(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 u(e,t,...i){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!c(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(!c(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(!c(e.algorithm,"PBKDF2"))throw l("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!c(e.algorithm,"RSA-OAEP"))throw l("RSA-OAEP");let i=parseInt(t.slice(9),10)||1;if(h(e.algorithm.hash)!==i)throw l(`SHA-${i}`,"algorithm.hash");break}default:throw TypeError("CryptoKey does not support this operation")}d(e,i)}function p(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}e.s(["default",0,o],781142),e.s(["checkEncCryptoKey",0,u,"checkSigCryptoKey",0,function(e,t,...i){switch(t){case"HS256":case"HS384":case"HS512":{if(!c(e.algorithm,"HMAC"))throw l
2("HMAC");let i=parseInt(t.slice(2),10);if(h(e.algorithm.hash)!==i)throw l(`SHA-${i}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!c(e.algorithm,"RSASSA-PKCS1-v1_5"))throw l("RSASSA-PKCS1-v1_5");let i=parseInt(t.slice(2),10);if(h(e.algorithm.hash)!==i)throw l(`SHA-${i}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!c(e.algorithm,"RSA-PSS"))throw l("RSA-PSS");let i=parseInt(t.slice(2),10);if(h(e.algorithm.hash)!==i)throw l(`SHA-${i}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw l("Ed25519 or Ed448");break;case"ES256":case"ES384":case"ES512":{if(!c(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")}d(e,i)}],489986);let f=(e,...t)=>p("Key must be ",e,...t);e.s(["default",0,f,"withAlg",0,function(e,t,...i){return p(`Key for the ${e} algorithm must be `,t,...i)}],477114);let g=["CryptoKey"];async function y(e,s,n,a,o,l){let c,h;if(!(s instanceof Uint8Array))throw TypeError(f(s,"Uint8Array"));let d=parseInt(e.slice(1,4),10),u=await r.default.subtle.importKey("raw",s.subarray(d>>3),"AES-CBC",!1,["decrypt"]),p=await r.default.subtle.importKey("raw",s.subarray(0,d>>3),{hash:`SHA-${d<<1}`,name:"HMAC"},!1,["sign"]),g=(0,i.concat)(l,a,n,(0,i.uint64be)(l.length<<3)),y=new Uint8Array((await r.default.subtle.sign("HMAC",p,g)).slice(0,d>>3));try{c=((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})(o,y)}catch(e){}if(!c)throw new t.JWEDecryptionFailed;try{h=new Uint8Array(await r.default.subtle.decrypt({iv:a,name:"AES-CBC"},u,n))}catch(e){}if(!h)throw new t.JWEDecryptionFailed;return h}async function m(e,s,n,a,o,l){let c;s instanceof Uint8Array?c=await r.default.subtle.importKey("raw",s,"AES-GCM",!1,["decrypt"]):(u(s,e,"decrypt"),c=s);try{return new Uint8Array(await r.default.subtle.decrypt({additionalData:l,iv:a,name:"AES-GCM",tagLength:128},c,(0,i.concat)(n,o)))}catch(e){throw new t.JWEDecryptionFailed}}e.s(["default",0,e=>(0,r.isCryptoKey)(e),"types",0,g],235613);let w=async(e,i,s,n,l,c)=>{if(!(0,r.isCryptoKey)(i)&&!(i instanceof Uint8Array))throw TypeError(f(i,...g,"Uint8Array"));switch(a(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return i instanceof Uint8Array&&o(i,parseInt(e.slice(-3),10)),y(e,i,s,n,l,c);case"A128GCM":case"A192GCM":case"A256GCM":return i instanceof Uint8Array&&o(i,parseInt(e.slice(1,4),10)),m(e,i,s,n,l,c);default:throw new t.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}};e.s(["default",0,w],303931);let b=async()=>{throw new t.JOSENotSupported('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.')},v=async()=>{throw new t.JOSENotSupported('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.')};e.s(["deflate",0,v,"inflate",0,b],496928),e.s(["default",0,(...e)=>{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}],11138)},529523,855036,672708,994565,680293,84951,943150,744423,634358,722193,303065,157854,83844,201444,488199,830841,603672,370652,308524,908574,832848,900336,807420,382111,e=>{"use strict";
2var t=e.i(194820),i=e.i(303931),r=e.i(496928),s=e.i(33867),n=e.i(11138),a=e.i(763162);let o=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]];var l=e.i(654544),c=e.i(489986),h=e.i(477114),d=e.i(235613);function u(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function p(e,t,i){if((0,l.isCryptoKey)(e))return(0,c.checkEncCryptoKey)(e,t,i),e;if(e instanceof Uint8Array)return l.default.subtle.importKey("raw",e,"AES-KW",!0,[i]);throw TypeError((0,h.default)(e,...d.types,"Uint8Array"))}let f=async(e,t,i)=>{let r=await p(t,e,"wrapKey");u(r,e);let s=await l.default.subtle.importKey("raw",i,...o);return new Uint8Array(await l.default.subtle.wrapKey("raw",s,r,"AES-KW"))},g=async(e,t,i)=>{let r=await p(t,e,"unwrapKey");u(r,e);let s=await l.default.subtle.unwrapKey("raw",i,r,"AES-KW",...o);return new Uint8Array(await l.default.subtle.exportKey("raw",s))};var y=e.i(932763);async function m(e,t,i,r,s=new Uint8Array(0),n=new Uint8Array(0)){let a;if(!(0,l.isCryptoKey)(e))throw TypeError((0,h.default)(e,...d.types));if((0,c.checkEncCryptoKey)(e,"ECDH"),!(0,l.isCryptoKey)(t))throw TypeError((0,h.default)(t,...d.types));(0,c.checkEncCryptoKey)(t,"ECDH","deriveBits");let o=(0,y.concat)((0,y.lengthAndInput)(y.encoder.encode(i)),(0,y.lengthAndInput)(s),(0,y.lengthAndInput)(n),(0,y.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 u=new Uint8Array(await l.default.subtle.deriveBits({name:e.algorithm.name,public:e},t,a));return(0,y.concatKdf)(u,r,o)}async function w(e){if(!(0,l.isCryptoKey)(e))throw TypeError((0,h.default)(e,...d.types));return l.default.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function b(e){if(!(0,l.isCryptoKey)(e))throw TypeError((0,h.default)(e,...d.types));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||"X25519"===e.algorithm.name||"X448"===e.algorithm.name}var v=e.i(692560);async function E(e,t,i,r){if(!(e instanceof Uint8Array)||e.length<8)throw new s.JWEInvalid("PBES2 Salt Input must be 8 or more octets");let n=(0,y.p2s)(t,e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:i,name:"PBKDF2",salt:n},u=await function(e,t){if(e instanceof Uint8Array)return l.default.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if((0,l.isCryptoKey)(e))return(0,c.checkEncCryptoKey)(e,t,"deriveBits","deriveKey"),e;throw TypeError((0,h.default)(e,...d.types,"Uint8Array"))}(r,t);if(u.usages.includes("deriveBits"))return new Uint8Array(await l.default.subtle.deriveBits(o,u,a));if(u.usages.includes("deriveKey"))return l.default.subtle.deriveKey(o,u,{length:a,name:"AES-KW"},!1,["wrapKey","unwrapKey"]);throw TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}let _=async(e,i,r,s=2048,n=(0,v.default)(new Uint8Array(16)))=>{let a=await E(n,e,s,i);return{encryptedKey:await f(e.slice(-6),a,r),p2c:s,p2s:(0,t.encode)(n)}},I=async(e,t,i,r,s)=>{let n=await E(s,e,r,t);return g(e.slice(-6),n,i)};function S(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new s.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}let A=(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`)}},x=async(e,t,i)=>{if(!(0,l.isCryptoKey)(t))throw TypeError((0,h.default)(t,...d.types));if((0,c.checkEncCryptoKey)(t,e,"encrypt","wrapKey"),A(e,t),t.usages.includes("encrypt"))return new Uint8Array(await l.default.subtle.encrypt(S(e),t,i));if(t.usages.includes("wrapKey")){let r=await l.default.subtle.importKey("raw",i,...o);return new Uint8Array(await l.default.subtle.wrapKey("raw",r,t,S(e)))}throw TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},P=async(e,t,i)=>{if(!(0,l.isCryptoKey)(t))throw TypeError((0,h.default)(t,...d.types));if((0,c.checkEncCryptoKey)(t,e,"decrypt","unwrapKey"),A(e,t),t.usages.includes("decrypt"))return new Uint8Array(await l.default.subtle.decrypt(S(e),t,i));if(t.usages.includes("unwrapKey")){let r=await l.default.subtle.unwrapKey("raw",i,t,
2S(e),...o);return new Uint8Array(await l.default.subtle.exportKey("raw",r))}throw TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')};function C(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 s.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}let k=e=>(0,v.default)(new Uint8Array(C(e)>>3)),O=(e,t)=>{let i=(e.match(/.{1,64}/g)||[]).join("\n");return`-----BEGIN ${t}-----
3${i}
4-----END ${t}-----`},T=async(e,i,r)=>{if(!(0,l.isCryptoKey)(r))throw TypeError((0,h.default)(r,...d.types));if(!r.extractable)throw TypeError("CryptoKey is not extractable");if(r.type!==e)throw TypeError(`key is not a ${e} key`);return O((0,t.encodeBase64)(new Uint8Array(await l.default.subtle.exportKey(i,r))),`${e.toUpperCase()} KEY`)},R=(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])||R(e,t,r+1))},N=e=>{switch(!0){case R(e,[42,134,72,206,61,3,1,7]):return"P-256";case R(e,[43,129,4,0,34]):return"P-384";case R(e,[43,129,4,0,35]):return"P-521";case R(e,[43,101,110]):return"X25519";case R(e,[43,101,111]):return"X448";case R(e,[43,101,112]):return"Ed25519";case R(e,[43,101,113]):return"Ed448";default:throw new s.JOSENotSupported("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},j=async(e,t,i,r,n)=>{var a;let o,c,h=new Uint8Array(atob(i.replace(e,"")).split("").map(e=>e.charCodeAt(0))),d="spki"===t;switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},c=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},c=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},c=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},c=d?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},c=d?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},c=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let e=N(h);o=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},c=d?[]:["deriveBits"];break}
4case"EdDSA":o={name:N(h)},c=d?["verify"]:["sign"];break;default:throw new s.JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value')}return l.default.subtle.importKey(t,h,o,null!=(a=null==n?void 0:n.extractable)&&a,c)};function D(e){let t=[],i=0;for(;i<e.length;){let r=U(e.subarray(i));t.push(r),i+=r.byteLength}return t}function U(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 M=async e=>{var i,r;if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:n,keyUsages:a}=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 s.JOSENotSupported(`${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 s.JOSENotSupported('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 s.JOSENotSupported('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 s.JOSENotSupported('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 s.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new s.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:i}}(e),o=[n,null!=(i=e.ext)&&i,null!=(r=e.key_ops)?r:a];if("PBKDF2"===n.name)return l.default.subtle.importKey("raw",(0,t.decode)(e.k),...o);let c={...e};return delete c.alg,delete c.use,l.default.subtle.importKey("jwk",c,...o)};async function L(e,t,i){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw TypeError('"spki" must be SPKI formatted string');return j(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,i)}async function B(e,i,r){let s;if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw TypeError('"x509" must be X.509 formatted string');try{let i,r;r=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),s=O((i=D(D(U((0,t.decodeBase64)(r)).contents)[0].contents),(0,t.encodeBase64)(i[160===i[0].raw[0]?6:5].raw)),"PUBLIC KEY")}catch(e){throw TypeError("Failed to parse the X.509 certificate",{cause:e})}
4return j(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",s,i,r)}async function W(e,t,i){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw TypeError('"pkcs8" must be PKCS#8 formatted string');return j(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,i)}async function q(e,i,r){var n;if(!(0,a.default)(e))throw TypeError("JWK must be an object");switch(i||(i=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');if(null!=r||(r=!0!==e.ext),r)return M({...e,alg:i,ext:null!=(n=e.ext)&&n});return(0,t.decode)(e.k);case"RSA":if(void 0!==e.oth)throw new s.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return M({...e,alg:i});default:throw new s.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')}}e.s(["importJWK",0,q,"importPKCS8",0,W,"importSPKI",0,L,"importX509",0,B],855036);let K=(e,t,i)=>{if(e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)){if(!(t instanceof Uint8Array)){if(!(0,d.default)(t))throw TypeError((0,h.withAlg)(e,t,...d.types,"Uint8Array"));if("secret"!==t.type)throw TypeError(`${d.types.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}}else{if(!(0,d.default)(t))throw TypeError((0,h.withAlg)(e,t,...d.types));if("secret"===t.type)throw TypeError(`${d.types.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===i&&"public"===t.type)throw TypeError(`${d.types.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===i&&"public"===t.type)throw TypeError(`${d.types.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===i&&"private"===t.type)throw TypeError(`${d.types.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===i&&"private"===t.type)throw TypeError(`${d.types.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)}};var H=e.i(273055),z=e.i(781142);async function $(e,t,i,r,s){if(!(i instanceof Uint8Array))throw TypeError((0,h.default)(i,"Uint8Array"));let n=parseInt(e.slice(1,4),10),a=await l.default.subtle.importKey("raw",i.subarray(n>>3),"AES-CBC",!1,["encrypt"]),o=await l.default.subtle.importKey("raw",i.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]),c=new Uint8Array(await l.default.subtle.encrypt({iv:r,name:"AES-CBC"},a,t)),d=(0,y.concat)(s,r,c,(0,y.uint64be)(s.length<<3));return{ciphertext:c,tag:new Uint8Array((await l.default.subtle.sign("HMAC",o,d)).slice(0,n>>3))}}async function J(e,t,i,r,s){let n;i instanceof Uint8Array?n=await l.default.subtle.importKey("raw",i,"AES-GCM",!1,["encrypt"]):((0,c.checkEncCryptoKey)(i,e,"encrypt"),n=i);let a=new Uint8Array(await l.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 F=async(e,t,i,r,n)=>{if(!(0,l.isCryptoKey)(i)&&!(i instanceof Uint8Array))throw TypeError((0,h.default)(i,...d.types,"Uint8Array"));switch((0,H.default)(e,r),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return i instanceof Uint8Array&&(0,z.default)(i,parseInt(e.slice(-3),10)),$(e,t,i,r,n);case"A128GCM":case"A192GCM":case"A256GCM":return i instanceof Uint8Array&&(0,z.default)(i,parseInt(e.slice(1,4),10)),J(e,t,i,r,n);default:throw new s.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}};var V=e.i(216816);async function G(e,i,r,s){let n=e.slice(0,7);s||(s=(0,V.default)(n));let{ciphertext:a,tag:o}=await F(n,r,i,s,new Uint8Array(0));return{encryptedKey:a,iv:(0,t.encode)(s),tag:(0,t.encode)(o)}}async function Y(e,t,r,s,n){let a=e.slice(0,7);return(0,i.default)(a,t,r,s,n,new Uint8Array(0))}async function Z(e,i,r,n,o){switch(K(e,i,"decrypt"),e){case"dir":if(void 0!==r)throw new s.JWEInvalid("Encountered unexpected JWE Encrypted Key");return i;case"ECDH-ES":if(void 0!==r)throw new s.JWEInvalid("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let o,l;if(!(0,a.default)(n.epk))throw new s.JWEInvalid('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!b(i))throw new s.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");let c=await q(n.epk,e);if(void 0!==n.apu){if("string"!=typeof n.apu)throw new s.JWEInvalid('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{o=(0,t.decode)(n.apu)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the apu")}}if(void 0!==n.apv){if("string"!=typeof n.apv)throw new s.JWEInvalid('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{l=(0,t.decode)(n.apv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the apv")}}let h=await m(c,i,"ECDH-ES"===e?n.enc:e,"ECDH-ES"===e?C(n.enc):parseInt(e.slice(-5,-2),10),o,l);if("ECDH-ES"===e)return h;if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return g(e.slice(-6),h,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return P(e,i,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{let a;if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");if("number"!=typeof n.p2c)throw new s.JWEInvalid('JOSE Header "p2c" (PBES2 Count) missing or invalid');let l=(null==o?void 0:o.maxPBES2Count)||1e4;if(n.p2c>l)throw new s.JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof n.p2s)throw new s.JWEInvalid('JOSE Header "p2s" (PBES2 Salt) missing or invalid');try{a=(0,t.decode)(n.p2s)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the p2s")}return I(e,i,r,n.p2c,a)}
4case"A128KW":case"A192KW":case"A256KW":if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");return g(e,i,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{let a,o;if(void 0===r)throw new s.JWEInvalid("JWE Encrypted Key missing");if("string"!=typeof n.iv)throw new s.JWEInvalid('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof n.tag)throw new s.JWEInvalid('JOSE Header "tag" (Authentication Tag) missing or invalid');try{a=(0,t.decode)(n.iv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the iv")}try{o=(0,t.decode)(n.tag)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the tag")}return Y(e,i,r,a,o)}default:throw new s.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}}let Q=function(e,t,i,r,n){let a;if(void 0!==n.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 o of(a=void 0!==i?new Map([...Object.entries(i),...t.entries()]):t,r.crit)){if(!a.has(o))throw new s.JOSENotSupported(`Extension Header Parameter "${o}" is not recognized`);if(void 0===n[o])throw new e(`Extension Header Parameter "${o}" is missing`);if(a.get(o)&&void 0===r[o])throw new e(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(r.crit)},X=(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 ee(e,o,l){var c;let h,d,u,p,f,g,m;if(!(0,a.default)(e))throw new s.JWEInvalid("Flattened JWE must be an object");if(void 0===e.protected&&void 0===e.header&&void 0===e.unprotected)throw new s.JWEInvalid("JOSE Header missing");if("string"!=typeof e.iv)throw new s.JWEInvalid("JWE Initialization Vector missing or incorrect type");if("string"!=typeof e.ciphertext)throw new s.JWEInvalid("JWE Ciphertext missing or incorrect type");if("string"!=typeof e.tag)throw new s.JWEInvalid("JWE Authentication Tag missing or incorrect type");if(void 0!==e.protected&&"string"!=typeof e.protected)throw new s.JWEInvalid("JWE Protected Header incorrect type");if(void 0!==e.encrypted_key&&"string"!=typeof e.encrypted_key)throw new s.JWEInvalid("JWE Encrypted Key incorrect type");if(void 0!==e.aad&&"string"!=typeof e.aad)throw new s.JWEInvalid("JWE AAD incorrect type");if(void 0!==e.header&&!(0,a.default)(e.header))throw new s.JWEInvalid("JWE Shared Unprotected Header incorrect type");if(void 0!==e.unprotected&&!(0,a.default)(e.unprotected))throw new s.JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");if(e.protected)try{let i=(0,t.decode)(e.protected);h=JSON.parse(y.decoder.decode(i))}catch(e){throw new s.JWEInvalid("JWE Protected Header is invalid")}if(!(0,n.default)(h,e.header,e.unprotected))throw new s.JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let w={...h,...e.header,...e.unprotected};if(Q(s.JWEInvalid,new Map,null==l?void 0:l.crit,h,w),void 0!==w.zip){if
4(!h||!h.zip)throw new s.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==w.zip)throw new s.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:b,enc:v}=w;if("string"!=typeof b||!b)throw new s.JWEInvalid("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof v||!v)throw new s.JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");let E=l&&X("keyManagementAlgorithms",l.keyManagementAlgorithms),_=l&&X("contentEncryptionAlgorithms",l.contentEncryptionAlgorithms);if(E&&!E.has(b))throw new s.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(_&&!_.has(v))throw new s.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed');if(void 0!==e.encrypted_key)try{d=(0,t.decode)(e.encrypted_key)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the encrypted_key")}let I=!1;"function"==typeof o&&(o=await o(h,e),I=!0);try{u=await Z(b,o,d,w,l)}catch(e){if(e instanceof TypeError||e instanceof s.JWEInvalid||e instanceof s.JOSENotSupported)throw e;u=k(v)}try{p=(0,t.decode)(e.iv)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the iv")}try{f=(0,t.decode)(e.tag)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the tag")}let S=y.encoder.encode(null!=(c=e.protected)?c:"");g=void 0!==e.aad?(0,y.concat)(S,y.encoder.encode("."),y.encoder.encode(e.aad)):S;try{m=(0,t.decode)(e.ciphertext)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the ciphertext")}let A=await (0,i.default)(v,u,m,p,f,g);"DEF"===w.zip&&(A=await ((null==l?void 0:l.inflateRaw)||r.inflate)(A));let x={plaintext:A};if(void 0!==e.protected&&(x.protectedHeader=h),void 0!==e.aad)try{x.additionalAuthenticatedData=(0,t.decode)(e.aad)}catch(e){throw new s.JWEInvalid("Failed to base64url decode the aad")}return(void 0!==e.unprotected&&(x.sharedUnprotectedHeader=e.unprotected),void 0!==e.header&&(x.unprotectedHeader=e.header),I)?{...x,key:o}:x}async function et(e,t,i){if(e instanceof Uint8Array&&(e=y.decoder.decode(e)),"string"!=typeof e)throw new s.JWEInvalid("Compact JWE must be a string or Uint8Array");let{0:r,1:n,2:a,3:o,4:l,length:c}=e.split(".");if(5!==c)throw new s.JWEInvalid("Invalid Compact JWE");let h=await ee({ciphertext:o,iv:a||void 0,protected:r||void 0,tag:l||void 0,encrypted_key:n||void 0},t,i),d={plaintext:h.plaintext,protectedHeader:h.protectedHeader};return"function"==typeof t?{...d,key:h.key}:d}async function ei(e,t,i){if(!(0,a.default)(e))throw new s.JWEInvalid("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(a.default))throw new s.JWEInvalid("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new s.JWEInvalid("JWE Recipients has no members");for(let r of e.recipients)try{return await ee({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 s.JWEDecryptionFailed}e.s(["flattenedDecrypt",0,ee],672708),e.s(["compactDecrypt",0,et],529523),e.s(["generalDecrypt",0,ei],994565);let er=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:(0,t.encode)(e)};if(!(0,l.isCryptoKey)(e))throw TypeError((0,h.default)(e,...d.types,"Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:i,key_ops:r,alg:s,use:n,...a}=await l.default.subtle.exportKey("jwk",e);return a};async function es(e){return T("public","spki",e)}async function en(e){return T("private","pkcs8",e)}async function ea(e){return er(e)}async function eo(e,i,r,n,a={}){let o,l,c;switch(K(e,r,"encrypt"),e){case"dir":c=r;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!b(r))throw new s.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:h,apv:d}=a,{epk:u}=a;u||(u=(await w(r)).privateKey);let{x:p,y:g,crv:y,kty:v}=await ea(u),E=await m(r,u,"ECDH-ES"===e?i:e,"ECDH-ES"===e?C(i):parseInt(e.slice(-5,-2),10),h,d);if(l={epk:{x:p,crv:y,kty:v}},"EC"===v&&(l.epk.y=g),h&&(l.apu=(0,t.encode)(h)),d&&(l.apv=(0,t.encode)(d)),"ECDH-ES"===e){c=E;break}c=n||k(i);let _=e.slice(-6);o=await f(_,E,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":c=n||k(i),o=await x(e,r,c);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||k(i);let{p2c:t,p2s:s}=a;({encryptedKey:o,...l}=await _(e,r,c,t,s));break}
4case"A128KW":case"A192KW":case"A256KW":c=n||k(i),o=await f(e,r,c);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||k(i);let{iv:t}=a;({encryptedKey:o,...l}=await G(e,r,c,t));break}default:throw new s.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:o,parameters:l}}e.s(["exportJWK",0,ea,"exportPKCS8",0,en,"exportSPKI",0,es],680293);let el=Symbol();class ec{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,i){let a,o,l,c,h,d,u;if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new s.JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!(0,n.default)(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new s.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let p={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(Q(s.JWEInvalid,new Map,null==i?void 0:i.crit,this._protectedHeader,p),void 0!==p.zip){if(!this._protectedHeader||!this._protectedHeader.zip)throw new s.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if("DEF"!==p.zip)throw new s.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:f,enc:g}=p;if("string"!=typeof f||!f)throw new s.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof g||!g)throw new s.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if("dir"===f){if(this._cek)throw TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if("ECDH-ES"===f&&this._cek)throw TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");{let t;({cek:o,encryptedKey:a,parameters:t}=await eo(f,g,e,this._cek,this._keyManagementParameters)),t&&(i&&el in i?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...t}:this.setUnprotectedHeader(t):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...t}:this.setProtectedHeader(t))}if(this._iv||(this._iv=(0,V.default)(g)),c=this._protectedHeader?y.encoder.encode((0,t.encode)(JSON.stringify(this._protectedHeader))):y.encoder.encode(""),this._aad?(h=(0,t.encode)(this._aad),l=(0,y.concat)(c,y.encoder.encode("."),y.encoder.encode(h))):l=c,"DEF"===p.zip){let e=await ((null==i?void 0:i.deflateRaw)||r.deflate)(this._plaintext);({ciphertext:d,tag:u}=await F(g,e,o,this._iv,l))}else({ciphertext:d,tag:u}=await F(g,this._plaintext,o,this._iv,l));let m={ciphertext:(0,t.encode)(d),iv:(0,t.encode)(this._iv),tag:(0,t.encode)(u)};return a&&(m.encrypted_key=(0,t.encode)(a)),h&&(m.aad=h),this._protectedHeader&&(m.protected=y.decoder.decode(c)),this._sharedUnprotectedHeader&&(m.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(m.header=this._unprotectedHeader),m}}e.s(["FlattenedEncrypt",0,ec,"unprotected",0,el],84951);class eh{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 ed(e,t){let i=`SHA-${e.slice(-3)}`;
4switch(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 s.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function eu(e,t,i){if((0,l.isCryptoKey)(t))return(0,c.checkSigCryptoKey)(t,e,i),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError((0,h.default)(t,...d.types));return l.default.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[i])}throw TypeError((0,h.default)(t,...d.types,"Uint8Array"))}e.s(["GeneralEncrypt",0,class{constructor(e){this._recipients=[],this._plaintext=e}addRecipient(e,t){let i=new eh(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 i,r,a;let o;if(!this._recipients.length)throw new s.JWEInvalid("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 ec(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(!(0,n.default)(this._protectedHeader,this._unprotectedHeader,t.unprotectedHeader))throw new s.JWEInvalid("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 s.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("dir"===r||"ECDH-ES"===r)throw new s.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');if("string"!=typeof i.enc||!i.enc)throw new s.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(o){if(o!==i.enc)throw new s.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}else o=i.enc;if(Q(s.JWEInvalid,new Map,t.options.crit,this._protectedHeader,i),void 0!==i.zip&&(!this._protectedHeader||!this._protectedHeader.zip))throw new s.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let l=k(o),c={ciphertext:"",iv:"",recipients:[],tag:""};for(let s=0;s<this._recipients.length;s++){let n=this._recipients[s],h={};c.recipients.push(h);let d=({...this._protectedHeader,...this._unprotectedHeader,...n.unprotectedHeader}).alg.startsWith("PBES2")?2048+s:void 0;if(0===s){let t=await new ec(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(l).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(n.unprotectedHeader).setKeyManagementParameters({p2c:d}).encrypt(n.key,{...n.options,...e,[el]:!0});c.ciphertext=t.ciphertext,c.iv=t.iv,c.tag=t.tag,t.aad&&(c.aad=t.aad),t.protected&&(c.protected=t.protected),t.unprotected&&(c.unprotected=t.unprotected),h.encrypted_key=t.encrypted_key,t.header&&(h.header=t.header);continue}let{encryptedKey:u,parameters:p}=await eo((null==(i=n.unprotectedHeader)?void 0:i.alg)||(null==(r=this._protectedHeader)?void 0:r.alg)||(null==(a=this._unprotectedHeader)?void 0:a.alg),o,n.key,l,{p2c:d});h.encrypted_key=(0,t.encode)(u),(n.unprotectedHeader||p)&&(h.header={...n.unprotectedHeader,...p})}return c}}],943150);let ep=async(e,t,i,r)=>{let s=await eu(e,t,"verify");A(e,s);let n=ed(e,s.algorithm);try{return await l.default.subtle.verify(n,s,i,r)}catch(e){return!1}};async function ef(e,i,r){var o;let l,c;if(!(0,a.default)(e))throw new s.JWSInvalid("Flattened JWS must be an object");
4if(void 0===e.protected&&void 0===e.header)throw new s.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new s.JWSInvalid("JWS Protected Header incorrect type");if(void 0===e.payload)throw new s.JWSInvalid("JWS Payload missing");if("string"!=typeof e.signature)throw new s.JWSInvalid("JWS Signature missing or incorrect type");if(void 0!==e.header&&!(0,a.default)(e.header))throw new s.JWSInvalid("JWS Unprotected Header incorrect type");let h={};if(e.protected)try{let i=(0,t.decode)(e.protected);h=JSON.parse(y.decoder.decode(i))}catch(e){throw new s.JWSInvalid("JWS Protected Header is invalid")}if(!(0,n.default)(h,e.header))throw new s.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let d={...h,...e.header},u=Q(s.JWSInvalid,new Map([["b64",!0]]),null==r?void 0:r.crit,h,d),p=!0;if(u.has("b64")&&"boolean"!=typeof(p=h.b64))throw new s.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:f}=d;if("string"!=typeof f||!f)throw new s.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');let g=r&&X("algorithms",r.algorithms);if(g&&!g.has(f))throw new s.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');if(p){if("string"!=typeof e.payload)throw new s.JWSInvalid("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new s.JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let m=!1;"function"==typeof i&&(i=await i(h,e),m=!0),K(f,i,"verify");let w=(0,y.concat)(y.encoder.encode(null!=(o=e.protected)?o:""),y.encoder.encode("."),"string"==typeof e.payload?y.encoder.encode(e.payload):e.payload);try{l=(0,t.decode)(e.signature)}catch(e){throw new s.JWSInvalid("Failed to base64url decode the signature")}if(!await ep(f,i,l,w))throw new s.JWSSignatureVerificationFailed;if(p)try{c=(0,t.decode)(e.payload)}catch(e){throw new s.JWSInvalid("Failed to base64url decode the payload")}else c="string"==typeof e.payload?y.encoder.encode(e.payload):e.payload;let b={payload:c};return(void 0!==e.protected&&(b.protectedHeader=h),void 0!==e.header&&(b.unprotectedHeader=e.header),m)?{...b,key:i}:b}async function eg(e,t,i){if(e instanceof Uint8Array&&(e=y.decoder.decode(e)),"string"!=typeof e)throw new s.JWSInvalid("Compact JWS must be a string or Uint8Array");let{0:r,1:n,2:a,length:o}=e.split(".");if(3!==o)throw new s.JWSInvalid("Invalid Compact JWS");let l=await ef({payload:n,protected:r,signature:a},t,i),c={payload:l.payload,protectedHeader:l.protectedHeader};return"function"==typeof t?{...c,key:l.key}:c}async function ey(e,t,i){if(!(0,a.default)(e))throw new s.JWSInvalid("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(a.default))throw new s.JWSInvalid("JWS Signatures missing or incorrect type");for(let r of e.signatures)try{return await ef({header:r.header,payload:e.payload,protected:r.protected,signature:r.signature},t,i)}catch(e){}throw new s.JWSSignatureVerificationFailed}e.s(["flattenedVerify",0,ef],744423),e.s(["compactVerify",0,eg],634358),e.s(["generalVerify",0,ey],722193);let em=e=>Math.floor(e.getTime()/1e3),ew=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,eb=e=>{let t=ew.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)}},ev=e=>e.toLowerCase().replace(/^application\//,""),eE=(e,t,i={})=>{var r,n;let o,l,{typ:c}=i;if(c&&("string"!=typeof e.typ||ev(e.typ)!==ev(c)))throw new s.JWTClaimValidationFailed('unexpected "typ" JWT header value',"typ","check_failed");try{o=JSON.parse(y.decoder.decode(t))}catch(e){}if(!(0,a.default)(o))throw new s.JWTInvalid("JWT Claims Set must be a top-level JSON object");let{requiredClaims:h=[],issuer:d,subject:u,audience:p,maxTokenAge:f}=i;for(let e of(void 0!==f&&h.push("iat"),void 0!==p&&h.push("aud"),void 0!==u&&h.push("sub"),void 0!==d&&h.push("iss"),new Set(h.reverse())))if(!(e in o))throw new s.JWTClaimValidationFailed(`missing required "${e}" claim`,e,"missing");if(d&&!(Array.isArray(d)?d:[d]).includes(o.iss))throw new s.JWTClaimValidationFailed('unexpected "iss" claim value',"iss","check_failed");if(u&&o.sub!==u)throw new s.JWTClaimValidationFailed('unexpected "sub" claim value',"sub","check_failed");if(p&&(r=o.aud,n="string"==typeof p?[p]:p,"string"==typeof r?!n.includes(r):!(Array.isArray(r)&&n.some(Set.prototype.has.bind(new Set(r))))))throw new s.JWTClaimValidationFailed('unexpected "aud" claim value',"aud","check_failed");switch(typeof i.clockTolerance){case"string":l=eb(i.clockTolerance);break;case"number":l=i.clockTolerance;break;case"undefined":l=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:g}=i,m=em(g||new Date);if((void 0!==o.iat||f)&&"number"!=typeof o.iat)throw new s.JWTClaimValidationFailed('"iat" claim must be a number',"iat","invali
4d");if(void 0!==o.nbf){if("number"!=typeof o.nbf)throw new s.JWTClaimValidationFailed('"nbf" claim must be a number',"nbf","invalid");if(o.nbf>m+l)throw new s.JWTClaimValidationFailed('"nbf" claim timestamp check failed',"nbf","check_failed")}if(void 0!==o.exp){if("number"!=typeof o.exp)throw new s.JWTClaimValidationFailed('"exp" claim must be a number',"exp","invalid");if(o.exp<=m-l)throw new s.JWTExpired('"exp" claim timestamp check failed',"exp","check_failed")}if(f){let e=m-o.iat;if(e-l>("number"==typeof f?f:eb(f)))throw new s.JWTExpired('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(e<0-l)throw new s.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return o};async function e_(e,t,i){var r;let n=await eg(e,t,i);if((null==(r=n.protectedHeader.crit)?void 0:r.includes("b64"))&&!1===n.protectedHeader.b64)throw new s.JWTInvalid("JWTs MUST NOT use unencoded payload");let a={payload:eE(n.protectedHeader,n.payload,i),protectedHeader:n.protectedHeader};return"function"==typeof t?{...a,key:n.key}:a}async function eI(e,t,i){let r=await et(e,t,i),n=eE(r.protectedHeader,r.plaintext,i),{protectedHeader:a}=r;if(void 0!==a.iss&&a.iss!==n.iss)throw new s.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(void 0!==a.sub&&a.sub!==n.sub)throw new s.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(void 0!==a.aud&&JSON.stringify(a.aud)!==JSON.stringify(n.aud))throw new s.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch',"aud","mismatch");let o={payload:n,protectedHeader:a};return"function"==typeof t?{...o,key:r.key}:o}e.s(["jwtVerify",0,e_],303065),e.s(["jwtDecrypt",0,eI],157854);class eS{constructor(e){this._flattened=new ec(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(".")}}e.s(["CompactEncrypt",0,eS],83844);let eA=async(e,t,i)=>{let r=await eu(e,t,"sign");return A(e,r),new Uint8Array(await l.default.subtle.sign(ed(e,r.algorithm),r,i))};class ex{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,i){let r;if(!this._protectedHeader&&!this._unprotectedHeader)throw new s.JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!(0,n.default)(this._protectedHeader,this._unprotectedHeader))throw new s.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let a={...this._protectedHeader,...this._unprotectedHeader},o=Q(s.JWSInvalid,new Map([["b64",!0]]),null==i?void 0:i.crit,this._protectedHeader,a),l=!0;if(o.has("b64")&&"boolean"!=typeof(l=this._protectedHeader.b64))throw new s.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:c}=a;if("string"!=typeof c||!c)throw new s.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');K(c,e,"sign");let h=this._payload;l&&(h=y.encoder.encode((0,t.encode)(h))),r=this._protectedHeader?y.encoder.encode((0,t.encode)(JSON.stringify(this._protectedHeader))):y.encoder.encode("");let d=(0,y.concat)(r,y.encoder.encode("."),h),u=await eA(c,e,d),p={signature:(0,t.encode)(u),payload:""};return l&&(p.payload=y.decoder.decode(h)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=y.decoder.decode(r)),p}}e.s(["FlattenedSign",0,ex],201444);class eP{constructor(e){this._flattened=new ex(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}`}}e.s(["CompactSign",0,eP],488199);class eC{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}}e.s(["GeneralSign",0,class{constructor(e){this._signatures=[],this._payload=e}addSignature(e,t){let i=new eC(this,e,t);return this._signatures.push(i),i}async sign(){if(!this._signatures.length)throw new s.JWSInvalid("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 ex(this._payload);r.setProtectedHeader(i.protectedHeader),r.setUnprotectedHeader(i.unprotectedHeader);let{payload:n,...a}=await r.sign(i.key,i.options);if(0===t)e.payload=n;else if(e.payload!==n)throw new s.JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");e.signatures.push(a)}return e}}],830841);class ek{constructor(e){if(!(0,a.default)(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}
4:this._payload={...this._payload,nbf:em(new Date)+eb(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:e}:this._payload={...this._payload,exp:em(new Date)+eb(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:em(new Date)}:this._payload={...this._payload,iat:e},this}}e.s(["SignJWT",0,class extends ek{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){var i;let r=new eP(y.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 s.JWTInvalid("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}],603672),e.s(["EncryptJWT",0,class extends ek{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 eS(y.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)}}],370652);var eO=e.i(797481);let eT=(e,t)=>{if("string"!=typeof e||!e)throw new s.JWKInvalid(`${t} missing or invalid`)};async function eR(e,i){let r;if(!(0,a.default)(e))throw TypeError("JWK must be an object");if(null!=i||(i="sha256"),"sha256"!==i&&"sha384"!==i&&"sha512"!==i)throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');switch(e.kty){case"EC":eT(e.crv,'"crv" (Curve) Parameter'),eT(e.x,'"x" (X Coordinate) Parameter'),eT(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":eT(e.crv,'"crv" (Subtype of Key Pair) Parameter'),eT(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":eT(e.e,'"e" (Exponent) Parameter'),eT(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":eT(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new s.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported')}let n=y.encoder.encode(JSON.stringify(r));return(0,t.encode)(await (0,eO.default)(i,n))}async function eN(e,t){null!=t||(t="sha256");let i=await eR(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${i}`}async function ej(e,t){let i={...e,...null==t?void 0:t.header};if(!(0,a.default)(i.jwk))throw new s.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let r=await q({...i.jwk,ext:!0},i.alg,!0);if(r instanceof Uint8Array||"public"!==r.type)throw new s.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');return r}function eD(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(eU)}function eU(e){return(0,a.default)(e)}e.s(["calculateJwkThumbprint",0,eR,"calculateJwkThumbprintUri",0,eN],308524),e.s(["EmbeddedJWK",0,ej],908574);class eM{constructor(e){if(this._cached=new WeakMap,!eD(e))throw new s.JWKSInvalid("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},n=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 s.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')}}(i),a=this._jwks.keys.filter(e=>{let t=n===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:o,length:l}=a;if(0===l)throw new s.JWKSNoMatchingKey;if(1!==l){let e=new s.JWKSMultipleMatchingKeys,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await eL(t,e,i)}catch(e){continue}},e}return eL(this._cached,o,i)}}async function eL(e,t,i){let r=e.get(t)||e.set(t,{}).get(t);if(void 0===r[i]){let e=await q({...t,ext:!0},i);if(e instanceof Uint8Array||"public"!==e.type)throw new s.JWKSInvalid("JSON Web Key Set members must be public keys");r[i]=e}return r[i]}e.s(["LocalJWKSet",0,eM,"createLocalJWKSet",0,function(e){let t=new eM(e);return async function(e,i){return t.getKey(e,i)}},"isJWKSLike",0,eD],832848);let eB=async(e,t,i)=>{let r,n,a=!1;"function"==typeof AbortController&&(r=new AbortController,n=setTimeout(()=>{a=!0,r.abort()},t));let o=await fetch(e.href,{signal:r?r.signal:void 0,redirect:"manual",headers:i.headers}).catch(e=>{if(a)throw new s.JWKSTimeout;throw e});if(void 0!==n&&clearTimeout(n),200!==o.status)throw new s.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch(e){throw new s.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON")}};class eW extends eM{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}
4,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 s.JWKSNoMatchingKey&&!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">typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=eB(this._url,this._timeoutDuration,this._options).then(e=>{if(!eD(e))throw new s.JWKSInvalid("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}}e.s(["createRemoteJWKSet",0,function(e,t){let i=new eW(e,t);return async function(e,t){return i.getKey(e,t)}}],900336),e.s(["UnsecuredJWT",0,class extends ek{encode(){let e=t.encode(JSON.stringify({alg:"none"})),i=t.encode(JSON.stringify(this._payload));return`${e}.${i}.`}static decode(e,i){let r;if("string"!=typeof e)throw new s.JWTInvalid("Unsecured JWT must be a string");let{0:n,1:a,2:o,length:l}=e.split(".");if(3!==l||""!==o)throw new s.JWTInvalid("Invalid Unsecured JWT");try{if(r=JSON.parse(y.decoder.decode(t.decode(n))),"none"!==r.alg)throw Error()}catch(e){throw new s.JWTInvalid("Invalid Unsecured JWT")}return{payload:eE(r,t.decode(a),i),header:r}}}],807420);var eq=e.i(840796);e.s(["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(y.decoder.decode((0,eq.decode)(t)));if(!(0,a.default)(e))throw Error();return e}catch(e){throw TypeError("Invalid Token or Protected Header formatting")}}],382111)},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 _=(e,t,i,r)=>t+i+r+(e/0x100000000|0)|0;i.add3H=_;let I=(e,t,i,r)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0);i.add4L=I;let S=(e,t,i,r,s)=>t+i+r+s+(e/0x100000000|0)|0;i.add4H=S;let A=(e,t,i,r,s)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0)+(s>>>0);i.add5L=A;let x=(e,t,i,r,s,n)=>t+i+r+s+n+(e/0x100000000|0)|0;i.add5H=x,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:_,add4L:I,add4H:S,add5H:x,add5L:A}},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 _=(e,t,i)=>(0,s.createXOFer)((r={})=>new v(t,e,void 0===r.dkLen?i:r.dkLen,!0));i.shake128=_(31,168,16),i.shake256=_(31,136,32)},321629,(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}}},132144,(e,t,i)=>{var r=e.i(467034);let s=e.r(321629);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
4"));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))}}},980423,(e,t,i)=>{var r=e.i(467034);let s=e.r(321629),n=e.r(132144),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];if(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)}}},927509,(e,t,i)=>{"use strict";var r=Object.prototype.hasOwnProperty,s="~";function n(){}function a(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function o(e,t,i,r,n){if("function"!=typeof i)throw TypeError("The listener must be a function");var o=new a(i,r||e,n),l=s?s+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function l(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function c(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(s=!1)),c.prototype.eventNames=function(){var e,t,i=[];if(0===this._eventsCount)return i;for(t in e=this._events)r.call(e,t)&&i.push(s?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},c.prototype.listeners=function(e){var t=s?s+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=Array(n);r<n;r++)a[r]=i[r].fn;return a},c.prototype.listenerCount=function(e){var t=s?s+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,r,n,a){var o=s?s+e:e;if(!this._events[o])return!1;var l,c,h=this._events[o],d=arguments.length;if(h.fn){switch(h.once&&this.removeListener(e,h.fn,void 0,!0),d){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,t),!0;case 3:return h.fn.call(h.context,t,i),!0;case 4:return h.fn.call(h.context,t,i,r),!0;case 5:return h.fn.call(h.context,t,i,r,n),!0;case 6:return h.fn.call(h.context,t,i,r,n,a),!0}for(c=1,l=Array(d-1);c<d;c++)l[c-1]=arguments[c];h.fn.apply(h.context,l)}else{var u,p=h.length;for(c=0;c<p;c++)switch(h[c].once&&this.removeListener(e,h[c].fn,void 0,!0),d){case 1:h[c].fn.call(h[c].context);break;case 2:h[c].fn.call(h[c].context,t);break;case 3:h[c].fn.call(h[c].context,t,i);break;case 4:h[c].fn.call(h[c].context,t,i,r);break;default:if(!l)for(u=1,l=Array(d-1);u<d;u++)l[u-1]=arguments[u];
4h[c].fn.apply(h[c].context,l)}}return!0},c.prototype.on=function(e,t,i){return o(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return o(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,r){var n=s?s+e:e;if(!this._events[n])return this;if(!t)return l(this,n),this;var a=this._events[n];if(a.fn)a.fn!==t||r&&!a.once||i&&a.context!==i||l(this,n);else{for(var o=0,c=[],h=a.length;o<h;o++)(a[o].fn!==t||r&&!a[o].once||i&&a[o].context!==i)&&c.push(a[o]);c.length?this._events[n]=1===c.length?c[0]:c:l(this,n)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=s?s+e:e,this._events[t]&&l(this,t)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=s,c.EventEmitter=c,t.exports=c},735071,(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||{},_=(t=e.browser.serialize,Array.isArray(t)?t.filter(function(e){return"!stdSerializers.err"!==e}):!0===t&&Object.keys(E)),I=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(I=!1);let S=Object.keys(e.customLevels||{}),A=["error","fatal","warn","info","debug","trace"].concat(S);"function"==typeof v&&A.forEach(function(e){v[e]=v}),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");let x=e.level||"info",P=Object.create(v);P.log||(P.log=m),o={},A.forEach(e=>{o[e]=v[e]?v[e]:s[e]||s[l[e]||"log"]||m}),P[a]=o,c({},P),Object.defineProperty(P,"levelVal",{get:function(){return n(this.level,this)}}),Object.defineProperty(P,"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,P,"error"),d(this,C,P,"fatal"),d(this,C,P,"warn"),d(this,C,P,"info"),d(this,C,P,"debug"),d(this,C,P,"trace"),S.forEach(e=>{d(this,C,P,e)})}});let C={transmit:y,serialize:_,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:A,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.serializers&&(r.serializers=i.serializers);let s=r.serializers;if(_&&s){var n=Object.assign({},E,s),a=!0===e.browser.serialize?Object.keys(n):_;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||{},P.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))},P.level=x,P.isLevelEnabled=function(e){return!!this.levels.values[e]&&this.levels.values[e]>=this.levels.values[this.level]},P.setMaxListeners=P.getMaxListeners=P.emit=P.addListener=P.on=P.prependListener=P.once=P.prependOnceListener=P.removeListener=P.removeAllListeners=P.listeners=P.listenerCount=P.eventNames=P.write=P.flush=m,P.serializers=E,P._serialize=_,P._stdErrSerialize=I,P.child=function(...e){return k.call(this,C,...e)},y&&(P._logEvent=p()),P}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?
4s: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},852532,(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||{},_=(t=e.browser.serialize,Array.isArray(t)?t.filter(function(e){return"!stdSerializers.err"!==e}):!0===t&&Object.keys(E)),I=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(I=!1);let S=Object.keys(e.customLevels||{}),A=["error","fatal","warn","info","debug","trace"].concat(S);"function"==typeof v&&A.forEach(function(e){v[e]=v}),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");let x=e.level||"info",P=Object.create(v);P.log||(P.log=m),o={}
4,A.forEach(e=>{o[e]=v[e]?v[e]:s[e]||s[l[e]||"log"]||m}),P[a]=o,c({},P),Object.defineProperty(P,"levelVal",{get:function(){return n(this.level,this)}}),Object.defineProperty(P,"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,P,"error"),d(this,C,P,"fatal"),d(this,C,P,"warn"),d(this,C,P,"info"),d(this,C,P,"debug"),d(this,C,P,"trace"),S.forEach(e=>{d(this,C,P,e)})}});let C={transmit:y,serialize:_,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:A,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.serializers&&(r.serializers=i.serializers);let s=r.serializers;if(_&&s){var n=Object.assign({},E,s),a=!0===e.browser.serialize?Object.keys(n):_;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||{},P.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))},P.level=x,P.isLevelEnabled=function(e){return!!this.levels.values[e]&&this.levels.values[e]>=this.levels.values[this.level]},P.setMaxListeners=P.getMaxListeners=P.emit=P.addListener=P.on=P.prependListener=P.once=P.prependOnceListener=P.removeListener=P.removeAllListeners=P.listeners=P.listenerCount=P.eventNames=P.write=P.flush=m,P.serializers=E,P._serialize=_,P._stdErrSerialize=I,P.child=function(...e){return k.call(this,C,...e)},y&&(P._logEvent=p()),P}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},563703,891507,764192,376664,e=>{"use strict";let t,i,r,s,n,a,o,l,c;e.i(964092);var h,d,u,p,f=e.i(529523),g=e.i(672708),y=e.i(994565),m=e.i(943150),w=e.i(634358),b=e.i(744423),v=e.i(722193),E=e.i(303065),_=e.i(157854),I=e.i(83844),S=e.i(84951),A=e.i(488199),x=e.i(201444),P=e.i(830841),C=e.i(603672),k=e.i(370652),O=e.i(308524),T=e.i(908574),R=e.i(832848),N=e.i(900336),j=e.i(807420),D=e.i(680293),U=e.i(855036),M=e.i(382111),L=e.i(576951),B=e.i(33867),W=e.i(654544),q=e.i(692560);async function K(e,t){var i;let r,s,n;
4switch(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 r=parseInt(e.slice(-3),10),(0,q.default)(new Uint8Array(r>>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 B.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return W.default.subtle.generateKey(s,null!=(i=null==t?void 0:t.extractable)&&i,n)}function H(e){var t;let i=null!=(t=null==e?void 0:e.modulusLength)?t:2048;if("number"!=typeof i||i<2048)throw new B.JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return i}async function z(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:H(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:H(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:H(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";
4switch(o){case"Ed25519":case"Ed448":n={name:o};break;default:throw new B.JOSENotSupported("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 B.JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new B.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return W.default.subtle.generateKey(n,null!=(s=null==t?void 0:t.extractable)&&s,a)}async function $(e,t){return z(e,t)}async function J(e,t){return K(e,t)}var F=e.i(840796);e.s(["CompactEncrypt",()=>I.CompactEncrypt,"CompactSign",()=>A.CompactSign,"EmbeddedJWK",()=>T.EmbeddedJWK,"EncryptJWT",()=>k.EncryptJWT,"FlattenedEncrypt",()=>S.FlattenedEncrypt,"FlattenedSign",()=>x.FlattenedSign,"GeneralEncrypt",()=>m.GeneralEncrypt,"GeneralSign",()=>P.GeneralSign,"SignJWT",()=>C.SignJWT,"UnsecuredJWT",()=>j.UnsecuredJWT,"base64url",0,F,"calculateJwkThumbprint",()=>O.calculateJwkThumbprint,"calculateJwkThumbprintUri",()=>O.calculateJwkThumbprintUri,"compactDecrypt",()=>f.compactDecrypt,"compactVerify",()=>w.compactVerify,"createLocalJWKSet",()=>R.createLocalJWKSet,"createRemoteJWKSet",()=>N.createRemoteJWKSet,"cryptoRuntime",0,"WebCryptoAPI","decodeJwt",()=>L.decodeJwt,"decodeProtectedHeader",()=>M.decodeProtectedHeader,"errors",0,B,"exportJWK",()=>D.exportJWK,"exportPKCS8",()=>D.exportPKCS8,"exportSPKI",()=>D.exportSPKI,"flattenedDecrypt",()=>g.flattenedDecrypt,"flattenedVerify",()=>b.flattenedVerify,"generalDecrypt",()=>y.generalDecrypt,"generalVerify",()=>v.generalVerify,"generateKeyPair",0,$,"generateSecret",0,J,"importJWK",()=>U.importJWK,"importPKCS8",()=>U.importPKCS8,"importSPKI",()=>U.importSPKI,"importX509",()=>U.importX509,"jwtDecrypt",()=>_.jwtDecrypt,"jwtVerify",()=>E.jwtVerify],563703);class V{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 V("CBWSDK").clear(),new V("walletlink").clear()}}var G=e.i(467034);let Y=-32602,Z=-32603,Q=4001,X=4100,ee=4200,et=4900,ei={"-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."}},er="Unspecified error message.";function es(e,t=er){if(e&&Number.isInteger(e)){var i;let t=e.toString();if(ea(ei,t))return ei[t].message;if((i=e)>=-32099&&i<=-32e3)return"Unspecified server error."}return t}function en(e){return e&&"object"==typeof e&&!Array.isArray(e)?Object.assign({},e):e}function ea(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function eo(e,t){return"object"==typeof e&&null!==e&&t in e&&"string"==typeof e[t]}let el=e=>eg(Y,e),ec=e=>eg(Z,e),eh=e=>ey(Q,e),ed=e=>ey(X,e),eu=e=>ey(ee,e),ep=e=>ey(et,e),ef=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 eb(t,i,r)};function eg(e,t){let[i,r]=em(t);return new ew(e,i||es(e),r)}function ey(e,t){let[i,r]=em(t);return new eb(e,i||es(e),r)}function em(e){if(e){if("string"==typeof e)return[e];else if("object"==typeof e&&!Array.isArray(e)){let{message:t,data:i}=e;
vendor: 9,664 bytes, line 4
4if(t&&"string"!=typeof t)throw Error("Must specify string message.");return[t||void 0,i]}}return[]}class ew 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 eb extends ew{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 ev(e){return Math.floor(e)}let eE=/^[0-9]*$/,e_=/^[a-f0-9]*$/;function eI(e){return eS(crypto.getRandomValues(new Uint8Array(e)))}function eS(e){return[...e].map(e=>e.toString(16).padStart(2,"0")).join("")}function eA(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>Number.parseInt(e,16)))}function ex(e,t=!1){let i=e.toString("hex");return t?`0x${i}`:i}function eP(e){return ex(eU(e),!0)}function eC(e){return e.toString(10)}function ek(e){return`0x${BigInt(e).toString(16)}`}function eO(e){return e.startsWith("0x")||e.startsWith("0X")}function eT(e){return eO(e)?e.slice(2):e}function eR(e){return eO(e)?`0x${e.slice(2)}`:`0x${e}`}function eN(e){if("string"!=typeof e)return!1;let t=eT(e).toLowerCase();return e_.test(t)}function ej(e,t=!1){let i=function(e,t=!1){if("string"==typeof e){let i=eT(e).toLowerCase();if(e_.test(i))return t?`0x${i}`:i}throw el(`"${String(e)}" is not a hexadecimal string`)}(e,!1);return i.length%2==1&&(i=`0${i}`),t?`0x${i}`:i}function eD(e){if("string"==typeof e){let t=eT(e).toLowerCase();if(eN(t)&&40===t.length)return eR(t)}throw el(`Invalid Ethereum address: ${String(e)}`)}function eU(e){if(G.Buffer.isBuffer(e))return e;if("string"==typeof e){if(eN(e)){let t=ej(e,!1);return G.Buffer.from(t,"hex")}return G.Buffer.from(e,"utf8")}throw el(`Not binary data: ${String(e)}`)}function eM(e){if("number"==typeof e&&Number.isInteger(e))return ev(e);if("string"==typeof e){if(eE.test(e))return ev(Number(e));if(eN(e))return ev(Number(BigInt(ej(e,!0))))}throw el(`Not an integer: ${String(e)}`)}function eL(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(eM(e));if("string"==typeof e){if(eE.test(e))return BigInt(e);if(eN(e))return BigInt(ej(e,!0))}throw el(`Not an integer: ${String(e)}`)}async function eB(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"])}async function eW(e,t){return crypto.subtle.deriveKey({name:"ECDH",public:t},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function eq(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 eK(e,{iv:t,cipherText:i}){let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:t},e,i);return new TextDecoder().decode(r)}function eH(e){switch(e){case"public":return"spki";case"private":return"pkcs8"}}async function ez(e,t){let i=eH(e);return eS(new Uint8Array(await crypto.subtle.exportKey(i,t)))}async function e$(e,t){let i=eH(e),r=eA(t).buffer;return await crypto.subtle.importKey(i,new Uint8Array(r),{name:"ECDH",namedCurve:"P-256"},!0,"private"===e?["deriveKey"]:[])}async function eJ(e,t){return eq(t,JSON.stringify(e,(e,t)=>t instanceof Error?Object.assign(Object.assign({},t.code?{code:t.code}:{}),{message:t.message}):t))}async function eF(e,t){return JSON.parse(await eK(t,e))}let eV={storageKey:"ownPrivateKey",keyType:"private"},eG={storageKey:"ownPublicKey",keyType:"public"},eY={storageKey:"peerPublicKey",keyType:"public"};class eZ{constructor(){this.storage=new V("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(eY,e),await this.loadKeysIfNeeded()}async clear(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null,this.storage.removeItem(eG.storageKey),this.storage.removeItem(eV.storageKey),this.storage.removeItem(eY.storageKey)}async generateKeyPair(){let e=await eB();this.ownPrivateKey=e.privateKey,this.ownPublicKey=e.publicKey,await this.storeKey(eV,e.privateKey),await this.storeKey(eG,e.publicKey)}async loadKeysIfNeeded(){null===this.ownPrivateKey&&(this.ownPrivateKey=await this.loadKey(eV)),null===this.ownPublicKey&&(this.ownPublicKey=await this.loadKey(eG)),(null===this.ownPrivateKey||null===this.ownPublicKey)&&await this.generateKeyPair(),null===this.peerPublicKey&&(this.peerPublicKey=await this.loadKey(eY)),null===this.sharedSecret&&null!==this.ownPrivateKey&&null!==this.peerPublicKey&&(this.sharedSecret=await eW(this.ownPrivateKey,this.peerPublicKey))}async loadKey(e){let t=this.storage.getItem(e.storageKey);return t?e$(e.keyType,t):null}async storeKey(e,t){let i=await ez(e.keyType,t);this.storage.setItem(e.storageKey,i)}}let eQ="4.3.2",eX="@coinbase/wallet-sdk";async function e0(e,t){let i=Object.assign(Object.assign({},e),{jsonrpc:"2.0",id:crypto.randomUUID()}),r=await window.fetch(t,{method:"POST",body:JSON.stringify(i),mode:"cors",headers:{"Content-Type":"application/json","X-Cbw-Sdk-Version":eQ,"X-Cbw-Sdk-Platform":eX}}),{result:s,error:n}=await r.json();if(n)throw n;return s}let e1="accounts",e2="activeChain",e3="availableChains",e5="walletCapabilities";class e8{constructor(e){var t,i,r;this.metadata=e.metadata,this.communicator=e.communicator,this.callback=e.callback,this.keyManager=new eZ,this.storage=new V("CBWSDK","SCWStateManager"),this.accounts=null!=(t=this.storage.loadObject(e1))?t:[],this.chain=this.storage.loadObject(e2)||{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 e$("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(e1,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 ed();switch(e.method){case"eth_requestAccounts":return null==(t=this.callback)||t.call(this,"connect",{chainId:ek(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 ek(this.chain.id);case"wallet_getCapabilities":return this.storage.loadObject(e5);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 ec("No RPC URL set for chain");return e0(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 el();let r=eM(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 ed("No valid session found, try requestAccounts before other methods");let i=await eJ({action:e,chainId:this.chain.id},t),r=await this.createRequestMessage({encrypted:i});return this.communicator.postRequestAndWaitForResponse(r)}async createRequestMessage(e){let t=await ez("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 ed("Invalid session");let n=await eF(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(e3,e),this.updateChain(this.chain.id,e)}let o=null==(i=n.data)?void 0:i.capabilities;return o&&this.storage.storeObject(e5,o),n}updateChain(e,t){var i;let r=null!=t?t:this.storage.loadObject(e3),s=null==r?void 0:r.find(t=>
4t.id===e);return!!s&&(s!==this.chain&&(this.chain=s,this.storage.storeObject(e2,s),null==(i=this.callback)||i.call(this,"chainChanged",ek(s.id))),!0)}}var e4=e.i(980423);let e6="Addresses";function e7(e){return void 0!==e.errorMessage}class e9{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",eA(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 eS(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",eA(t),{name:"aes-gcm"},!1,["encrypt","decrypt"]),n=eA(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 te{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}`)}}(tp=tf||(tf={}))[tp.DISCONNECTED=0]="DISCONNECTED",tp[tp.CONNECTING=1]="CONNECTING",tp[tp.CONNECTED=2]="CONNECTED";class tt{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,tf.CONNECTING),r.onclose=e=>{var i;this.clearWebSocket(),t(Error(`websocket error ${e.code}: ${e.reason}`)),null==(i=this.connectionStateListener)||i.call(this,tf.DISCONNECTED)},r.onopen=t=>{var i;e(),null==(i=this.connectionStateListener)||i.call(this,tf.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,tf.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 ti{constructor({session:e,linkAPIUrl:t,listener:i}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=ev(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=>
4e.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 e9(e.secret),this.listener=i;const r=new tt(`${t}/rpc`,WebSocket);r.setConnectionStateListener(async e=>{let t=!1;switch(e){case tf.DISCONNECTED:if(!this.destroyed){let e=async()=>{await new Promise(e=>setTimeout(e,5e3)),this.destroyed||r.connect().catch(()=>{e()})};e()}break;case tf.CONNECTED:t=await this.handleConnected(),this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},1e4),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();case tf.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 te(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:ev(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:ev(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)})})])}
4async handleConnected(){return"Fail"!==(await this.makeRequest({type:"HostSession",id:ev(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key})).type&&(this.sendData({type:"IsLinked",id:ev(this.nextReqId++),sessionId:this.session.id}),this.sendData({type:"GetSessionConfig",id:ev(this.nextReqId++),sessionId:this.session.id}),!0)}}class tr{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%0x7fffffff;let e=this._nextRequestId,t=eR(e.toString(16));return this.callbacks.get(t)&&this.callbacks.delete(t),e}}var ts=e.i(280355),tn=e.i(470525);let ta="session:id",to="session:secret",tl="session:linked";class tc{constructor(e,t,i,r=!1){this.storage=e,this.id=t,this.secret=i,this.key=(0,tn.bytesToHex)((0,ts.sha256)(`${t}, ${i} WalletLink`)),this._linked=!!r}static create(e){return new tc(e,eI(16),eI(32)).save()}static load(e){let t=e.getItem(ta),i=e.getItem(tl),r=e.getItem(to);return t&&r?new tc(e,t,r,"1"===i):null}get linked(){return this._linked}set linked(e){this._linked=e,this.persistLinked()}save(){return this.storage.setItem(ta,this.id),this.storage.setItem(to,this.secret),this.persistLinked(),this}persistLinked(){this.storage.setItem(tl,this._linked?"1":"0")}}function th(){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 td(){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)}function tu(){for(var e,t,i=0,r="";i<arguments.length;)(e=arguments[i++])&&(t=function e(t){var i,r,s="";if("string"==typeof t||"number"==typeof t)s+=t;else if("object"==typeof t)if(Array.isArray(t))for(i=0;i<t.length;i++)t[i]&&(r=e(t[i]))&&(s&&(s+=" "),s+=r);else for(i in t)t[i]&&(s&&(s+=" "),s+=i);return s}(e))&&(r&&(r+=" "),r+=t);return r}var tp,tf,tg,ty,tm,tw,tb,tv,tE,t_,tI,tS,tA,tx,tP,tC,tk={},tO=[],tT=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,tR=Array.isArray;function tN(e,t){for(var i in t)e[i]=t[i];return e}function tj(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function tD(e,t,i){var r,s,n,a={};for(n in t)"key"==n?r=t[n]:"ref"==n?s=t[n]:a[n]=t[n];if(arguments.length>2&&(a.children=arguments.length>3?tg.call(arguments,2):i),"function"==typeof e&&null!=e.defaultProps)for(n in e.defaultProps)void 0===a[n]&&(a[n]=e.defaultProps[n]);return tU(e,a,r,s,null)}function tU(e,t,i,r,s){var n={type:e,props:t,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==s?++tm:s,__i:-1,__u:0};return null==s&&null!=ty.vnode&&ty.vnode(n),n}function tM(e){return e.children}function tL(e,t){this.props=e,this.context=t}function tB(e,t){if(null==t)return e.__?tB(e.__,e.__i+1):null;for(var i;t<e.__k.length;t++)if(null!=(i=e.__k[t])&&null!=i.__e)return i.__e;return"function"==typeof e.type?tB(e):null}function tW(e){(!e.__d&&(e.__d=!0)&&tw.push(e)&&!tq.__r++||tb!=ty.debounceRendering)&&((tb=ty.debounceRendering)||tv)(tq)}function tq(){try{for(var e,t=1;tw.length;)tw.length>t&&tw.sort(tE),e=tw.shift(),t=tw.length,function(e){if(e.__P&&e.__d){var t=e.__v,i=t.__e,r=[],s=[],n=tN({},t);n.__v=t.__v+1,ty.vnode&&ty.vnode(n),tJ(e.__P,n,t,e.__n,e.__P.namespaceURI,32&t.__u?[i]:null,r,null==i?tB(t):i,!!(32&t.__u),s),n.__v=t.__v,n.__.__k[n.__i]=n,tF(r,n,s),t.__e=t.__=null,n.__e!=i&&function e(t){if(null!=(t=t.__)&&null!=t.__c)return t.__e=t.__c.base=null,t.__k.some(function(e){if(null!=e&&null!=e.__e)return t.__e=t.__c.base=e.__e}),e(t)}(n)}}(e)}finally{tw.length=tq.__r=0}}function tK(e,t,i,r,s,n,a,o,l,c,h){var d,u,p,f,g,y,m=r&&r.__k||tO,w=t.length;for(l=function(e,t,i,r,s){var n,a,o,l,c,h=i.length,d=h,u=0;for(e.__k=Array(s),n=0;n<s;n++)null!=(a=t[n])&&"boolean"!=typeof a&&"function"!=typeof a?("string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?a=e.__k[n]=tU(null,a,null,null,null):tR(a)?a=e.__k[n]=tU(tM,{children:a},null,null,null):void 0===a.constructor&&a.__b>0?a=e.__k[n]=tU(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[n]=a,l=n+u,a.__=e,a.__b=e.__b+1,o=null,-1!=(c=a.__i=function(e,t,i,r){var s,n,a,o=e.key,l=e.type,c=t[i],h=null!=c&&0==(2&c.__u);if(null===c&&null==o||h&&o==c.key&&l==c.type)return i;if(r>+!!h){for(s=i-1,n=i+1;s>=0||n<t.length;)if(null!=(c=t[a=s>=0?s--:n++])&&0==(2&c.__u)&&o==c.key&&l==c.type)return a}return -1}(a,i,l,d))&&(d--,(o=i[c])&&(o.__u|=2)),null==o||null==o.__v?(-1==c&&(s>h?u--:s<h&&u++),"function"!=typeof a.type&&(a.__u|=4)):c!=l&&(c==l-1?u--:c==l+1?u++:(c>l?u--:u++,a.__u|=4))):e.__k[n]=null;if(d)for(n=0;n<h;n++)null!=(o=i[n])&&0==(2&o.__u)&&(o.__e==r&&(r=tB(o)),function e(t,i,r){var s,n;if(ty.unmount&&ty.unmount(t),(s=t.ref)&&(s.current&&s.current!=t.__e||tV(s,null,i)),null!=(s=t.__c)){if(s.componentWillUnmount)try{s.componentWillUnmount()}catch(e){ty.__e(e,i)}s.base=s.__P=s.__n=null}if(s=t.__k)for(n=0;n<s.length;n++)s[n]&&e(s[n],i,r||"function"!=typeof t.type);r||tj(t.__e),t.__c=t.__=t.__e=void 0}(o,o));return r}(i,t,m,l,w),d=0;d<w;d++)null!=(p=i.__k[d])&&(u=-1!=p.__i&&m[p.__i]||tk,p.__i=d,y=tJ(e,p,u,s,n,a,o,l,c,h),f=p.__e,p.ref&&u.ref!=p.ref&&(u.ref&&tV(u.ref,null,p),h.push(p.ref,p.__c||f,p)),null==g&&null!=f&&(g=f),4&p.__u?(l=function e(t,i,r){var s,n;if("function"==typeof t.type){for(s=t.__k,n=0;s&&n<s.length;n++)s[n]&&(s[n].__=t,i=e(s[n],i,r));return i}t.__e!=i&&(i&&t.type&&!i.parentNode&&(i=tB(t)),i=r.insertBefore(t.__e,i||null));do i=i&&i.nextSibling;while(null!=i&&8==i.nodeType)return i}
vendor: 4,744 bytes, line 4
4(p,l,e),u.__e&&(u.__e=null)):"function"==typeof p.type&&void 0!==y?l=y:f&&(l=f.nextSibling),p.__u&=-7);return i.__e=g,l}function tH(e,t,i){"-"==t[0]?e.setProperty(t,null==i?"":i):e[t]=null==i?"":"number"!=typeof i||tT.test(t)?i:i+"px"}function tz(e,t,i,r,s){var n,a;e:if("style"==t)if("string"==typeof i)e.style.cssText=i;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)i&&t in i||tH(e.style,t,"");if(i)for(t in i)r&&i[t]==r[t]||tH(e.style,t,i[t])}else if("o"==t[0]&&"n"==t[1])n=t!=(t=t.replace(tA,"$1")),t=(a=t.toLowerCase())in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+n]=i,i?r?i[tS]=r[tS]:(i[tS]=tx,e.addEventListener(t,n?tC:tP,n)):e.removeEventListener(t,n?tC:tP,n);else{if("http://www.w3.org/2000/svg"==s)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==i?"":i;break e}catch(e){}"function"==typeof i||(null==i||!1===i&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==i?"":i))}}function t$(e){return function(t){if(this.l){var i=this.l[t.type+e];if(null==t[tI])t[tI]=tx++;else if(t[tI]<i[tS])return;return i(ty.event?ty.event(t):t)}}}function tJ(e,t,i,r,s,n,a,o,l,c){var h,d,u,p,f,g,y,m,w,b,v,E,_,I,S,A,x=t.type;if(void 0!==t.constructor)return null;128&i.__u&&(l=!!(32&i.__u),n=[o=t.__e=i.__e]),(h=ty.__b)&&h(t);e:if("function"==typeof x){d=a.length;try{if(w=t.props,b=x.prototype&&x.prototype.render,v=(h=x.contextType)&&r[h.__c],E=h?v?v.props.value:h.__:r,i.__c?m=(u=t.__c=i.__c).__=u.__E:(b?t.__c=u=new x(w,E):(t.__c=u=new tL(w,E),u.constructor=x,u.render=tG),v&&v.sub(u),u.state||(u.state={}),u.__n=r,p=u.__d=!0,u.__h=[],u._sb=[]),b&&null==u.__s&&(u.__s=u.state),b&&null!=x.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=tN({},u.__s)),tN(u.__s,x.getDerivedStateFromProps(w,u.__s))),f=u.props,g=u.state,u.__v=t,p)b&&null==x.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),b&&null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(b&&null==x.getDerivedStateFromProps&&w!==f&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(w,E),t.__v==i.__v||!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(w,u.__s,E)){t.__v!=i.__v&&(u.props=w,u.state=u.__s,u.__d=!1),t.__e=i.__e,t.__k=i.__k,t.__k.some(function(e){e&&(e.__=t)}),tO.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&a.push(u),o=tB(i);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(w,u.__s,E),b&&null!=u.componentDidUpdate&&u.__h.push(function(){u.componentDidUpdate(f,g,y)})}if(u.context=E,u.props=w,u.__P=e,u.__e=!1,_=ty.__r,I=0,b)u.state=u.__s,u.__d=!1,_&&_(t),h=u.render(u.props,u.state,u.context),tO.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,_&&_(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++I<25)u.state=u.__s,null!=u.getChildContext&&(r=tN(tN({},r),u.getChildContext())),b&&!p&&null!=u.getSnapshotBeforeUpdate&&(y=u.getSnapshotBeforeUpdate(f,g)),S=null!=h&&h.type===tM&&null==h.key?function e(t){return"object"!=typeof t||null==t||t.__b>0?t:tR(t)?t.map(e):void 0!==t.constructor?null:tN({},t)}(h.props.children):h,o=tK(e,tR(S)?S:[S],t,i,r,s,n,a,o,l,c),u.base=t.__e,t.__u&=-161,u.__h.length&&a.push(u),m&&(u.__E=u.__=null)}catch(e){if(a.length=d,t.__v=null,l||null!=n){if(e.then){for(t.__u|=l?160:128;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;null!=n&&(n[n.indexOf(o)]=null),t.__e=o}else if(null!=n)for(A=n.length;A--;)tj(n[A])}else t.__e=i.__e;null==t.__k&&(t.__k=i.__k||[]),e.then||function e(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(e))}(t),ty.__e(e,t,i)}}else null==n&&t.__v==i.__v?(t.__k=i.__k,t.__e=i.__e):o=t.__e=function(e,t,i,r,s,n,a,o,l){var c,h,d,u,p,f,g,y=i.props||tk,m=t.props,w=t.type;if("svg"==w?s="http://www.w3.org/2000/svg":"math"==w?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),null!=n){for(c=0;c<n.length;c++)if((p=n[c])&&"setAttribute"in p==!!w&&(w?p.localName==w:3==p.nodeType)){e=p,n[c]=null;break}}if(null==e){if(null==w)return document.createTextNode(m);e=document.createElementNS(s,w,m.is&&m),o&&(ty.__m&&ty.__m(t,n),o=!1),n=null}if(null==w)y===m||o&&e.data==m||(e.data=m);else{if(n="textarea"==w&&null!=m.defaultValue?null:n&&tg.call(e.childNodes),!o&&null!=n)for(y={},c=0;c<e.attributes.length;c++)y[(p=e.attributes[c]).name]=p.value;for(c in y)p=y[c],"dangerouslySetInnerHTML"==c?d=p:"children"==c||c in m||"value"==c&&"defaultValue"in m||"checked"==c&&"defaultChecked"in m||tz(e,c,null,p,s);for(c in m)p=m[c],"children"==c?u=p:"dangerouslySetInnerHTML"==c?h=p:"value"==c?f=p:"checked"==c?g=p:o&&"function"!=typeof p||y[c]===p||tz(e,c,p,y[c],s);
vendor: 2,012 bytes, line 4
4if(h)o||d&&(h.__html==d.__html||h.__html==e.innerHTML)||(e.innerHTML=h.__html),t.__k=[];else if(d&&(e.innerHTML=""),tK("template"==t.type?e.content:e,tR(u)?u:[u],t,i,r,"foreignObject"==w?"http://www.w3.org/1999/xhtml":s,n,a,n?n[0]:i.__k&&tB(i,0),o,l),null!=n)for(c=n.length;c--;)tj(n[c]);o&&"textarea"!=w||(c="value","progress"==w&&null==f?e.removeAttribute("value"):null==f||f===e[c]&&("progress"!=w||f)&&("option"!=w||f==y[c])||tz(e,c,f,y[c],s),c="checked",null!=g&&g!=e[c]&&tz(e,c,g,y[c],s))}return e}(i.__e,t,i,r,s,n,a,l,c);return(h=ty.diffed)&&h(t),128&t.__u?void 0:o}function tF(e,t,i){for(var r=0;r<i.length;r++)tV(i[r],i[++r],i[++r]);ty.__c&&ty.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){ty.__e(e,t.__v)}})}function tV(e,t,i){try{if("function"==typeof e){var r="function"==typeof e.__u;r&&e.__u(),r&&null==t||(e.__u=e(t))}else e.current=t}catch(e){ty.__e(e,i)}}function tG(e,t,i){return this.constructor(e,i)}function tY(e,t,i){var r,s,n,a;t==document&&(t=document.documentElement),ty.__&&ty.__(e,t),s=(r="function"==typeof i)?null:i&&i.__k||t.__k,n=[],a=[],tJ(t,e=(!r&&i||t).__k=tD(tM,null,[e]),s||tk,tk,t.namespaceURI,!r&&i?[i]:s?null:t.firstChild?tg.call(t.childNodes):null,n,!r&&i?i:s?s.__e:t.firstChild,r,a),tF(n,e,a),e.props.children=null}tg=tO.slice,ty={__e:function(e,t,i,r){for(var s,n,a;t=t.__;)if((s=t.__c)&&!s.__)try{if((n=s.constructor)&&null!=n.getDerivedStateFromError&&(s.setState(n.getDerivedStateFromError(e)),a=s.__d),null!=s.componentDidCatch&&(s.componentDidCatch(e,r||{}),a=s.__d),a)return s.__E=s}catch(t){e=t}throw e}},tm=0,tL.prototype.setState=function(e,t){var i;i=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=tN({},this.state),"function"==typeof e&&(e=e(tN({},i),this.props)),e&&tN(i,e),null!=e&&this.__v&&(t&&this._sb.push(t),tW(this))},tL.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),tW(this))},tL.prototype.render=tM,tw=[],tv="function"==typeof Promise?Promise.prototype.then.bind(Prom
4ise.resolve()):setTimeout,tE=function(e,t){return e.__v.__b-t.__v.__b},tq.__r=0,tI="__d"+(t_=Math.random().toString(8)),tS="__a"+t_,tA=/(PointerCapture)$|Capture$/i,tx=0,tP=t$(!1),tC=t$(!0);var tZ,tQ,tX,t0,t1=0,t2=[],t3=ty,t5=t3.__b,t8=t3.__r,t4=t3.diffed,t6=t3.__c,t7=t3.unmount,t9=t3.__;function ie(e,t){t3.__h&&t3.__h(tQ,e,t1||t),t1=0;var i=tQ.__H||(tQ.__H={__:[],__h:[]});return e>=i.__.length&&i.__.push({}),i.__[e]}function it(e,t,i){var r=ie(tZ++,2);if(r.t=e,!r.__c&&(r.__=[i?i(t):io(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],i=r.t(t,e);t!==i&&(r.__N=[i,r.__[1]],r.__c.setState({}))}],r.__c=tQ,!tQ.__f)){var s=function(e,t,i){if(!r.__c.__H)return!0;var s=!1,a=r.__c.props!==e;if(r.__c.__H.__.some(function(e){if(e.__N){s=!0;var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(a=!0)}}),n){var o=n.call(this,e,t,i);return s?o||a:o}return!s||a};tQ.__f=!0;var n=tQ.shouldComponentUpdate,a=tQ.componentWillUpdate;tQ.componentWillUpdate=function(e,t,i){if(this.__e){var r=n;n=void 0,s(e,t,i),n=r}a&&a.call(this,e,t,i)},tQ.shouldComponentUpdate=s}return r.__N||r.__}function ii(){for(var e;e=t2.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(is),t.__h.some(ia),t.__h=[]}catch(i){t.__h=[],t3.__e(i,e.__v)}}}t3.__b=function(e){tQ=null,t5&&t5(e)},t3.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),t9&&t9(e,t)},t3.__r=function(e){t8&&t8(e),tZ=0;var t=(tQ=e.__c).__H;t&&(tX===tQ?(t.__h=[],tQ.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.some(is),t.__h.some(ia),t.__h=[],tZ=0)),tX=tQ},t3.diffed=function(e){t4&&t4(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==t2.push(t)&&t0===t3.requestAnimationFrame||((t0=t3.requestAnimationFrame)||function(e){var t,i=function(){clearTimeout(r),ir&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(i,35);ir&&(t=requestAnimationFrame(i))})(ii)),t.__H.__.some(function(e){e.u&&(e.__H=e.u,e.u=void 0)})),tX=tQ=null},t3.__c=function(e,t){t.some(function(e){try{e.__h.some(is),e.__h=e.__h.filter(function(e){return!e.__||ia(e)})}catch(i){t.some(function(e){e.__h&&(e.__h=[])}),t=[],t3.__e(i,e.__v)}}),t6&&t6(e,t)},t3.unmount=function(e){t7&&t7(e);var t,i=e.__c;i&&i.__H&&(i.__H.__.some(function(e){try{is(e)}catch(e){t=e}}),i.__H=void 0,t&&t3.__e(t,i.__v))};var ir="function"==typeof requestAnimationFrame;function is(e){var t=tQ,i=e.__c;"function"==typeof i&&(e.__c=void 0,i()),tQ=t}function ia(e){var t=tQ;e.__c=e.__(),tQ=t}function io(e,t){return"function"==typeof t?t(e):t}class il{constructor(){this.items=new Map,this.nextItemKey=0,this.root=null,this.darkMode=th()}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&&tY(tD("div",null,tD(ic,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([e,t])=>tD(ih,Object.assign({},t,{key:e}))))),this.root)}}let ic=e=>tD("div",{class:tu("-cbwsdk-snackbar-container")},tD("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;
4cursor: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}"),tD("div",{class:"-cbwsdk-snackbar"},e.children)),ih=({autoExpand:e,message:t,menuItems:i})=>{var r,s,n,a;let[o,l]=(t1=1,it(io,!0)),[c,h]=(t1=1,it(io,null!=e&&e));return r=()=>{let e=[window.setTimeout(()=>{l(!1)},1),window.setTimeout(()=>{h(!0)},1e4)];return()=>{e.forEach(window.clearTimeout)}},s=ie(tZ++,3),!t3.__s&&(n=s.__H,a=void 0,!n||n.length!==a.length||a.some(function(e,t){return e!==n[t]}))&&(s.__=r,s.u=void 0,tQ.__H.__h.push(s)),tD("div",{class:tu("-cbwsdk-snackbar-instance",o&&"-cbwsdk-snackbar-instance-hidden",c&&"-cbwsdk-snackbar-instance-expanded")},tD("div",{class:"-cbwsdk-snackbar-instance-header",onClick:()=>{h(!c)}},tD("img",{src:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+",class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",tD("div",{class:"-cbwsdk-snackbar-instance-header-message"},t),tD("div",{class:"-gear-container"},!c&&tD("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},tD("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),tD("img",{src:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwu
4NTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=",class:"-gear-icon",title:"Expand"}))),i&&i.length>0&&tD("div",{class:"-cbwsdk-snackbar-instance-menu"},i.map((e,t)=>tD("div",{class:tu("-cbwsdk-snackbar-instance-menu-item",e.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:e.onClick,key:t},tD("svg",{width:e.svgWidth,height:e.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},tD("path",{"fill-rule":e.defaultFillRule,"clip-rule":e.defaultClipRule,d:e.path,fill:"#AAAAAA"})),tD("span",{class:tu("-cbwsdk-snackbar-instance-menu-item-info",e.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},e.info)))))},id="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 iu{constructor(){this.attached=!1,this.snackbar=new il}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,td()}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:id,defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]},this.snackbar.presentItem(t)}}class ip{constructor(){this.root=null,this.darkMode=th()}attach(){let e=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",e.appendChild(this.root),td()}present(e){this.render(e)}clear(){this.render(null)}render(e){!this.root||(tY(null,this.root),e&&tY(tD(ig,Object.assign({},e,{onDismiss:()=>{this.clear()},darkMode:this.darkMode})),this.root))}}let ig=({title:e,buttonText:t,darkMode:i,onButtonClick:r,onDismiss:s})=>tD(ic,{darkMode:i},tD("div",{class:"-cbwsdk-redirect-dialog"},tD("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}
4.-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}"),tD("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:s}),tD("div",{class:tu("-cbwsdk-redirect-dialog-box",i?"dark":"light")},tD("p",null,e),tD("button",{onClick:r},t)))),iy="https://www.walletlink.org";class im{constructor(){this.attached=!1,this.redirectDialog=new ip}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 iw{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(e6);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]),iw.accountRequestCallbackIds.size>0&&(Array.from(iw.accountRequestCallbackIds.values()).forEach(t=>{this.invokeCallback(t,{method:"requestEthereumAccounts",result:[e]})}),iw.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 tr,this.ui=i,this.ui.attach()}subscribe(){let e=tc.load(this.storage)||tc.create(this.storage),{linkAPIUrl:t}=this,i=new ti({session:e,linkAPIUrl:t,listener:this}),r=this.isMobileWeb?new im:new iu;return i.connect(),{session:e,ui:r,connection:i}}resetAndReload(){this.connection.destroy().then(()=>{let e=tc.load(this.storage);(null==e?void 0:e.id)===this._session.id&&V.clearAll(),document.location.reload()}).catch(e=>{})}signEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:eC(e.weiValue),data:ex(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?eC(e.gasPriceInWei):null,maxFeePerGas:e.gasPriceInWei?eC(e.gasPriceInWei):null,maxPriorityFeePerGas:e.gasPriceInWei?eC(e.gasPriceInWei):null,gasLimit:e.gasLim
vendor: 13,914 bytes, lines 4-6
4it?eC(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:eC(e.weiValue),data:ex(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?eC(e.gasPriceInWei):null,maxFeePerGas:e.maxFeePerGas?eC(e.maxFeePerGas):null,maxPriorityFeePerGas:e.maxPriorityFeePerGas?eC(e.maxPriorityFeePerGas):null,gasLimit:e.gasLimit?eC(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!0}})}submitEthereumTransaction(e,t){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:ex(e,!0),chainId:t}})}getWalletLinkSession(){return this._session}sendRequest(e){let t=null,i=eI(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(),e7(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 im)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){iw.accountRequestCallbackIds.forEach(e=>this.invokeCallback(e,t)),iw.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=eI(8);return new Promise((e,t)=>{this.relayEventManager.callbacks.set(r,i=>{if(e7(i))return t(Error(i.errorMessage));e(i)}),iw.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=eI(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(),e7(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=eI(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(),e7(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=eI(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(),e7(i)&&i.errorCode)?t(ef({code:i.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."})):e7(i)?t(Error(i.errorMessage)):void e(i)),this.publishWeb3RequestEvent(s,i)})}}iw.accountRequestCallbackIds=new Set;let ib="DefaultChainId",iv="DefaultJsonRpcUrl";class iE{constructor(e){this._relay=null,this._addresses=[],this.metadata=e.metadata,this._storage=new V("walletlink",iy),this.callback=e.callback||null;const t=this._storage.getItem(e6);if(t){const e=t.split(" ");""!==e[0]&&(this._addresses=e.map(e=>eD(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(iv))?e:void 0}set jsonRpcUrl(e){this._storage.setItem(iv,e)}updateProviderInfo(e,t){var i;this.jsonRpcUrl=e;let r=this.getChainId();this._storage.setItem(ib,t.toString(10)),eM(t)!==r&&(null==(i=this.callback)||i.call(this,"chainChanged",ek(t)))}async watchAsset(e){let t=Array.isArray(e)?e[0]:e;if(!t.type)throw el("Type is required");if((null==t?void 0:t.type)!=="ERC20")throw el(`Asset of type '${t.type}' is not supported`);if(!(null==t?void 0:t.options))throw el("Options are required");if(!(null==t?void 0:t.options.address))throw el("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!e7(l)&&!!l.result}async addEthereumChain(e){var t,i;let r=e[0];if((null==(t=r.rpcUrls)?void 0:t.length)===0)throw el("please pass in at least 1 rpcUrl");if(!r.chainName||""===r.chainName.trim())throw el("chainName is a required field");if(!r.nativeCurrency)throw el("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(e7(d))return!1;if((null==(i=d.result)?void 0:i.isApproved)===!0)return this.updateProviderInfo(a[0],s),null;throw ec("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(e7(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=>eD(e));JSON.stringify(r)!==JSON.stringify(this._addresses)&&(this._addresses=r,null==(i=this.callback)||i.call(this,"accountsChanged",r),this._storage.setItem(e6,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 ek(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 ec("No RPC URL set for chain");return e0(e,this.jsonRpcUrl)}}_ensureKnownAddress(e){let t=eD(e);if(!this._addresses.map(e=>eD(e)).includes(t))throw Error("Unknown Ethereum address")}_prepareTransactionParams(e){let t=e.from?eD(e.from):this.selectedAddress;if(!t)throw Error("Ethereum address is unavailable");this._ensureKnownAddress(t);let i=e.to?eD(e.to):null,r=null!=e.value?eL(e.value):BigInt(0),s=e.data?eU(e.data):G.Buffer.alloc(0),n=null!=e.nonce?eM(e.nonce):null,a=null!=e.gasPrice?eL(e.gasPrice):null,o=null!=e.maxFeePerGas?eL(e.maxFeePerGas):null,l=null!=e.maxPriorityFeePerGas?eL(e.maxPriorityFeePerGas):null;return{fromAddress:t,toAddress:i,weiValue:r,data:s,nonce:n,gasPriceInWei:a,maxFeePerGas:o,maxPriorityFeePerGas:l,gasLimit:null!=e.gas?eL(e.gas):null,chainId:e.chainId?eM(e.chainId):this.getChainId()}}async ecRecover(e){let{method:t,params:i}=e;if(!Array.isArray(i))throw el();let r=this.initializeRelay(),s=await r.sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:eP(i[0]),signature:eP(i[1]),addPrefix:"personal_ecRecover"===t}});if(e7(s))throw s;return s.result}getChainId(){var e;return Number.parseInt(null!=(e=this._storage.getItem(ib))?e:"1",10)}async _eth_requestAccounts(){var e,t;if(this._addresses.length>0)return null==(e=this.callback)||e.call(this,"connect",{chainId:ek(this.getChainId())}),this._addresses;let i=this.initializeRelay(),r=await i.requestEthereumAccounts();if(e7(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:ek(this.getChainId())}),this._addresses}async personalSign({params:e}){if(!Array.isArray(e))throw el();let t=e[1],i=e[0];this._ensureKnownAddress(t);let r=this.initializeRelay(),s=await r.sendRequest({method:"signEthereumMessage",params:{address:eD(t),message:eP(i),addPrefix:!0,typedDataJson:null}});if(e7(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(e7(r))throw r;return r.result}async _eth_sendRawTransaction(e){let t=eU(e[0]),i=this.initializeRelay(),r=await i.submitEthereumTransaction(t,this.getChainId());if(e7(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(e7(r))throw r;return r.result}async signTypedData(e){let{method:t,params:i}=e;if(!Array.isArray(i))throw el();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:eD(r),message:ex(({eth_signTypedData_v1:e4.default.hashForSignTypedDataLegacy,eth_signTypedData_v3:e4.default.hashForSignTypedData_v3,eth_signTypedData_v4:e4.default.hashForSignTypedData_v4,eth_signTypedData:e4.default.hashForSignTypedData_v4})[t]({data:function(e){if("string"==typeof e)return JSON.parse(e);if("object"==typeof e)return e;throw el(`Not a JSON string or an object: ${String(e)}`)}(s)}),!0),typedDataJson:JSON.stringify(s,null,2),addPrefix:!1}});if(e7(a))throw a;return a.result}initializeRelay(){return this._relay||(this._relay=new iw({linkAPIUrl:iy,storage:this._storage,metadata:this.metadata,accountsCallback:this._setAddresses.bind(this),chainCallback:this.updateProviderInfo.bind(this)})),this._relay}}let i_="SignerType",iI=new V("CBWSDK","SignerConfigurator");async function iS(e){let{communicator:t,metadata:i,handshakeRequest:r,callback:s}=e;iA(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 iA(e,t,i){await e.onMessage(({event:e})=>"WalletLinkSessionRequest"===e);let r=new iE({metadata:t,callback:i});e.postMessage({event:"WalletLinkUpdate",data:{session:r.getSession()}}),await r.handshake(),e.postMessage({event:"WalletLinkUpdate",data:{connected:!0}})}let ix=`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.
5
6Please see https://www.smartwallet.dev/guides/tips/popup-tips#cross-origin-opener-policy for more information.`,{checkCrossOriginOpenerPolicy:iP,getCrossOriginOpenerPolicy:iC}={getCrossOriginOpenerPolicy:()=>void 0===i?"undefined":i,checkCrossOriginOpenerPolicy:async()=>{if("u"<typeof window){i="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 r=t.headers.get("Cross-Origin-Opener-Policy");i=null!=r?r:"null","same-origin"===i&&console.error(ix)}catch(e){console.error("Error checking Cross-Origin-Opener-Policy:",e.message),i="error"}}},ik={isRed:!1,info:"Retry",svgWidth:"10",svgHeight:"11",path:id,defaultFillRule:"evenodd",defaultClipRule:"evenodd"},iO=null;class iT{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,231 bytes, line 6
6h(({reject:e},t)=>{e(eh("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:eX,sdkVersion:eQ,origin:window.location.origin,coop:iC()}))s.searchParams.append(e,t.toString());let n=r();if(!n){let e=function(){if(!iO){let e=document.createElement("div");e.className="-cbwsdk-css-reset",document.body.appendChild(e),(iO=new il).attach(e)}return iO}();return new Promise((t,i)=>{e.presentItem({autoExpand:!0,message:"Popup was blocked. Try again.",menuItems:[Object.assign(Object.assign({},ik),{onClick:()=>{(n=r())?t(n):i(ec("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:eQ,metadata:this.metadata,preference:this.preference,location:window.location.toString()}})}).then(()=>{if(!this.popup)throw ec();return this.popup})),this.url=new URL(e),this.metadata=t,this.preference=i}}var iR=e.i(927509);iR.default;var iN=iR;class ij extends iN.default{}var iD=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 iU extends ij{constructor(e){var{metadata:t}=e,i=e.preference,{keysUrl:r}=i,s=iD(i,["keysUrl"]);super(),this.signer=null,this.isCoinbaseWallet=!0,this.metadata=t,this.preference=s,this.communicator=new iT({url:r,metadata:t,preference:s});const n=iI.getItem(i_);n&&(this.signer=this.initSigner(n))}async request(e){try{if(!function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw el({message:"Expected a single, non-array, object argument.",data:e});let{method:t,params:i}=e;if("string"!=typeof t||0===t.length)throw el({message:"'args.method' must be a non-empty string.",data:e});if(void 0!==i&&!Array.isArray(i)&&("object"!=typeof i||null===i))throw el({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 eu()}}(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,iI.setItem(i_,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 e0(e,"https://rpc.wallet.coinbase.com");case"net_version":return 1;case"eth_chainId":return ek(1);default:throw ed("Must call 'eth_requestAccounts' before other methods")}return await this.signer.request(e)}catch(r){let e,t,{code:i}=r;return i===X&&this.disconnect(),Promise.reject((e=function(e,{shouldIncludeStack:t=!1}={}){var i,r;let s={};if(e&&"object"==typeof e&&!Array.isArray(e)&&ea(e,"code")&&Number.isInteger(i=e.code)&&(ei[i.toString()]||(r=i)>=-32099&&r<=-32e3))s.code=e.code,e.message&&"string"==typeof e.message?(s.message=e.message,ea(e,"data")&&(s.data=e.data)):(s.message=es(s.code),s.data={originalError:en(e)});else s.code=Z,s.message=eo(e,"message")?e.message:er,s.data={originalError:en(e)};return t&&(s.stack=eo(e,"stack")?e.stack:void 0),s}(function(e){var t;if("string"==typeof e)return{message:e,code:Z};if(e7(e)){let i=e.errorMessage,r=null!=(t=e.errorCode)?t:i.match(/(denied|rejected)/i)?Q: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",eQ),t.searchParams.set("co
6de",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,V.clearAll(),this.emit("disconnect",ep("User initiated disconnection"))}requestSignerSelection(e){return iS({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 e8({metadata:i,callback:s,communicator:r});case"walletlink":return new iE({metadata:i,callback:s})}}({signerType:e,metadata:this.metadata,communicator:this.communicator,callback:this.emit.bind(this)})}}let iM={options:"all"};e.s(["createCoinbaseWalletSDK",0,function(e){new V("CBWSDK").setItem("VERSION",eQ),iP();let t={metadata:{appName:e.appName||"Dapp",appLogoUrl:e.appLogoUrl||"",appChainIds:e.appChainIds||[]},preference:Object.assign(iM,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 iU(i)),s}}}],891507);var iL=e.i(219298),iB=e.i(247167),iW=e.i(277945),iq=e.i(648512),iK=e.i(36610),iH=e.i(275221),iz=e.i(44314),i$=e.i(140965);let iJ=BigInt(0),iF=BigInt(1);function iV(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function iG(e){if(!iV(e))throw Error("Uint8Array expected")}function iY(e,t){if("boolean"!=typeof t)throw Error(e+" boolean expected, got "+t)}function iZ(e){let t=e.toString(16);return 1&t.length?"0"+t:t}function iQ(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return""===e?iJ:BigInt("0x"+e)}let iX="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,i0=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function i1(e){if(iG(e),iX)return e.toHex();let t="";for(let i=0;i<e.length;i++)t+=i0[e[i]];return t}function i2(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function i3(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(iX)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=i2(e.charCodeAt(s)),n=i2(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 i5(e){return iQ(i1(e))}function i8(e){return iG(e),iQ(i1(Uint8Array.from(e).reverse()))}function i4(e,t){return i3(e.toString(16).padStart(2*t,"0"))}function i6(e,t){return i4(e,t).reverse()}function i7(e,t,i){let r;if("string"==typeof t)try{r=i3(t)}catch(t){throw Error(e+" must be hex string or Uint8Array, cause: "+t)}else if(iV(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 i9(...e){let t=0;for(let i=0;i<e.length;i++){let r=e[i];iG(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 re=e=>"bigint"==typeof e&&iJ<=e;function rt(e,t,i){return re(e)&&re(t)&&re(i)&&t<=e&&e<i}function ri(e,t,i,r){if(!rt(t,i,r))throw Error("expected valid "+e+": "+i+" <= n < "+r+", got "+t)}let rr=e=>(iF<<BigInt(e))-iF,rs=e=>
vendor: 21,133 bytes, line 6
6new Uint8Array(e),rn={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||iV(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 ra(e,t,i={}){let r=(t,i,r)=>{let s=rn[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 invalid. 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 ro(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 rl=BigInt(0),rc=BigInt(1),rh=BigInt(2),rd=BigInt(3),ru=BigInt(4),rp=BigInt(5),rf=BigInt(8);function rg(e,t){let i=e%t;return i>=rl?i:t+i}function ry(e,t,i){let r=e;for(;t-- >rl;)r*=r,r%=i;return r}function rm(e,t){if(e===rl)throw Error("invert: expected non-zero number");if(t<=rl)throw Error("invert: expected positive modulus, got "+t);let i=rg(e,t),r=t,s=rl,n=rc,a=rc,o=rl;for(;i!==rl;){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!==rc)throw Error("invert: does not exist");return rg(s,t)}function rw(e,t){let i=(e.ORDER+rc)/ru,r=e.pow(t,i);if(!e.eql(e.sqr(r),t))throw Error("Cannot find square root");return r}function rb(e,t){let i=(e.ORDER-rp)/rf,r=e.mul(t,rh),s=e.pow(r,i),n=e.mul(t,s),a=e.mul(e.mul(n,rh),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 rv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rE(e){return ra(e,rv.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}))}function r_(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 rI(e,t){let i=(e.ORDER-rc)/rh,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 rS(e,t){void 0!==t&&(0,tn.anumber)(t);let i=void 0!==t?t:e.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function rA(e,t,i=!1,r={}){let s;if(e<=rl)throw Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:n,nByteLength:a}=rS(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:rr(n),ZERO:rl,ONE:rc,create:t=>rg(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error("invalid field element: expected bigint, got "+typeof t);return rl<=t&&t<e},is0:e=>e===rl,isOdd:e=>(e&rc)===rc,neg:t=>rg(-t,e),eql:(e,t)=>e===t,sqr:t=>rg(t*t,e),add:(t,i)=>rg(t+i,e),sub:(t,i)=>rg(t-i,e),mul:(t,i)=>rg(t*i,e),pow:(e,t)=>(function(e,t,i){if(i<rl)throw Error("invalid exponent, negatives unsupported");if(i===rl)return e.ONE;if(i===rc)return t;let r=e.ONE,s=t;for(;i>rl;)i&rc&&(r=e.mul(r,s)),s=e.sqr(s),i>>=rc;return r})(o,e,t),div:(t,i)=>rg(t*rm(i,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>rm(t,e),sqrt:r.sqrt||(t=>(s||(s=e%ru===rd?rw:e%rf===rp?rb:function(e){if(e<BigInt(3))throw Error("sqrt is not defined for small field");let t=e-rc,i=0;for(;t%rh===rl;)t/=rh,i++;let r=rh,s=rA(e);for(;1===rI(s,r);)if(r++>1e3)throw Error("Cannot find square root: probably non-prime P");if(1===i)return rw;let n=s.pow(r,t),a=(t+rc)/rh;return function(e,r){if(e.is0(r))return r;if(1!==rI(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=rc<<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?i6(e,a):i4(e,a),fromBytes:e=>{if(e.length!==a)throw Error("Field.fromBytes: expected "+a+" bytes, got "+e.length);return i?i8(e):i5(e)},invertBatch:e=>r_(o,e),cmov:(e,t,i)=>i?t:e});return Object.freeze(o)}function rx(e){if("bigint"!=typeof e)throw Error("field order must be bigint");return Math.ceil(e.toString(2).length/8)}function rP(e){let t=rx(e);return t+Math.ceil(t/2)}let rC=BigInt(0),rk=BigInt(1);function rO(e,t){let i=t.negate();return e?i:t}function rT(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function rR(e,t){rT(e,t);let i=Math.ceil(t/e)+1,r=2**(e-1),s=2**e;return{windows:i,windowSize:r,mask:rr(e),maxNumber:s,shiftBy:BigInt(e)}}function rN(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+=rk);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 rj=new WeakMap,rD=new WeakMap;function rU(e){return rD.get(e)||1}function rM(e){return rE(e.Fp),ra(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...rS(e.n,e.nBitLength),...e,...{p:e.Fp.ORDER}})}function rL(e){void 0!==e.lowS&&iY("lowS",e.lowS),void 0!==e.prehash&&iY("prehash",e.prehash)}let rB={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(e,t)=>{let{Err:i}=rB;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=iZ(r);if(s.length/2&128)throw new i("tlv.encode: long form length too big");let n=r>127?iZ(s.length/2|128):"";return iZ(e)+n+s+t},decode(e,t){let{Err:i}=rB,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}=rB;if(e<rW)throw new t("integer: negative integers are not allowed");let i=iZ(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}=rB;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 i5(e)}},toSig(e){let{Err:t,_int:i,_tlv:r}=rB,s=i7("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}=rB,r=t.encode(2,i.encode(e.r)),s=t.encode(2,i.encode(e.s));return t.encode(48,r+s)}},rW=BigInt(0),rq=BigInt(1),rK=BigInt(2),rH=BigInt(3),rz=BigInt(4),r$=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),rJ=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),rF=BigInt(0),rV=BigInt(1),rG=BigInt(2),rY=(e,t)=>(e+t/rG)/t,rZ=rA(r$,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%r$,c=l*l*e%r$,h=ry(c,t,r$)*c%r$,d=ry(h,t,r$)*c%r$,u=ry(d,rG,r$)*l%r$,p=ry(u,r,r$)*u%r$,f=ry(p,s,r$)*p%r$,g=ry(f,a,r$)*f%r$,y=ry(g,o,r$)*g%r$,m=ry(y,a,r$)*f%r$,w=ry(m,t,r$)*c%r$,b=ry(w,n,r$)*p%r$,v=ry(b,i,r$)*l%r$,E=ry(v,rG,r$);if(!rZ.eql(rZ.sqr(E),e))throw Error("Cannot find square root");return E}}),rQ=(h={a:rF,b:BigInt(7),Fp:rZ,n:rJ,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),i=-rV*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=BigInt("0x100000000000000000000000000000000"),n=rY(t*e,rJ),a=rY(-i*e,rJ),o=rg(e-n*t-a*r,rJ),l=rg(-n*i-a*t,rJ),c=o>s,h=l>s;if(c&&(o=rJ-o),h&&(l=rJ-l),o>s||l>s)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:c,k1:o,k2neg:h,k2:l}}}},d=iz.sha256,{...(r=e=>(function(e){let t,i=(ra(t=rM(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 rg(e,s)}let{ProjectivePoint:h,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:p}=function(e){var t;let i=function(e){let t=rM(e);ra(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=rA(i.n,i.nBitLength),n=i.toBytes||((e,t,i)=>{let s=t.toAffine();return i9(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,rH),rz),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(iV(e)&&(e=i1(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:i5(i7("private key",e,s))}catch(t){throw Error("invalid private key, expected hex or "+s+" bytes, got "+typeof e)}return n&&(t=rg(t,a)),ri("private key",t,rq,a),t}function u(e){if(!(e instanceof g))throw Error("ProjectivePoint expected")}let p=ro((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=ro(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=r_(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(i7("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>iJ;e>>=iF,t+=1);return t}(BigInt(s)),l=1;o>12?l=o-3:o>4?l=o-2:o>0&&(l=2);let c=rr(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,rH),{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,rH),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;ri("scalar",e,rW,s);let n=g.ZERO;if(e===rW)return n;if(this.is0()||e===rq)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>rW||c>rW;)o&rq&&(h=h.add(u)),c&rq&&(d=d.add(u)),u=u.double(),o>>=rq,c>>=rq;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(ri("scalar",e,rq,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!==rW&&t!==rq&&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===rq)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===rq?this:t?t(g,this):this.multiplyUnsafe(i.h)}toRawBytes(e=!0){return iY("isCompressed",e),this.assertValidity(),n(g,this,e)}toHex(e=!0){return iY("isCompressed",e),i1(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:rO,hasPrecomputes:e=>1!==rU(e),unsafeLadder(e,t,i=g.ZERO){let r=e;for(;t>rC;)t&rk&&(i=i.add(r)),r=r.double(),t>>=rk;return i},precomputeWindow(e,i){let{windows:r,windowSize:s}=rR(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=rR(e,t);for(let e=0;e<a.windows;e++){let{nextN:t,offset:o,isZero:l,isNeg:c,isNegF:h,offsetF:d}=rN(r,e,a);r=t,l?n=n.add(rO(h,i[d])):s=s.add(rO(c,i[o]))}return{p:s,f:n}},wNAFUnsafe(e,i,r,s=g.ZERO){let n=rR(e,t);for(let e=0;e<n.windows&&r!==rC;e++){let{nextN:t,offset:a,isZero:o,isNeg:l}=rN(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=rj.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&rj.set(t,i(r))),r},wNAFCached(e,t,i){let r=rU(e);return this.wNAF(r,this.getPrecomputes(r,e,i),t)},wNAFCachedUnsafe(e,t,i,r){let s=rU(e);return 1===s?this.unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,i),t,r)},setWindowSize(e,i){rT(i,t),rD.set(e,i),rj.delete(e)}});return{CURVE:i,ProjectivePoint:g,normPrivateKeyToScalar:d,weierstrassEquation:o,isWithinCurveOrder:function(e){return rt(e,rq,i.n)}}}({...i,toBytes(e,t,i){let s=t.toAffine(),n=r.toBytes(s.x);return(iY("isCompressed",i),i)?i9(Uint8Array.from([t.hasEvenY()?2:3]),n):i9(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=i5(s);if(!rt(t,rq,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&rq)===rq)&&(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)=>i5(e.slice(t,i));class g{constructor(e,t,i){ri("r",e,rq,s),ri("s",t,rq,s),this.r=e,this.s=t,null!=i&&(this.recovery=i),Object.freeze(this)}static fromCompact(e){return new g(f(e=i7("compactSignature",e,2*n),0,n),f(e,n,2*n))}static fromDER(e){let{r:t,s:i}=rB.toSig(i7("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(i7("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+i1(i4(l,r.BYTES))),p=rm(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>>rq}normalizeS(){return this.hasHighS()?new g(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return i3(this.toDERHex())}toDERHex(){return rB.hexFromSig(this)}toCompactRawBytes(){return i3(this.toCompactHex())}toCompactHex(){return i1(i4(this.r,n))+i1(i4(this.s,n))}}function y(e){if("bigint"==typeof e)return!1;if(e instanceof h)return!0;let t=i7("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=i5(e),i=8*e.length-a;return i>0?t>>BigInt(i):t},w=i.bits2int_modN||function(e){return c(m(e))},b=rr(a);function v(e){return ri("num < 2^"+a,e,rW,b),i4(e,n)}let E={lowS:i.lowS,prehash:!1},_={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=i7("msgHash",e),rL(n),u&&(e=i7("prehashed msgHash",a(e)));let y=w(e),b=d(t),_=[v(b),v(y)];if(null!=f&&!1!==f){let e=!0===f?o(r.BYTES):f;_.push(i7("extraEntropy",e))}return{seed:i9(..._),k2sig:function(e){var t;let i=m(e);if(!p(i))return;let r=rm(i,s),n=h.BASE.multiply(i).toAffine(),a=c(n.x);if(a===rW)return;let o=c(r*c(y+a*b));if(o===rW)return;let d=2*(n.x!==a)|Number(n.y&rq),u=o;return l&&o>s>>rq&&(u=(t=o)>s>>rq?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=rs(e),s=rs(e),n=0,a=()=>{r.fill(1),s.fill(0),n=0},o=(...e)=>i(s,r,...e),l=(e=rs(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=()=>{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}
6return i9(...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=_){let a,o;t=i7("msgHash",t),r=i7("publicKey",r);let{lowS:l,prehash:d,format:u}=n;if(rL(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||iV(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 rB.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=rm(m,s),E=c(b*v),I=c(y*v),S=h.BASE.multiplyAndAddUnsafe(a,E,I)?.toAffine();return!!S&&c(S.x)===y},ProjectivePoint:h,Signature:g,utils:{isValidPrivateKey(e){try{return d(e),!0}catch(e){return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let e=rP(i.n);return function(e,t,i=!1){let r=e.length,s=rx(t),n=rP(t);if(r<16||r<n||r>1024)throw Error("expected "+n+"-1024 bytes of input, got "+r);let a=rg(i?i8(e):i5(e),t-rc)+rc;return i?i6(a,s):i4(a,s)}(i.randomBytes(e),i.n)},precompute:(e=8,t=h.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}})({...h,...{hash:e,hmac:(t,...i)=>(0,i$.hmac)(e,t,(0,tn.concatBytes)(...i)),randomBytes:tn.randomBytes}}))(d),create:r});rQ.ProjectivePoint;let rX=(s=[["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,n,a]=s.map(t=>t.reduce((t,i)=>rZ.add(rZ.mul(t,e),i))),[o,l]=r_(rZ,[r,a],!0);return e=rZ.mul(i,o),t=rZ.mul(t,rZ.mul(n,l)),{x:e,y:t}}),r0=function(e,t){if(rE(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=rW;for(let e=i-rq;e%rK===rW;e/=rK)r+=rq;let s=r,n=rK<<s-rq-rq,a=n*rK,o=(i-rq)/a,l=(o-rq)/rK,c=a-rq,h=e.pow(t,o),d=e.pow(t,(o+rq)/rK),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>rq;t--){let i=t-rK;i=rK<<i-rq;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%rz===rH){let i=(e.ORDER-rH)/rz,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=r_(e,[o],!0)[0];return{x:h=e.mul(h,g),y:d}}}(rZ,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:rZ.create(BigInt("-11"))});!function(e,t,i){if("function"!=typeof t)throw Error("mapToCurve() must be defined")}(rQ.ProjectivePoint,e=>{let{x:t,y:i}=r0(rZ.create(e[0]));return rX(t,i)},(rZ.ORDER,iz.sha256));
vendor: 4,183 bytes, line 6
6class r1 extends Error{constructor(e,t={}){const i=(()=>{if(t.cause instanceof r1){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 r1&&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 r2(e,t){if(si(e)>t)throw new so({givenSize:si(e),maxSize:t})}function r3(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 sc({size:Math.ceil(s.length/2),targetSize:r,type:"Hex"});return`0x${s["right"===i?"padEnd":"padStart"](2*r,"0")}`}function r5(e,t,i){return JSON.stringify(e,(e,i)=>"function"==typeof t?t(e,i):"bigint"==typeof i?i.toString()+"#__bigint":i,i)}let r8=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function r4(...e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}function r6(e){return e instanceof Uint8Array?r7(e):Array.isArray(e)?r7(new Uint8Array(e)):e}function r7(e,t={}){let i="";for(let t=0;t<e.length;t++)i+=r8[e[t]];let r=`0x${i}`;return"number"==typeof t.size?(r2(r,t.size),se(r,t.size)):r}function r9(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 ss({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,r3(i,{dir:"left",size:n})):c}function se(e,t){return r3(e,{dir:"right",size:t})}function st(e,t,i,r={}){let{strict:s}=r;if("number"==typeof t&&t>0&&t>si(e)-1)throw new sl({offset:t,position:"start",size:si(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&&si(e)!==i-t)throw new sl({offset:i,position:"end",size:si(e)})}(n,t,i),n}function si(e){return Math.ceil((e.length-2)/2)}function sr(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 ss extends r1{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 sn extends r1{constructor(e){super(`Value \`${"object"==typeof e?r5(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 sa extends r1{constructor(e){super(`Value \`${e}
6\` 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 so extends r1{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 sl extends r1{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 sc extends r1{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 sh(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}let sd=new TextEncoder;function su(e){var t;return e instanceof Uint8Array?e:"string"==typeof e?sp(e):(t=e)instanceof Uint8Array?t:new Uint8Array(t)}function sp(e,t={}){let{size:i}=t,r=e;i&&(r2(e,i),r=se(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=sh(s.charCodeAt(t++)),r=sh(s.charCodeAt(t++));if(void 0===i||void 0===r)throw new r1(`Invalid byte sequence ("${s[t-2]}${s[t-1]}" in "${s}").`);a[e]=16*i+r}return a}class sf extends r1{constructor(e){super(`Value \`${"object"==typeof e?r5(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 sg extends r1{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 sy extends r1{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 sm=2n**256n-1n;function sw(e,t={}){let{recovered:i}=t;if(void 0===e.r||void 0===e.s||i&&void 0===e.yParity)throw new sk({signature:e});if(e.r<0n||e.r>sm)throw new sO({value:e.r});if(e.s<0n||e.s>sm)throw new sT({value:e.s});if("number"==typeof e.yParity&&0!==e.yParity&&1!==e.yParity)throw new sR({value:e.yParity})}function sb(e){return sv(r7(e))}function sv(e){if(130!==e.length&&132!==e.length)throw new sC({signature:e});let t=BigInt(st(e,0,32)),i=BigInt(st(e,32,64)),r=(()=>{let t=Number(`0x${e.slice(130)}`);if(!Number.isNaN(t))try{return sx(t)}catch{throw new sR({value:t})}})();return void 0===r?{r:t,s:i}:{r:t,s:i,yParity:r}}function sE(e){let t="string"==typeof e?sv(e):e instanceof Uint8Array?sb(e):"string"==typeof e.r?sS(e):e.v?sI(e):{r:e.r,s:e.s,...void 0!==e.yParity?{yParity:e.yParity}:{}};return sw(t),t}function s_(e){let{r:t,s:i}=rQ.Signature.fromDER(r6(e).slice(2));return{r:t,s:i}}function sI(e){return{r:e.r,s:e.s,yParity:sx(e.v)}}function sS(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=sx(t)),"number"!=typeof i)throw new sR({value:e.yParity});return i})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function sA(e){sw(e);let t=e.r,i=e.s;return r4(r9(t,{size:32}),r9(i,{size:32}),"number"==typeof e.yParity?r9(sP(e.yParity),{size:1}):"0x")}function sx(e){if(0===e||27===e)return 0;if(1===e||28===e)return 1;if(e>=35)return+(e%2==0);throw new sN({value:e})}function sP(e){if(0===e)return 27;if(1===e)return 28;throw new sR({value:e})}class sC extends r1{constructor({signature:e}){super(`Value \`${e}
6\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${si(r6(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class sk extends r1{constructor({signature:e}){super(`Signature \`${r5(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class sO extends r1{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 sT extends r1{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 sR extends r1{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 sN extends r1{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,sO,"InvalidSError",0,sT,"InvalidSerializedSizeError",0,sC,"InvalidVError",0,sN,"InvalidYParityError",0,sR,"MissingPropertiesError",0,sk,"assert",0,sw,"extract",0,function(e){if(void 0!==e.r&&void 0!==e.s)return sE(e)},"from",0,sE,"fromBytes",0,sb,"fromDerBytes",0,function(e){return s_(r7(e))},"fromDerHex",0,s_,"fromHex",0,sv,"fromLegacy",0,sI,"fromRpc",0,sS,"fromTuple",0,function(e){let[t,i,r]=e;return sE({r:"0x"===i?0n:BigInt(i),s:"0x"===r?0n:BigInt(r),yParity:"0x"===t?0:Number(t)})},"toBytes",0,function(e){return sp(sA(e))},"toDerBytes",0,function(e){return new rQ.Signature(e.r,e.s).toDERRawBytes()},"toDerHex",0,function(e){let t=new rQ.Signature(e.r,e.s);return`0x${t.toDERHex()}`},"toHex",0,sA,"toLegacy",0,function(e){return{r:e.r,s:e.s,v:sP(e.yParity)}},"toRpc",0,function(e){let{r:t,s:i,yParity:r}=e;return{r:r9(t,{size:32}),s:r9(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":sr(r9(t)),0n===i?"0x":sr(r9(i))]},"vToYParity",0,sx,"validate",0,function(e,t={}){try{return sw(e,t),!0}catch{return!1}},"yParityToV",0,sP],869859);var sj=e.i(869859),sj=sj;class sD 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 sU={checksum:new sD(8192)}.checksum;var sM=e.i(145535);function sL(e,t={}){let{as:i="string"==typeof e?"Hex":"Bytes"}=t,r=(0,sM.keccak_256)(su(e));return"Bytes"===i?r:r7(r)}function sB(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 sz({prefix:r,cause:new sJ});return}if(!0===i||"bigint"==typeof s&&void 0===n){if(3!==r&&2!==r)throw new sz({prefix:r,cause:new s$});return}throw new sH({publicKey:e})}function sW(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 sn(e);if(i&&!/^0x[0-9a-fA-F]*$/.test(e)||!e.startsWith("0x"))throw new sa(e)}(e,{strict:i}),!0}catch{return!1}}(e))return sq(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 sf(e);return!0}catch{return!1}}(e))return sq(r7(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 sB(t),t}function sq(e){if(132!==e.length&&130!==e.length&&68!==e.length)throw new sF({publicKey:e});if(130===e.length)return{prefix:4,x:BigInt(st(e,0,32)),y:BigInt(st(e,32,64))};
6if(132===e.length){let t=Number(st(e,0,1));return{prefix:t,x:BigInt(st(e,1,33)),y:BigInt(st(e,33,65))}}return{prefix:Number(st(e,0,1)),x:BigInt(st(e,1,33))}}function sK(e,t={}){sB(e);let{prefix:i,x:r,y:s}=e,{includePrefix:n=!0}=t;return r4(n?r9(i,{size:1}):"0x",r9(r,{size:32}),"bigint"==typeof s?r9(s,{size:32}):"0x")}class sH extends r1{constructor({publicKey:e}){super(`Value \`${r5(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 sz extends r1{constructor({prefix:e,cause:t}){super(`Prefix "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class s$ extends r1{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 sJ extends r1{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class sF extends r1{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 ${si(r6(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}let sV=/^0x[a-fA-F0-9]{40}$/;function sG(e,t={}){let{strict:i=!0}=t;if(!sV.test(e))throw new sZ({address:e,cause:new sQ});if(i){if(e.toLowerCase()===e)return;if(sY(e)!==e)throw new sZ({address:e,cause:new sX})}}function sY(e){if(sU.has(e))return sU.get(e);sG(e,{strict:!1});let t=e.substring(2).toLowerCase(),i=sL(function(e,t={}){let{size:i}=t,r=sd.encode(e);if("number"==typeof i){var s;if(r.length>i)throw new sg({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 sy({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 sU.set(e,s),s}class sZ extends r1{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 sQ extends r1{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 sX extends r1{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}function s0(e){let{privateKey:t}=e;return sW(rQ.ProjectivePoint.fromPrivateKey(r6(t).slice(2)))}function s1(e={}){let{as:t="Hex"}=e,i=rQ.utils.randomPrivateKey();return"Hex"===t?r7(i):i}function s2(e){return function(e,t={}){let i=sL(`0x${sK(e).slice(4)}`).substring(26);return function(e,t={}){let{checksum:i=!1}=t;return(sG(e),i)?sY(e):e}(`0x${i}`,t)}(s3(e))}function s3(e){let{payload:t,signature:i}=e,{r,s,yParity:n}=i;return sW(new rQ.Signature(BigInt(r),BigInt(s)).addRecoveryBit(n).recoverPublicKey(r6(t).substring(2)))}e.s(["createKeyPair",0,function(e={}){let{as:t="Hex"}=e,i=s1({as:t}),r=s0({privateKey:i});return{privateKey:i,publicKey:r}},"getPublicKey",0,s0,"getSharedSecret",0,function(e){let{as:t="Hex",privateKey:i,publicKey:r}=e,s=rQ.ProjectivePoint.fromHex(sK(r).slice(2)).multiply(rQ.utils.normPrivateKeyToScalar(r6(i).slice(2))).toRawBytes(!0);return"Hex"===t?r7(s):s},"noble",0,rQ,"randomPrivateKey",0,s1,"recoverAddress",0,s2,"recoverPublicKey",0,s3,"sign",0,function(e){let{extraEntropy:t=!1,hash:i,payload:r,privateKey:s}=e,{r:n,s:a,recovery:o}=rQ.sign(su(r),su(s),{extraEntropy:"boolean"==typeof t?t:r6(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=s2({payload:r,signature:n}),sG(t,{strict:!1}),sG(a,{strict:!1}),t.toLowerCase()===a.toLowerCase()}return rQ.verify(n,su(r),function(e,t={}){return sp(sK(e,t))}(s),...i?[{prehash:!0,lowS:!0}]:[])}],520735);var s5=e.i(520735),s5=s5,s8=e.i(103476),s4=e.i(626335),s6=e.i(425748),s7=e.i(166953),s9=e.i(121609);e.i(262265);var ne=e.i(773912),nt=e.i(120483),ni=e.i(310998),nr=e.i(281223),ns=e.i(5625),nn=e.i(735071),na=e.i(31794),no=Object.defineProperty,nl=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?no(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};
6class nc{constructor(e){nl(this,"nodeValue"),nl(this,"sizeInBytes"),nl(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 nh{constructor(e){nl(this,"lengthInNodes"),nl(this,"sizeInBytes"),nl(this,"head"),nl(this,"tail"),nl(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){let t=new nc(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 nd=Object.defineProperty,nu=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?nd(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class np{constructor(e,t=1024e3){nu(this,"logs"),nu(this,"level"),nu(this,"levelValue"),nu(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=nn.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new nh(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===nn.levels.values.error?console.error(e):t===nn.levels.values.warn?console.warn(e):t===nn.levels.values.debug||nn.levels.values.trace}appendToLogs(e){this.logs.append((0,na.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 nh(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){let t=this.getLogArray();return t.push((0,na.safeJsonStringify)({extraMetadata:e})),new Blob(t,{type:"application/json"})}}var nf=Object.defineProperty;class ng{constructor(e,t=1024e3){((e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?nf(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(this,"baseChunkLogger"),this.baseChunkLogger=new np(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 ny=Object.defineProperty;class nm{constructor(e,t=1024e3){((e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?ny(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(this,"baseChunkLogger"),this.baseChunkLogger=new np(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 nw=Object.defineProperty,nb=Object.defineProperties,nv=Object.getOwnPropertyDescriptors,nE=Object.getOwnPropertySymbols,n_=Object.prototype.hasOwnProperty,nI=Object.prototype.propertyIsEnumerable,nS=(e,t,i)=>t in e?nw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,nA=(e,t)=>{for(var i in t||(t={}))n_.call(t,i)&&nS(e,i,t[i]);if(nE)for(var i of nE(t))nI.call(t,i)&&nS(e,i,t[i]);return e};function nx(e){let[t,i]=e.split(":");return{namespace:t,reference:i}}function nP(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 nC(e,t){return e.includes(":")?[e]:t.chains||[]}var nk=Object.defineProperty,nO=Object.defineProperties,nT=Object.getOwnPropertyDescriptors,nR=Object.getOwnPropertySymbols,nN=Object.prototype.hasOwnProperty,nj=Object.prototype.propertyIsEnumerable,nD=(e,t,i)=>t in e?nk(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,nU=(e,t)=>{for(var i in t||(t={}))nN.call(t,i)&&nD(e,i,t[i]);if(nR)for(var i of nR(t))nj.call(t,i)&&nD(e,i,t[i]);return e},nM=(e,t,i)=>nD(e,"symbol"!=typeof t?t+"":t,i);let nL="react-native",nB="node",nW="browser";function nq(){return"u">typeof iB.default&&"u">typeof iB.default.versions&&"u">typeof iB.default.versions.node}
6function nK(){return!(0,iK.getDocument)()&&!!(0,iK.getNavigator)()&&"ReactNative"===navigator.product}function nH(){return!nq()&&!!(0,iK.getNavigator)()&&!!(0,iK.getDocument)()}function nz(){return nK()?nL:nq()?nB:nH()?nW:"unknown"}function n$(){var t;try{return nK()&&"u">typeof(null==e.g?void 0:e.g.Application)?null==(t=e.g.Application)?void 0:t.applicationId:void 0}catch{return}}function nJ(){return(0,iH.getWindowMetadata)()||{name:"",description:"",url:"",icons:[""]}}function nF(t,i,r){var s;let n,a=function(){if(nz()===nL&&"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,iW.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=nz())===nW?[n,(null==(s=(0,iK.getLocation)())?void 0:s.host)||"unknown"].join(":"):n;return[[t,i].join("-"),["js",r].join("-"),a,o].join("/")}function nV(e,t){return e.filter(e=>t.includes(e)).length===e.length}function nG(e){return Object.fromEntries(e.entries())}function nY(e){return new Map(Object.entries(e))}function nZ(e=iq.FIVE_MINUTES,t){let i,r,s,n,a=(0,iq.toMiliseconds)(e||iq.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 nQ(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 nX(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 n0(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 n1(e,t){return(0,iq.fromMiliseconds)((t||Date.now())+(0,iq.toMiliseconds)(e))}function n2(e){return Date.now()>=(0,iq.toMiliseconds)(e)}function n3(e,t){return`${e}${t?`:${t}`:""}`}function n5(e=[],t=[]){return[...new Set([...e,...t])]}async function n8({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=G.Buffer.from(e).toString("base64");return t?i.replace(/[=]/g,""):i}(r,!0)}`}else s=`${s}/wc?${r}`;return s}(o,t,i),c=nz();if(c===nW){let e;if(!(null!=(s=(0,iK.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===nL&&"u">typeof(null==e.g?void 0:e.g.Linking)&&await e.g.Linking.openURL(l)}catch(e){console.error(e)}}async function n4(e,t){let i="";try{if(nH()&&(i=localStorage.getItem(t)))return i;i=await e.getItem(t)}catch(e){console.error(e)}return i}function n6(e,t){if(!e.includes(t))return null;let i=e.split(/([&,?,=])/),r=i.indexOf(t);return i[r+2]}function n7(){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 n9(){return"u">typeof iB.default&&"true"===iB.default.env.IS_VITEST}function ae(e){return G.Buffer.from(e,"base64").toString("utf-8")}class at{constructor({limit:e}){nM(this,"limit"),nM(this,"set"),this.limit=e,this.set=new Set}
6add(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 ai=BigInt(0x100000000-1),ar=BigInt(32);function as(e,t=!1){return t?{h:Number(e&ai),l:Number(e>>ar&ai)}:{h:0|Number(e>>ar&ai),l:0|Number(e&ai)}}function an(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}=as(e[n],t);[r[n],s[n]]=[i,a]}return[r,s]}let aa=(e,t,i)=>e>>>i,ao=(e,t,i)=>e<<32-i|t>>>i,al=(e,t,i)=>e>>>i|t<<32-i,ac=(e,t,i)=>e<<32-i|t>>>i,ah=(e,t,i)=>e<<64-i|t>>>i-32,ad=(e,t,i)=>e>>>i-32|t<<64-i;function au(e,t,i,r){let s=(t>>>0)+(r>>>0);return{h:e+i+(s/0x100000000|0)|0,l:0|s}}let ap=(e,t,i)=>(e>>>0)+(t>>>0)+(i>>>0),af=(e,t,i,r)=>t+i+r+(e/0x100000000|0)|0,ag=(e,t,i,r)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0),ay=(e,t,i,r,s)=>t+i+r+s+(e/0x100000000|0)|0,am=(e,t,i,r,s)=>(e>>>0)+(t>>>0)+(i>>>0)+(r>>>0)+(s>>>0),aw=(e,t,i,r,s,n)=>t+i+r+s+n+(e/0x100000000|0)|0,ab="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function av(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function aE(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function a_(e,...t){if(!av(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 aI(e){if("function"!=typeof e||"function"!=typeof e.create)throw Error("Hash should be wrapped by utils.createHasher");aE(e.outputLen),aE(e.blockLen)}function aS(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 aA(e,t){a_(e);let i=t.outputLen;if(e.length<i)throw Error("digestInto() expects output buffer of length at least "+i)}function ax(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function aP(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function aC(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ak(e,t){return e<<32-t|e>>>t}let aO=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0];function aT(e){return e<<24&0xff000000|e<<8&0xff0000|e>>>8&65280|e>>>24&255}let aR=aO?e=>e:e=>aT(e),aN=aO?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=aT(e[t]);return e},aj="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,aD=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function aU(e){if(a_(e),aj)return e.toHex();let t="";for(let i=0;i<e.length;i++)t+=aD[e[i]];return t}function aM(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function aL(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);if(aj)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=aM(e.charCodeAt(s)),n=aM(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 aB(e){if("string"!=typeof e)throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function aW(e){return"string"==typeof e&&(e=aB(e)),a_(e),e}function aq(...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}class aK{}function aH(e){let t=t=>e().update(aW(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}function az(e=32){if(ab&&"function"==typeof ab.getRandomValues)return ab.getRandomValues(new Uint8Array(e));if(ab&&"function"==typeof ab.randomBytes)return Uint8Array.from(ab.randomBytes(e));throw Error("crypto.getRandomValues must be defined")}let a$=BigInt(0),aJ=BigInt(1),aF=BigInt(2),aV=BigInt(7),aG=BigInt(256),aY=BigInt(113),aZ=[],aQ=[],aX=[];for(let e=0,t=aJ,i=1,r=0;e<24;e++){[i,r]=[r,(2*i+3*r)%5],aZ.push(2*(5*r+i)),aQ.push((e+1)*(e+2)/2%64);let s=a$;for(let e=0;e<7;e++)(t=(t<<aJ^(t>>aV)*aY)%aG)&aF&&(s^=aJ<<(aJ<<BigInt(e))-aJ);aX.push(s)}let a0=an(aX,!0),a1=a0[0],a2=a0[1],a3=(e,t,i)=>i>32?t<<i-32|e>>>64-i:e<<i|t>>>32-i,a5=(e,t,i)=>i>32?e<<i-32|t>>>64-i:t<<i|e>>>32-i;class a8 extends aK{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,aE(i),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ax(this.state)}clone(){return this._cloneInto()}keccak(){aN(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=a3(n,a,1)^i[r],l=a5(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=aQ[i],n=a3(t,s,r),a=a5(t,s,r),o=aZ[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]^=a1[r],e[1]^=a2[r]}aP(i)}(this.state32,this.rounds),aN(this.state32),this.posOut=0,this.pos=0}update(e){aS(this),a_(e=aW(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){aS(this,!1),a_(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 aE(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(aA(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,aP(this.state)}_cloneInto(e){let{blockLen:t,suffix:i,outputLen:r,rounds:s,enableXOF:n}=this;return e||(e=new a8(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 a4=aH(()=>new a8(136,1,32));class a6 extends aK{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=aC(this.buffer)}update(e){aS(this),a_(e=aW(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=aC(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){aS(this),aA(e,this),this.finished=!0;let{buffer:t,view:i,blockLen:r,isLE:s}=this,{pos:n}=this;t[n++]=128,aP(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=aC(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()}}
6let a7=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),a9=Uint32Array.from([0xcbbb9d5d,0xc1059ed8,0x629a292a,0x367cd507,0x9159015a,0x3070dd17,0x152fecd8,0xf70e5939,0x67332667,0xffc00b31,0x8eb44a87,0x68581511,0xdb0c2e0d,0x64f98fa7,0x47b5481d,0xbefa4fa4]),oe=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),ot=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]),oi=new Uint32Array(64);class or extends a6{constructor(e=32){super(64,e,8,!1),this.A=0|a7[0],this.B=0|a7[1],this.C=0|a7[2],this.D=0|a7[3],this.E=0|a7[4],this.F=0|a7[5],this.G=0|a7[6],this.H=0|a7[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)oi[i]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=oi[e-15],i=oi[e-2],r=ak(t,7)^ak(t,18)^t>>>3,s=ak(i,17)^ak(i,19)^i>>>10;oi[e]=s+oi[e-7]+r+oi[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+(ak(a,6)^ak(a,11)^ak(a,25))+((h=a)&o^~h&l)+ot[e]+oi[e]|0,f=(ak(i,2)^ak(i,13)^ak(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(){aP(oi)}destroy(){this.set(0,0,0,0,0,0,0,0),aP(this.buffer)}}let os=an(["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
65771202a","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))),on=os[0],oa=os[1],oo=new Uint32Array(80),ol=new Uint32Array(80);class oc extends a6{constructor(e=64){super(128,e,16,!1),this.Ah=0|oe[0],this.Al=0|oe[1],this.Bh=0|oe[2],this.Bl=0|oe[3],this.Ch=0|oe[4],this.Cl=0|oe[5],this.Dh=0|oe[6],this.Dl=0|oe[7],this.Eh=0|oe[8],this.El=0|oe[9],this.Fh=0|oe[10],this.Fl=0|oe[11],this.Gh=0|oe[12],this.Gl=0|oe[13],this.Hh=0|oe[14],this.Hl=0|oe[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)oo[i]=e.getUint32(t),ol[i]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=0|oo[e-15],i=0|ol[e-15],r=al(t,i,1)^al(t,i,8)^aa(t,i,7),s=ac(t,i,1)^ac(t,i,8)^ao(t,i,7),n=0|oo[e-2],a=0|ol[e-2],o=al(n,a,19)^ah(n,a,61)^aa(n,a,6),l=ag(s,ac(n,a,19)^ad(n,a,61)^ao(n,a,6),ol[e-7],ol[e-16]),c=ay(l,r,o,oo[e-7],oo[e-16]);oo[e]=0|c,ol[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=al(h,d,14)^al(h,d,18)^ah(h,d,41),w=ac(h,d,14)^ac(h,d,18)^ad(h,d,41),b=h&u^~h&f,v=am(m,w,d&p^~d&g,oa[e],ol[e]),E=aw(v,y,t,b,on[e],oo[e]),_=0|v,I=al(i,r,28)^ah(i,r,34)^ah(i,r,39),S=ac(i,r,28)^ad(i,r,34)^ad(i,r,39),A=i&s^i&a^s&a,x=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}=au(0|l,0|c,0|E,0|_)),l=0|a,c=0|o,a=0|s,o=0|n,s=0|i,n=0|r;let P=ap(_,S,x);i=af(P,E,I,A),r=0|P}({h:i,l:r}=au(0|this.Ah,0|this.Al,0|i,0|r)),({h:s,l:n}=au(0|this.Bh,0|this.Bl,0|s,0|n)),({h:a,l:o}=au(0|this.Ch,0|this.Cl,0|a,0|o)),({h:l,l:c}=au(0|this.Dh,0|this.Dl,0|l,0|c)),({h:h,l:d}=au(0|this.Eh,0|this.El,0|h,0|d)),({h:u,l:p}=au(0|this.Fh,0|this.Fl,0|u,0|p)),({h:f,l:g}=au(0|this.Gh,0|this.Gl,0|f,0|g)),({h:y,l:m}=au(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(){aP(oo,ol)}destroy(){aP(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class oh extends oc{constructor(){super(48),this.Ah=0|a9[0],this.Al=0|a9[1],this.Bh=0|a9[2],this.Bl=0|a9[3],this.Ch=0|a9[4],this.Cl=0|a9[5],this.Dh=0|a9[6],this.Dl=0|a9[7],this.Eh=0|a9[8],this.El=0|a9[9],this.Fh=0|a9[10],this.Fl=0|a9[11],this.Gh=0|a9[12],this.Gl=0|a9[13],this.Hh=0|a9[14],this.Hl=0|a9[15]}}let od=Uint32Array.from([0x22312194,0xfc2bf72c,0x9f555fa3,0xc84c64c2,0x2393b86b,0x6f53b151,0x96387719,0x5940eabd,0x96283ee2,0xa88effe3,0xbe5e1e25,0x53863992,0x2b0199fc,0x2c85b8aa,0xeb72ddc,0x81c52ca2]);class ou extends oc{constructor(){super(32),this.Ah=0|od[0],this.Al=0|od[1],this.Bh=0|od[2],this.Bl=0|od[3],this.Ch=0|od[4],this.Cl=0|od[5],this.Dh=0|od[6],this.Dl=0|od[7],this.Eh=0|od[8],this.El=0|od[9],this.Fh=0|od[10],this.Fl=0|od[11],this.Gh=0|od[12],this.Gl=0|od[13],this.Hh=0|od[14],this.Hl=0|od[15]}}let op=aH(()=>new or),of=aH(()=>new oc),og=aH(()=>new oh),oy=aH(()=>new ou),om=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]),ow=Uint32Array.from([0xf3bcc908,0x6a09e66
67,0x84caa73b,0xbb67ae85,0xfe94f82b,0x3c6ef372,0x5f1d36f1,0xa54ff53a,0xade682d1,0x510e527f,0x2b3e6c1f,0x9b05688c,0xfb41bd6b,0x1f83d9ab,0x137e2179,0x5be0cd19]),ob=new Uint32Array(32);function ov(e,t,i,r,s,n){let a=s[n],o=s[n+1],l=ob[2*e],c=ob[2*e+1],h=ob[2*t],d=ob[2*t+1],u=ob[2*i],p=ob[2*i+1],f=ob[2*r],g=ob[2*r+1],y=ap(l,h,a);c=af(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}=au(p,u,g,f)),({Bh:d,Bl:h}={Bh:d^p,Bl:h^u}),({Bh:d,Bl:h}={Bh:al(d,h,24),Bl:ac(d,h,24)}),ob[2*e]=l,ob[2*e+1]=c,ob[2*t]=h,ob[2*t+1]=d,ob[2*i]=u,ob[2*i+1]=p,ob[2*r]=f,ob[2*r+1]=g}function oE(e,t,i,r,s,n){let a=s[n],o=s[n+1],l=ob[2*e],c=ob[2*e+1],h=ob[2*t],d=ob[2*t+1],u=ob[2*i],p=ob[2*i+1],f=ob[2*r],g=ob[2*r+1],y=ap(l,h,a);c=af(y,c,d,o),l=0|y,({Dh:g,Dl:f}={Dh:g^c,Dl:f^l}),({Dh:g,Dl:f}={Dh:al(g,f,16),Dl:ac(g,f,16)}),({h:p,l:u}=au(p,u,g,f)),({Bh:d,Bl:h}={Bh:d^p,Bl:h^u}),({Bh:d,Bl:h}={Bh:ah(d,h,63),Bl:ad(d,h,63)}),ob[2*e]=l,ob[2*e+1]=c,ob[2*t]=h,ob[2*t+1]=d,ob[2*i]=u,ob[2*i+1]=p,ob[2*r]=f,ob[2*r+1]=g}class o_ extends aK{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,aE(e),aE(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=ax(this.buffer)}update(e){aS(this),a_(e=aW(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&&(aN(r),this.compress(r,0,!1),aN(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));aN(e);for(let i=0;o+t<s;i+=r.length,o+=t)this.length+=t,this.compress(e,i,!1);aN(e);continue}i.set(e.subarray(o,o+l),this.pos),this.pos+=l,this.length+=l,o+=l}return this}digestInto(e){aS(this),aA(e,this);let{pos:t,buffer32:i}=this;this.finished=!0,aP(this.buffer.subarray(t)),aN(i),this.compress(i,0,!0),aN(i);let r=ax(e);this.get().forEach((e,t)=>r[t]=aR(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 oI extends o_{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|ow[0],this.v0h=0|ow[1],this.v1l=0|ow[2],this.v1h=0|ow[3],this.v2l=0|ow[4],this.v2h=0|ow[5],this.v3l=0|ow[6],this.v3h=0|ow[7],this.v4l=0|ow[8],this.v4h=0|ow[9],this.v5l=0|ow[10],this.v5h=0|ow[11],this.v6l=0|ow[12],this.v6h=0|ow[13],this.v7l=0|ow[14],this.v7h=0|ow[15],function(e,t={}){if(aE(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=aW(i)).length),this.v0l^=this.outputLen|n<<8|0x1010000,void 0!==s){const e=ax(s=aW(s));this.v4l^=aR(e[0]),this.v4h^=aR(e[1]),this.v5l^=aR(e[2]),this.v5h^=aR(e[3])}if(void 0!==r){const e=ax(r=aW(r));this.v6l^=aR(e[0]),this.v6h^=aR(e[1]),this.v7l^=aR(e[2]),this.v7h^=aR(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)=>ob[t]=e),ob.set(ow,16);let{h:r,l:s}=as(BigInt(this.length));ob[24]=ow[8]^s,ob[25]=ow[9]^r,i&&(ob[28]=~ob[28],ob[29]=~ob[29]);let n=0;for(let i=0;i<12;i++)ov(0,4,8,12,e,t+2*om[n++]),oE(0,4,8,12,e,t+2*om[n++]),ov(1,5,9,13,e,t+2*om[n++]),oE(1,5,9,13,e,t+2*om[n++]),ov(2,6,10,14,e,t+2*om[n++]),oE(2,6,10,14,e,t+2*om[n++]),ov(3,7,11,15,e,t+2*om[n++]),oE(3,7,11,15,e,t+2*om[n++]),ov(0,5,10,15,e,t+2*om[n++]),oE(0,5,10,15,e,t+2*om[n++]),ov(1,6,11,12,e,t+2*om[n++]),oE(1,6,11,12,e,t+2*om[n++]),ov(2,7,8,13,e,t+2*om[n++]),oE(2,7,8,13,e,t+2*om[n++]),ov(3,4,9,14,e,t+2*om[n++]),oE(3,4,9,14,e,t+2*om[n++]);this.v0l^=ob[0]^ob[16],this.v0h^=ob[1]^ob[17],this.v1l^=ob[2]^ob[18],this.v1h^=ob[3]^ob[19],this.v2l^=ob[4]^ob[20],this.v2h^=ob[5]^ob[21],this.v3l^=ob[6]^ob[22],this.v3h^=ob[7]^ob[23],this.v4l^=ob[8]^ob[24],this.v4h^=ob[9]^ob[25],this.v5l^=ob[10]^ob[26],this.v5h^=ob[11
6]^ob[27],this.v6l^=ob[12]^ob[28],this.v6h^=ob[13]^ob[29],this.v7l^=ob[14]^ob[30],this.v7h^=ob[15]^ob[31],aP(ob)}destroy(){this.destroyed=!0,aP(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}let oS=(u=e=>new oI(e),(n=(e,t)=>u(t).update(aW(e)).digest()).outputLen=(a=u({})).outputLen,n.blockLen=a.blockLen,n.create=e=>u(e),n);function oA(e){let t=`�Ethereum Signed Message:
7${e.length}`,i=new TextEncoder().encode(t+e);return"0x"+G.Buffer.from(a4(i)).toString("hex")}async function ox(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=sj.fromHex(l),s5.recoverAddress({payload:oA(o),signature:c}).toLowerCase()===a.toLowerCase());case"eip1271":return await oP(e,t,i.s,r,s,n);default:throw Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${i.t}`)}}async function oP(e,t,i,r,s,n){let a=nx(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:oA(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 oC(e){let t=new Uint8Array(op(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 s8.default.encode(t)}function ok(e){let t=G.Buffer.from(e,"base64"),i=(0,s4.decode)(t).txn;if(!i)throw Error("Invalid signed transaction: missing 'txn' field");let r=(0,s6.encode)(i),s=G.Buffer.from("TX"),n=oy(G.Buffer.concat([s,G.Buffer.from(r)]));return s7.base32.encode(n).replace(/=+$/,"")}function oO(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)),G.Buffer.from(t)}var oT=Object.defineProperty,oR=Object.defineProperties,oN=Object.getOwnPropertyDescriptors,oj=Object.getOwnPropertySymbols,oD=Object.prototype.hasOwnProperty,oU=Object.prototype.propertyIsEnumerable,oM=(e,t,i)=>t in e?oT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;let oL=e=>e?.split(":"),oB=e=>{let t=e&&oL(e);if(t)return t[2]+":"+t[3]},oW=e=>{let t=e&&oL(e);if(t)return t.pop()};async function oq(e){let{cacao:t,projectId:i}=e,{s:r,p:s}=t,n=oK(s,s.iss),a=oW(s.iss);return await ox(a,n,r,oB(s.iss),i)}let oK=(e,t)=>{let i=`${e.domain} wants you to sign in with your Ethereum account:`,r=oW(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&&oL(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=>`
8- ${e}`).join("")}`:void 0,f=oV(e.resources);return f&&(s=function(e="",t){oH(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;Object.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}'.`));
8r.push(a.join(", ").replace(".,","."))});let n=r.join(" "),a=`${i}${n}`;return`${e?e+" ":""}${a}`}(s,o$(f))),[i,r,"",s,"",n,a,o,l,c,h,d,u,p].filter(e=>null!=e).join(`
9`)};function oH(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 oz(e){return oH(e),`urn:recap:${G.Buffer.from(JSON.stringify(e)).toString("base64").replace(/=/g,"")}`}function o$(e){var t;let i=(t=e.replace("urn:recap:",""),JSON.parse(G.Buffer.from(t,"base64").toString("utf-8")));return oH(i),i}function oJ(e){var t;let i=o$(e);oH(i);let r=null==(t=i.att)?void 0:t.eip155;return r?Object.keys(r).map(e=>e.split("/")[1]):[]}function oF(e){let t=o$(e);oH(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 oV(e){if(!e)return;let t=e?.[e.length-1];return t&&t.includes("urn:recap:")?t:void 0}function oG(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function oY(e){if("boolean"!=typeof e)throw Error(`boolean expected, not ${e}`)}function oZ(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function oQ(e,...t){if(!oG(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 oX(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 o0(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function o1(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}let o2=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0];function o3(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(oG(e))e=o4(e);else throw Error("Uint8Array expected, got "+typeof e);return e}function o5(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 o8(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 o4(e){return Uint8Array.from(e)}let o6=e=>Uint8Array.from(e.split("").map(e=>e.charCodeAt(0))),o7=o6("expand 16-byte k"),o9=o6("expand 32-byte k"),le=o0(o7),lt=o0(o9);function li(e,t){return e<<t|e>>>32-t}function lr(e){return e.byteOffset%4==0}let ls=0x100000000-1,ln=new Uint32Array,la=(e,t)=>255&e[t++]|(255&e[t++])<<8;class lo{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,oQ(e=o3(e),32);const t=la(e,0),i=la(e,2),r=la(e,4),s=la(e,6),n=la(e,8),a=la(e,10),o=la(e,12),l=la(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]=la(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=la(e,t+0),y=la(e,t+2),m=la(e,t+4),w=la(e,t+6),b=la(e,t+8),v=la(e,t+10),E=la(e,t+12),_=la(e,t+14),I=r[0]+(8191&g),S=r[1]+((g>>>13|y<<3)&8191),A=r[2]+((y>>>10|m<<6)&8191),x=r[3]+((m>>>7|w<<9)&8191),P=r[4]+((w>>>4|b<<12)&8191),C=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|_<<8)&8191),R=r[9]+(_>>>5|2048*!i),N=0,j=0+I*n+5*f*S+5*p*A+5*u*x+5*d*P;N=j>>>13,j&=8191,j+=5*h*C+5*c*k+5*l*O+5*o*T+5*a*R,N+=j>>>13,j&=8191;let D=N+I*a+S*n+5*f*A+5*p*x+5*u*P;N=D>>>13,D&=8191,D+=5*d*C+5*h*k+5*c*O+5*l*T+5*o*R,N+=D>>>13,D&=8191;let U=N+I*o+S*a+A*n+5*f*x+5*p*P;N=U>>>13,U&=8191,U+=5*u*C+5*d*k+5*h*O+5*c*T+5*l*R,N+=U>>>13,U&=8191;let M=N+I*l+S*o+A*a+x*n+5*f*P;N=M>>>13,M&=8191,M+=5*p*C+5*u*k+5*d*O+5*h*T+5*c*R,N+=M>>>13,M&=8191;let L=N+I*c+S*l+A*o+x*a+P*n;N=L>>>13,L&=8191,L+=5*f*C+5*p*k+5*u*O+5*d*T+5*h*R,N+=L>>>13,L&=8191;let B=N+I*h+S*c+A*l+x*o+P*a;N=B>>>
913,B&=8191,B+=C*n+5*f*k+5*p*O+5*u*T+5*d*R,N+=B>>>13,B&=8191;let W=N+I*d+S*h+A*c+x*l+P*o;N=W>>>13,W&=8191,W+=C*a+k*n+5*f*O+5*p*T+5*u*R,N+=W>>>13,W&=8191;let q=N+I*u+S*d+A*h+x*c+P*l;N=q>>>13,q&=8191,q+=C*o+k*a+O*n+5*f*T+5*p*R,N+=q>>>13,q&=8191;let K=N+I*p+S*u+A*d+x*h+P*c;N=K>>>13,K&=8191,K+=C*l+k*o+O*a+T*n+5*f*R,N+=K>>>13,K&=8191;let H=N+I*f+S*p+A*u+x*d+P*h;N=H>>>13,H&=8191,H+=C*c+k*l+O*o+T*a+R*n,N+=H>>>13,H&=8191,j=8191&(N=(N=(N<<2)+N|0)+j|0),N>>>=13,D+=N,r[0]=j,r[1]=D,r[2]=U,r[3]=M,r[4]=L,r[5]=B,r[6]=W,r[7]=q,r[8]=K,r[9]=H}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;o1(i)}update(e){oX(this),oQ(e=o3(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(){o1(this.h,this.r,this.buffer,this.pad)}digestInto(e){oX(this),function(e,t){oQ(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 ll=(p=e=>new lo(e),(o=(e,t)=>p(t).update(o3(e)).digest()).outputLen=(l=p(new Uint8Array(32))).outputLen,o.blockLen=l.blockLen,o.create=e=>p(e),o),lc=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 oZ(s),oZ(a),oY(n),oY(i),(t,o,l,c,h=0)=>{oQ(t),oQ(o),oQ(l);let d=l.length;if(void 0===c&&(c=new Uint8Array(d)),oQ(c),oZ(h),h<0||h>=ls)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=o4(t)),g=lt;else if(16===p&&i)(f=new Uint8Array(32)).set(t),f.set(t,16),g=le,u.push(f);else throw Error(`arx: invalid 32-byte key, got length=${p}`);lr(o)||u.push(o=o4(o));let y=o0(f);if(r){if(24!==o.length)throw Error("arx: extended nonce must be 24 bytes");r(g,y,o0(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=o0(c),d=lr(s)&&lr(n),u=d?o0(s):ln,p=d?o0(n):ln;for(let f=0;f<l;a++){if(e(t,i,r,h,a,o),a>=ls)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,o0(o),l,c,h,a),o1(...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,_=o,I=l,S=c,A=h,x=d,P=u,C=p,k=f,O=g,T=y,R=m,N=s,j=w,D=b,U=v;for(let e=0;e<n;e+=2)k=k+(N=li(N^(E=E+A|0),16))|0,E=E+(A=li(A^k,12))|0,k=k+(N=li(N^E,8))|0,A=li(A^k,7),O=O+(j=li(j^(_=_+x|0),16))|0,_=_+(x=li(x^O,12))|0,O=O+(j=li(j^_,8))|0,x=li(x^O,7),T=T+(D=li(D^(I=I+P|0),16))|0,I=I+(P=li(P^T,12))|0,T=T+(D=li(D^I,8))|0,P=li(P^T,7),R=R+(U=li(U^(S=S+C|0),16))|0,S=S+(C=li(C^R,12))|0,R=R+(U=li(U^S,8))|0,C=li(C^R,7),T=T+(U=li(U^(E=E+x|0),16))|0,E=E+(x=li(x^T,12))|0,T=T+(U=li(U^E,8))|0,x=li(x^T,7),R=R+(N=li(N^(_=_+P|0),16))|0,_=_+(P=li(P^R,12))|0,R=R+(N=li(N^_,8))|0,P=li(P^R,7),k=k+(j=li(j^(I=I+C|0),16))|0,I=I+(C=li(C^k,12))|0,k=k+(j=li(j^I,8))|0,C=li(C^k,7),O=O+(D=li(D^(S=S+A|0),16))|0,S=S+(A=li(A^O,12))|0,O=O+(D=li(D^S,8))|0,A=li(A^O,7);let M=0;r[M++]=a+E|0,r[M++]=o+_|0,r[M++]=l+I|0,r[M++]=c+S|0,r[M++]=h+A|0,r[M++]=d+x|0,r[M++]=u+P|0,r[M++]=p+C|0,r[M++]=f+k|0,r[M++]=g+O|0,r[M++]=y+T|0,r[M++]=m+R|0,r[M++]=s+N|0,r[M++]=w+j|0,r[M++]=b+D|0,r[M++]=v+U|0},{counterRight:!1,counterLength:4,allowShortKeys:!1}),lh=new Uint8Array(16),ld=(e,t)=>{e.update(t);let i=t.length%16;i&&e.update(lh.subarray(i))},lu=new Uint8Array(32);function lp(e,t,i,r,s){var n,a;let o,l,c=e(t,i,lu),h=ll.create(c);s&&ld(h,s),ld(h,r);let d=(n=r.length,a=s?s.length:0,oY(!0),o8(l=new DataView((o=new Uint8Array(16)).buffer,o.byteOffset,o.byteLength),0,BigInt(a),!0),o8(l,8,BigInt(n),!0),o);h.update(d);let u=h.digest();return o1(c,d),u}let lf=((e,t)=>{function i(r,...s){if(oQ(r),!o2)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?oQ(t):oQ(t,e.nonceLength)}let n=e.tagLength;n&&void 0!==s[1]&&oQ(s[1]);let a=t(r,...s),o=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");oQ(t)}},l=!1;
9return{encrypt(e,t){if(l)throw Error("cannot encrypt() twice with same key + nonce");return l=!0,oQ(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(oQ(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=o5(n+16,s,!1)).set(r);let a=s.subarray(0,-16);lc(e,t,a,a,1);let o=lp(lc,e,t,a,i);return s.set(o,n),o1(o),s},decrypt(r,s){s=o5(r.length-16,s,!1);let n=r.subarray(0,-16),a=r.subarray(-16),o=lp(lc,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)),lc(e,t,s,s,1),o1(o),s}}));class lg extends aK{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,aI(e);const i=aW(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),aP(s)}update(e){return aS(this),this.iHash.update(e),this}digestInto(e){aS(this),a_(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 ly=(e,t,i)=>new lg(e,t).update(i).digest();ly.create=(e,t)=>new lg(e,t);let lm=Uint8Array.from([0]),lw=Uint8Array.of(),lb=BigInt(0),lv=BigInt(1);function lE(e,t=""){if("boolean"!=typeof e)throw Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function l_(e,t,i=""){let r=av(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 lI(e){let t=e.toString(16);return 1&t.length?"0"+t:t}function lS(e){if("string"!=typeof e)throw Error("hex string expected, got "+typeof e);return""===e?lb:BigInt("0x"+e)}function lA(e){return a_(e),lS(aU(Uint8Array.from(e).reverse()))}function lx(e,t){return aL(e.toString(16).padStart(2*t,"0"))}function lP(e,t){return lx(e,t).reverse()}function lC(e,t,i){let r;if("string"==typeof t)try{r=aL(t)}catch(t){throw Error(e+" must be hex string or Uint8Array, cause: "+t)}else if(av(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 lk=e=>"bigint"==typeof e&&lb<=e;function lO(e,t,i,r){if(!(lk(t)&&lk(i)&&lk(r))||!(i<=t)||!(t<r))throw Error("expected valid "+e+": "+i+" <= n < "+r+", got "+t)}function lT(e){let t;for(t=0;e>lb;e>>=lv,t+=1);return t}let lR=e=>(lv<<BigInt(e))-lv;function lN(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 lj(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 lD=BigInt(0),lU=BigInt(1),lM=BigInt(2),lL=BigInt(3),lB=BigInt(4),lW=BigInt(5),lq=BigInt(7),lK=BigInt(8),lH=BigInt(9),lz=BigInt(16);function l$(e,t){let i=e%t;return i>=lD?i:t+i}function lJ(e,t,i){let r=e;for(;t-- >lD;)r*=r,r%=i;return r}function lF(e,t){if(e===lD)throw Error("invert: expected non-zero number");if(t<=lD)throw Error("invert: expected positive modulus, got "+t);let i=l$(e,t),r=t,s=lD,n=lU;for(;i!==lD;){let e=r/i,t=r%i,a=s-n*e;r=i,i=t,s=n,n=a}if(r!==lU)throw Error("invert: does not exist");return l$(s,t)}function lV(e,t,i){if(!e.eql(e.sqr(t),i))throw Error("Cannot find square root")}function lG(e,t){let i=(e.ORDER+lU)/lB,r=e.pow(t,i);return lV(e,r,t),r}function lY(e,t){let i=(e.ORDER-lW)/lK,r=e.mul(t,lM),s=e.pow(r,i),n=e.mul(t,s),a=e.mul(e.mul(n,lM),s),o=e.mul(n,e.sub(a,e.ONE));return lV(e,o,t),o}function lZ(e){if(e<lL)throw Error("sqrt is not defined for small field");let t=e-lU,i=0;for(;t%lM===lD;)t/=lM,i++;let r=lM,s=l2(e);for(;1===l0(s,r);)if(r++>1e3)throw Error("Cannot find square root: probably non-prime P");if(1===i)return lG;let n=s.pow(r,t),a=(t+lU)/lM;return function(e,r){if(e.is0(r))return r;if(1!==l0(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=lU<<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 lQ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function lX(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 l0(e,t){let i=(e.ORDER-lU)/lM,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 l1(e,t){void 0!==t&&aE(t);let i=void 0!==t?t:e.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function l2(e,t,i=!1,r={}){let s;if(e<=lD)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 9
9t.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}=l1(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:lR(c),ZERO:lD,ONE:lU,allowedLengths:l,create:t=>l$(t,e),isValid:t=>{if("bigint"!=typeof t)throw Error("invalid field element: expected bigint, got "+typeof t);return lD<=t&&t<e},is0:e=>e===lD,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&lU)===lU,neg:t=>l$(-t,e),eql:(e,t)=>e===t,sqr:t=>l$(t*t,e),add:(t,i)=>l$(t+i,e),sub:(t,i)=>l$(t-i,e),mul:(t,i)=>l$(t*i,e),pow:(e,t)=>(function(e,t,i){if(i<lD)throw Error("invalid exponent, negatives unsupported");if(i===lD)return e.ONE;if(i===lU)return t;let r=e.ONE,s=t;for(;i>lD;)i&lU&&(r=e.mul(r,s)),s=e.sqr(s),i>>=lU;return r})(d,e,t),div:(t,i)=>l$(t*lF(i,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>lF(t,e),sqrt:a||(t=>{let i,r,n,a,o,l;return s||(s=e%lB===lL?lG:e%lK===lW?lY:e%lz===lH?(i=l2(e),n=(r=lZ(e))(i,i.neg(i.ONE)),a=r(i,n),o=r(i,i.neg(n)),l=(e+lq)/lz,(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 lV(e,p,t),p}):lZ(e)),s(d,t)}),toBytes:e=>i?lP(e,h):lx(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?lA(t):lS(aU(t));if(o&&(s=l$(s,e)),!r&&!d.isValid(s))throw Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>lX(d,e),cmov:(e,t,i)=>i?t:e});return Object.freeze(d)}function l3(e){if("bigint"!=typeof e)throw Error("field order must be bigint");return Math.ceil(e.toString(2).length/8)}function l5(e){let t=l3(e);return t+Math.ceil(t/2)}let l8=BigInt(0),l4=BigInt(1);function l6(e,t){let i=t.negate();return e?i:t}function l7(e,t){let i=lX(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(i[r])))}function l9(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function ce(e,t){l9(e,t);let i=Math.ceil(t/e)+1,r=2**(e-1),s=2**e;return{windows:i,windowSize:r,mask:lR(e),maxNumber:s,shiftBy:BigInt(e)}}function ct(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+=l4);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 ci=new WeakMap,cr=new WeakMap;function cs(e){return cr.get(e)||1}function cn(e){if(e!==l8)throw Error("invalid wNAF")}class ca{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>l8;)t&l4&&(i=i.add(r)),r=r.double(),t>>=l4;return i}precomputeWindow(e,t){let{windows:i,windowSize:r}=ce(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=ce(e,this.bits);for(let e=0;e<n.windows;e++){let{nextN:a,offset:o,isZero:l,isNeg:c,isNegF:h,offsetF:d}=ct(i,e,n);i=a,l?s=s.add(l6(h,t[d])):r=r.add(l6(c,t[o]))}return cn(i),{p:r,f:s}}wNAFUnsafe(e,t,i,r=this.ZERO){let s=ce(e,this.bits);for(let e=0;e<s.windows&&i!==l8;e++){let{nextN:n,offset:a,isZero:o,isNeg:l}=ct(i,e,s);if(i=n,!o){let e=t[a];r=r.add(l?e.negate():e)}}return cn(i),r}getPrecomputes(e,t,i){let r=ci.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof i&&(r=i(r)),ci.set(t,r))),r}cached(e,t,i){let r=cs(e);
9return this.wNAF(r,this.getPrecomputes(r,e,i),t)}unsafe(e,t,i,r){let s=cs(e);return 1===s?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,i),t,r)}createCache(e,t){l9(t,this.bits),cr.set(e,t),ci.delete(e)}hasCache(e){return 1!==cs(e)}}function co(e,t,i){if(!t)return l2(e,{isLE:i});if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return lN(t,lQ.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"})),t}BigInt(0),BigInt(1),BigInt(2),BigInt(8),aB("HashToScalar-");let cl=BigInt(0),cc=BigInt(1),ch=BigInt(2),cd=BigInt(1),cu=BigInt(2),cp=BigInt(3),cf=BigInt(5),cg=BigInt(8),cy=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),cm={p:cy,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:cg,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")},cw=function(e){let{P:t,type:i,adjustScalarBytes:r,powPminus2:s,randomBytes:n}=(lN(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})),a="x25519"===i;if(!a&&"x448"!==i)throw Error("invalid type");let o=n||az,l=a?255:448,c=a?32:56,h=BigInt(a?9:5),d=BigInt(a?121665:39081),u=a?ch**BigInt(254):ch**BigInt(447),p=u+(a?BigInt(8)*ch**BigInt(251)-cc:BigInt(4)*ch**BigInt(445)-cc)+cc,f=e=>l$(e,t),g=lP(f(h),c);function y(e,i){let n,o=function(e,i){lO("u",e,cl,t),lO("scalar",i,u,p);let r=cc,n=cl,a=e,o=cc,c=cl;for(let t=BigInt(l-1);t>=cl;t--){let s=i>>t&cc;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=lC("u coordinate",i,c),a&&(n[31]&=127),f(lA(n))),lA(r(lC("scalar",e,c))));if(o===cl)throw Error("invalid private or public key received");return lP(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))=>(a_(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:c=l2(cm.p,{isLE:!0}).ORDER,type:"x25519",powPminus2:e=>{let t,i,r,s,n,a,o,l,h,d,u,p,f,g,{pow_p_5_8:y,b2:m}=(t=BigInt(10),i=BigInt(20),r=BigInt(40),s=BigInt(80),a=lJ(n=e*e%cy*e%cy,cu,cy)*n%cy,o=lJ(a,cd,cy)*e%cy,l=lJ(o,cf,cy)*o%cy,h=lJ(l,t,cy)*l%cy,d=lJ(h,i,cy)*h%cy,u=lJ(d,r,cy)*d%cy,p=lJ(u,s,cy)*u%cy,f=lJ(p,s,cy)*u%cy,g=lJ(f,t,cy)*l%cy,{pow_p_5_8:lJ(g,cu,cy)*e%cy,b2:n});return l$(lJ(y,cp,c)*m,c)},adjustScalarBytes:function(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}}),cb=(e,t)=>(e+(e>=0?t:-t)/cA)/t;function cv(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function cE(e,t){let i={};for(let r of Object.keys(t))i[r]=void 0===e[r]?t[r]:e[r];return lE(i.lowS,"lowS"),lE(i.prehash,"prehash"),void 0!==i.format&&cv(i.format),i}let c_={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(e,t)=>{let{Err:i}=c_;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=lI(r);if(s.length/2&128)throw new i("tlv.encode: long form length too big");let n=r>127?lI(s.length/2|128):"";return lI(e)+n+s+t},decode(e,t){let{Err:i}=c_,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}=c_;if(e<cI)throw new t("integer: negative integers are not allowed");let i=lI(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}=c_;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 lS(aU(e))}},toSig(e){let{Err:t,_int:i,_tlv:r}=c_,s=lC("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}=c_,r=t.encode(2,i.encode(e.r)),s=t.encode(2,i.encode(e.s));return t.encode(48,r+s)}},cI=BigInt(0),cS=BigInt(1),cA=BigInt(2),cx=BigInt(3),cP=BigInt(4);function cC(e,t){let i,{BYTES:r}=e;if("bigint"==typeof t)i=t;else{let s=lC("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 ck(e){return Uint8Array.of(e?2:3)}function cO(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function cT(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:l2(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={}){aI(t),lN(i,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=i.randomBytes||az,s=i.hmac||((e,...i)=>ly(t,e,aq(...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||az,s=Object.assign(cO(e.Fp,i),{seed:l5(i.ORDER)});function n(e){try{return!!cC(i,e)}catch{return!1}}function a(e=r(s.seed)){return function(e,t,i=!1){let r=e.length,s=l3(t),n=l5(t);if(r<16||r<n||r>1024)throw Error("expected "+n+"-1024 bytes of input, got "+r);
9let a=l$(i?lA(e):lS(aU(e)),t-lU)+lU;return i?lP(a,s):lx(a,s)}(l_(e,s.seed,"seed"),i.ORDER)}function o(t,r=!0){return e.BASE.multiply(cC(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=lC("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=cC(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=>cC(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,cv(r=t),n=p.signature,l_(i,"compact"===r?n:"recovered"===r?n+1:void 0,`${r} signature`),"der"===t){let{r:t,s:i}=c_.toSig(l_(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(aL(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*cA<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(aq(ck((1&l)==0),h)),u=a.inv(c),p=b(lC("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>>cS}toBytes(e=g){if(cv(e),"der"===e)return aL(c_.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 aq(Uint8Array.of(this.recovery),t,i)}return aq(t,i)}toHex(e){return aU(this.toBytes(e))}assertValidity(){}static fromCompact(e){return m.fromBytes(lC("sig",e),"compact")}static fromDER(e){return m.fromBytes(lC("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 aU(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return aU(this.toBytes("compact"))}}let w=i.bits2int||function(e){if(e.length>8192)throw Error("input is too large");let t=lS(aU(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=lR(l);function E(e){return lO("num < 2^"+l,e,cI,v),a.toBytes(e)}function _(e,i){return l_(e,void 0,"message"),i?l_(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}=cE(s,f),h=b(t=_(t,l)),d=cC(a,i),u=[E(d),E(h)];if(null!=c&&!1!==c){let e=!0===c?r(p.secretKey):c;u.push(lC("extraEntropy",e))}return{seed:aq(...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===cI)return;let c=a.create(r*a.create(h+l*d));if(c===cI)return;let u=2*(s.x!==l)|Number(s.y&cS),p=c;return n&&c>o>>cS&&(p=a.neg(c),u^=1),new m(l,p,u)}}}(i=lC("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=()=>
vendor: 4,158 bytes, line 9
9{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 aq(...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}=cE(s,f);if(r=lC("publicKey",r),i=_(lC("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||av(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(lC("sig",e),"der")}catch(e){if(!(e instanceof c_.Err))throw e}if(!t)try{t=m.fromBytes(lC("sig",e),"compact")}catch{return!1}}return t||!1}(t):m.fromBytes(lC("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}=cE(i,f);return t=_(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>l8))throw Error(`CURVE.${e} must be positive bigint`)}let s=co(t.p,i.Fp,r),n=co(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;lN(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=cO(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(lE(i,"isCompressed"),i)?(h(),aq(ck(!r.isOdd(n)),a)):aq(Uint8Array.of(4),a,r.toBytes(n))},u=t.fromBytes||function(e){l_(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,cx),cP),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 I))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=cb(a*e,i),l=cb(-s*e,i),c=e-o*r-l*n,h=-o*s-l*a,d=c<cI,u=h<cI;d&&(c=-c),u&&(h=-h);let p=lR(Math.ceil(lT(i)/2))+cS;if(c<cI||c>=p||h<cI||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=lj((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};
vendor: 4,077 bytes, line 9
9if(!r.eql(c,r.ONE))throw Error("invZ was invalid");return{x:o,y:l}}),E=lj(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 _(e,t,i,s,n){return i=new I(r.mul(i.X,e),i.Y,i.Z),t=l6(s,t),i=l6(n,i),t.add(i)}class I{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 I)throw Error("projective point not allowed");return r.is0(t)&&r.is0(i)?I.ZERO:new I(t,i,r.ONE)}static fromBytes(e){let t=I.fromAffine(u(l_(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return I.fromBytes(lC("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return A.createCache(this,e),t||this.multiply(cx),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 I(this.X,r.neg(this.Y),this.Z)}double(){let{a:e,b:t}=n,i=r.mul(t,cx),{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(o,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 I(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,cx),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 I(c,h,d=r.add(d,f))}subtract(e){return this.add(e.negate())}is0(){return this.equals(I.ZERO)}multiply(e){let i,r,{endo:n}=t;if(!s.isValidNot0(e))throw Error("invalid scalar: out of range");let a=e=>A.cached(this,e,e=>l7(I,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=_(n.beta,c,d,t,o)}else{let{p:t,f:s}=a(e);i=t,r=s}return l7(I,[i,r])[0]}multiplyUnsafe(e){let{endo:i}=t;if(!s.isValid(e))throw Error("invalid scalar: out of range");if(e===cI||this.is0())return I.ZERO;if(e===cS)return this;if(A.hasCache(this))return this.multiply(e);if(!i)return A.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>l8||r>l8;)i&l4&&(n=n.add(s)),r&l4&&(a=a.add(s)),s=s.double(),i>>=l4,r>>=l4;return{p1:n,p2:a}}(I,this,r,n);return _(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===cS||(e?e(I,this):A.unsafe(this,o).is0())}clearCofactor(){let{clearCofactor:e}=t;return a===cS?this:e?e(I,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(e=!0){return lE(e,"isCompressed"),this.assertValidity(),d(I,this,e)}toHex(e=!0){return aU(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)}
9_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return l7(I,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=lT(BigInt(s)),l=1;o>12?l=o-3:o>4?l=o-2:o>0&&(l=2);let c=lR(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}(I,s,e,t)}static fromPrivateKey(e){return I.BASE.multiply(cC(s,e))}}I.BASE=new I(n.Gx,n.Gy,r.ONE),I.ZERO=new I(r.ZERO,r.ONE,r.ZERO),I.Fp=r,I.Fn=s;let S=s.BITS,A=new ca(I,t.endo?Math.ceil(S/2):S);return I.BASE.precompute(8),I}(i,r),s,n);return t=a.Point,Object.assign({},a,{ProjectivePoint:t,CURVE:Object.assign({},e,l1(t.Fn.ORDER,t.Fn.BITS))})})({...e,hash:t});return{...i(t),create:i}}let cR={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},cN={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},cj={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},cD=l2(cR.p),cU=l2(cN.p),cM=l2(cj.p),cL=cT({...cR,Fp:cD,lowS:!1},op);cT({...cN,Fp:cU,lowS:!1},og),cT({...cj,Fp:cM,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},of);let cB="base10",cW="base16",cq="base64pad",cK="base64url",cH="utf8";function cz(){let e=az(32);return(0,ne.toString)(e,cW)}function c$(e){let t=op((0,nt.fromString)(e,cW));return(0,ne.toString)(t,cW)}function cJ(e){let t=op((0,nt.fromString)(e,cH));return(0,ne.toString)(t,cW)}function cF(e){return(0,nt.fromString)(`${e}`,cB)}function cV(e){return Number((0,ne.toString)(e,cB))}function cG(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function cY(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4;return t+"=".repeat(i)}function cZ(e){if(2===cV(e.type))return(0,ne.toString)((0,ni.concat)([e.type,e.sealed]),cq);if(1===cV(e.type)){if(typeof e.senderPublicKey>"u")throw Error("Missing sender public key for type 1 envelope");return(0,ne.toString)((0,ni.concat)([e.type,e.senderPublicKey,e.
9iv,e.sealed]),cq)}return(0,ne.toString)((0,ni.concat)([e.type,e.iv,e.sealed]),cq)}function cQ(e){let t=(e.encoding||cq)===cK?cY(e.encoded):e.encoded,i=(0,nt.fromString)(t,cq),r=i.slice(0,1);if(1===cV(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===cV(r))return{type:r,sealed:i.slice(1),iv:az(12)};let s=i.slice(1,13);return{type:r,sealed:i.slice(13),iv:s}}function cX(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 c0(e){return 1===e.type&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function c1(e){return e?.relay||{protocol:"irn"}}function c2(e){let t=nr.RELAY_JSONRPC[e];if(typeof t>"u")throw Error(`Relay Protocol not supported: ${e}`);return t}var c3=Object.defineProperty,c5=Object.defineProperties,c8=Object.getOwnPropertyDescriptors,c4=Object.getOwnPropertySymbols,c6=Object.prototype.hasOwnProperty,c7=Object.prototype.propertyIsEnumerable,c9=(e,t,i)=>t in e?c3(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,he=(e,t)=>{for(var i in t||(t={}))c6.call(t,i)&&c9(e,i,t[i]);if(c4)for(var i of c4(t))c7.call(t,i)&&c9(e,i,t[i]);return e};function ht(e){var t;if(!e.includes("wc:")){let t=ae(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 hi(e){let t=new URLSearchParams;return Object.entries(he(he(c5(he({},function(e,t="-"){let i={};return Object.keys(e).forEach(r=>{e[r]&&(i["relay"+t+r]=e[r])}),i}(e.relay)),c8({symKey:e.symKey})),e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()}),e.methods&&{methods:e.methods.join(",")})).sort(([e],[t])=>e.localeCompare(t)).forEach(([e,i])=>{void 0!==i&&t.append(e,String(i))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function hr(e,t,i){return`${e}?wc_ev=${i}&topic=${t}`}var hs=Object.defineProperty,hn=Object.defineProperties,ha=Object.getOwnPropertyDescriptors,ho=Object.getOwnPropertySymbols,hl=Object.prototype.hasOwnProperty,hc=Object.prototype.propertyIsEnumerable,hh=(e,t,i)=>t in e?hs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,hd=(e,t)=>{for(var i in t||(t={}))hl.call(t,i)&&hh(e,i,t[i]);if(ho)for(var i of ho(t))hc.call(t,i)&&hh(e,i,t[i]);return e},hu=(e,t)=>hn(e,ha(t));function hp(e){let t=[];return e.forEach(e=>{let[i,r]=e.split(":");t.push(`${i}:${r}`)}),t}function hf(e){return e.includes(":")}function hg(e){return hf(e)?e.split(":")[0]:e}function hy(e){var t,i,r;let s={};if(!hI(e))return s;for(let[n,a]of Object.entries(e)){let e=hf(n)?[n]:a.chains,o=a.methods||[],l=a.events||[],c=hg(n);s[c]=hu(hd({},s[c]),{chains:n5(e,null==(t=s[c])?void 0:t.chains),methods:n5(o,null==(i=s[c])?void 0:i.methods),events:n5(l,null==(r=s[c])?void 0:r.events)})}return s}function hm(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=n5(i.methods,e):i.methods=e,i.events=["chainChanged","accountsChanged"];return s}
9let hw={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}},hb={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 hv(e,t){let{message:i,code:r}=hb[e];return{message:t?`${i} ${t}`:i,code:r}}function hE(e,t){let{message:i,code:r}=hw[e];return{message:t?`${i} ${t}`:i,code:r}}function h_(e,t){return!!Array.isArray(e)&&(!("u">typeof t)||!e.length||e.every(t))}function hI(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function hS(e){return typeof e>"u"}function hA(e,t){return!!(t&&hS(e))||"string"==typeof e&&!!e.trim().length}function hx(e,t){return!!(t&&hS(e))||"number"==typeof e&&!isNaN(e)}function hP(e){return!!(hA(e,!1)&&e.includes(":"))&&2===e.split(":").length}function hC(e){let t=!0;return h_(e)?e.length&&(t=e.every(e=>hA(e,!1))):t=!1,t}function hk(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,hC(e?.methods)?hC(e?.events)||(s=hE("UNSUPPORTED_EVENTS",`${r}, events should be an array of strings or empty array for no events`)):s=hE("UNSUPPORTED_METHODS",`${r}, methods should be an array of strings or empty array for no methods`),s);n&&(i=n)}),i}function hO(e,t){let i=null;if(e&&hI(e)){let r,s=hk(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,h_(i)?i.forEach(e=>{n||function(e){if(hA(e,!1)&&e.includes(":")){let t=e.split(":");if(3===t.length){let e=t[0]+":"+t[1];return!!t[2]&&hP(e)}}return!1}(e)||(n=hE("UNSUPPORTED_ACCOUNTS",`${s}, account ${e} should be a string and conform to "namespace:chainId:address" format`))}):n=hE("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=hv("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return i}function hT(e){return hA(e.protocol,!0)}function hR(e){return"u">typeof e}function hN(e,t){let i;return!(!hP(t)||!(i=[],Object.values(e).forEach(e=>{i.push(...hp(e.accounts))}),i).includes(t))}function hj(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=hp(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=hD(Object.keys(e)),p=hD(Object.keys(t)),f=u.filter(e=>!p.includes(e));return f.length&&(o=hv("NON_CONFORMING_NAMESPACES",`${i} namespaces keys don't satisfy requiredNamespaces.
10      Required: ${f.toString()}
11      Received: ${Object.keys(t).toString()}`)),nV(h,d)||(o=hv("NON_CONFORMING_NAMESPACES",`${i} namespaces chains don't satisfy required namespaces.
12      Required: ${h.toString()}
13      Approved: ${d.toString()}
13`)),Object.keys(t).forEach(e=>{if(!e.includes(":")||o)return;let r=hp(t[e].accounts);r.includes(e)||(o=hv("NON_CONFORMING_NAMESPACES",`${i} namespaces accounts don't satisfy namespace accounts for ${e}
14        Required: ${e}
15        Approved: ${r.toString()}`))}),h.forEach(e=>{o||(nV(l[e].methods,c[e].methods)?nV(l[e].events,c[e].events)||(o=hv("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${e}`)):o=hv("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${e}`))}),o}function hD(e){return[...new Set(e.map(e=>e.includes(":")?e.split(":")[0]:e))]}function hU(){let e=nz();return new Promise(t=>{switch(e){case nW:t(nH()&&navigator?.onLine);break;case nL:t(hM());break;default:t(!0)}})}async function hM(){if(nK()&&null!=e.g&&e.g.NetInfo){let t=await (null==e.g?void 0:e.g.NetInfo.fetch());return t?.isConnected}return!0}let hL={};class hB{static get(e){return hL[e]}static set(e,t){hL[e]=t}static delete(e){delete hL[e]}}function hW(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function hq({logger:e,name:t}){var i,r,s,n,a;let o,l,c,h,d="string"==typeof e?("u">typeof(i={opts:{level:e,name:t}}).loggerOverride&&"string"!=typeof i.loggerOverride?{logger:i.loggerOverride,chunkLoggerController:null}:"u">typeof window?(c=new ng(null==(n=(s=i).opts)?void 0:n.level,s.maxSizeInBytes),{logger:(0,nn.default)((o=nA({},s.opts),l={level:"trace",browser:nb(nA({},null==(a=s.opts)?void 0:a.browser),nv({write:e=>c.write(e)}))},nb(o,nv(l)))),chunkLoggerController:c}):(h=new nm(null==(r=i.opts)?void 0:r.level,i.maxSizeInBytes),{logger:(0,nn.default)(nb(nA({},i.opts),nv({level:"trace"})),h),chunkLoggerController:h})).logger:e;return d.level="string"==typeof e?e:e.level,d}var hK=e.i(180476),hH=e.i(499276),hz=e.i(852532);let h$="custom_context";var hJ=Object.defineProperty,hF=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?hJ(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class hV{constructor(e){hF(this,"nodeValue"),hF(this,"sizeInBytes"),hF(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 hG{constructor(e){hF(this,"lengthInNodes"),hF(this,"sizeInBytes"),hF(this,"head"),hF(this,"tail"),hF(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){let t=new hV(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 hY=Object.defineProperty,hZ=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?hY(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class hQ{constructor(e,t=1024e3){hZ(this,"logs"),hZ(this,"level"),hZ(this,"levelValue"),hZ(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=hz.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new hG(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===hz.levels.values.error?console.error(e):t===hz.levels.values.warn?console.warn(e):t===hz.levels.values.debug||hz.levels.values.trace}appendToLogs(e){this.logs.append((0,na.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 hG(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){let t=this.getLogArray();return t.push((0,na.safeJsonStringify)({extraMetadata:e})),new Blob(t,{type:"application/json"})}}var hX=Object.defineProperty;class h0{constructor(e,t=1024e3){((e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?hX(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(this,"baseChunkLogger"),this.baseChunkLogger=new hQ(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 h1=Object.defineProperty;class h2{constructor(e,t=1024e3){((e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?h1(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(this,"baseChunkLogger"),this.baseChunkLogger=new hQ(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 h3=Object.defineProperty,h5=Object.defineProperties,h8=Object.getOwnPropertyDescriptors,h4=Object.getOwnPropertySymbols,h6=Object.prototype.hasOwnProperty,h7=Object.prototype.propertyIsEnumerable,h9=(e,t,i)=>t in e?h3(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,de=(e,t)=>{for(var i in t||(t={}))h6.call(t,i)&&h9(e,i,t[i]);if(h4)for(var i of h4(t))h7.call(t,i)&&h9(e,i,t[i]);return e};function dt(e,t=h$){return e[t]||""}function di(e,t,i=h$){let r=function(e,t,i=h$){let r=dt(e,i);return r.trim()?`${r}/${t}`:t}(e,t,i);return function(e,t,i=h$){return e[i]=t,e}(e.child({context:r}),r,i)}var dr=e.i(81775),ds=Object.defineProperty,dn=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?ds(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class da extends dr.IEvents{constructor(e){super(),this.opts=e,dn(this,"protocol","wc"),dn(this,"version",2)}}var dl=Object.defineProperty;class dc 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?dl(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i})(this,"records",new Map)}}class dh{constructor(e,t){this.logger=e,this.core=t}}class dd extends dr.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}class du extends dr.IEvents{constructor(e){super()}}class dp{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}}class df extends dr.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}class dg extends dr.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}}class dy{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}}class dm{constructor(e,t){this.projectId=e,this.logger=t}}class dw{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}}var db=Object.defineProperty,dv=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?db(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};iL.default;class dE{constructor(e){this.opts=e,dv(this,"protocol","wc"),dv(this,"version",2)}}iL.EventEmitter;class d_{constructor(e){this.client=e}}var dI=e.i(501365);e.i(424047);var dS=e.i(329193),dA=e.i(850967),dx=e.i(112324);let dP="core",dC=`wc@2:${dP}:`,dk={database:":memory:"},dO="client_ed25519_seed",dT=iq.ONE_DAY,dR=iq.SIX_HOURS,dN="wss://relay.walletconnect.org",dj="relayer_message",dD="relayer_message_ack",dU="relayer_connection_stalled",dM="relayer_publish",dL="payload",dB="connect",dW="disconnect",dq="error",dK="2.22.4",d
15H="link_mode",dz="relay",d$="inbound",dJ="WALLETCONNECT_LINK_MODE_APPS",dF="subscription_created",dV="subscription_deleted",dG=(iq.THIRTY_DAYS,iq.FIVE_SECONDS,iq.THIRTY_DAYS,{wc_pairingDelete:{req:{ttl:iq.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:iq.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:iq.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:iq.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:iq.ONE_DAY,prompt:!1,tag:0},res:{ttl:iq.ONE_DAY,prompt:!1,tag:0}}}),dY="pairing_create",dZ="pairing_delete",dQ="history_created",dX="history_updated",d0="history_deleted",d1="expirer_created",d2="expirer_deleted",d3="expirer_expired",d5=(iq.ONE_DAY,"https://verify.walletconnect.org"),d8=`${d5}/v3`,d4=["https://verify.walletconnect.com",d5],d6="malformed_pairing_uri",d7="session_approve_started";var d9=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 ue=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 ut{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 ui{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 us(this,e)}}class ur{constructor(e){this.decoders=e}or(e){return us(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 us=(e,t)=>new ur({...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 ut(e,t,i),this.decoder=new ui(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}let ua=({name:e,prefix:t,encode:i,decode:r})=>new un(e,t,i,r),uo=({prefix:e,name:t,alphabet:i})=>{let{encode:r,decode:s}=d9(i,t);return ua({prefix:e,name:t,encode:r,decode:e=>ue(s(e))})},ul=({name:e,prefix:t,bitsPerChar:i,alphabet:r})=>ua({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}
15)(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 uc=Object.freeze({__proto__:null,identity:ua({prefix:"\0",name:"identity",encode:e=>new TextDecoder().decode(e),decode:e=>new TextEncoder().encode(e)})}),uh=Object.freeze({__proto__:null,base2:ul({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})}),ud=Object.freeze({__proto__:null,base8:ul({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})}),uu=Object.freeze({__proto__:null,base10:uo({prefix:"9",name:"base10",alphabet:"0123456789"})}),up=Object.freeze({__proto__:null,base16:ul({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper:ul({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})}),uf=Object.freeze({__proto__:null,base32:ul({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),base32upper:ul({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),base32pad:ul({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),base32padupper:ul({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),base32hex:ul({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),base32hexupper:ul({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),base32hexpad:ul({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),base32hexpadupper:ul({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),base32z:ul({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})}),ug=Object.freeze({__proto__:null,base36:uo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),base36upper:uo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})}),uy=Object.freeze({__proto__:null,base58btc:uo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),base58flickr:uo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})}),um=Object.freeze({__proto__:null,base64:ul({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad:ul({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url:ul({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad:ul({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});let uw=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ub=uw.reduce((e,t,i)=>(e[i]=t,e),[]),uv=uw.reduce((e,t,i)=>(e[t.codePointAt(0)]=i,e),[]);var uE=Object.freeze({__proto__:null,base256emoji:ua({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>
15e+=ub[t],"")},decode:function(e){let t=[];for(let i of e){let e=uv[i.codePointAt(0)];if(void 0===e)throw Error(`Non-base256emoji character: ${i}`);t.push(e)}return new Uint8Array(t)}})});function u_(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,u_.bytes=i-r+1,t}var uI=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 uS=(e,t,i=0)=>(u_(e,t,i),t),uA=(e,t)=>{let i=t.byteLength,r=uI(e),s=r+uI(i),n=new Uint8Array(s+i);return uS(e,n,0),uS(i,n,r),n.set(t,s),new ux(e,i,t,n)};class ux{constructor(e,t,i,r){this.code=e,this.size=t,this.digest=i,this.bytes=r}}let uP=({name:e,code:t,encode:i})=>new uC(e,t,i);class uC{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?uA(this.code,t):t.then(e=>uA(this.code,e))}throw Error("Unknown type, must be binary type")}}let uk=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t));var uO=Object.freeze({__proto__:null,sha256:uP({name:"sha2-256",code:18,encode:uk("SHA-256")}),sha512:uP({name:"sha2-512",code:19,encode:uk("SHA-512")})}),uT=Object.freeze({__proto__:null,identity:{code:0,name:"identity",encode:ue,digest:e=>uA(0,ue(e))}});new TextEncoder,new TextDecoder;let uR={...uc,...uh,...ud,...uu,...up,...uf,...ug,...uy,...um,...uE};function uN(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function uj(e,t,i,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:i},decoder:{decode:r}}}({...uO,...uT});let uD=uj("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),uU=uj("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?uN(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}),uM={utf8:uD,"utf-8":uD,hex:uR.base16,latin1:uU,ascii:uU,binary:uU,...uR};var uL=Object.defineProperty,uB=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?uL(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class uW{constructor(e,t){this.core=e,this.logger=t,uB(this,"keychain",new Map),uB(this,"name","keychain"),uB(this,"version","0.3"),uB(this,"initialized",!1),uB(this,"storagePrefix",dC),uB(this,"init",async()=>{if(!this.initialized){let e=await this.getKeyChain();"u">typeof e&&(this.keychain=e),this.initialized=!0}}),uB(this,"has",e=>(this.isInitialized(),this.keychain.has(e))),uB(this,"set",async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()}),uB(this,"get",e=>{this.isInitialized();let t=this.keychain.get(e);if(typeof t>"u"){let{message:t}=hv("NO_MATCHING_KEY",`${this.name}: ${e}`);throw Error(t)}return t}),uB(this,"del",async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()}),this.core=e,this.logger=di(t,this.name)}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,nG(e))}async getKeyChain(){let e=await this.core.storage.getItem(this.storageKey);return"u">typeof e?nY(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:e}=hv("NOT_INITIALIZED",this.name);throw Error(e)}}}var uq=Object.defineProperty,uK=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?uq(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class uH{constructor(e,t,i){this.core=e,this.logger=t,uK(this,"name","crypto"),uK(this,"keychain"),uK(this,"randomSessionIdentifier",cz()),uK(this,"initialized",!1),uK(this,"clientId"),uK(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),uK(this,"hasKeys",e=>(this.isInitialized(),this.keychain.has(e))),uK(this,"getClientId",async()=>
15{if(this.isInitialized(),this.clientId)return this.clientId;let e=await this.getClientSeed(),t=s9.generateKeyPair(e),i=s9.encodeIss(t.publicKey);return this.clientId=i,i}),uK(this,"generateKeyPair",()=>{let e,t;this.isInitialized();let i=(e=cw.utils.randomPrivateKey(),t=cw.getPublicKey(e),{privateKey:(0,ne.toString)(e,cW),publicKey:(0,ne.toString)(t,cW)});return this.setPrivateKey(i.publicKey,i.privateKey)}),uK(this,"signJWT",async e=>{this.isInitialized();let t=await this.getClientSeed(),i=s9.generateKeyPair(t),r=this.randomSessionIdentifier;return await s9.signJWT(r,e,dT,i)}),uK(this,"generateSharedKey",(e,t,i)=>{var r,s,n;let a,o;this.isInitialized();let l=(r=this.getPrivateKey(e),a=cw.getSharedSecret((0,nt.fromString)(r,cW),(0,nt.fromString)(t,cW)),s=void 0,o=function(e,t,i,r=32){aI(e),aE(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=lw);let a=new Uint8Array(n*s),o=ly.create(e,t),l=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let e=0;e<n;e++)lm[0]=e+1,l.update(0===e?lw:c).update(i).update(lm).digestInto(c),a.set(c,s*e),o._cloneInto(l);return o.destroy(),l.destroy(),aP(c,lm),a.slice(0,r)}(op,(n=void 0,aI(op),void 0===n&&(n=new Uint8Array(op.outputLen)),ly(op,aW(n),aW(a))),s,32),(0,ne.toString)(o,cW));return this.setSymKey(l,i)}),uK(this,"setSymKey",async(e,t)=>{this.isInitialized();let i=t||c$(e);return await this.keychain.set(i,e),i}),uK(this,"deleteKeyPair",async e=>{this.isInitialized(),await this.keychain.del(e)}),uK(this,"deleteSymKey",async e=>{this.isInitialized(),await this.keychain.del(e)}),uK(this,"encode",async(e,t,i)=>{this.isInitialized();let r=cX(i),s=(0,na.safeJsonStringify)(t);if(2===r.type){var n;let e,t,r;return n=i?.encoding,e=cF(2),t=az(12),r=cZ({type:e,sealed:(0,nt.fromString)(s,cH),iv:t}),n===cK?cG(r):r}if(c0(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=cF("u">typeof e.type?e.type:0);if(1===cV(t)&&typeof e.senderPublicKey>"u")throw Error("Missing sender public key for type 1 envelope");let i="u">typeof e.senderPublicKey?(0,nt.fromString)(e.senderPublicKey,cW):void 0,r="u">typeof e.iv?(0,nt.fromString)(e.iv,cW):az(12),s=cZ({type:t,sealed:lf((0,nt.fromString)(e.symKey,cW),r).encrypt((0,nt.fromString)(e.message,cH)),iv:r,senderPublicKey:i});return e.encoding===cK?cG(s):s}({type:o,symKey:a,message:s,senderPublicKey:l,encoding:i?.encoding})}),uK(this,"decode",async(e,t,i)=>{let r;this.isInitialized();let s=cX({type:cV((r=cQ({encoded:t,encoding:i?.encoding})).type),senderPublicKey:"u">typeof r.senderPublicKey?(0,ne.toString)(r.senderPublicKey,cW):void 0,receiverPublicKey:i?.receiverPublicKey});if(2===s.type){let e=function(e,t){let{sealed:i}=cQ({encoded:e,encoding:t});return(0,ne.toString)(i,cH)}(t,i?.encoding);return(0,na.safeJsonParse)(e)}if(c0(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,nt.fromString)(e.symKey,cW),{sealed:i,iv:r}=cQ({encoded:e.encoded,encoding:e.encoding}),s=lf(t,r).decrypt(i);if(null===s)throw Error("Failed to decrypt");return(0,ne.toString)(s,cH)}({symKey:r,encoded:t,encoding:i?.encoding});return(0,na.safeJsonParse)(s)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}}),uK(this,"getPayloadType",(e,t=cq)=>cV(cQ({encoded:e,encoding:t}).type)),uK(this,"getPayloadSenderPublicKey",(e,t=cq)=>{let i=cQ({encoded:e,encoding:t});return i.senderPublicKey?(0,ne.toString)(i.senderPublicKey,cW):void 0}),this.core=e,this.logger=di(t,this.name),this.keychain=i||new uW(this.core,this.logger)}get context(){return dt(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(dO)}catch{e=cz(),await this.keychain.set(dO,e)}return function(e,t="utf8"){let i=uM[t];if(!i)throw Error(`Unsupported encoding "${t}"`);return("utf8"===t||"utf-8"===t)&&null!=globalThis.Buffer&&null!=globalThis.Buffer.from?uN(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}=hv("NOT_INITIALIZED",this.name);throw Error(e)}}}var uz=Object.defineProperty,u$=Object.defineProperties,uJ=Object.getOwnPropertyDescriptors,uF=Object.getOwnPropertySymbols,uV=Object.prototype.hasOwnProperty,uG=Object.prototype.propertyIsEnumerable,uY=(e,t,i)=>t in e?uz(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,uZ=(e,t,i)=>uY(e,"symbol"!=typeof t?t+"":t,i);class uQ extends dh{constructor(e,t){super(e,t),this.logger=e,this.core=t,uZ(this,"messages",new Map),uZ(this,"messagesWithoutClientAck",new Map),uZ(this,"name","messages"),uZ(this,"version","0.3"),uZ(this,"initialized",!1),uZ(this,"storagePrefix",dC),uZ(this,"init",async()=>
15{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}}}),uZ(this,"set",async(e,t,i)=>{this.isInitialized();let r=cJ(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===d$){let i=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,u$(((e,t)=>{for(var i in t||(t={}))uV.call(t,i)&&uY(e,i,t[i]);if(uF)for(var i of uF(t))uG.call(t,i)&&uY(e,i,t[i]);return e})({},i),uJ({[r]:t})))}return await this.persist(),r}),uZ(this,"get",e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t}),uZ(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}),uZ(this,"has",(e,t)=>(this.isInitialized(),"u">typeof this.get(e)[cJ(t)])),uZ(this,"ack",async(e,t)=>{this.isInitialized();let i=this.messagesWithoutClientAck.get(e);if(typeof i>"u")return;let r=cJ(t);delete i[r],0===Object.keys(i).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,i),await this.persist()}),uZ(this,"del",async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()}),this.logger=di(e,this.name),this.core=t}get context(){return dt(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,nG(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,nG(e))}async getRelayerMessages(){let e=await this.core.storage.getItem(this.storageKey);return"u">typeof e?nY(e):void 0}async getRelayerMessagesWithoutClientAck(){let e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return"u">typeof e?nY(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){let{message:e}=hv("NOT_INITIALIZED",this.name);throw Error(e)}}}var uX=Object.defineProperty,u0=Object.defineProperties,u1=Object.getOwnPropertyDescriptors,u2=Object.getOwnPropertySymbols,u3=Object.prototype.hasOwnProperty,u5=Object.prototype.propertyIsEnumerable,u8=(e,t,i)=>t in e?uX(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,u4=(e,t)=>{for(var i in t||(t={}))u3.call(t,i)&&u8(e,i,t[i]);if(u2)for(var i of u2(t))u5.call(t,i)&&u8(e,i,t[i]);return e},u6=(e,t,i)=>u8(e,"symbol"!=typeof t?t+"":t,i);class u7 extends dd{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,u6(this,"events",new iL.EventEmitter),u6(this,"name","publisher"),u6(this,"queue",new Map),u6(this,"publishTimeout",(0,iq.toMiliseconds)(iq.ONE_MINUTE)),u6(this,"initialPublishTimeout",(0,iq.toMiliseconds)(15*iq.ONE_SECOND)),u6(this,"needsTransportRestart",!1),u6(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||dR,c=i?.prompt||!1,h=i?.tag||0,d=i?.id||(0,dS.getBigIntRpcId)().toString(),u=c2(c1().protocol),p={id:d,method:i?.publishMethod||u.publish,params:u4({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{hS(null==(r=p.params)?void 0:r.prompt)&&(null==(s=p.params)||delete s.prompt),hS(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(dM,t),e())};this.relayer.events.on(dM,t);let r=nQ(new Promise((e,t)=>
15{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(dM,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 nQ(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)}}),u6(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=iq.FIVE_MINUTES}=o,f=o.id||(0,dS.getBigIntRpcId)().toString(),g=c2(c1().protocol),y=h||g.publish,m={id:f,method:y,params:u4(u0(u4({},a),u1({ttl:p,prompt:d,tag:u,attestation:l})),c)},w=`Failed to publish custom payload, please try again. id:${f} tag:${u}`;try{hS(null==(t=m.params)?void 0:t.prompt)&&(null==(i=m.params)||delete i.prompt),hS(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(dM,t),e())};this.relayer.events.on(dM,t);let i=nQ(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(dM,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 nQ(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)}}),u6(this,"on",(e,t)=>{this.events.on(e,t)}),u6(this,"once",(e,t)=>{this.events.once(e,t)}),u6(this,"off",(e,t)=>{this.events.off(e,t)}),u6(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.relayer=e,this.logger=di(t,this.name),this.registerEventListeners()}get context(){return dt(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(dM,u4(u4({},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,u0(u4({},e),u1({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(hK.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(dU);return}this.checkQueue()}),this.relayer.on(dD,e=>{this.removeRequestFromQueue(e.id.toString())})}}var u9=Object.defineProperty,pe=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?u9(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class pt{constructor(){pe(this,"map",new Map),pe(this,"set",(e,t)=>{let i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),pe(this,"get",e=>this.map.get(e)||[]),pe(this,"exists",(e,t)=>this.get(e).includes(t)),pe(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)}),pe(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var pi=Object.defineProperty,pr=Object.defineProperties,ps=Object.getOwnPropertyDescriptors,pn=Object.getOwnPropertySymbols,pa=Object.prototype.hasOwnProperty,po=Object.prototype.propertyIsEnumerable,pl=(e,t,i)=>t in e?pi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,pc=(e,t)=>{for(var i in t||(t={}))pa.call(t,i)&&pl(e,i,t[i]);if(pn)for(var i of pn(t))po.call(t,i)&&pl(e,i,t[i]);return e},ph=(e,t,i)=>pl(e,"symbol"!=typeof t?t+"":t,i);class pd extends df{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ph(this,"subscriptions",new Map),ph(this,"topicMap",new pt),ph(this,"events",new iL.EventEmitter),ph(this,"name","subscription"),ph(this,"version","0.3"),ph(this,"pending",new Map),ph(this,"cac
15hed",[]),ph(this,"initialized",!1),ph(this,"storagePrefix",dC),ph(this,"subscribeTimeout",(0,iq.toMiliseconds)(iq.ONE_MINUTE)),ph(this,"initialSubscribeTimeout",(0,iq.toMiliseconds)(15*iq.ONE_SECOND)),ph(this,"clientId"),ph(this,"batchSubscribeTopicsLimit",500),ph(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ph(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=c1(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}}),ph(this,"unsubscribe",async(e,t)=>{this.isInitialized(),"u">typeof t?.id?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)}),ph(this,"isSubscribed",e=>new Promise(t=>{t(this.topicMap.topics.includes(e))})),ph(this,"isKnownTopic",e=>new Promise(t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some(t=>t.topic===e))})),ph(this,"on",(e,t)=>{this.events.on(e,t)}),ph(this,"once",(e,t)=>{this.events.once(e,t)}),ph(this,"off",(e,t)=>{this.events.off(e,t)}),ph(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),ph(this,"start",async()=>{await this.onConnect()}),ph(this,"stop",async()=>{await this.onDisconnect()}),ph(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ph(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)}),ph(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(hK.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.events.on(dF,async e=>{this.logger.info(`Emitting ${dF}`),this.logger.debug({type:"event",event:dF,data:e}),await this.persist()}),this.events.on(dV,async e=>{this.logger.info(`Emitting ${dV}`),this.logger.debug({type:"event",event:dV,data:e}),await this.persist()})}),this.relayer=e,this.logger=di(t,this.name),this.clientId=""}get context(){return dt(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=c1(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);let s=hE("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;
15let n=await this.getSubscriptionId(e);if(null!=(r=i?.internal)&&r.skipSubscribe)return n;i&&i?.transportType!==dz||await this.restartToComplete({topic:e,id:e,relay:t});let a={method:c2(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===dH)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(e=>this.logger.warn(e))},(0,iq.toMiliseconds)(iq.ONE_SECOND)),n;let t=new Promise(async t=>{let i=r=>{r.topic===e&&(this.events.removeListener(dF,i),t(r.id))};this.events.on(dF,i);try{let r=await nQ(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(dF,i),t(r)}catch{}}),r=await nQ(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(dU),o)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return;let t={method:c2(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 nQ(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(dU)}}async rpcBatchFetchMessages(e){let t;if(!e.length)return;let i={method:c2(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 nQ(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(dU)}return t}rpcUnsubscribe(e,t,i){let r={method:c2(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,pr(pc({},t),ps({id:e}))),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(e=>{this.setSubscription(e.id,pc({},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,pc({},t)),this.topicMap.set(t.topic,e),this.events.emit(dF,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}=hv("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(dV,pr(pc({},i),ps({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")}
15async 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}=hv("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=>pr(pc({},e),ps({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,iq.toMiliseconds)(iq.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}=hv("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 cJ(e+await this.getClientId())}}var pu=Object.defineProperty,pp=Object.getOwnPropertySymbols,pf=Object.prototype.hasOwnProperty,pg=Object.prototype.propertyIsEnumerable,py=(e,t,i)=>t in e?pu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,pm=(e,t)=>{for(var i in t||(t={}))pf.call(t,i)&&py(e,i,t[i]);if(pp)for(var i of pp(t))pg.call(t,i)&&py(e,i,t[i]);return e},pw=(e,t,i)=>py(e,"symbol"!=typeof t?t+"":t,i);class pb extends du{constructor(t){var i;super(t),pw(this,"protocol","wc"),pw(this,"version",2),pw(this,"core"),pw(this,"logger"),pw(this,"events",new iL.EventEmitter),pw(this,"provider"),pw(this,"messages"),pw(this,"subscriber"),pw(this,"publisher"),pw(this,"name","relayer"),pw(this,"transportExplicitlyClosed",!1),pw(this,"initialized",!1),pw(this,"connectionAttemptInProgress",!1),pw(this,"relayUrl"),pw(this,"projectId"),pw(this,"packageName"),pw(this,"bundleId"),pw(this,"hasExperiencedNetworkDisruption",!1),pw(this,"pingTimeout"),pw(this,"heartBeatTimeout",(0,iq.toMiliseconds)(iq.THIRTY_SECONDS+iq.FIVE_SECONDS)),pw(this,"reconnectTimeout"),pw(this,"connectPromise"),pw(this,"reconnectInProgress",!1),pw(this,"requestsInFlight",[]),pw(this,"connectTimeout",(0,iq.toMiliseconds)(15*iq.ONE_SECOND)),pw(this,"request",async e=>{var t,i;this.logger.debug("Publishing Request Payload");let r=e.id||(0,dS.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}}),pw(this,"resetPingTimeout",()=>{nq()&&(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))}),pw(this,"onPayloadHandler",e=>{this.onProviderPayload(e),this.resetPingTimeout()}),pw(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit("relayer_connect")}),pw(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),pw(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()}),pw(this,"registerProviderListeners",()=>{this.provider.on(dL,this.onPayloadHandler),this.provider.on(dB,this.onConnectHandler),this.provider.on(dW,this.onDisconnectHandler),this.provider.on(dq,this.onProviderErrorHandler)}),this.core=t.core,this.logger=hq({logger:null!=(i=t.logger)?i:"error",name:this.name}),this.messages=new uQ(this.logger,t.core),this.subscriber=new pd(this,this.logger),this.publisher=new u7(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||dN,nK()&&"u">typeof(null==e.g?void 0:e.g.Platform)&&(null==e.g?void 0:e.g.Platform.OS)==="android"?this.packageName=n$():nK()&&"u">typeof(null==e.g?void 0:e.g.Platform)&&(null==e.g?void 0:e.g.Platform.OS)==="ios"&&(this.bundleId=n$()),this.provider={}}
15async 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 dt(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:dz},"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(dF,l),o())};return await Promise.all([new Promise(e=>{o=e,this.subscriber.on(dF,l)}),new Promise(async(i,r)=>{a=await this.subscriber.subscribe(e,pm({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 nQ(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 hU())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=n1(iq.FIVE_MINUTES);await this.core.pairing.pairings.set(i,{topic:i,expiry:e,relay:{protocol:"irn"},active:!1})}this.events.emit(dj,e),await this.recordMessageEvent(e,d$)}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=()=>{t(Error("Connection interrupted while trying to connect"))};this.provider.once(dW,i),await nQ(new Promise((e,t)=>
15{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(dW,i),clearTimeout(this.reconnectTimeout)}),await new Promise(async(e,i)=>{let r=()=>{t(Error("Connection interrupted while trying to subscribe"))};this.provider.once(dW,r),await this.subscriber.start().then(e).catch(i).finally(()=>{this.provider.off(dW,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,iq.toMiliseconds)(+t))),t++}}startPingTimeout(){var e,t,i,r,s;if(nq())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 dI.JsonRpcProvider(new dx.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=nF(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:dK,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,dA.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:dz,attestation:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(pm({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else(0,dA.isJsonRpcResponse)(e)&&this.events.emit(dD,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,d$),this.events.emit(dj,e))}async acknowledgePayload(e){let t=(0,dS.formatJsonRpcResult)(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(dL,this.onPayloadHandler),this.provider.off(dB,this.onConnectHandler),this.provider.off(dW,this.onDisconnectHandler),this.provider.off(dq,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await hU();(function(t){var i,r;switch(nz()){case nW:i=t,!nK()&&nH()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)));break;case nL:r=t,nK()&&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(hK.HEARTBEAT_EVENTS.pulse,async()=>{var e;if(!this.transportExplicitlyClosed&&!this.connected&&(!(nH()&&(0,iK.getDocument)())||
15(null==(e=(0,iK.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,iq.toMiliseconds)(.1)))))}isInitialized(){if(!this.initialized){let{message:e}=hv("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 pv(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function pE(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}let p_="[object Arguments]",pI="[object Object]";function pS(){}function pA(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 px=Object.defineProperty,pP=Object.getOwnPropertySymbols,pC=Object.prototype.hasOwnProperty,pk=Object.prototype.propertyIsEnumerable,pO=(e,t,i)=>t in e?px(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,pT=(e,t)=>{for(var i in t||(t={}))pC.call(t,i)&&pO(e,i,t[i]);if(pP)for(var i of pP(t))pk.call(t,i)&&pO(e,i,t[i]);return e},pR=(e,t,i)=>pO(e,"symbol"!=typeof t?t+"":t,i);class pN extends dp{constructor(e,t,i,r=dC,s){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,pR(this,"map",new Map),pR(this,"version","0.3"),pR(this,"cached",[]),pR(this,"initialized",!1),pR(this,"getKey"),pR(this,"storagePrefix",dC),pR(this,"recentlyDeleted",[]),pR(this,"recentlyDeletedLimit",200),pR(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>{var t;this.getKey&&null!==e&&!hS(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)}),pR(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())}),pR(this,"get",e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e))),pR(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=pE(i),o=pE(r);if(a===p_&&(a=pI),o===p_&&(o=pI),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
15]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object BigInt64Array]":case"[object Float32Array]":case"[object Float64Array]":if("u">typeof G.Buffer&&G.Buffer.isBuffer(i)!==G.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 pI:{if(!(t(i.constructor,r.constructor,s,n)||pA(i)&&pA(r)))return!1;let a=[...Object.keys(i),...pv(i)],o=[...Object.keys(r),...pv(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,pS)})):this.values)),pR(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=pT(pT({},this.getData(e)),t);this.map.set(e,i),await this.persist()}),pR(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=di(t,this.name),this.storagePrefix=r,this.getKey=s}get context(){return dt(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}=hv("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),Error(t)}let{message:t}=hv("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}=hv("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}=hv("NOT_INITIALIZED",this.name);throw Error(e)}}}var pj=Object.defineProperty,pD=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?pj(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class pU{constructor(e,t){this.core=e,this.logger=t,pD(this,"name","pairing"),pD(this,"version","0.3"),pD(this,"events",new iL.default),pD(this,"pairings"),pD(this,"initialized",!1),pD(this,"storagePrefix",dC),pD(this,"ignoredPayloadTypes",[1]),pD(this,"registeredMethods",[]),pD(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),pD(this,"register",({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]}),pD(this,"create",async e=>{this.isInitialized();let t=cz(),i=await this.core.crypto.setSymKey(t),r=n1(iq.FIVE_MINUTES),s={protocol:"irn"},n={topic:i,expiry:r,relay:s,active:!1,methods:e?.methods},a=hi({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:t,relay:s,expiryTimestamp:r,methods:e?.methods});return this.events.emit(dY,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}}),pD(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}=ht(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.`);
15i.addTrace("pairing_not_expired")}let l=a||n1(iq.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(dY,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}),pD(this,"activate",async({topic:e})=>{this.isInitialized();let t=n1(iq.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})}),pD(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}=nZ();this.events.once(n3("pairing_ping",e),({error:e})=>{e?s(e):r()}),await i()}}),pD(this,"updateExpiry",async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})}),pD(this,"updateMetadata",async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})}),pD(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),pD(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",hE("USER_DISCONNECTED")),await this.deletePairing(t))}),pD(this,"formatUriFromPairing",e=>{this.isInitialized();let{topic:t,relay:i,expiry:r,methods:s}=e,n=this.core.crypto.keychain.get(t);return hi({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:n,relay:i,expiryTimestamp:r,methods:s})}),pD(this,"sendRequest",async(e,t,i)=>{let r=(0,dS.formatJsonRpcRequest)(t,i),s=await this.core.crypto.encode(e,r),n=dG[t].req;return this.core.history.set(e,r),this.core.relayer.publish(e,s,n),r.id}),pD(this,"sendResult",async(e,t,i)=>{let r=(0,dS.formatJsonRpcResult)(e,i),s=await this.core.crypto.encode(t,r),n=dG[(await this.core.history.get(t,e)).request.method].res;await this.core.relayer.publish(t,s,n),await this.core.history.resolve(r)}),pD(this,"sendError",async(e,t,i)=>{let r=(0,dS.formatJsonRpcError)(e,i),s=await this.core.crypto.encode(t,r),n=(await this.core.history.get(t,e)).request.method,a=dG[n]?dG[n].res:dG.unregistered_method.res;await this.core.relayer.publish(t,s,a),await this.core.history.resolve(r)}),pD(this,"deletePairing",async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,hE("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])}),pD(this,"cleanup",async()=>{let e=this.pairings.getAll().filter(e=>n2(e.expiry));await Promise.all(e.map(e=>this.deletePairing(e.topic)))}),pD(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)}}),pD(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)}),pD(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)}}),pD(this,"onPairingPingResponse",(e,t)=>{let{id:i}=t;setTimeout(()=>{(0,dA.isJsonRpcResult)(t)?this.events.emit(n3("pairing_ping",i),{}):(0,dA.isJsonRpcError)(t)&&this.events.emit(n3("pairing_ping",i),{error:t.error})},500)}),pD(this,"onPairingDeleteRequest",async(e,t)=>{let{id:i}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(dZ,{id:i,topic:e})}catch(t){await this.sendError(i,e,t),this.logger.error(t)}}),pD(this,"onUnknownRpcMethodRequest",async(e,t)=>{let{id:i,method:r}=t;try{if(this.registeredMethods.includes(r))return;let t=hE("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)}}),pD(this,"onUnknownRpcMethodResponse",e=>{this.registeredMethods.includes(e)||this.logger.error(hE("WC_METHOD_UNSUPPORTED",e))}),pD(this,"isValidPair",(e,t)=>{var i;if(!hR(e)){let{message:i}=hv("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(d6),Error(i)}if(!function(e){function t(e){try{return"u">typeof new URL(e)}catch{return!1}}try{if(hA(e,!1)){if(t(e))return!0;let i=ae(e);return t(i)}}catch{}return!1}(e.uri)){let{message:i}=hv("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(d6),Error(i)}let r=ht(e?.uri);if(!(null!=(i=r?.relay)&&i.protocol)){let{message:e}=hv("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(d6),Error(e)}if(!(null!=r&&r.symKey)){let{message:e}=hv("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(d6),Error(e)}if(null!=r&&r.expiryTimestamp&&(0,iq.toMiliseconds)(r?.expiryTimestamp)<Date.now()){t.setError("pairing_expired");let{message:e}=hv("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw Error(e)}}),pD(this,"isValidPing",async e=>
15{if(!hR(e)){let{message:t}=hv("MISSING_OR_INVALID",`ping() params: ${e}`);throw Error(t)}let{topic:t}=e;await this.isValidPairingTopic(t)}),pD(this,"isValidDisconnect",async e=>{if(!hR(e)){let{message:t}=hv("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw Error(t)}let{topic:t}=e;await this.isValidPairingTopic(t)}),pD(this,"isValidPairingTopic",async e=>{if(!hA(e,!1)){let{message:t}=hv("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw Error(t)}if(!this.pairings.keys.includes(e)){let{message:t}=hv("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw Error(t)}if(n2(this.pairings.get(e).expiry)){await this.deletePairing(e);let{message:t}=hv("EXPIRED",`pairing topic: ${e}`);throw Error(t)}}),this.core=e,this.logger=di(t,this.name),this.pairings=new pN(this.core,this.logger,this.name,this.storagePrefix)}get context(){return dt(this.logger)}isInitialized(){if(!this.initialized){let{message:e}=hv("NOT_INITIALIZED",this.name);throw Error(e)}}registerRelayerEvents(){this.core.relayer.on(dj,async e=>{let{topic:t,message:i,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==dH&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{let e=await this.core.crypto.decode(t,i);(0,dA.isJsonRpcRequest)(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):(0,dA.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(d3,async e=>{let{topic:t}=n0(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit("pairing_expire",{topic:t}))})}}var pM=Object.defineProperty,pL=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?pM(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class pB extends dc{constructor(e,t){super(e,t),this.core=e,this.logger=t,pL(this,"records",new Map),pL(this,"events",new iL.EventEmitter),pL(this,"name","history"),pL(this,"version","0.3"),pL(this,"cached",[]),pL(this,"initialized",!1),pL(this,"storagePrefix",dC),pL(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)}),pL(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:n1(iq.THIRTY_DAYS)};this.records.set(r.id,r),this.persist(),this.events.emit(dQ,r)}),pL(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,dA.isJsonRpcError)(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit(dX,t))}),pL(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))),pL(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(d0,i)))}),this.persist()}),pL(this,"exists",async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e)),pL(this,"on",(e,t)=>{this.events.on(e,t)}),pL(this,"once",(e,t)=>{this.events.once(e,t)}),pL(this,"off",(e,t)=>{this.events.off(e,t)}),pL(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=di(t,this.name)}get context(){return dt(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=[];
15return this.values.forEach(t=>{if("u">typeof t.response)return;let i={topic:t.topic,request:(0,dS.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}=hv("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}=hv("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(dQ,e=>{this.logger.info(`Emitting ${dQ}`),this.logger.debug({type:"event",event:dQ,record:e})}),this.events.on(dX,e=>{this.logger.info(`Emitting ${dX}`),this.logger.debug({type:"event",event:dX,record:e})}),this.events.on(d0,e=>{this.logger.info(`Emitting ${d0}`),this.logger.debug({type:"event",event:d0,record:e})}),this.core.heartbeat.on(hK.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{(0,iq.toMiliseconds)(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(d0,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){let{message:e}=hv("NOT_INITIALIZED",this.name);throw Error(e)}}}var pW=Object.defineProperty,pq=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?pW(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class pK extends dg{constructor(e,t){super(e,t),this.core=e,this.logger=t,pq(this,"expirations",new Map),pq(this,"events",new iL.EventEmitter),pq(this,"name","expirer"),pq(this,"version","0.3"),pq(this,"cached",[]),pq(this,"initialized",!1),pq(this,"storagePrefix",dC),pq(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)}),pq(this,"has",e=>{try{let t=this.formatTarget(e);return"u">typeof this.getExpiration(t)}catch{return!1}}),pq(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(d1,{target:i,expiration:r})}),pq(this,"get",e=>{this.isInitialized();let t=this.formatTarget(e);return this.getExpiration(t)}),pq(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(d2,{target:t,expiration:i})}}),pq(this,"on",(e,t)=>{this.events.on(e,t)}),pq(this,"once",(e,t)=>{this.events.once(e,t)}),pq(this,"off",(e,t)=>{this.events.off(e,t)}),pq(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=di(t,this.name)}get context(){return dt(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 nX("topic",e);if("number"==typeof e)return nX("id",e);let{message:t}=hv("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}=hv("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}=hv("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),Error(t)}return t}checkExpiry(e,t){let{expiry:i}=t;(0,iq.toMiliseconds)(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(d3,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(hK.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(d1,e=>{this.logger.info(`Emitting ${d1}`),this.logger.debug({type:"event",event:d1,data:e}),this.persist()}),this.events.on(d3,e=>{this.logger.info(`Emitting ${d3}`),this.logger.debug({type:"event",event:d3,data:e}),this.persist()}),this.events.on(d2,e=>{this.logger.info(`Emitting ${d2}`),this.logger.debug({type:"event",event:d2,data:e}),this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=hv("NOT_INITIALIZED",this.name);throw Error(e)}}}var pH=Object.defineProperty,pz=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?pH(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class p$ extends dy{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,pz(this,"name","verify-api"),pz(this,"abortController"),pz(this,"isDevEnv"),pz(this,"verifyUrlV3",d8),pz(this,"storagePrefix",dC),pz(this,"version",2),pz(this,"publicKey"),pz(this,"fetchPromise"),pz(this,"init",async()=>{var e;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,iq.toMiliseconds)(null==(e=this.publicKey)?void 0:e.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),pz(this,"register",async e=>{if(!nH()||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,iK.getDocument)(),t=this.startAbortTimer(5*iq.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,s9.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})});
15return this.logger.debug(r,"jwt attestation"),r}catch(e){this.logger.warn(e)}return""}),pz(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,s9.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)}),pz(this,"fetchAttestation",async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);let i=this.startAbortTimer(5*iq.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}),pz(this,"getVerifyUrl",e=>{let t=e||d5;return d4.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${d5}`),t=d5),t}),pz(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);let e=this.startAbortTimer(iq.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)}}),pz(this,"persistPublicKey",async e=>{this.logger.debug(e,"persisting public key to local storage"),await this.store.setItem(this.storeKey,e),this.publicKey=e}),pz(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),pz(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")}}),pz(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),pz(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}),pz(this,"validateAttestation",(e,t)=>{let i=function(e,t){let i,r,[s,n,a]=e.split("."),o=G.Buffer.from(cY(a),"base64");if(64!==o.length)throw Error("Invalid signature length");let l=o.slice(0,32),c=o.slice(32,64),h=op(`${s}.${n}`),d=(i=G.Buffer.from(t.x,"base64"),r=G.Buffer.from(t.y,"base64"),(0,ni.concat)([new Uint8Array([4]),i,r]));if(!cL.verify((0,ni.concat)([l,c]),h,d))throw Error("Invalid signature");return(0,s9.decodeJWT)(e).payload}(e,t.publicKey),r={hasExpired:(0,iq.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=di(t,this.name),this.abortController=new AbortController,this.isDevEnv=n9(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return dt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),(0,iq.toMiliseconds)(e))}}var pJ=Object.defineProperty,pF=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?pJ(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class pV extends dm{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,pF(this,"context","echo"),pF(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})})}
15),this.logger=di(t,this.context)}}var pG=Object.defineProperty,pY=Object.getOwnPropertySymbols,pZ=Object.prototype.hasOwnProperty,pQ=Object.prototype.propertyIsEnumerable,pX=(e,t,i)=>t in e?pG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,p0=(e,t)=>{for(var i in t||(t={}))pZ.call(t,i)&&pX(e,i,t[i]);if(pY)for(var i of pY(t))pQ.call(t,i)&&pX(e,i,t[i]);return e},p1=(e,t,i)=>pX(e,"symbol"!=typeof t?t+"":t,i);class p2 extends dw{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,p1(this,"context","event-client"),p1(this,"storagePrefix",dC),p1(this,"storageVersion",.1),p1(this,"events",new Map),p1(this,"shouldPersist",!1),p1(this,"init",async()=>{if(!n9())try{let e={eventId:n7(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:nF(this.core.relayer.protocol,this.core.relayer.version,dK)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}}),p1(this,"createEvent",e=>{let{event:t="ERROR",type:i="",properties:{topic:r,trace:s}}=e,n=n7(),a=this.core.projectId||"",o=p0({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}),p1(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 p0(p0({},r),this.setMethods(r.eventId))}),p1(this,"deleteEvent",e=>{let{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0}),p1(this,"setEventListeners",()=>{this.core.heartbeat.on(hK.HEARTBEAT_EVENTS.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(e=>{(0,iq.fromMiliseconds)(Date.now())-(0,iq.fromMiliseconds)(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)})})}),p1(this,"setMethods",e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)})),p1(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)}),p1(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)}),p1(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),p1(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,p0(p0({},e),this.setMethods(e.eventId)))})}catch(e){this.logger.warn(e)}}),p1(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)}}),p1(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-${dK}${t}`,{method:"POST",body:JSON.stringify(e)})}),p1(this,"getAppDomain",()=>nJ().url),this.logger=di(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 p3=Object.defineProperty,p5=Object.getOwnPropertySymbols,p8=Object.prototype.hasOwnProperty,p4=Object.prototype.propertyIsEnumerable,p6=(e,t,i)=>t in e?p3(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,p7=(e,t)=>{for(var i in t||(t={}))p8.call(t,i)&&p6(e,i,t[i]);if(p5)for(var i of p5(t))p4.call(t,i)&&p6(e,i,t[i]);return e},p9=(e,t,i)=>p6(e,"symbol"!=typeof t?t+"":t,i);class fe extends da{constructor(e){var t;super(e),p9(this,"protocol","wc"),p9(this,"version",2),p9(this,"name",dP),p9(this,"relayUrl"),p9(this,"projectId"),p9(this,"customStoragePrefix"),p9(this,"events",new iL.EventEmitter),p9(this,"logger"),p9(this,"heartbeat"),p9(this,"relayer"),p9(this,"crypto"),p9(this,"storage"),p9(this,"history"),p9(this,"expirer"),p9(this,"pairing"),p9(this,"verify"),p9(this,"echoClient"),p9(this,"linkModeSupportedApps"),p9(this,"eventClient"),p9(this,"initialized",!1),p9(this,"logChunkController"),p9(this,"on",(e,t)=>this.events.on(e,t)),p9(this,"once",(e,t)=>this.events.once(e,t)),p9(this,"off",(e,t)=>this.events.off(e,t)),p9(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),p9(this,"dispatchEnvelope",({topic:e,message:t,sessionExists:i})=>{if(!e||!t)return;let r={topic:e,message:t,publishedAt:Date.now(),transportType:dH};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||dN,this.customStoragePrefix=null!=e&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const{logger:r,chunkLoggerController:s}=function(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 h0(null==(r=(i=e).opts)?void 0:r.level,i.maxSizeInBytes),{logger:(0,hz.default)((a=de({},i.opts),o={level:"trace",browser:h5(de({},null==(s=i.opts)?void 0:s.browser),h8({write:e=>l.write(e)}))},h5(a,h8(o)))),chunkLoggerController:l}):(n=new h2(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes),{logger:(0,hz.default)(h5(de({},e.opts),h8({level:"trace"})),n),chunkLoggerController:n})}({opts:function(e){return h5(de({},e),h8({level:e?.level||"info"}))}({level:"string"==typeof e?.logger&&e.logger?e.logger:"error",name:dP}),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()}))}
15),this.logger=di(r,this.name),this.heartbeat=new hK.HeartBeat,this.crypto=new uH(this,this.logger,e?.keychain),this.history=new pB(this,this.logger),this.expirer=new pK(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new hH.default(p7(p7({},dk),e?.storageOptions)),this.relayer=new pb({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new pU(this,this.logger),this.verify=new p$(this,this.logger,this.storage),this.echoClient=new pV(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new p2(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){let t=new fe(e);await t.initialize();let i=await t.crypto.getClientId();return await t.storage.setItem("WALLETCONNECT_CLIENT_ID",i),t}get context(){return dt(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(dJ,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(dJ)||[],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 iB.default&&"true"===iB.default.env.DISABLE_GLOBAL_CORE}catch{return!0}}}let ft="client",fi=`wc@2:${ft}:`,fr="WALLETCONNECT_DEEPLINK_CHOICE",fs=(iq.THIRTY_DAYS,"Proposal expired"),fn=iq.SEVEN_DAYS,fa={wc_sessionPropose:{req:{ttl:iq.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:iq.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:iq.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:iq.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:iq.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:iq.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:iq.ONE_DAY,prompt:!1,tag:1104},res:{ttl:iq.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:iq.ONE_DAY,prompt:!1,tag:1106},res:{ttl:iq.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:iq.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:iq.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:iq.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:iq.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:iq.ONE_DAY,prompt:!1,tag:1112},res:{ttl:iq.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:iq.ONE_DAY,prompt:!1,tag:1114},res:{ttl:iq.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:iq.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:iq.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:iq.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:iq.FIVE_MINUTES,prompt:!1,tag:1119}}},fo={min:iq.FIVE_MINUTES,max:iq.SEVEN_DAYS},fl="IDLE",fc="ACTIVE",fh={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:""}
15,cosmos_signDirect:{key:""}},fd=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],fu="[email protected]:auth:",fp=`${fu}:PUB_KEY`;var ff=Object.defineProperty,fg=Object.defineProperties,fy=Object.getOwnPropertyDescriptors,fm=Object.getOwnPropertySymbols,fw=Object.prototype.hasOwnProperty,fb=Object.prototype.propertyIsEnumerable,fv=(e,t,i)=>t in e?ff(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,fE=(e,t)=>{for(var i in t||(t={}))fw.call(t,i)&&fv(e,i,t[i]);if(fm)for(var i of fm(t))fb.call(t,i)&&fv(e,i,t[i]);return e},f_=(e,t,i)=>fv(e,"symbol"!=typeof t?t+"":t,i);class fI extends d_{constructor(t){super(t),f_(this,"name","engine"),f_(this,"events",new iL.default),f_(this,"initialized",!1),f_(this,"requestQueue",{state:fl,queue:[]}),f_(this,"sessionRequestQueue",{state:fl,queue:[]}),f_(this,"emittedSessionRequests",new at({limit:500})),f_(this,"requestQueueDelay",iq.ONE_SECOND),f_(this,"expectedPairingMethodMap",new Map),f_(this,"recentlyDeletedMap",new Map),f_(this,"recentlyDeletedLimit",200),f_(this,"relayMessageCache",[]),f_(this,"pendingSessions",new Map),f_(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(fa)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,iq.toMiliseconds)(this.requestQueueDelay)))}),f_(this,"connect",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();let t=fg(fE({},e),fy({requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}}));await this.isValidConnect(t),t.optionalNamespaces=function(e,t){var i,r,s,n,a,o;let l=hy(e),c=hy(t),h={};for(let e of Object.keys(l).concat(Object.keys(c)))h[e]={chains:n5(null==(i=l[e])?void 0:i.chains,null==(r=c[e])?void 0:r.chains),methods:n5(null==(s=l[e])?void 0:s.methods,null==(n=c[e])?void 0:n.methods),events:n5(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}=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}=hv("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw Error(e)}let d=await this.client.core.crypto.generateKeyPair(),u=fa.wc_sessionPropose.req.ttl||iq.FIVE_MINUTES,p=n1(u),f=fg(fE(fE({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}),fy({id:(0,dS.payloadId)()})),g=n3("session_connect",f.id),{reject:y,resolve:m,done:w}=nZ(u,fs),b=({id:e})=>{e===f.id&&(this.client.events.off("proposal_expire",b),this.pendingSessions.delete(f.id),this.events.emit(g,{error:{message:fs,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}}),f_(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}}),f_(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:[d7]}});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:d7,properties:{topic:u,trace:[d7,"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=fE(fE(fE({relay:{protocol:a??"irn"},namespaces:o,controller:{publicKey:m,metadata:this.client.metadata},expiry:n1(fn)},l&&{sessionProperties:l}),c&&{scopedProperties:c}),h&&{sessionConfig:h});y.addTrace("subscribing_session_topic");try{await this.client.core.relayer.subscribe(b,{transportType:dz,internal:{skipSubscribe:!0}})}catch(e){throw y.setError("subscribe_session_topic_failure"),e}y.addTrace("subscribe_session_topic_success");let E=fg(fE({},v),fy({topic:b,requiredNamespaces:f,optionalNamespaces:g,pairingTopic:u,acknowledged:!1,self:v.controller,peer:{publicKey:p.publicKey,metadata:p.metadata},controller:m,transportType:dz}));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,hE("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,n1(fn)),{topic:b,acknowledged:()=>Promise.resolve(this.client.session.get(b))}}),f_(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}
15t&&await this.sendError({id:i,topic:t,error:r,rpcOpts:fa.wc_sessionPropose.reject}),await this.deleteProposal(i)}),f_(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}=nZ(),a=(0,dS.payloadId)(),o=(0,dS.getBigIntRpcId)().toString(),l=this.client.session.get(t).namespaces;return this.events.once(n3("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}}),f_(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,dS.payloadId)(),{done:r,resolve:s,reject:n}=nZ();return this.events.once(n3("session_extend",i),({error:e})=>{e?n(e):s()}),await this.setExpiry(t,n1(fn)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(e=>{n(e)}),{acknowledged:r}}),f_(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=fa.wc_sessionRequest.req.ttl}=e,n=this.client.session.get(r);n?.transportType===dz&&await this.confirmOnlineStateOrThrow();let a=(0,dS.payloadId)(),o=(0,dS.getBigIntRpcId)().toString(),{done:l,resolve:c,reject:h}=nZ(s,"Request expired. Please try again.");this.events.once(n3("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:fg(fE({},i),fy({expiryTimestamp:n1(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:fg(fE({},i),fy({expiryTimestamp:n1(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 n4(this.client.core.storage,fr);await n8({id:a,topic:r,wcDeepLink:e})}e()}),l()]).then(e=>e[2])}),f_(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===dz&&await this.confirmOnlineStateOrThrow();let l=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);try{r.addTrace("session_request_response_publish_started"),(0,dA.isJsonRpcResult)(n)?await this.sendResult({id:a,topic:s,result:n.result,throwOnFailedPublish:!0,appLink:l}):(0,dA.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}}),f_(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,dS.payloadId)(),i=(0,dS.getBigIntRpcId)().toString(),{done:r,resolve:s,reject:n}=nZ();this.events.once(n3("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}))}),f_(this,"emit",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);
15let{topic:t,event:i,chainId:r}=e,s=(0,dS.getBigIntRpcId)().toString(),n=(0,dS.payloadId)();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:i,chainId:r},throwOnFailedPublish:!0,relayRpcId:s,clientRpcId:n})}),f_(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:hE("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}=hv("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw Error(e)}}),f_(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!!nV(s,r)&&(r.forEach(t=>{let{accounts:r,methods:s,events:a}=e.namespaces[t],o=hp(r),l=i[t];nV(nC(t,l),o)&&nV(l.methods,s)&&nV(l.events,a)||(n=!1)}),n)})(t,e)))),f_(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),f_(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?dH:dz;c===dz&&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:_}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:c});this.client.logger.info({message:"Generated new pairing",pairing:{topic:E,uri:_}});let I=await this.client.core.crypto.generateKeyPair(),S=c$(I);if(await Promise.all([this.client.auth.authKeys.set(fp,{responseTopic:S,publicKey:I}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:E})]),await this.client.core.relayer.subscribe(S,{transportType:c}),this.client.logger.info(`sending request to new pairing topic: ${E}`),w.length>0){let e,t,{namespace:i}=nx(h[0]),o=oz(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));oV(v)&&(r=o,s=v.pop(),o=oz((n=o$(r),a=o$(s),oH(n),oH(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]=oR(((e,t)=>{for(var i in t||(t={}))oD.call(t,i)&&oM(e,i,t[i]);if(oj)for(var i of oj(t))oU.call(t,i)&&oM(e,i,t[i]);return e})({},t.att[e]),oN({[i]:(null==(r=n.att[e])?void 0:r[i])||(null==(s=a.att[e])?void 0:s[i])}))})}),t))),v.push(o)}let A=b&&b>fa.wc_sessionAuthenticate.req.ttl?b:fa.wc_sessionAuthenticate.req.ttl,x={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:I,metadata:this.client.metadata},expiryTimestamp:n1(A)},P={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:h,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:E,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:n1(fa.wc_sessionPropose.req.ttl),id:(0,dS.payloadId)()},{done:C,resolve:k,reject:O}=nZ(A,"Request expired"),T=(0,dS.payloadId)(),R=n3("session_connect",P.id),N=n3("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=hE("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(R,j),O(e.error.message))}await this.deleteProposal(P.id),this.events.off(R,j);let{cacaos:a,responder:o}=e.result,l=[],h=[];for(let e of a){await oq({cacao:e,projectId:this.client.core.projectId})||(this.client.logger.error(e,"Signature verification failed"),O(hE("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:t}=e,i=oV(t.resources),r=[oB(t.iss)],s=oW(t.iss);if(i){let e=oJ(i),t=oF(i);l.push(...e),r.push(...t)}for(let e of r)h.push(`${e}:${s}`)}let d=await this.client.core.crypto.generateSharedKey(I,o.publicKey);l.length>0&&(n={topic:d,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:o,controller:o.publicKey,expiry:n1(fn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:E,namespaces:hm([...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:dH})),k({auths:a,session:n})};this.events.once(R,j),this.events.once(N,D);try{if(l){let e=(0,dS.formatJsonRpcRequest)("wc_sessionAuthenticate",x,T);this.client.core.history.set(E,e);let i=await this.client.core.crypto.encode("",e,{type:2,encoding:cK});o=hr(t,E,i)}else await Promise.all([this.sendRequest({topic:E,method:"wc_sessionAuthenticate",params:x,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:T}),this.sendRequest({topic:E,method:"wc_sessionPropose",params:P,expiry:fa.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:P.id})])}catch(e){throw this.events.off(R,j),this.events.off(N,D),e}
15return await this.setProposal(P.id,P),await this.setAuthRequest(T,{request:fg(fE({},x),fy({verifyContext:{}})),pairingTopic:E,transportType:c}),{uri:o??_,response:C}}),f_(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||dz;a===dz&&await this.confirmOnlineStateOrThrow();let o=n.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),c=c$(o),h={type:1,receiverPublicKey:o,senderPublicKey:l},d=[],u=[];for(let e of r){if(!await oq({cacao:e,projectId:this.client.core.projectId})){s.setError("invalid_cacao");let e=hE("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=oV(t.resources),n=[oB(t.iss)],a=oW(t.iss);if(r){let e=oJ(r),t=oF(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:n1(fn),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:n.pairingTopic,namespaces:hm([...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");try{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}}),f_(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===dz&&await this.confirmOnlineStateOrThrow();let s=r.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),a=c$(s);await this.sendError({id:t,topic:a,error:i,encodeOpts:{type:1,receiverPublicKey:s,senderPublicKey:n},rpcOpts:fa.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)}),f_(this,"formatAuthMessage",e=>{this.isInitialized();let{request:t,iss:i}=e;return oK(t,i)}),f_(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)}),f_(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)}}),f_(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,hE("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(fr).catch(e=>this.client.logger.warn(e)),this.getPendingSessionRequests().forEac
15h(e=>{e.topic===i&&this.deletePendingSessionRequest(e.id,hE("USER_DISCONNECTED"))}),i===(null==(t=this.sessionRequestQueue.queue[0])?void 0:t.topic)&&(this.sessionRequestQueue.state=fl),s&&this.client.events.emit("session_delete",{id:n,topic:i})}),f_(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,hE("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")}),f_(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=fl,this.client.events.emit("session_request_expire",{id:e}))}),f_(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)])}),f_(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}))}),f_(this,"setProposal",async(e,t)=>{this.client.core.expirer.set(e,n1(fa.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)}),f_(this,"setAuthRequest",async(e,t)=>{let{request:i,pairingTopic:r,transportType:s=dz}=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})}),f_(this,"setPendingSessionRequest",async e=>{let{id:t,topic:i,params:r,verifyContext:s}=e,n=r.request.expiryTimestamp||n1(fa.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,n),await this.client.pendingRequest.set(t,{id:t,topic:i,params:r,verifyContext:s})}),f_(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,dS.formatJsonRpcRequest)(n,a,c),g=!!d;try{let e=g?cK:cq;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(fd.includes(n)){let e=cJ(JSON.stringify(f)),t=cJ(i);r=await this.client.core.verify.register({id:t,decryptedId:e})}let y=fE(fE({},fa[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=hr(d,s,i);await e.g.Linking.openURL(t,this.client.name)}else{let e;y.tvf=fg(fE({},u),fy({correlationId:f.id})),h?(e=fE({},y.internal),y.internal=fg(e,fy({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}),f_(this,"sendProposeSession",async e=>{let{proposal:t,publishOpts:i}=e,r=(0,dS.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:cq}),n=cJ(JSON.stringify(r)),a=cJ(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:fg(fE({},i),fy({publishMethod:"wc_proposeSession",attestation:o}))})}),f_(this,"sendApproveSession",async e=>{let{sessionTopic:t,pairingProposalResponse:i,proposal:r,sessionSettleRequest:s,publishOpts:n}=e,a=(0,dS.formatJsonRpcResult)(r.id,i),o=await this.client.core.crypto.encode(r.pairingTopic,a,{encoding:cq}),l=(0,dS.formatJsonRpcRequest)("wc_sessionSettle",s,n?.id),c=await this.client.core.crypto.encode(t,l,{encoding:cq});this.client.core.history.set(t,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:t,pairingTopic:r.pairingTopic,sessionProposalResponse:o,sessionSettlementRequest:c},opts:fg(fE({},n),fy({publishMethod:"wc_approveSession"}))})}),f_(this,"sendResult",async t=>{let i,r,s,{id:n,topic:a,result:o,throwOnFailedPublish:l,encodeOpts:c,appLink:h}=t,d=(0,dS.formatJsonRpcResult)(n,o),u=h&&"u">typeof(null==e.g?void 0:e.g.Linking);try{let e,t,r=u?cK:cq;i=await this.client.core.crypto.encode(a,d,(e=fE({},c||{}),t={encoding:r},fg(e,fy(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=hr(h,a,i);await e.g.Linking.openURL(t,this.client.name)}else{let e,t=fa[r.request.method].res;t.tvf=fg(fE({},s),fy({correlationId:n})),l?(e=fE({},t.internal),t.internal=fg(e,fy({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)}),f_(this,"sendError",async t=>{let i,r,{id:s,topic:n,error:a,encodeOpts:o,rpcOpts:l,appLink:c}=t,h=(0,dS.formatJsonRpcError)(s,a),d=c&&"u">typeof(null==e.g?void 0:e.g.Linking);try{let e,t,r=d?cK:cq;i=await this.client.core.crypto.encode(n,h,(e=fE({},o||{}),t={encoding:r},fg(e,fy(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=hr(c,n,i);await e.g.Linking.openURL(t,this.client.name)}else{let e=r.request.method,t=l||fa[e].res;this.client.core.relayer.publish(n,i,t)}
15await this.client.core.history.resolve(h)}),f_(this,"cleanup",async()=>{let e=[],t=[];this.client.session.getAll().forEach(t=>{let i=!1;n2(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=>{n2(e.expiryTimestamp)&&t.push(e.id)}),await Promise.all([...e.map(e=>this.deleteSession({topic:e})),...t.map(e=>this.deleteProposal(e))])}),f_(this,"onProviderMessageEvent",async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)}),f_(this,"onRelayEventRequest",async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()}),f_(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===fc)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=fc;let e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=fl}),f_(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
15({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}`)}}),f_(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}`)}}),f_(this,"onRelayEventUnknownPayload",e=>{let{topic:t}=e,{message:i}=hv("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw Error(i)}),f_(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)}),f_(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(fE({},i.params));let o=n.expiryTimestamp||n1(fa.wc_sessionPropose.req.ttl),l=fE({id:a,pairingTopic:t,expiryTimestamp:o,attestation:r,encryptedId:s},n);await this.setProposal(a,l);let c=await this.getVerifyContext({attestationId:r,hash:cJ(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:fa.wc_sessionPropose.autoReject}),this.client.logger.error(e)}}),f_(this,"onSessionProposeResponse",async(e,t,i)=>{let{id:r}=t;if((0,dA.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,dA.isJsonRpcError)(t)){await this.deleteProposal(r);let e=n3("session_connect",r);if(0===this.events.listenerCount(e))throw Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:t.error})}}),f_(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}`);let p=this.client.proposal.get(u.proposalId),f=(i=fE(fE(fE({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:dz},fg(i,fy(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(n3("session_connect",u.proposalId),{session:f}),this.pendingSessions.delete(u.proposalId),this.deleteProposal(u.proposalId,!1),this.cleanupDupl
15icatePairings(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)}}),f_(this,"onSessionSettleResponse",async(e,t)=>{let{id:i}=t;(0,dA.isJsonRpcResult)(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(n3("session_approve",i),{})):(0,dA.isJsonRpcError)(t)&&(await this.client.session.delete(e,hE("USER_DISCONNECTED")),this.events.emit(n3("session_approve",i),{error:t.error}))}),f_(this,"onSessionUpdateRequest",async(e,t)=>{let{params:i,id:r}=t;try{let t=`${e}_session_update`,s=hB.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:hE("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(fE({topic:e},i));try{hB.set(t,r),await this.client.session.update(e,{namespaces:i.namespaces}),await this.sendResult({id:r,topic:e,result:!0})}catch(e){throw hB.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)}}),f_(this,"isRequestOutOfSync",(e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3)),f_(this,"onSessionUpdateResponse",(e,t)=>{let{id:i}=t,r=n3("session_update",i);if(0===this.events.listenerCount(r))throw Error(`emitting ${r} without any listeners`);(0,dA.isJsonRpcResult)(t)?this.events.emit(n3("session_update",i),{}):(0,dA.isJsonRpcError)(t)&&this.events.emit(n3("session_update",i),{error:t.error})}),f_(this,"onSessionExtendRequest",async(e,t)=>{let{id:i}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,n1(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)}}),f_(this,"onSessionExtendResponse",(e,t)=>{let{id:i}=t,r=n3("session_extend",i);if(0===this.events.listenerCount(r))throw Error(`emitting ${r} without any listeners`);(0,dA.isJsonRpcResult)(t)?this.events.emit(n3("session_extend",i),{}):(0,dA.isJsonRpcError)(t)&&this.events.emit(n3("session_extend",i),{error:t.error})}),f_(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)}}),f_(this,"onSessionPingResponse",(e,t)=>{let{id:i}=t,r=n3("session_ping",i);setTimeout(()=>{if(0===this.events.listenerCount(r))throw Error(`emitting ${r} without any listeners 2176`);(0,dA.isJsonRpcResult)(t)?this.events.emit(n3("session_ping",i),{}):(0,dA.isJsonRpcError)(t)&&this.events.emit(n3("session_ping",i),{error:t.error})},500)}),f_(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(dM,async()=>{t(await this.deleteSession({topic:e,id:i}))})}),this.sendResult({id:i,topic:e,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:e,error:hE("USER_DISCONNECTED")})]).catch(e=>this.client.logger.error(e))}catch(e){this.client.logger.error(e)}}),f_(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(fE({topic:s},h));let e=this.client.session.get(s),n=await this.getVerifyContext({attestationId:a,hash:cJ(JSON.stringify((0,dS.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===dH&&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())}catch(e){await this.sendError({id:c,topic:s,error:e}),this.client.logger.error(e)}}),f_(this,"onSessionRequestResponse",(e,t)=>{let{id:i}=t,r=n3("session_request",i);if(0===this.events.listenerCount(r))throw Error(`emitting ${r}
15 without any listeners`);(0,dA.isJsonRpcResult)(t)?this.events.emit(n3("session_request",i),{result:t.result}):(0,dA.isJsonRpcError)(t)&&this.events.emit(n3("session_request",i),{error:t.error})}),f_(this,"onSessionEventRequest",async(e,t)=>{let{id:i,params:r}=t;try{let t=`${e}_session_event_${r.event.name}`,s=hB.get(t);if(s&&this.isRequestOutOfSync(s,i))return void this.client.logger.info(`Discarding out of sync request - ${i}`);this.isValidEmit(fE({topic:e},r)),this.client.events.emit("session_event",{id:i,topic:e,params:r}),hB.set(t,i)}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}}),f_(this,"onSessionAuthenticateResponse",(e,t)=>{let{id:i}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),(0,dA.isJsonRpcResult)(t)?this.events.emit(n3("session_request",i),{result:t.result}):(0,dA.isJsonRpcError)(t)&&this.events.emit(n3("session_request",i),{error:t.error})}),f_(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:cJ(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===dH&&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:fa.wc_sessionAuthenticate.autoReject,appLink:s})}}),f_(this,"addSessionRequestToSessionRequestQueue",e=>{this.sessionRequestQueue.queue.push(e)}),f_(this,"cleanupAfterResponse",e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=fl,this.processSessionRequestQueue()},(0,iq.toMiliseconds)(this.requestQueueDelay))}),f_(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=n3("session_request",e.request.id);if(0===this.events.listenerCount(i))throw Error(`emitting ${i} without any listeners`);this.events.emit(n3("session_request",e.request.id),{error:t})})}),f_(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===fc)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)}}),f_(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=fc,this.emittedSessionRequests.add(e.id),this.client.events.emit("session_request",e))}),f_(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);
15t&&this.onSessionProposeRequest({topic:e.topic,payload:(0,dS.formatJsonRpcRequest)("wc_sessionPropose",fg(fE({},t),fy({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})}),f_(this,"isValidConnect",async e=>{let t;if(!hR(e)){let{message:t}=hv("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(hS(i)||await this.isValidPairingTopic(i),t=!1,o?o&&h_(o)&&o.length&&o.forEach(e=>{t=hT(e)}):t=!0,!t){let{message:e}=hv("MISSING_OR_INVALID",`connect() relays: ${o}`);throw Error(e)}if(r&&!hS(r)&&0!==hI(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&&!hS(s)&&0!==hI(s)&&this.validateNamespaces(s,"optionalNamespaces"),n&&!hS(n)&&this.validateSessionProps(n,"sessionProperties"),a&&!hS(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)}`)}}),f_(this,"validateNamespaces",(e,t)=>{let i=function(e,t,i){let r=null;if(e&&hI(e)){let s,n=hk(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=nC(e,r),a=`${t} ${i}`,o=null,h_(n)&&n.length?n.forEach(e=>{o||hP(e)||(o=hE("UNSUPPORTED_CHAINS",`${a}, chain ${e} should be a string and conform to "namespace:chainId" format`))}):hP(e)||(o=hE("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=hv("MISSING_OR_INVALID",`${t}, ${i} should be an object with data`);return r}(e,"connect()",t);if(i)throw Error(i.message)}),f_(this,"isValidApprove",async e=>{if(!hR(e))throw Error(hv("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=hO(i,"approve()");if(o)throw Error(o.message);let l=hj(a.requiredNamespaces,i,"approve()");if(l)throw Error(l.message);if(!hA(r,!0)){let{message:e}=hv("MISSING_OR_INVALID",`approve() relayProtocol: ${r}`);throw Error(e)}if(s&&!hS(s)&&this.validateSessionProps(s,"sessionProperties"),n&&!hS(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(", ")}`)}}),f_(this,"isValidReject",async e=>{if(!hR(e)){let{message:t}=hv("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||!hx(i.code,!1)||!i.message||!hA(i.message,!1)){let{message:e}=hv("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw Error(e)}}),f_(this,"isValidSessionSettleRequest",e=>{let t;if(!hR(e)){let{message:t}=hv("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw Error(t)}
15let{relay:i,controller:r,namespaces:s,expiry:n}=e;if(!hT(i)){let{message:e}=hv("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw Error(e)}let a=(t=null,hA(r?.publicKey,!1)||(t=hv("MISSING_OR_INVALID","onSessionSettleRequest() controller public key should be a string")),t);if(a)throw Error(a.message);let o=hO(s,"onSessionSettleRequest()");if(o)throw Error(o.message);if(n2(n)){let{message:e}=hv("EXPIRED","onSessionSettleRequest()");throw Error(e)}}),f_(this,"isValidUpdate",async e=>{if(!hR(e)){let{message:t}=hv("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=hO(i,"update()");if(s)throw Error(s.message);let n=hj(r.requiredNamespaces,i,"update()");if(n)throw Error(n.message)}),f_(this,"isValidExtend",async e=>{if(!hR(e)){let{message:t}=hv("MISSING_OR_INVALID",`extend() params: ${e}`);throw Error(t)}let{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)}),f_(this,"isValidRequest",async e=>{var t;let i;if(!hR(e)){let{message:t}=hv("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(!hN(o,n)){let{message:e}=hv("MISSING_OR_INVALID",`request() chainId: ${n}`);throw Error(e)}if(hS(s)||!hA(s.method,!1)){let{message:e}=hv("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw Error(e)}if(!(hA(t=s.method,!1)&&(i=[],Object.values(o).forEach(e=>{hp(e.accounts).includes(n)&&i.push(...e.methods)}),i).includes(t))){let{message:e}=hv("MISSING_OR_INVALID",`request() method: ${s.method}`);throw Error(e)}if(a&&(!hx(a,!1)||!(a<=fo.max)||!(a>=fo.min))){let{message:e}=hv("MISSING_OR_INVALID",`request() expiry: ${a}. Expiry must be a number (in seconds) between ${fo.min} and ${fo.max}`);throw Error(e)}}),f_(this,"isValidRespond",async e=>{var t;if(!hR(e)){let{message:t}=hv("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(hS(r)||hS(r.result)&&hS(r.error)||!hx(r.id,!1)||!hA(r.jsonrpc,!1)){let{message:e}=hv("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}=hv("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${r.id}, expected topic: ${s.topic}, received topic: ${i}`);throw Error(e)}}),f_(this,"isValidPing",async e=>{if(!hR(e)){let{message:t}=hv("MISSING_OR_INVALID",`ping() params: ${e}`);throw Error(t)}let{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),f_(this,"isValidEmit",async e=>{var t;let i;if(!hR(e)){let{message:t}=hv("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(!hN(a,n)){let{message:e}=hv("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw Error(e)}if(hS(s)||!hA(s.name,!1)||!(hA(t=s.name,!1)&&(i=[],Object.values(a).forEach(e=>{hp(e.accounts).includes(n)&&i.push(...e.events)}),i).includes(t))){let{message:e}=hv("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw Error(e)}}),f_(this,"isValidDisconnect",async e=>{if(!hR(e)){let{message:t}=hv("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw Error(t)}let{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),f_(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(!hA(i,!1))throw Error("uri is required parameter");if(!hA(r,!1))throw Error("domain is required parameter");if(!hA(s,!1))throw Error("nonce is required parameter");if([...new Set(t.map(e=>nx(e).namespace))].length>1)throw Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:n}=nx(t[0]);if("eip155"!==n)throw Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),f_(this,"getVerifyContext",async e=>{let{attestationId:t,hash:i,encryptedId:r,metadata:s,transportType:n}
15=e,a={verified:{verifyUrl:s.verifyUrl||d5,validation:"UNKNOWN",origin:s.url||""}};try{if(n===dH){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}),f_(this,"validateSessionProps",(e,t)=>{Object.values(e).forEach((i,r)=>{if(null==i){let{message:s}=hv("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${i} for key ${Object.keys(e)[r]}`);throw Error(s)}})}),f_(this,"getPendingAuthRequest",e=>{let t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0}),f_(this,"addToRecentlyDeleted",(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0,t=this.recentlyDeletedLimit/2;for(let i of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(i)}}}),f_(this,"checkRecentlyDeleted",e=>{let t=this.recentlyDeletedMap.get(e);if(t){let{message:i}=hv("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw Error(i)}}),f_(this,"isLinkModeEnabled",(t,i)=>{var r,s,n,a,o,l,c,h,d;return!!t&&i===dH&&(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)}),f_(this,"getAppLinkIfEnabled",(e,t)=>{var i;return this.isLinkModeEnabled(e,t)?null==(i=e?.redirect)?void 0:i.universal:void 0}),f_(this,"handleLinkModeMessage",({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;let t=n6(e,"topic")||"",i=decodeURIComponent(n6(e,"wc_ev")||""),r=this.client.session.keys.includes(t);r&&this.client.session.update(t,{transportType:dH}),this.client.core.dispatchEnvelope({topic:t,message:i,sessionExists:r})}),f_(this,"registerLinkModeListeners",async()=>{var t;if(n9()||nK()&&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)}}}),f_(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}),f_(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}),f_(this,"extractTxHashesFromResult",(e,t)=>{var i,r,s,n,a;try{if(!t)return[];let o=e.method,l=fh[o];if("sui_signTransaction"===o){let e,i,r,n;return[(s=t.transactionBytes,e=new Uint8Array(G.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=oS(r,{dkLen:32}),s8.default.encode(n))]}if("near_signTransaction"===o)return[oC(t)];if("near_signTransactions"===o)return t.map(e=>oC(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(G.Buffer.from(r.signature,"hex")),a=function({publicKey:e,signature:t,payload:i}){var r,s,n;
15let a,o=hW(i.method),l=128|parseInt((null==(r=i.version)?void 0:r.toString())||"4"),c=(s=i.address,a=s8.default.decode(s)[0],42===a?0:60===a?2:1),h="00"===i.era?new Uint8Array([0]):hW(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=s8.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=hW(G.Buffer.from(a).toString("hex")),s=(0,ns.blake2b)(i,void 0,32),"0x"+G.Buffer.from(s).toString("hex"))]}if("algo_signTxn"===o)return h_(t)?t.map(e=>ok(e)):[ok(t)];if("cosmos_signDirect"===o){let e,i,r,s,n;return[(e=G.Buffer.from(t.signed.bodyBytes,"base64"),i=G.Buffer.from(t.signed.authInfoBytes,"base64"),r=G.Buffer.from(t.signature.signature,"base64"),(s=[]).push(G.Buffer.from([10])),s.push(oO(e.length)),s.push(e),s.push(G.Buffer.from([18])),s.push(oO(i.length)),s.push(i),s.push(G.Buffer.from([26])),s.push(oO(r.length)),s.push(r),n=op(G.Buffer.concat(s)),G.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(h_(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=G.Buffer.from(e,"base64").slice(1,65);return s8.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}=hv("NOT_INITIALIZED",this.name);throw Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(dj,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(fp)?this.client.auth.authKeys.get(fp):{responseTopic:void 0,publicKey:void 0};try{let e=await this.client.core.crypto.decode(t,i,{receiverPublicKey:n,encoding:s===dH?cK:cq});(0,dA.isJsonRpcRequest)(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:r,transportType:s,encryptedId:cJ(i)})):(0,dA.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(d3,async e=>
15{let{topic:t,id:i}=n0(e.target);return i&&this.client.pendingRequest.keys.includes(i)?await this.deletePendingSessionRequest(i,hv("EXPIRED"),!0):i&&this.client.auth.requests.keys.includes(i)?await this.deletePendingAuthRequest(i,hv("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(dY,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(dZ,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!hA(e,!1)){let{message:t}=hv("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}=hv("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw Error(t)}if(n2(this.client.core.pairing.pairings.get(e).expiry)){let{message:t}=hv("EXPIRED",`pairing topic: ${e}`);throw Error(t)}}async isValidSessionTopic(e){if(!hA(e,!1)){let{message:t}=hv("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}=hv("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw Error(t)}if(n2(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});let{message:t}=hv("EXPIRED",`session topic: ${e}`);throw Error(t)}if(!this.client.core.crypto.keychain.has(e)){let{message:t}=hv("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(hA(e,!1)){let{message:t}=hv("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw Error(t)}else{let{message:t}=hv("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}=hv("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw Error(t)}if(!this.client.proposal.keys.includes(e)){let{message:t}=hv("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw Error(t)}if(n2(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);let{message:t}=hv("EXPIRED",`proposal id: ${e}`);throw Error(t)}}}class fS extends pN{constructor(e,t){super(e,t,"proposal",fi),this.core=e,this.logger=t}}class fA extends pN{constructor(e,t){super(e,t,"session",fi),this.core=e,this.logger=t}}class fx extends pN{constructor(e,t){super(e,t,"request",fi,e=>e.id),this.core=e,this.logger=t}}class fP extends pN{constructor(e,t){super(e,t,"authKeys",fu,()=>fp),this.core=e,this.logger=t}}class fC extends pN{constructor(e,t){super(e,t,"pairingTopics",fu),this.core=e,this.logger=t}}class fk extends pN{constructor(e,t){super(e,t,"requests",fu,e=>e.id),this.core=e,this.logger=t}}var fO=Object.defineProperty,fT=(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 fR{constructor(e,t){this.core=e,this.logger=t,fT(this,"authKeys"),fT(this,"pairingTopics"),fT(this,"requests"),this.authKeys=new fP(this.core,this.logger),this.pairingTopics=new fC(this.core,this.logger),this.requests=new fk(this.core,this.logger)}
15async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var fN=Object.defineProperty,fj=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?fN(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class fD extends dE{constructor(e){super(e),fj(this,"protocol","wc"),fj(this,"version",2),fj(this,"name",ft),fj(this,"metadata"),fj(this,"core"),fj(this,"logger"),fj(this,"events",new iL.EventEmitter),fj(this,"engine"),fj(this,"session"),fj(this,"proposal"),fj(this,"pendingRequest"),fj(this,"auth"),fj(this,"signConfig"),fj(this,"on",(e,t)=>this.events.on(e,t)),fj(this,"once",(e,t)=>this.events.once(e,t)),fj(this,"off",(e,t)=>this.events.off(e,t)),fj(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),fj(this,"removeAllListeners",e=>this.events.removeAllListeners(e)),fj(this,"connect",async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"pair",async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"approve",async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"reject",async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"update",async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"extend",async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"request",async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"respond",async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"ping",async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"emit",async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"disconnect",async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"find",e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}}),fj(this,"authenticate",async(e,t)=>{try{return await this.engine.authenticate(e,t)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"formatAuthMessage",e=>{try{return this.engine.formatAuthMessage(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"approveSessionAuthenticate",async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}}),fj(this,"rejectSessionAuthenticate",async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}}),this.name=e?.name||ft,this.metadata=function(e){var t,i;let r=nJ();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=nU(nU({},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},nO(s,nT(n))}catch(t){return console.warn("Error populating app metadata",t),e||r}}(e?.metadata),this.signConfig=e?.signConfig;const t=hq({logger:e?.logger||"error",name:this.name});this.logger=t,this.core=e?.core||new fe(e),this.session=new fA(this.core,this.logger),this.proposal=new fS(this.core,this.logger),this.pendingRequest=new fx(this.core,this.logger),this.engine=new fI(this),this.auth=new fR(this.core,this.logger)}static async init(e){let t=new fD(e);return await t.initialize(),t}get context(){return dt(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 fU=e.i(98418);function fM(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function fL(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}
15function fB(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}let fW="[object String]",fq="[object Number]",fK="[object Boolean]",fH="[object Arguments]";function fz(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function f$(e,t,i,r=new Map,s){let n=s?.(e,t,i,r);if(null!=n)return n;if(fM(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]=f$(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,f$(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(f$(n,void 0,i,r,s));return t}if("u">typeof G.Buffer&&G.Buffer.isBuffer(e))return e.subarray();if(fz(e)){let t=new(Object.getPrototypeOf(e)).constructor(e.length);r.set(e,t);for(let n=0;n<e.length;n++)t[n]=f$(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),fJ(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),fJ(t,e,i,r,s),t}if(e instanceof Blob){let t=new Blob([e],{type:e.type});return r.set(e,t),fJ(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,fJ(t,e,i,r,s),t}if("object"==typeof e&&function(e){switch(fB(e)){case fH:case"[object Array]":case"[object ArrayBuffer]":case"[object DataView]":case fK:case"[object Date]":case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Map]":case fq:case"[object Object]":case"[object RegExp]":case"[object Set]":case fW: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),fJ(t,e,i,r,s),t}return e}function fJ(e,t,i=e,r,s){let n=[...Object.keys(t),...fL(t)];for(let a=0;a<n.length;a++){let o=n[a],l=Object.getOwnPropertyDescriptor(e,o);(null==l||l.writable)&&(e[o]=f$(t[o],o,i,r,s))}}function fF(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 fq:case fW:case fK:{let t=new e.constructor(e?.valueOf());return fJ(t,e),t}case fH:{let t={};return fJ(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}},f$(e,void 0,e,new Map,t)}function fV(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===fB(e)}function fG(e){return"object"==typeof e&&null!==e}function fY(){}let fZ="error",fQ="universal_provider",fX=`wc@2:${fQ}:`,f0="https://rpc.walletconnect.org/v1/",f1="generic",f2=`${f0}bundler`,f3="call_status",f5="default_chain_changed";var f8=Object.defineProperty,f4=Object.defineProperties,f6=Object.getOwnPropertyDescriptors,f7=Object.getOwnPropertySymbols,f9=Object.prototype.hasOwnProperty,ge=Object.prototype.propertyIsEnumerable,gt=(e,t,i)=>t in e?f8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,gi=(e,t)=>{for(var i in t||(t={}))f9.call(t,i)&&gt(e,i,t[i]);if(f7)for(var i of f7(t))ge.call(t,i)&&gt(e,i,t[i]);return e},gr=(e,t)=>f4(e,f6(t));function gs(e,t,i){var r;let s=nx(e);return(null==(r=t.rpcMap)?void 0:r[s.reference])||`${f0}?chainId=${s.namespace}:${s.reference}&projectId=${i}`}function gn(e){return e.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function ga(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 go(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(fM(t)&&(t=Object(t)),null==i||"object"!=typeof i)return t;if(s.has(i))return function(e){if(fM(e))return e;if(Array.isArray(e)||fz(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),...fL(i)];for(let a=0;a<n.length;a++){let o=n[a],l=i[o],c=t[o];if(fV(l)&&(l={...l}),fV(c)&&(c={...c}),"u">typeof G.Buffer&&G.Buffer.isBuffer(l)&&(l=fF(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)||fG(c)&&fG(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;
15if("[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&&fz(l)?t[o]=fF(l):(void 0===c||void 0!==l)&&(t[o]=l)}return t}(s,i[e],r,new Map);return s}(e,...t,fY)}(ga(gl(e)),ga(gl(t)))}function gl(e){var t,i,r,s,n;let a={};if(!hI(e))return a;for(let[o,l]of Object.entries(e)){let e=hf(o)?[o]:l.chains,c=l.methods||[],h=l.events||[],d=l.rpcMap||{},u=hg(o);a[u]=gr(gi(gi({},a[u]),l),{chains:n5(e,null==(t=a[u])?void 0:t.chains),methods:n5(c,null==(i=a[u])?void 0:i.methods),events:n5(h,null==(r=a[u])?void 0:r.events)}),(hI(d)||hI((null==(s=a[u])?void 0:s.rpcMap)||{}))&&(a[u].rpcMap=gi(gi({},d),null==(n=a[u])?void 0:n.rpcMap))}return a}function gc(e){return e.includes(":")?e.split(":")[2]:e}function gh(e){let t={};for(let[i,r]of Object.entries(e)){let e=r.methods||[],s=r.events||[],n=r.accounts||[],a=hf(i)?[i]:r.chains?r.chains:gn(r.accounts);t[i]={chains:a,methods:e,events:s,accounts:n}}return t}function gd(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 gu={},gp=e=>gu[e],gf=(e,t)=>{gu[e]=t};var gg=Object.defineProperty,gy=Object.getOwnPropertySymbols,gm=Object.prototype.hasOwnProperty,gw=Object.prototype.propertyIsEnumerable,gb=(e,t,i)=>t in e?gg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,gv=(e,t)=>{for(var i in t||(t={}))gm.call(t,i)&&gb(e,i,t[i]);if(gy)for(var i of gy(t))gw.call(t,i)&&gb(e,i,t[i]);return e};let gE="eip155",g_=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],gI=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,gS=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,gA=e=>Object.keys(e).filter(e=>g_.includes(e)).reduce((t,i)=>(t[i]=gx(e[i]),t),{}),gx=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 gP=Object.defineProperty;class gC{constructor(e){((e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?gP(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 gC(e)),t}}var gk=Object.defineProperty,gO=Object.defineProperties,gT=Object.getOwnPropertyDescriptors,gR=Object.getOwnPropertySymbols,gN=Object.prototype.hasOwnProperty,gj=Object.prototype.propertyIsEnumerable,gD=(e,t,i)=>t in e?gk(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;async function gU(e,t){let i,r=nx(e.result.capabilities.caip345.caip2),s=e.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(s.map(e=>gM(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 gM(e,t,i){return await i(parseInt(e)).request((0,dS.formatJsonRpcRequest)("eth_getTransactionReceipt",[t]))}async function gL({sendCalls:e,storage:t}){let i=await t.getItem(f3);await t.setItem(f3,gO(((e,t)=>{for(var i in t||(t={}))gN.call(t,i)&&gD(e,i,t[i]);if(gR)for(var i of gR(t))gj.call(t,i)&&gD(e,i,t[i]);return e})({},i),gT({[e.result.id]:{request:e.request,result:e.result,expiry:n1(86400)}})))}async function gB({resultId:e,storage:t}){let i=await t.getItem(f3);if(i){for(let r in delete i[e],await t.setItem(f3,i),i)n2(i[r].expiry)&&delete i[r];await t.setItem(f3,i)}}async function gW({resultId:e,storage:t}){let i=await t.getItem(f3),r=i?.[e];if(r&&!n2(r.expiry))return r;await gB({resultId:e,storage:t})}var gq=Object.defineProperty,gK=Object.defineProperties,gH=Object.getOwnPropertyDescriptors,gz=Object.getOwnPropertySymbols,g$=Object.prototype.hasOwnProperty,gJ=Object.prototype.propertyIsEnumerable,gF=(e,t,i)=>t in e?gq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,gV=(e,t)=>{for(var i in t||(t={}))g$.call(t,i)&&gF(e,i,t[i]);if(gz)for(var i of gz(t))gJ.call(t,i)&&gF(e,i,t[i]);return e},gG=(e,t,i)=>gF(e,"symbol"!=typeof t?t+"":t,i);class gY{constructor(e){gG(this,"name","eip155"),gG(this,"client"),gG(this,"chainId"),gG(this,"namespace"),gG(this,"httpProviders"),gG(this,"events"),gG(this,"storage"),this.namespace=e.namespace,this.events=gp("events"),this.client=gp("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=gC.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(f5,{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||gs(`${this.name}:${e}`,this.namespace,this.client.core.projectId);return new dI.JsonRpcProvider(new fU.HttpConnection(i,gp("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=gK(gV({},this.httpProviders),gH({[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(!hI(s)&&!hI(r))return;let a=gA(r);for(let e of i){let i=gI(e);if(!i)continue;n[gS(i)]=a;let r=s?.[`${gE}:${i}`];if(r){let e=r?.[`${gE}:${i}:${t}`];n[gS(i)]=gv(gv({},n[gS(i)]),gA(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=gV({},c.sessionProperties||{}),s={capabilities:(t=gV({},h||{}),i={[d]:p}
15,gK(t,gH(i)))},gK(r,gH(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 gW({resultId:null==(r=e.request.params)?void 0:r[0],storage:this.storage});if(o)try{return await gU(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,dS.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()}getBundlerUrl(e,t){return`${f2}?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 gL({sendCalls:{request:n,result:s},storage:this.storage}),s}}var gZ=Object.defineProperty,gQ=(e,t,i)=>{let r;return(r="symbol"!=typeof t?t+"":t)in e?gZ(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i};class gX{constructor(e){gQ(this,"name",f1),gQ(this,"client"),gQ(this,"httpProviders"),gQ(this,"events"),gQ(this,"namespace"),gQ(this,"chainId"),this.namespace=e.namespace,this.events=gp("events"),this.client=gp("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(f5,{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 nx(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=nx(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=nx(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||gs(e,this.namespace,this.client.core.projectId);return new dI.JsonRpcProvider(new fU.default(i,gp("disableProviderPing")))}}var g0=Object.defineProperty,g1=Object.defineProperties,g2=Object.getOwnPropertyDescriptors,g3=Object.getOwnPropertySymbols,g5=Object.prototype.hasOwnProperty,g8=Object.prototype.propertyIsEnumerable,g4=(e,t,i)=>t in e?g0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,g6=(e,t)=>{for(var i in t||(t={}))g5.call(t,i)&&g4(e,i,t[i]);if(g3)for(var i of g3(t))g8.call(t,i)&&g4(e,i,t[i]);return e},g7=(e,t,i)=>g4(e,"symbol"!=typeof t?t+"":t,i);class g9{constructor(e){var t,i;g7(this,"client"),g7(this,"namespaces"),g7(this,"optionalNamespaces"),g7(this,"sessionProperties"),g7(this,"scopedProperties"),g7(this,"events",new iL.default),g7(this,"rpcProviders",{}),g7(this,"session"),g7(this,"providerOpts"),g7(this,"logger"),g7(this,"uri"),g7(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=hq({logger:null!=(t=e.logger)?t:fZ,name:null!=(i=this.providerOpts.name)?i:fQ}),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){let t=new g9(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:g6({}
15,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,dS.formatJsonRpcResult)(s,e))).catch(e=>t(e,void 0))}async enable(){if(!this.client)throw Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw Error("Please call connect() before enable()");await this.client.disconnect({topic:null==(e=this.session)?void 0:e.topic,reason:hE("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=gh(this.session.namespaces);this.namespaces=go(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=gh(r.namespaces);return this.namespaces=go(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(!h_(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 fD.init({core:this.providerOpts.core,logger:this.providerOpts.logger||fZ,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=>hg(e)))];gf("client",this.client),gf("events",this.events),gf("disableProviderPing",this.disableProviderPing),e.forEach(e
15=>{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=[];return 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=g1(g6({},go(this.namespaces,this.optionalNamespaces)[e]),g2({accounts:t,chains:i}));"eip155"===e?this.rpcProviders[e]=new gY({namespace:r}):this.rpcProviders[e]=new gX({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&&h_(e)&&this.events.emit("accountsChanged",e.map(gc))}else if("chainChanged"===s.name){let e=i.chainId,t=i.event.data,r=hg(e),s=gd(e)!==gd(t)?`${r}:${gd(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=g1(g6({},n),g2({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",g1(g6({},hE("USER_DISCONNECTED")),g2({data:e.topic}))))}),this.on(f5,e=>{this.onChainChanged(g1(g6({},e),g2({internal:!0})))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[f1]}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=go(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=>hg(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=hg(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(gc);if(!h_(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(`${fX}/${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(`${fX}/${e}${i}`)}async deleteFromStore(e){var t;let i=(null==(t=this.session)?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${fX}/${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(fX)&&await this.client.core.storage.removeItem(e)}catch(e){this.logger.warn(e,"Failed to cleanup storage")}}}let ye=["eth_sendTransaction","personal_sign"],yt=["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"],yi=["chainChanged","accountsChanged"],yr=["chainChanged","accountsChanged","message","disconnect","connect"],ys=async()=>{let{createAppKit:t}=await e.A(156814);return 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);function yf(e){return Number(e[0].split(":")[1])}function yg(e){return`0x${e.toString(16)}`}class yy{constructor(){yp(this,"events",new iL.EventEmitter),yp(this,"namespace","eip155"),yp(this,"accounts",[]),yp(this,"signer"),yp(this,"chainId",1),yp(this,"modal"),yp(this,"rpc"),yp(this,"STORAGE_KEY","wc@2:ethereum_provider:"),yp(this,"on",(e,t)=>(this.events.on(e,t),this)),yp(this,"once",(e,t)=>(this.events.once(e,t),this)),yp(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),yp(this,"off",(e,t)=>(this.events.off(e,t),this)),yp(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){let t=new yy;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(!h_(t))throw Error("Invalid chains");let l={chains:t,methods:r||ye,events:n||yi,rpcMap:yu({},t.length?{[yf(t)]:o[yf(t)]}:{})},c=n?.filter(e=>!yi.includes(e)),h=r?.filter(e=>!ye.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:yt))],events:[...new Set(l.events.concat(null!=a&&a.length?a:yr))],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=yu({namespaces:yu({},i&&{[this.namespace]:i})},r&&{optionalNamespaces:{[this.namespace]:r}}),l={pairingTopic:e?.pairingTopic,scopedProperties:c},ya(o,yo(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=nP(t.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:yg(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=yu({},e),o={chains:this.rpc.chains},ya(a,yo(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=nP(r.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:e),this.setAccounts(e),this.events.emit("connect",{chainId:yg(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",yg(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",ya(yu({},hE("USER_DISCONNECTED")),yo({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",yg(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||ye:[],o=r.length?e?.events||yi:[],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={};
15return 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?yf(this.rpc.chains):yf(this.rpc.optionalChains),this.signer=await g9.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 ys(),{convertWCMToAppKitOptions:o}=await Promise.resolve().then(function(){return yP}),l=o((i=yu({},this.rpc.qrModalOptions),r={chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId},ya(i,yo(r))));if(!l.networks.length)throw Error("No networks found for WalletConnect·");e=a((s=yu({},l),n={universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:(null==(t=this.rpc.qrModalOptions)?void 0:t.enableMobileFullScreen)===!0},ya(s,yo(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&&h_(t)&&(this.rpc.chains=t.map(e=>this.formatChainId(e)),t.forEach(e=>{this.rpc.rpcMap[e]=r?.[e]||this.getRpcUrl(e)})),i&&h_(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 ym=Object.defineProperty,yw=Object.defineProperties,yb=Object.getOwnPropertyDescriptors,yv=Object.getOwnPropertySymbols,yE=Object.prototype.hasOwnProperty,y_=Object.prototype.propertyIsEnumerable,yI=(e,t,i)=>t in e?ym(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,yS=(e,t)=>{for(var i in t||(t={}))yE.call(t,i)&&yI(e,i,t[i]);if(yv)for(var i of yv(t))y_.call(t,i)&&yI(e,i,t[i]);return e};let yA=e=>{let[t,i]=e.split(":");return yx({id:i,caipNetworkId:e,chainNamespace:t,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function yx(e){return yS({formatters:void 0,fees:void 0,serializers:void 0},e)}var yP=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(yA).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:yw(yS({},e.metadata),yb({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:yx});function yC(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)e[r]=i[r]}return e}e.s(["EthereumProvider",0,yy,"OPTIONAL_EVENTS",0,yr,"OPTIONAL_METHODS",0,yt],764192);var yk=function e(t,i){function r(e,r,s){if("u">typeof document){"number"==typeof(s=yC({},i,s)).expires&&(s.expires=new Date(Date.now()+864e5*s.expires)),s.expires&&(s.expires=s.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decode
15URIComponent).replace(/[()]/g,escape);var n="";for(var a in s)s[a]&&(n+="; "+a,!0!==s[a]&&(n+="="+s[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+n}}return Object.create({set:r,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],r={},s=0;s<i.length;s++){var n=i[s].split("="),a=n.slice(1).join("=");try{var o=decodeURIComponent(n[0]);if(r[o]=t.read(a,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",yC({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,yC({},this.attributes,t))},withConverter:function(t){return e(yC({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});e.s(["default",0,yk],376664)},249474,e=>{"use strict";let t,i,r,s;e.i(563703);var n=e.i(576951),a=e.i(199220),o=e.i(823859),l=e.i(68798),c=e.i(722271),h=e.i(767700),d=e.i(951186),u=e.i(843476),p=e.i(891507),f=e.i(877225),g=e.i(33750),y=e.i(764192),m=e.i(91838),w=e.i(283291),b=e.i(768834),v=e.i(450223),E=e.i(844224),_=e.i(559754);e.i(858959);var I=e.i(376664);e.i(577906);var S=e.i(740382);class A{static parse(e){try{return new A(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return n.decodeJwt(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=n.decodeJwt(e)}}class x extends A{static parse(e){try{return new x(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}let P="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PScwIDAgMTAyNCAxMDI0JyBmaWxsPSdub25lJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHN0eWxlPSdoZWlnaHQ6MjhweDt3aWR0aDoyOHB4Jz48cmVjdCB3aWR0aD0nMTAyNCcgaGVpZ2h0PScxMDI0JyBmaWxsPScjMDA1MkZGJyByeD0nMTAwJyByeT0nMTAwJz48L3JlY3Q+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBjbGlwLXJ1bGU9J2V2ZW5vZGQnIGQ9J00xNTIgNTEyQzE1MiA3MTAuODIzIDMxMy4xNzcgODcyIDUxMiA4NzJDNzEwLjgyMyA4NzIgODcyIDcxMC44MjMgODcyIDUxMkM4NzIgMzEzLjE3NyA3MTAuODIzIDE1MiA1MTIgMTUyQzMxMy4xNzcgMTUyIDE1MiAzMTMuMTc3IDE1MiA1MTJaTTQyMCAzOTZDNDA2Ljc0NSAzOTYgMzk2IDQwNi43NDUgMzk2IDQyMFY2MDRDMzk2IDYxNy4yNTUgNDA2Ljc0NSA2MjggNDIwIDYyOEg2MDRDNjE3LjI1NSA2MjggNjI4IDYxNy4yNTUgNjI4IDYwNFY0MjBDNjI4IDQwNi43NDUgNjE3LjI1NSAzOTYgNjA0IDM5Nkg0MjBaJyBmaWxsPSd3aGl0ZSc+PC9wYXRoPjwvc3ZnPg==",C="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAALZJREFUaEPtmjEOhDAMBNc/O14GvOzys3CAKK6eAlmaVGl2Zc+kTOU685vkc9/bnD2prZK5/TZY24z9P+g4F5hNh7/GdoG37WlAA5CATwgCxHENYISwQAMQII5rACOEBRqAAHFcAxghLNAABIjjGsAIYYEGIEAc1wBGCAs0AAHiuAYwQligAQgQxzWAEcICDUCAOK4BjBAWaAACxHENYISwQAMQII6fBjr+VHkW3+u+tfyxMpJaDgYzYxb/ALZVAAAAAElFTkSuQmCC";class k extends c.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:C,id:"com.coinbase.wallet"}}async promptConnection(){h.c.debug("Prompting connection via Base Account",{wallet:this.walletClientType});try{await this.importPromise,h.c.rpcRequest("eth_requestAccounts",this.walletClientType);let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(h.c.rpcResponse("eth_requestAccounts",this.walletClientType),!e||0===e.length||!e[0])throw new d.g("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw h.c.connectionFailed(this.walletClientType,e,{method:"base_account"}),(0,h.j)(e)}}constructor(i,r,s,n,a){super("base_account",i,r,s),this.connectorType="base_account",this.walletClientType="base_account",this.displayName="Base",this.setBaseAccountSdk=a,this.proxyProvider=new c.P(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.baseAccountConfig={...n,appChainIds:[r.id].concat(i.map(e=>e.id))},t?(this.proxyProvider.setWalletProvider(t.getProvider()),this.setBaseAccountSdk(t)):this.importPromise=e.A(224814).then(({createBaseAccountSDK:e})=>{t=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider(t.getProvider()),this.setBaseAccountSdk(t)}).catch(console.error)}}let O=[1,0xaa36a7,137,10,8453,84532,42161,7777777,43114,56];class T extends c.E{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit
15("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:P,id:"com.coinbase.wallet"}}async promptConnection(){h.c.debug("Prompting connection via Coinbase Wallet",{wallet:this.walletClientType});try{h.c.rpcRequest("eth_requestAccounts",this.walletClientType);let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(h.c.rpcResponse("eth_requestAccounts",this.walletClientType),!e||0===e.length||!e[0])throw new d.g("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw h.c.connectionFailed(this.walletClientType,e,{method:"coinbase_wallet"}),(0,h.j)(e)}}updateConnectionPreference(e){this.coinbaseWalletConfig={...this.coinbaseWalletConfig,preference:{...this.coinbaseWalletConfig.preference,options:e}},this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",i=(0,p.createCoinbaseWalletSDK)({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(i.getProvider())}constructor(e,t,r,s){if(super("coinbase_wallet",e,t,r),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new c.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"),!i){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter(e=>!O.includes(e)):[];e.length>0&&!e.every(e=>f.DEFAULT_SUPPORTED_CHAIN_IDS.has(e))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${e.join(", ")}`),i=(0,p.createCoinbaseWalletSDK)(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(i.getProvider())}}let R=({style:e,...t}={})=>(0,u.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,u.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"})}),N=({style:e,...t}={})=>(0,u.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,u.jsx)("rect",{width:"108",height:"108",rx:"23",fill:"#AB9FF2"}),(0,u.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 j(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var D=0;class U extends c.E{async initialize(){h.c.debug("Initializing injected connector (EIP-6963)",{wallet:this.walletClientType}
15),await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){if(h.c.connectionStart(this.walletClientType,"injected",{showPrompt:e.showPrompt}),e.showPrompt&&await this.promptConnection(),!await this.isConnected())return h.c.debug("Not connected after prompt",{wallet:this.walletClientType}),null;let t=await this.getConnectedWallet();return t&&h.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(){h.c.debug("Prompting connection via eth_requestAccounts",{wallet:this.walletClientType});try{h.c.rpcRequest("eth_requestAccounts",this.walletClientType);let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(h.c.rpcResponse("eth_requestAccounts",this.walletClientType),!e||0===e.length||!e[0])throw new d.g("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw h.c.connectionFailed(this.walletClientType,e,{method:"injected"}),(0,h.j)(e)}}constructor(e,t,i,r,s){super(s||"unknown",e,t,i),this.connectorType="injected",this.proxyProvider=new c.P(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=r;let n=r.provider;this.proxyProvider.setWalletProvider(n)}}var M="__private_"+D+++"__walletBranding";class L extends c.E{async initialize(){h.c.debug("Initializing legacy injected connector",{wallet:this.walletClientType}),await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){if(h.c.connectionStart(this.walletClientType,"injected (legacy)",{showPrompt:e.showPrompt}),e.showPrompt&&await this.promptConnection(),!await this.isConnected())return h.c.debug("Not connected after prompt",{wallet:this.walletClientType}),null;let t=await this.getConnectedWallet();return t&&h.c.connectionSuccess(this.walletClientType),t}get walletBranding(){return j(this,M)[M]??{name:"Browser Extension",icon:R,id:"extension"}}disconnect(){h.c.debug("Disconnect requested (not supported for legacy injected)",{wallet:this.walletClientType})}async promptConnection(){h.c.debug("Prompting connection via eth_requestAccounts (legacy)",{wallet:this.walletClientType});try{h.c.rpcRequest("eth_requestAccounts",this.walletClientType);let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(h.c.rpcResponse("eth_requestAccounts",this.walletClientType),!e||0===e.length||!e[0])throw new d.g("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw h.c.connectionFailed(this.walletClientType,e,{method:"injected (legacy)"}),(0,h.j)(e)}}constructor(e,t,i,r,s){super(s??"unknown",e,t,i),Object.defineProperty(this,M,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new c.P(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(r),"metamask"===s?j(this,M)[M]={name:"MetaMask",icon:c.M,id:"io.metamask"}:"phantom"===s&&(j(this,M)[M]={name:"Phantom",icon:N,id:"phantom"})}}class B extends U{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){h.c.debug("Prompting connection via MetaMask",{wallet:this.walletClientType});try{g.isMobile||(h.c.rpcRequest("wallet_requestPermissions",this.walletClientType),await this.proxyProvider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]}),h.c.rpcResponse("wallet_requestPermissions",this.walletClientType)),h.c.rpcRequest("eth_requestAccounts",this.walletClientType);let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(h.c.rpcResponse("eth_requestAccounts",this.walletClientType),!e||0===e.length||!e[0])throw new d.g("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw h.c.connectionFailed(this.walletClientType,e,{method:"metamask"}),(0,h.j)(e)}}}class W extends c.E{async initialize(){h.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;h.c.debug("Restoring existing WalletConnect session",{peerName:e?.name,accountsCount:this.walletProvider?.accounts?.length}),this.walletProvider?.session?.peer.metadata.url&&(this.walletEntry=(0,c.e)(this.walletProvider?.session?.peer.metadata.url),this.walletClientType=this.walletEntry?.slug||"unknown"),this.connected=!0,await this.syncAccounts()}
15this.initialized=!0,this.emit("initialized")}async connect(e){h.c.connectionStart(this.walletClientType,"wallet_connect_v2",{showPrompt:e.showPrompt}),e.showPrompt&&await this.promptConnection();let t=await this.getConnectedWallet();return t&&h.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,h.k)(this.walletProvider?.session?.peer.metadata.name||"")||"WalletConnect",icon:"string"==typeof e?e:h.h,id:this.walletProvider?.session?.peer.metadata.name.toLowerCase()||"wallet_connect_v2"}}async resetConnection(e){let t=this.walletClientType;h.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,m.e)(),this.onDisconnect())}async promptConnection(){if(this.provider)return h.c.debug("Prompting WalletConnect connection",{wallet:this.walletClientType}),new Promise((e,t)=>{(async()=>{h.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],h.c.debug("WalletConnect accounts received",{address:t,accountsCount:i.length})),!t||""===t)throw new d.g("Unable to retrieve address");this.walletProvider?.session?.peer.metadata.url&&(this.walletEntry=(0,c.e)(this.walletProvider?.session?.peer.metadata.url),this.walletClientType=this.walletEntry?.slug||"unknown",h.c.debug("Identified wallet from session",{wallet:this.walletClientType}),this.proxyProvider.rpcTimeoutDuration=(0,c.g)(this.rpcConfig,this.walletClientType)),this.connected=!0,await this.syncAccounts(i),e()})().catch(e=>{h.c.connectionFailed(this.walletClientType,e,{method:"wallet_connect_v2"}),t(e?(0,h.j)(e):new d.g("Unknown error during connection"))})});h.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(){h.c.debug("Creating WalletConnect EthereumProvider",{chainsCount:this.chains.length,defaultChainId:this.defaultChain.id});let e={};for(let t of this.chains){let i=(0,h.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);h.c.debug("Initializing WalletConnect EthereumProvider",{requiredChains:t.join(", ")||"none",optionalChainsCount:i.length});let r=await y.EthereumProvider.init({projectId:this.walletConnectCloudProjectId,chains:t,optionalChains:i,optionalEvents:y.OPTIONAL_EVENTS,optionalMethods:y.OPTIONAL_METHODS,rpcMap:e,showQrModal:!1,metadata:{description:this.privyAppName,name:this.privyAppName,url:window.location.origin,icons:[]}});return r.on("display_uri",e=>{if(h.c.debug("WalletConnect URI generated",{wallet:this.walletClientType,isMobile:g.isMobile,hasWalletEntry:!!this.walletEntry}),h.c.debug("Aborting WalletConnect pairing attempt"),r.signer.abortPairingAttempt(),(0,m.r)(),!this.showPrivyQrModal)throw new d.g("WalletConnect modal not available - Privy handles wallet connections through its own UI");if(g.isMobile&&this.walletEntry){let{redirect:t,href:i}=(0,m.b)(e,this.walletEntry),r=t.startsWith("http");h.c.debug("Opening mobile wallet via deep link",{wallet:this.walletEntry.name,redirectType:r?"universal":"native"}),(0,m.o)(t,"_self"),(0,m.s)({href:i,name:this.walletEntry.metadata?.shortName||this.walletEntry.name});let s=(0,m.f)(e,this.walletEntry);return this.redirectUri=t,this.fallbackUniversalRedirectUri=s?.redirect,this.showPrivyQrModal({native:t,universal:t})}if(h.c.debug("Displaying WalletConnect QR code",{wallet:this.walletEntry?.name||"generic"}),this.redirectUri=void 0,this.walletEntry){let t=(0,m.f)(e,this.walletEntry);this.fallbackUniversalRedirectUri=t?.redirect}this.showPrivyQrModal({native:e,universal:void 0})}),r.on("connect",()=>{let e=r.session?.peer.metadata;h.c.debug("WalletConnect session established",{peerName:e?.name,peerIcon:e?.icons?.[0]?"present":"none"}),r.session?.peer.metadata.url&&(this.walletEntry=(0,c.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 c.P(void 0,this.rpcTimeoutDuration),o&&(this.walletEntry=(0,c.f)(o),this.walletClientType=o)}}class q extends l.default{get wallets(){let e=new Set;return this.walletConnectors.flatMap(e=>e.wallets).sort((e,t)=>
15e.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(h.c.info("Starting connector initialization",{reInit:e??!1}),this.initialized&&!e)return;if(e&&this.removeAllConnectors(),this.externalWalletConfig.disableAllExternalWallets)return void h.c.info("All external wallets disabled, skipping initialization");let t=(0,h.n)({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then(e=>{h.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(c.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 c.S({id:e.client,name:e.name})));let i=this.walletList.includes("wallet_connect_qr_solana")||(0,c.s)(this.walletList)&&"ethereum-only"!==this.walletChainType,r=this.externalWalletConfig.walletConnect.enabled&&(this.walletList.includes("wallet_connect_qr")||(0,c.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(c.h).find(t=>t.connectorType===e&&(!i||t.wallets.some(e=>e.address===i)))??null:this.walletConnectors.filter(c.h).find(r=>r.connectorType===e&&r.walletClientType===t&&(!i||r.wallets.some(e=>e.address===i)))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(c.d).find(t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e)??null}onInitialized(e){h.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}){h.c.debug("Creating Ethereum wallet connector",{connector:e,wallet:t});let s=this.findWalletConnector(e,t);if(s&&(0,c.h)(s))return h.c.debug("Found existing connector, reusing",{connector:e,wallet:t}),s instanceof W&&s.resetConnection(t),s;let n="injected"!==e?"coinbase_wallet"===e?new T(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new k(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new W({walletConnectCloudProjectId:this.walletConnectCloudProjectId,rpcConfig:this.rpcConfig,chains:this.chains,defaultChain:this.defaultChain,shouldEnforceDefaultChainOnConnect:this.shouldEnforceDefaultChainOnConnect,privyAppId:this.privyAppId,privyAppName:this.privyAppName,walletClientType:t}):r?new c.j({id:r.client,name:r.name,defaultChain:this.defaultChain,walletClientType:r.client}):null:"metamask"===t&&i?.eip6963InjectedProvider?new B(this.chains,this.defaultChain,this.rpcConfig,i?.eip6963InjectedProvider,"metamask"):"metamask"===t&&i?.legacyInjectedProvider?new L(this.chains,this.defaultChain,this.rpcConfig,i?.legacyInjectedProvider,"metamask"):"phantom"===t&&i?.legacyInjectedProvider?new L(this.chains,this.defaultChain,this.rpcConfig,i?.legacyInjectedProvider,"phantom"):i?.legacyInjectedProvider&&"unknown_browser_extension"===t?new L(this.chains,this.defaultChain,this.rpcConfig,i?.legacyInjectedProvider):i?.eip6963InjectedProvider?new U(this.chains,this.defaultChain,this.rpcConfig,i?.eip6963InjectedProvider,t):void 0;return n?(h.c.connectorCreated(e,t),this.addWalletConnector(n)):h.c.debug("No connector created",{connector:e,wallet:t}),n||null}addWalletConnector(e){h.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=>
15{h.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,d,u,p){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)}},h.c.setEnabled(p??!1),h.c.info("ConnectorManager initializing",{walletChainType:u||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=u||"ethereum-only",this.setBaseAccountSdk=d,this.storedConnections=(0,h.l)()}}let K=(0,b.create)(()=>({identityToken:null})),H=[E.s,E.m,E.n];class z{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw(0,d.f)(e)}}async post(e,t,i){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...i})}catch(e){throw(0,d.f)(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw(0,d.f)(e)}}constructor({appId:e,appClientId:t,client:i,defaults:r}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=i.clientAnalyticsId,this.sdkVersion=w.V,this.client=i,this.defaults=r,this.fallbackApiUrl=i.fallbackApiUrl,this.baseFetch=v.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=H.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 d.h}})}}let $=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});crypto.randomUUID();let J=Symbol("cross-tab-user-sync-plugin");class F{async authenticate(){if(!this.api)throw new d.P("Auth flow has no API instance");try{return await this.api.post(E.q,{token:this.meta.token})}catch(e){throw(0,d.f)(e)}}async link(){if(!this.api)throw new d.P("Auth flow has no API instance");try{return await this.api.post(E.r,{token:this.meta.token})}catch(e){throw(0,d.f)(e)}}constructor(e){this.meta={token:e}}}function V(e){return e?{"privy-ui":"t"}:void 0}class G{async authenticate(){if(!this.api)throw new d.P("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new d.P("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(E.u,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw(0,d.f)(e)}}async link(){if(!this.api)throw new d.P("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new d.P("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(E.v,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw(0,d.f)(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:i}){if(!this.api)throw new d.P("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new d.P("Email must be set when initialzing authentication.");let r=V(i);try{return await this.api.post(E.w,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...r}})}catch(e){throw(0,d.f)(e)}}constructor({email:e,captchaToken:t,disableSignup:i}){this.meta={email:e,captchaToken:t,disableSignup:i??!1}}}class Y{getOrCreateGuestCredential(e){let t=(0,w.g)(e);
15if((0,h.e)()){if(h.s.get(t))return h.s.get(t);{let e=a.base64url.encode((0,m.g)(32));return h.s.put(t,e),e}}return a.base64url.encode((0,m.g)(32))}async authenticate(){if(!this.api)throw new d.P("Auth flow has no API instance");try{return await this.api.post(E.y,{guest_credential:this.meta.guestCredential})}catch(e){throw(0,d.f)(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}function Z(){return"u">typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function Q(){if(!Z())return;let e=window.chrome;return e?.runtime?.id}function X(){if(!Z())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function ee(e){return new Promise((t,i)=>{X()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},async e=>{try{let i=function(){if(!Z())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=Q();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 et{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new d.P("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new d.P("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new d.P("User denied confirmation during OAuth flow");let e=(0,m.h)();try{let t=await this.api.post(E.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 h.s.del(w.f),h.s.del(w.H),h.s.del(w.O),t}catch(t){let e=(0,d.f)(t);if(e.privyErrorCode)throw new d.P(e.message||"Invalid code during OAuth flow.",void 0,e.privyErrorCode);if("User denied confirmation during OAuth flow"===e.message)throw new d.P("Invalid code during oauth flow.",void 0,d.a.OAUTH_USER_DENIED);throw new d.P("Invalid code during OAuth flow.",void 0,d.a.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new d.P("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new d.P("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new d.P("User denied confirmation during OAuth flow");let e=h.s.get(w.f);if(!e)throw new d.P("Authentication error.");try{let t=await this.api.post(E.k,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return h.s.del(w.f),t}catch(e){throw(0,d.f)(e)}}async getAuthorizationUrl(){if(!this.api)throw new d.P("Auth flow has no API instance");if(!this.meta.provider)throw new d.P("Provider must be set when initializing OAuth authentication.");let e=(0,m.c)();h.s.put(w.f,e);let t=(0,m.a)();h.s.put(w.S,t);let i=await (0,m.d)(e);this.meta.withPrivyUi||h.s.put(w.H,!0),this.meta.disableSignup?h.s.put(w.O,!0):h.s.del(w.O);let r=V(this.meta.withPrivyUi),s=window.location.href,n=function(){let e=Q();if(e)return`https://${e}.chromiumapp.org`}();n&&(s=n);try{return await this.api.post(E.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,d.f)(e)}}constructor(e){this.meta=e}}class ei{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 er=({address:e,chainId:t,nonce:i})=>`${window.location.host} wants you to sign in with your Ethereum account:
16${e}
17
18By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.
19
20URI: ${window.location.origin}
21Version: 1
22Chain ID: ${t}
23Nonce: ${i}
24Issued At: ${(new Date).toISOString()}
25Resources:
26- https://privy.io`;
26class es{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 d.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 d.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,d.f)(e)}}async link(){if(!this.client)throw new d.P("SiweFlow has no client instance");try{if(!this.wallet)throw new d.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,d.f)(e)}}async sign(){if(!this.client)throw new d.P("SiweFlow has no client instance");if(await this.buildMessage(),!this.preparedMessage)throw new d.P("Could not prepare SIWE message");if(!this.wallet)throw new d.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 d.P("SiweFlow has no client instance");if(!this.wallet)throw new d.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 d.P("SiweFlow has no client instance");if(!this.wallet)throw new d.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=er({address:e,chainId:t,nonce:this.nonce}),this.preparedMessage}constructor(e,t,i,r=!1,s){this._meta={disableSignup:!1},this.getNonceOnce=new ei(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 en{async authenticate(){if(!this.api)throw new d.P("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new d.P("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(E.z,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw(0,d.f)(e)}}async link(){if(!this.api)throw new d.P("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new d.P("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(E.A,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw(0,d.f)(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:i}){if(!this.api)throw new d.P("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new d.P("phone nNumber must be set when initialzing authentication.");let r=V(i);try{return await this.api.post(E.B,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...r}})}catch(e){throw(0,d.f)(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:i}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:i??!1}}}function ea(){return!(g.isSafari&&window.location.origin.startsWith("http://localhost"))}var eo,el=((eo={}).PRIVY="privy_access_token",eo.CUSTOMER="customer_access_token",eo);class ec{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(w.d)}get privyAccessToken(){return this._getToken(w.h)}_getToken(e){try{let t=h.s.get(e);return"string"==typeof t?A.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=h.s.get(w.R);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=h.s.get((0,w.e)(e));if("string"!=typeof t)return null;{let i=new A(t);return i.isExpired()?(h.s.del((0,w.e)(e)),null):i.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=I.default.get(w.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!==w.j;return this.mightHaveServerCookies||t&&i}hasActiveAccessToken(e){let t=A.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?h.s.put((0,w.e)(e),t):h.s.del((0,w.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,o.j)(i),isNewUser:r,oAuthTokens:n}}catch(e){throw console.warn("Error authenticating session"),(0,d.i)(e)}}_trackAuthenticateEvents(e,t){let i=e instanceof G?"email":e instanceof en?"sms":e instanceof es?"siwe":e instanceof Y?"guest":e instanceof F?"custom_auth":e instanceof et?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,o.j)(t),oAuthTokens:r}}catch(e){throw console.warn("Error linking account"),(0,d.i)(e)}}async _refresh(){if(!this.api)throw new d.P("Session has no API instance");if(!this.client)throw new d.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(E.s,t?{refresh_token:t}:{},{headers:r})}return this.handleTokenResponse(i),(0,o.j)(i.user)}catch(e){if(e instanceof d.d&&e.privyErrorCode===d.a.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw(0,d.i)(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(E.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=h.s.get(w.d);if(h.s.put(w.d,e),!this.client?.useServerCookies){let t=A.parse(e)?.expiration;
26I.default.set(w.k,e,{sameSite:"Strict",secure:ea(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else h.s.del(w.d),I.default.remove(w.k),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(h.s.put(w.R,e),this.client?.useServerCookies||I.default.set(w.i,"t",{sameSite:"Strict",secure:ea(),expires:30})):(h.s.del(w.R),I.default.remove(w.l),I.default.remove(w.i))}storePrivyAccessToken(e){"string"==typeof e?h.s.put(w.h,e):h.s.del(w.h)}storeIdentityToken(e){if(K.setState({identityToken:e}),this.client?.useServerCookies)return;h.s.put(w.I,e);let t=A.parse(e)?.expiration;I.default.set(w.m,e,{sameSite:"Strict",secure:ea(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){h.s.del(w.I),K.setState({identityToken:null}),I.default.remove(w.m)}constructor(){this.authenticateOnce=new ei(async e=>this._authenticate(e)),this.linkOnce=new ei(async e=>this._link(e)),this.refreshOnce=new ei(this._refresh.bind(this)),this.destroyOnce=new ei(this._destroy.bind(this))}}var eh=0,ed="__private_"+eh+++"__getOrGenerateClientAnalyticsId";class eu{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 q(this.appId,e,t,i,r,s,n,a,o,l,h,c,d))}generateApi(){let e=new z({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 d.P("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new d.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(E.D,{action:"verify"})}catch(e){throw(0,d.f)(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(E.E,{});return $(e.options)}catch(e){throw(0,d.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(E.F,{});return(0,o.j)(e)}catch(e){throw(0,d.i)(e)}}async unlinkEmail(e){try{let t=await this.api.post(E.G,{address:e});return await this.getAuthenticatedUser()??(0,o.j)(t)}catch(e){throw(0,d.i)(e)}}async unlinkPhone(e){try{let t=await this.api.post(E.H,{phoneNumber:e});return await this.getAuthenticatedUser()??(0,o.j)(t)}catch(e){throw(0,d.i)(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(E.I,{address:e});return await this.getAuthenticatedUser()??(0,o.j)(t)}catch(e){throw(0,d.i)(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(E.J,{address:e});return await this.getAuthenticatedUser()??(0,o.j)(t)}catch(e){throw(0,d.i)(e)}}async unlinkOAuth(e,t){try{let i=await this.api.post(E.K,{provider:e,subject:t});return await this.getAuthenticatedUser()??(0,o.j)(i)}catch(e){throw(0,d.i)(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(E.L,{fid:e});return await this.getAuthenticatedUser()??(0,o.j)(t)}catch(e){throw(0,d.i)(e)}}async unlinkTelegram(e){try{let t=await this.api.post(E.M,{telegram_user_id:e});return await this.getAuthenticatedUser()??(0,o.j)(t)}catch(e){throw(0,d.i)(e)}}async revokeDelegatedWallet(){try{await this.api.post(E.N,{})}catch(e){throw(0,d.i)(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:i,options:r}){if("u">typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(E.n,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:i?i.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:r?.keepAlive??!1})}catch(e){console.log("Unable to submit event. This is not an issue.")}}async signMoonpayOnRampUrl(e){try{return this.api.post(E.O,e)}catch(e){throw(0,d.i)(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(E.P,e)}catch(e){throw(0,d.i)(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${E.Q}?partnerUserId=${e}`)}catch(e){throw(0,d.i)(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(el.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(el.PRIVY,e)}async _getToken(e,t){if(!this.session.getToken(e))return null;if(this.session.hasActiveAccessToken(e))return this.session.hasRefreshCredentials(e)?x.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 t=(0,_.g)(J);return t?await t.withRefreshLock({onLeader:async()=>(await this.session.refresh(),this.session.getToken(e)),onFollowerReleased:async()=>this.session.hasActiveAccessToken(e)?this.session.getToken(e):null}):(await this.session.refresh(),this.session.getToken(e))}}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}
26&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(E.R,{address:e,token:t})).nonce}catch(e){throw(0,d.i)(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:i,walletClientType:r,connectorType:s,mode:n}){return await this.api.post(E.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(E.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(E.U,{message:e,signature:t,smart_wallet_type:i,smart_wallet_version:r});return(0,o.j)(s)}catch(e){throw(0,d.i)(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,o.j)(n)}catch(e){throw(0,d.i)(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(E.V,{address:e,token:t})).nonce}catch(e){throw(0,d.i)(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:i,connectorType:r,mode:s,messageType:n="plain"}){return await this.api.post(E.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 l=(0,o.j)(a.user);if(!l)throw Error("Authentication failed - no user returned");return{user:l,isNewUser:a.is_new_user||!1}}async sendAccountTransferRequest({nonce:e,account:t,accountType:i,externalWalletMetadata:r,telegramAuthResult:s,telegramWebAppData:n,farcasterEmbeddedAddress:a,oAuthUserInfo:l}){try{let c,h;switch(i){case"email":c=E.a1,h={nonce:e,email:t};break;case"sms":c=E.a0,h={nonce:e,phoneNumber:t};break;case"siwe":if(c=E.$,!r)throw Error("Wallet parameters must be defined");h={nonce:e,address:t,...r};break;case"farcaster":c=E._,h={nonce:e,farcaster_id:t,farcaster_embedded_address:a};break;case"telegram":c=E.Z,h={nonce:e,telegram_auth_result:s,telegram_web_app_data:n};break;case"siws":c=E.Y,h={nonce:e,address:t,...r};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:c=E.X,h={nonce:e,userInfo:l}}let d=await this.api.post(c,h);return await this.getAuthenticatedUser()??(0,o.j)(d)}catch(e){throw(0,d.i)(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:i,connectorType:r,messageType:s="plain"}){return await this.api.post(E.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,o.j)(n)}catch(e){throw(0,d.i)(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(E.a3);return this.session.updateIdentityToken(e.identity_token),(0,o.j)(e.user)}catch(e){throw(0,d.i)(e)}}async scanTransaction(e){try{return await this.api.post(E.a4,e)}catch(e){throw(0,d.i)(e)}}constructor({apiUrl:e=w.D,appId:t,appClientId:i,timeout:s=w.n}){Object.defineProperty(this,ed,{value:ep}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==w.D&&e.startsWith("https://privy."),this.timeout=s,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,ed)[ed](),r||(r=new ec),this.session=r,this.api=this.generateApi(),this.session.client=this}}function ep(){if("u"<typeof window)return null;try{let e=h.s.get(w.c);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=crypto.randomUUID();try{return h.s.put(w.c,e),e}catch(t){return e}}function ef(){if(!s)throw new d.P("No global PrivyClient instance found. Please ensure you have initialized the PrivyProvider.");return s}async function eg(){let e=ef();return e?e.getAccessToken():Promise.resolve(h.s.get(w.h)||h.s.get(w.d)||null)}async function ey(e,t,i,r){let s=(0,S.toViemTransactionSerializable)(e),{chain:n,...a}=await (async()=>r?await r():await t.prepareTransactionRequest({...s,account:{address:i,type:"json-rpc"}}))();return{...a,type:S.STRING_TO_NUMBER_TXN_TYPE[a.type]}}e.s(["B",0,R,"C",0,F,"E",0,G,"G",0,Y,"O",0,et,"R",0,ei,"S",0,es,"T",0,A,"U",0,class extends en{async link(){if(!this.api)throw new d.P("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new d.P("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(E.C,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw(0,d.f)(e)}}constructor(e,t,i){super({phoneNumber:t,captchaToken:i}),this.meta={phoneNumber:t,captchaToken:i,oldPhoneNumber:e,disableSignup:!1}}},"W",0,W,"a",0,eg,"b",0,en,"c",0,class extends G{async link(){if(!this.api)throw new d.P("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new d.P("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(E.x,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw(0,d.f)(e)}}constructor(e,t,i){super({email:t,captchaToken:i}),this.meta={email:t,captchaToken:i,oldAddress:e,disableSignup:!1}}},"d",0,ey,"e",0,function(e){s||(s=new eu({appId:e.appId,appClientId:e.clientId,apiUrl:e.apiUrl}))}
26,"f",0,ef,"g",0,V,"h",0,X,"l",0,ee,"n",0,P,"o",0,C,"p",0,er,"q",0,N,"r",0,({style:e,...t})=>(0,u.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,u.jsx)("rect",{width:"1024",height:"1024",fill:"#0052FF",rx:100,ry:100}),(0,u.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"})]}),"t",0,$])}]);
27
28//# debugId=bd2c9d0e-a766-7f5b-5492-41e18f706019

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.