diff --git a/assets/index-CCN2EzLo.js b/assets/index-C_OlKanQ.js similarity index 99% rename from assets/index-CCN2EzLo.js rename to assets/index-C_OlKanQ.js index e5f085e..0ea04cb 100644 --- a/assets/index-CCN2EzLo.js +++ b/assets/index-C_OlKanQ.js @@ -156,7 +156,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _unsupportedIterableToArray(e,a){if(e){if(typeof e=="string")return _arrayLikeToArray(e,a);var o=Object.prototype.toString.call(e).slice(8,-1);if(o==="Object"&&e.constructor&&(o=e.constructor.name),o==="Map"||o==="Set")return Array.from(e);if(o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o))return _arrayLikeToArray(e,a)}}function _arrayLikeToArray(e,a){(a==null||a>e.length)&&(a=e.length);for(var o=0,c=new Array(a);oo.split("").map(c=>{const h=c.charCodeAt(0);if(h<32||h>126)throw new Error("Cannot encode character that is out of printable ASCII range: "+h);return h});return Uint8Array.from(a(e))}ascii.toAscii=toAscii;function fromAscii(e){return(o=>o.map(c=>{if(c<32||c>126)throw new Error("Cannot decode character that is out of printable ASCII range: "+c);return String.fromCharCode(c)}))(Array.from(e)).join("")}ascii.fromAscii=fromAscii;var base64={},base64Js={};base64Js.byteLength=byteLength;base64Js.toByteArray=toByteArray;base64Js.fromByteArray=fromByteArray;var lookup=[],revLookup=[],Arr=typeof Uint8Array<"u"?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");var o=e.indexOf("=");o===-1&&(o=a);var c=o===a?0:4-o%4;return[o,c]}function byteLength(e){var a=getLens(e),o=a[0],c=a[1];return(o+c)*3/4-c}function _byteLength(e,a,o){return(a+o)*3/4-o}function toByteArray(e){var a,o=getLens(e),c=o[0],h=o[1],d=new Arr(_byteLength(e,c,h)),_=0,_e=h>0?c-4:c,tt;for(tt=0;tt<_e;tt+=4)a=revLookup[e.charCodeAt(tt)]<<18|revLookup[e.charCodeAt(tt+1)]<<12|revLookup[e.charCodeAt(tt+2)]<<6|revLookup[e.charCodeAt(tt+3)],d[_++]=a>>16&255,d[_++]=a>>8&255,d[_++]=a&255;return h===2&&(a=revLookup[e.charCodeAt(tt)]<<2|revLookup[e.charCodeAt(tt+1)]>>4,d[_++]=a&255),h===1&&(a=revLookup[e.charCodeAt(tt)]<<10|revLookup[e.charCodeAt(tt+1)]<<4|revLookup[e.charCodeAt(tt+2)]>>2,d[_++]=a>>8&255,d[_++]=a&255),d}function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[e&63]}function encodeChunk(e,a,o){for(var c,h=[],d=a;d_e?_e:_+d));return c===1?(a=e[o-1],h.push(lookup[a>>2]+lookup[a<<4&63]+"==")):c===2&&(a=(e[o-2]<<8)+e[o-1],h.push(lookup[a>>10]+lookup[a>>4&63]+lookup[a<<2&63]+"=")),h.join("")}var __createBinding$1=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(e,a,o,c){c===void 0&&(c=o);var h=Object.getOwnPropertyDescriptor(a,o);(!h||("get"in h?!a.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return a[o]}}),Object.defineProperty(e,c,h)}:function(e,a,o,c){c===void 0&&(c=o),e[c]=a[o]}),__setModuleDefault$1=commonjsGlobal&&commonjsGlobal.__setModuleDefault||(Object.create?function(e,a){Object.defineProperty(e,"default",{enumerable:!0,value:a})}:function(e,a){e.default=a}),__importStar$1=commonjsGlobal&&commonjsGlobal.__importStar||function(e){if(e&&e.__esModule)return e;var a={};if(e!=null)for(var o in e)o!=="default"&&Object.prototype.hasOwnProperty.call(e,o)&&__createBinding$1(a,e,o);return __setModuleDefault$1(a,e),a};Object.defineProperty(base64,"__esModule",{value:!0});base64.fromBase64=base64.toBase64=void 0;const base64js=__importStar$1(base64Js);function toBase64(e){return base64js.fromByteArray(e)}base64.toBase64=toBase64;function fromBase64(e){if(!e.match(/^[a-zA-Z0-9+/]*={0,2}$/))throw new Error("Invalid base64 string format");return base64js.toByteArray(e)}base64.fromBase64=fromBase64;var bech32$2={},ALPHABET="qpzry9x8gf2tvdw0s3jn54khce6mua7l",ALPHABET_MAP={};for(var z=0;z>25;return(e&33554431)<<5^-(a>>0&1)&996825010^-(a>>1&1)&642813549^-(a>>2&1)&513874426^-(a>>3&1)&1027748829^-(a>>4&1)&705979059}function prefixChk(e){for(var a=1,o=0;o126)return"Invalid prefix ("+e+")";a=polymodStep(a)^c>>5}for(a=polymodStep(a),o=0;oo)throw new TypeError("Exceeds length limit");e=e.toLowerCase();var c=prefixChk(e);if(typeof c=="string")throw new Error(c);for(var h=e+"1",d=0;d>5)throw new Error("Non 5-bit word");c=polymodStep(c)^_,h+=ALPHABET.charAt(_)}for(d=0;d<6;++d)c=polymodStep(c);for(c^=1,d=0;d<6;++d){var _e=c>>(5-d)*5&31;h+=ALPHABET.charAt(_e)}return h}function __decode(e,a){if(a=a||90,e.length<8)return e+" too short";if(e.length>a)return"Exceeds length limit";var o=e.toLowerCase(),c=e.toUpperCase();if(e!==o&&e!==c)return"Mixed-case string "+e;e=o;var h=e.lastIndexOf("1");if(h===-1)return"No separator character for "+e;if(h===0)return"Missing prefix for "+e;var d=e.slice(0,h),_=e.slice(h+1);if(_.length<6)return"Data too short";var _e=prefixChk(d);if(typeof _e=="string")return _e;for(var tt=[],rt=0;rt<_.length;++rt){var it=_.charAt(rt),st=ALPHABET_MAP[it];if(st===void 0)return"Unknown character "+it;_e=polymodStep(_e)^st,!(rt+6>=_.length)&&tt.push(st)}return _e!==1?"Invalid checksum for "+e:{prefix:d,words:tt}}function decodeUnsafe(){var e=__decode.apply(null,arguments);if(typeof e=="object")return e}function decode(e){var a=__decode.apply(null,arguments);if(typeof a=="object")return a;throw new Error(a)}function convert(e,a,o,c){for(var h=0,d=0,_=(1<=o;)d-=o,_e.push(h>>d&_);if(c)d>0&&_e.push(h<=a)return"Excess padding";if(h<0&&!a.includes(e.length))throw new Error(`Uint8Array expected of length ${a}, not of length=${e.length}`)}function exists$1(e,a=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(a&&e.finished)throw new Error("Hash#digest() has already been called")}function output$1(e,a){bytes$1(e);const o=a.outputLen;if(e.lengthnew DataView(e.buffer,e.byteOffset,e.byteLength),rotr$1=(e,a)=>e<<32-a|e>>>a,rotl=(e,a)=>e<>>32-a>>>0;new Uint8Array(new Uint32Array([287454020]).buffer)[0];function utf8ToBytes$2(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function toBytes$1(e){return typeof e=="string"&&(e=utf8ToBytes$2(e)),bytes$1(e),e}let Hash$1=class{clone(){return this._cloneInto()}};function wrapConstructor$1(e){const a=c=>e().update(toBytes$1(c)).digest(),o=e();return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=()=>e(),a}function setBigUint64$1(e,a,o,c){if(typeof e.setBigUint64=="function")return e.setBigUint64(a,o,c);const h=BigInt(32),d=BigInt(4294967295),_=Number(o>>h&d),_e=Number(o&d),tt=c?4:0,rt=c?0:4;e.setUint32(a+tt,_,c),e.setUint32(a+rt,_e,c)}const Chi$1=(e,a,o)=>e&a^~e&o,Maj$1=(e,a,o)=>e&a^e&o^a&o;class HashMD extends Hash$1{constructor(a,o,c,h){super(),this.blockLen=a,this.outputLen=o,this.padOffset=c,this.isLE=h,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(a),this.view=createView$1(this.buffer)}update(a){exists$1(this);const{view:o,buffer:c,blockLen:h}=this;a=toBytes$1(a);const d=a.length;for(let _=0;_h-_&&(this.process(c,0),_=0);for(let st=_;stit.length)throw new Error("_sha2: outputLen bigger than state");for(let st=0;st>>3,yt=rotr$1(mt,17)^rotr$1(mt,19)^mt>>>10;SHA256_W$1[st]=yt+SHA256_W$1[st-7]+vt+SHA256_W$1[st-16]|0}let{A:c,B:h,C:d,D:_,E:_e,F:tt,G:rt,H:it}=this;for(let st=0;st<64;st++){const ht=rotr$1(_e,6)^rotr$1(_e,11)^rotr$1(_e,25),mt=it+ht+Chi$1(_e,tt,rt)+SHA256_K$1[st]+SHA256_W$1[st]|0,yt=(rotr$1(c,2)^rotr$1(c,13)^rotr$1(c,22))+Maj$1(c,h,d)|0;it=rt,rt=tt,tt=_e,_e=_+mt|0,_=d,d=h,h=c,c=mt+yt|0}c=c+this.A|0,h=h+this.B|0,d=d+this.C|0,_=_+this.D|0,_e=_e+this.E|0,tt=tt+this.F|0,rt=rt+this.G|0,it=it+this.H|0,this.set(c,h,d,_,_e,tt,rt,it)}roundClean(){SHA256_W$1.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const sha256$2=wrapConstructor$1(()=>new SHA256$1),Rho=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Id=new Uint8Array(new Array(16).fill(0).map((e,a)=>a)),Pi=Id.map(e=>(9*e+5)%16);let idxL=[Id],idxR=[Pi];for(let e=0;e<4;e++)for(let a of[idxL,idxR])a.push(a[e].map(o=>Rho[o]));const shifts=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>new Uint8Array(e)),shiftsL=idxL.map((e,a)=>e.map(o=>shifts[a][o])),shiftsR=idxR.map((e,a)=>e.map(o=>shifts[a][o])),Kl=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Kr=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function f(e,a,o,c){return e===0?a^o^c:e===1?a&o|~a&c:e===2?(a|~o)^c:e===3?a&c|o&~c:a^(o|~c)}const R_BUF=new Uint32Array(16);class RIPEMD160 extends HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:a,h1:o,h2:c,h3:h,h4:d}=this;return[a,o,c,h,d]}set(a,o,c,h,d){this.h0=a|0,this.h1=o|0,this.h2=c|0,this.h3=h|0,this.h4=d|0}process(a,o){for(let mt=0;mt<16;mt++,o+=4)R_BUF[mt]=a.getUint32(o,!0);let c=this.h0|0,h=c,d=this.h1|0,_=d,_e=this.h2|0,tt=_e,rt=this.h3|0,it=rt,st=this.h4|0,ht=st;for(let mt=0;mt<5;mt++){const vt=4-mt,yt=Kl[mt],_t=Kr[mt],$t=idxL[mt],bt=idxR[mt],xt=shiftsL[mt],St=shiftsR[mt];for(let Rt=0;Rt<16;Rt++){const Ot=rotl(c+f(mt,d,_e,rt)+R_BUF[$t[Rt]]+yt,xt[Rt])+st|0;c=st,st=rt,rt=rotl(_e,10)|0,_e=d,d=Ot}for(let Rt=0;Rt<16;Rt++){const Ot=rotl(h+f(vt,_,tt,it)+R_BUF[bt[Rt]]+_t,St[Rt])+ht|0;h=ht,ht=it,it=rotl(tt,10)|0,tt=_,_=Ot}}this.set(this.h1+_e+it|0,this.h2+rt+ht|0,this.h3+st+h|0,this.h4+c+_|0,this.h0+d+tt|0)}roundClean(){R_BUF.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const ripemd160=wrapConstructor$1(()=>new RIPEMD160);var ellipticExports=requireElliptic();const elliptic=getDefaultExportFromCjs$1(ellipticExports),secp256k1$1=new elliptic.ec("secp256k1");function hexStringToBase64(e){return e.substring(0,2)==="0x"&&(e=e.substring(2)),Buffer$B.from(e,"hex").toString("base64")}function compressPubkey(e){switch(e.length){case 33:return e;case 65:return Uint8Array.from(secp256k1$1.keyFromPublic(e).getPublic(!0,"array"));default:throw new Error("Invalid pubkey length")}}function rawSecp256k1PubkeyToRawAddress(e){if(e.length!==33)throw new Error(`Invalid Secp256k1 pubkey length (compressed): ${e.length}`);return ripemd160(sha256$2(e))}function getCosmosAddress(e,a){const o=new Uint8Array(Buffer$B.from(e.startsWith("0x")?e.slice(2):e,"hex")),c=compressPubkey(o);return build.toBech32(a,rawSecp256k1PubkeyToRawAddress(c))}function truncateAddress(e,a,{prefix:o=a==="COSMOS"?"cosmos":void 0}={}){const c=(a==="COSMOS"?o.length:a==="SOLANA"?0:2)+4;return`${e.slice(0,c)}...${e.slice(-4)}`}class TransactionReviewError extends Error{constructor(a){super("transaction review error"),this.name="TransactionReviewError",this.transactionReviewUrl=a}}class TransactionReviewDenied extends Error{constructor(){super("transaction review has been denied by the user"),this.name="TransactionReviewDenied"}}class TransactionReviewTimeout extends TransactionReviewError{constructor(a,o){super("transaction review has timed out"),this.name="TransactionReviewTimeout",this.transactionReviewUrl=a,this.pendingTransactionId=o}}var __awaiter$9=function(e,a,o,c){function h(d){return d instanceof o?d:new o(function(_){_(d)})}return new(o||(o=Promise))(function(d,_){function _e(it){try{rt(c.next(it))}catch(st){_(st)}}function tt(it){try{rt(c.throw(it))}catch(st){_(st)}}function rt(it){it.done?d(it.value):h(it.value).then(_e,tt)}rt((c=c.apply(e,a||[])).next())})},__classPrivateFieldGet=function(e,a,o,c){if(o==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof a=="function"?e!==a||!c:!a.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?c:o==="a"?c.call(e):c?c.value:a.get(e)},__classPrivateFieldSet=function(e,a,o,c,h){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!h)throw new TypeError("Private accessor was defined without a setter");if(typeof a=="function"?e!==a||!h:!a.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?h.call(e,o):h?h.value=o:a.set(e,o),o},__rest$2=function(e,a){var o={};for(var c in e)Object.prototype.hasOwnProperty.call(e,c)&&a.indexOf(c)<0&&(o[c]=e[c]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var h=0,c=Object.getOwnPropertySymbols(e);ho?`&${a}=${encodeURIComponent(o)}`:"").join("")}function isWalletSupported(e,a){return e.some(o=>!!WalletSchemeTypeMap[a.scheme][o])}function getSchemes(e){return Object.keys(WalletSchemeTypeMap).filter(a=>a===WalletScheme.CGGMP?!1:(Array.isArray(e)?e:Object.keys(e)).some(o=>WalletSchemeTypeMap[a][o]))}function getWalletTypes(e){return[...new Set(e.reduce((a,o)=>[...a,...Object.keys(WalletSchemeTypeMap[o]).filter(c=>WalletSchemeTypeMap[o][c])],[]))]}function getEquivalentTypes(e){return getWalletTypes(getSchemes((Array.isArray(e)?e:[e]).map(a=>WalletType[a])))}class CoreCapsule{get currentWalletIdsArray(){return this.supportedWalletTypes.reduce((a,{type:o})=>{var c;return[...a,...((c=this.currentWalletIds[o])!==null&&c!==void 0?c:[]).map(h=>[h,o])]},[])}get currentWalletIdsUnique(){return[...new Set(Object.values(this.currentWalletIds).flat())]}get isMultiWallet(){return this.currentWalletIdsArray.length>1}get supportedWalletTypes(){var a;return(a=__classPrivateFieldGet(this,_CoreCapsule_supportedWalletTypes,"f"))!==null&&a!==void 0?a:[]}get isWalletTypeEnabled(){return this.supportedWalletTypes.reduce((a,{type:o})=>Object.assign(Object.assign({},a),{[o]:!0}),{})}convertBigInt(a){const o=new jsbn.BigInteger(null);return o.data=a.data,o.s=a.s,o.t=a.t,o}convertEncryptionKeyPair(a){return{privateKey:pki.setRsaPrivateKey(this.convertBigInt(a.privateKey.n),this.convertBigInt(a.privateKey.e),this.convertBigInt(a.privateKey.d),this.convertBigInt(a.privateKey.p),this.convertBigInt(a.privateKey.q),this.convertBigInt(a.privateKey.dP),this.convertBigInt(a.privateKey.dQ),this.convertBigInt(a.privateKey.qInv)),publicKey:pki.setRsaPublicKey(this.convertBigInt(a.publicKey.n),this.convertBigInt(a.publicKey.e))}}isPortal(){return typeof window<"u"&&getPortalBaseURL(this.ctx).includes(window.location.host)}requireApiKey(){if(!this.ctx.apiKey)throw new Error(`in order to create a wallet or user with Capsule, you must provide an API key to the capsule instance`)}isWalletSupported(a){var o;return!__classPrivateFieldGet(this,_CoreCapsule_supportedWalletTypes,"f")||isWalletSupported((o=this.supportedWalletTypes.map(({type:c})=>c))!==null&&o!==void 0?o:[],a)}isWalletOwned(a){return this.isWalletSupported(a)&&!a.pregenIdentifier&&!a.pregenIdentifierType&&!!this.userId&&a.userId===this.userId}isPregenWalletUnclaimed(a){return this.isWalletSupported(a)&&(!a.userId||a.isPregen&&!!a.pregenIdentifier&&!!a.pregenIdentifierType)}isPregenWalletClaimable(a){return this.isWalletSupported(a)&&this.isPregenWalletUnclaimed(a)&&(a.pregenIdentifier===this.email&&a.pregenIdentifierType===PregenIdentifierType.EMAIL||stringToPhoneNumber(a.pregenIdentifier)===this.getPhoneNumber()&&a.pregenIdentifierType===PregenIdentifierType.PHONE)}isWalletUsable(a,{type:o,scheme:c,forbidPregen:h=!1}={},d=!1){let _;if(!this.wallets[a])_=`wallet with id ${a} does not exist`;else{const _e=this.wallets[a],[tt,rt]=[this.isPregenWalletUnclaimed(_e),this.isWalletOwned(_e)];h&&tt?_=`pre-generated wallet with id ${_e.id} cannot be selected`:!rt&&!tt?_=`wallet with id ${_e.id} is not owned by the current user`:this.isWalletSupported(_e)?o&&(!getEquivalentTypes(o).includes(_e.type)||rt&&!o.some(it=>{var st;return((st=this.currentWalletIds[it])!==null&&st!==void 0?st:[]).includes(a)}))?_=`wallet with id ${_e.id} and type ${_e.type} cannot be selected`:c&&!c.includes(_e.scheme)&&(_=`wallet with id ${_e.id} and scheme ${_e.scheme} cannot be selected`):_=`wallet with id ${_e.id} and type ${_e.type} is not supported, supported types are: ${this.supportedWalletTypes.map(({type:it})=>it).join(", ")}`}if(_){if(d)throw new Error(_);return!1}return!0}getDisplayAddress(a,o={}){var c;if(this.externalWallets[a]){const _=this.externalWallets[a];return o.truncate?truncateAddress(_.address,_.type,{prefix:this.cosmosPrefix}):_.address}const h=this.findWallet(a,o.addressType);if(!h)return;let d;switch(h.type){case WalletType.COSMOS:d=getCosmosAddress(h.publicKey,(c=this.cosmosPrefix)!==null&&c!==void 0?c:"cosmos");break;default:d=h.address;break}return o.truncate?truncateAddress(d,h.type,{prefix:this.cosmosPrefix}):d}getIdenticonHash(a,o){if(this.externalWallets[a]){const h=this.externalWallets[a];return`${h.id}-${h.address}-${h.type}`}const c=this.findWallet(a,o);return c?`${c.id}-${c.address}-${c.type}`:void 0}getWallets(){return this.wallets}getAddress(a){var o,c;return a?this.wallets[a].address:(c=(o=Object.values(this.wallets))===null||o===void 0?void 0:o[0])===null||c===void 0?void 0:c.address}constructor(a,o,c){var h;if(this.isAwaitingAccountCreation=!1,this.isAwaitingLogin=!1,this.isAwaitingFarcaster=!1,this.isAwaitingOAuth=!1,this.currentWalletIds={},_CoreCapsule_supportedWalletTypes.set(this,void 0),_CoreCapsule_supportedWalletTypesOpt.set(this,void 0),this.localStorageGetItem=_t=>this.platformUtils.localStorage.get(_t),this.localStorageSetItem=(_t,$t)=>this.platformUtils.localStorage.set(_t,$t),this.sessionStorageGetItem=_t=>this.platformUtils.sessionStorage.get(_t),this.sessionStorageSetItem=(_t,$t)=>this.platformUtils.sessionStorage.set(_t,$t),this.sessionStorageRemoveItem=_t=>this.platformUtils.sessionStorage.removeItem(_t),this.retrieveSessionCookie=()=>this.sessionCookie,this.clearStorage=(_t="all")=>__awaiter$9(this,void 0,void 0,function*(){const $t=_t==="all";($t||_t==="local")&&this.platformUtils.localStorage.clear(PREFIX),($t||_t==="session")&&this.platformUtils.sessionStorage.clear(PREFIX),($t||_t==="secure")&&this.platformUtils.secureStorage&&this.platformUtils.secureStorage.clear(PREFIX)}),this.createWalletPerMissingType=this.createWalletPerType,c||(c={}),this.emailPrimaryColor=c.emailPrimaryColor,this.emailTheme=c.emailTheme,this.homepageUrl=c.homepageUrl,this.supportUrl=c.supportUrl,this.xUrl=c.xUrl,this.githubUrl=c.githubUrl,this.linkedinUrl=c.linkedinUrl,this.portalBackgroundColor=c.portalBackgroundColor,this.portalPrimaryButtonColor=c.portalPrimaryButtonColor,this.portalTextColor=c.portalTextColor,this.portalPrimaryButtonTextColor=c.portalPrimaryButtonTextColor,this.portalTheme=c.portalTheme,this.platformUtils=this.getPlatformUtils(),this.disableProviderModal=this.platformUtils.disableProviderModal,c.useStorageOverrides&&(this.localStorageGetItem=c.localStorageGetItemOverride,this.localStorageSetItem=c.localStorageSetItemOverride,this.sessionStorageGetItem=c.sessionStorageGetItemOverride,this.sessionStorageSetItem=c.sessionStorageSetItemOverride,this.sessionStorageRemoveItem=c.sessionStorageRemoveItemOverride,this.clearStorage=c.clearStorageOverride),c.useSessionStorage&&(this.localStorageGetItem=this.sessionStorageGetItem,this.localStorageSetItem=this.sessionStorageSetItem),this.persistSessionCookie=_t=>{this.sessionCookie=_t,(c.useSessionStorage?this.sessionStorageSetItem:this.localStorageSetItem)(LOCAL_STORAGE_SESSION_COOKIE,_t)},this.ctx={env:a,apiKey:o,capsuleClient:initClient$1(a,CoreCapsule.version,o,c.disableWorkers,this.retrieveSessionCookie,this.persistSessionCookie),disableWorkers:c.disableWorkers,offloadMPCComputationURL:c.offloadMPCComputationURL,useLocalFiles:c.useLocalFiles,useDKLS:c.useDKLSForCreation||!c.offloadMPCComputationURL,disableWebSockets:!!c.disableWebSockets,wasmOverride:c.wasmOverride,cosmosPrefix:this.cosmosPrefix},c.offloadMPCComputationURL&&(this.ctx.mpcComputationClient=initClient(c.offloadMPCComputationURL,c.disableWorkers)),!this.platformUtils.isSyncStorage||c.useStorageOverrides)return;this.email=this.localStorageGetItem(LOCAL_STORAGE_EMAIL)||void 0,this.countryCode=this.localStorageGetItem(LOCAL_STORAGE_COUNTRY_CODE)||void 0,this.phone=this.localStorageGetItem(LOCAL_STORAGE_PHONE)||void 0,this.userId=this.localStorageGetItem(LOCAL_STORAGE_USER_ID)||void 0;const d=this.platformUtils.secureStorage?this.platformUtils.secureStorage.get(LOCAL_STORAGE_WALLETS):this.localStorageGetItem(LOCAL_STORAGE_WALLETS),_=JSON.parse(d||"{}"),_e=this.platformUtils.secureStorage?this.platformUtils.secureStorage.get(LOCAL_STORAGE_ED25519_WALLETS):this.localStorageGetItem(LOCAL_STORAGE_ED25519_WALLETS),tt=JSON.parse(_e||"{}"),rt=Object.assign(Object.assign({},Object.keys(_).reduce((_t,$t)=>Object.assign(Object.assign({},_t),{[$t]:migrateWallet(_[$t])}),{})),Object.keys(tt).reduce((_t,$t)=>Object.assign(Object.assign({},_t),_t[$t]?{}:{[$t]:migrateWallet(tt[$t])}),{}));this.setWallets(rt);try{__classPrivateFieldSet(this,_CoreCapsule_supportedWalletTypes,c.supportedWalletTypes?(()=>{if(Object.values(c.supportedWalletTypes).every(_t=>!!_t&&typeof _t=="object"&&_t.optional))throw new Error("at least one wallet type must be non-optional");if(!Object.keys(c.supportedWalletTypes).every(_t=>Object.values(WalletType).includes(_t)))throw new Error("unsupported wallet type");return __classPrivateFieldSet(this,_CoreCapsule_supportedWalletTypesOpt,c.supportedWalletTypes,"f"),Object.entries(c.supportedWalletTypes).reduce((_t,[$t,bt])=>{var xt;return bt?($t===WalletType.COSMOS&&typeof bt=="object"&&bt.prefix&&(this.cosmosPrefix=bt.prefix),[..._t,{type:$t,optional:bt===!0?!1:(xt=bt.optional)!==null&&xt!==void 0?xt:!1}]):_t},[])})():void 0,"f")}catch{__classPrivateFieldSet(this,_CoreCapsule_supportedWalletTypes,void 0,"f")}const it=(h=this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS))!==null&&h!==void 0?h:void 0,st=[void 0,null,"undefined"].includes(it)?{}:(()=>{const _t=JSON.parse(it);return Array.isArray(_t)?Object.keys(WalletType).reduce(($t,bt)=>{const xt=Object.values(this.wallets).find(St=>_t.includes(St.id)&&WalletSchemeTypeMap[St.scheme][bt]);return Object.assign(Object.assign({},$t),xt&&!$t[bt]?{[bt]:[xt.id]}:{})},{}):_t})();this.setCurrentWalletIds(st),this.sessionCookie=this.localStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE)||this.sessionStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE)||void 0,Object.values(this.wallets).filter(_t=>this.isWalletOwned(_t)).length>0&&this.currentWalletIdsArray.length===0&&this.findWalletId(void 0,{forbidPregen:!0});const ht=this.sessionStorageGetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);ht&&ht!=="undefined"&&(this.loginEncryptionKeyPair=this.convertEncryptionKeyPair(JSON.parse(ht)));const mt=this.localStorageGetItem(LOCAL_STORAGE_EXTERNAL_WALLETS),vt=JSON.parse(mt||"{}");this.setExternalWallets(vt);const yt=this.localStorageGetItem(LOCAL_STORAGE_CURRENT_EXTERNAL_WALLET_ADDRESSES)||void 0;this.currentExternalWalletAddresses=yt?JSON.parse(yt):void 0}touchSession(a=!1){return __awaiter$9(this,void 0,void 0,function*(){const o=yield this.ctx.capsuleClient.touchSession(a);return this.setSupportedWalletTypes(o.data.supportedWalletTypes,o.data.cosmosPrefix),o})}setSupportedWalletTypes(a,o){a&&!__classPrivateFieldGet(this,_CoreCapsule_supportedWalletTypes,"f")&&(__classPrivateFieldSet(this,_CoreCapsule_supportedWalletTypes,a,"f"),Object.keys(this.currentWalletIds).forEach(c=>{var h;!((h=__classPrivateFieldGet(this,_CoreCapsule_supportedWalletTypes,"f"))===null||h===void 0)&&h.some(({type:d})=>d===c)||delete this.currentWalletIds[c]})),o&&!this.cosmosPrefix&&(this.cosmosPrefix=o)}getVerificationEmailProps(){return{brandColor:this.emailPrimaryColor,theme:this.emailTheme,supportUrl:this.supportUrl,homepageUrl:this.homepageUrl,xUrl:this.xUrl,githubUrl:this.githubUrl,linkedinUrl:this.linkedinUrl}}getBackupKitEmailProps(){return{brandColor:this.emailPrimaryColor,theme:this.emailTheme,homepageUrl:this.homepageUrl,xUrl:this.xUrl,linkedinUrl:this.linkedinUrl,githubUrl:this.githubUrl,supportUrl:this.supportUrl}}init(){return __awaiter$9(this,void 0,void 0,function*(){this.email=(yield this.localStorageGetItem(LOCAL_STORAGE_EMAIL))||void 0,this.userId=(yield this.localStorageGetItem(LOCAL_STORAGE_USER_ID))||void 0,this.sessionCookie=(yield this.localStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE))||(yield this.sessionStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE))||void 0;const a=this.platformUtils.secureStorage?yield this.platformUtils.secureStorage.get(LOCAL_STORAGE_WALLETS):yield this.localStorageGetItem(LOCAL_STORAGE_WALLETS);this.wallets=JSON.parse(a||"{}");const o=yield this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS),c=o?JSON.parse(o):void 0;this.currentWalletIds=c;const h=yield this.localStorageGetItem(LOCAL_STORAGE_EXTERNAL_WALLETS);this.externalWallets=JSON.parse(h||"{}");const d=yield this.localStorageGetItem(LOCAL_STORAGE_CURRENT_EXTERNAL_WALLET_ADDRESSES),_=d?JSON.parse(d):void 0;this.currentExternalWalletAddresses=_;const _e=yield this.sessionStorageGetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);_e&&_e!=="undefined"&&(this.loginEncryptionKeyPair=this.convertEncryptionKeyPair(JSON.parse(_e))),yield this.touchSession()})}setEmail(a){return __awaiter$9(this,void 0,void 0,function*(){this.email=a,yield this.localStorageSetItem(LOCAL_STORAGE_EMAIL,a)})}setPhoneNumber(a,o){return __awaiter$9(this,void 0,void 0,function*(){this.phone=a,this.countryCode=o,yield this.localStorageSetItem(LOCAL_STORAGE_PHONE,a),yield this.localStorageSetItem(LOCAL_STORAGE_COUNTRY_CODE,o)})}setFarcasterUsername(a){return __awaiter$9(this,void 0,void 0,function*(){this.farcasterUsername=a,yield this.localStorageSetItem(LOCAL_STORAGE_FARCASTER_USERNAME,a)})}setExternalWallet(a,o,c){return __awaiter$9(this,void 0,void 0,function*(){this.externalWallets={[a]:{id:a,address:a,type:o,name:c,isExternal:!0,signer:""}},this.currentExternalWalletAddresses=[a],this.setCurrentExternalWalletAddresses(this.currentExternalWalletAddresses),this.setExternalWallets(this.externalWallets),typeof window<"u"&&window.dispatchEvent(new Event(EXTERNAL_WALLET_CHANGE_EVENT))})}setUserId(a){return __awaiter$9(this,void 0,void 0,function*(){this.userId=a,yield this.localStorageSetItem(LOCAL_STORAGE_USER_ID,a)})}setWallets(a){return __awaiter$9(this,void 0,void 0,function*(){if(this.wallets=a,this.platformUtils.secureStorage){yield this.platformUtils.secureStorage.set(LOCAL_STORAGE_WALLETS,JSON.stringify(a));return}yield this.localStorageSetItem(LOCAL_STORAGE_WALLETS,JSON.stringify(a))})}setExternalWallets(a){return __awaiter$9(this,void 0,void 0,function*(){this.externalWallets=a,yield this.localStorageSetItem(LOCAL_STORAGE_EXTERNAL_WALLETS,JSON.stringify(a))})}setCurrentExternalWalletAddresses(a){return __awaiter$9(this,void 0,void 0,function*(){this.currentExternalWalletAddresses=a,yield this.localStorageSetItem(LOCAL_STORAGE_CURRENT_EXTERNAL_WALLET_ADDRESSES,JSON.stringify(a))})}setLoginEncryptionKeyPair(a){return __awaiter$9(this,void 0,void 0,function*(){a||(a=yield getAsymmetricKeyPair(this.ctx)),this.loginEncryptionKeyPair=a,yield this.sessionStorageSetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR,JSON.stringify(a))})}deleteLoginEncryptionKeyPair(){return __awaiter$9(this,void 0,void 0,function*(){this.loginEncryptionKeyPair=void 0,yield this.sessionStorageRemoveItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR)})}getUserId(){return this.userId}getEmail(){return this.email}getPhone(){return{phone:this.phone,countryCode:this.countryCode}}getPhoneNumber(){if(!(!this.phone||!this.countryCode))return normalizePhoneNumber(this.countryCode,this.phone)}setCurrentWalletIds(a,o,c=!1){return __awaiter$9(this,void 0,void 0,function*(){this.currentWalletIds=a,yield this.localStorageSetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS,JSON.stringify(a)),o&&(yield this.ctx.capsuleClient.setCurrentWalletIds(this.getUserId(),this.currentWalletIds,c,o)),typeof window<"u"&&window.dispatchEvent(new Event(CURRENT_WALLET_IDS_CHANGE_EVENT))})}findWalletId(a,o={}){if(a)this.assertIsValidWalletId(a,o);else{for(const c of[...this.currentWalletIdsUnique,...Object.keys(this.wallets)])if(this.isWalletUsable(c,o)){a=c;break}if(!a)throw new Error("no valid wallet id found")}return a}findWalletByAddress(a,o){if(this.externalWallets[a])return this.externalWallets[a];let c;if(Object.entries(this.currentWalletIds).forEach(([h,d])=>{const _=Object.keys(this.wallets).filter(_e=>this.wallets[_e].type===h&&this.isPregenWalletClaimable(this.wallets[_e]));[...d,..._].forEach(_e=>{a.toLowerCase()===this.getDisplayAddress(_e,{addressType:h}).toLowerCase()&&(c=this.wallets[_e])})}),!c)throw new Error(`wallet with address ${a} not found`);return this.assertIsValidWalletId(c.id,o),c}findWallet(a,o,c={}){var h,d;if(!a&&Object.keys(this.externalWallets).length>0)return Object.values(this.externalWallets)[0];if(this.externalWallets[a])return this.externalWallets[a];try{const _=this.findWalletId(a,c);if(_&&this.wallets[_]){const _e=this.wallets[_],{signer:tt}=_e,rt=__rest$2(_e,["signer"]),it=(d=o??((h=this.currentWalletIdsArray.find(([st])=>st===_))===null||h===void 0?void 0:h[1]))!==null&&d!==void 0?d:rt.type;return Object.assign(Object.assign({},rt),{type:WalletType[it]})}}catch{return}}get availableWallets(){var a;return[...this.currentWalletIdsArray.map(([o,c])=>[o,c,!1]).map(([o,c])=>{const h=this.findWallet(o,c);return h?{id:h.id,type:c,address:this.getDisplayAddress(o,{addressType:c}),name:h.name}:null}).filter(o=>o!==null),...Object.values((a=this.externalWallets)!==null&&a!==void 0?a:{})]}getWalletsByType(a){return Object.values(this.wallets).filter(o=>this.isWalletUsable(o.id,{type:[a]}))}assertIsValidWalletId(a,o={}){this.isWalletUsable(a,o,!0)}assertIsValidWalletType(a,o){return __awaiter$9(this,void 0,void 0,function*(){if(__classPrivateFieldGet(this,_CoreCapsule_supportedWalletTypes,"f")||(yield this.touchSession()),!a||!Object.values(WalletType).includes(a)||!(o??this.supportedWalletTypes.map(({type:c})=>c)).includes(a))throw new Error(`wallet type ${a} is not supported`);return a})}getMissingTypes(){return __awaiter$9(this,void 0,void 0,function*(){return __classPrivateFieldGet(this,_CoreCapsule_supportedWalletTypes,"f")||(yield this.touchSession()),this.supportedWalletTypes.filter(({type:a,optional:o})=>!o&&Object.values(this.wallets).every(c=>!WalletSchemeTypeMap[c.scheme][a])).map(({type:a})=>a)})}getTypesToCreate(a){return __awaiter$9(this,void 0,void 0,function*(){return __classPrivateFieldGet(this,_CoreCapsule_supportedWalletTypes,"f")||(yield this.touchSession()),getSchemes(a??(yield this.getMissingTypes())).map(o=>{switch(o){case WalletScheme.ED25519:return WalletType.SOLANA;default:return this.supportedWalletTypes.some(({type:c,optional:h})=>c===WalletType.COSMOS&&!h)?WalletType.COSMOS:WalletType.EVM}})})}getPartnerURL(a){return __awaiter$9(this,void 0,void 0,function*(){return(yield this.ctx.capsuleClient.getPartner(a)).data.partner.portalUrl})}getPortalURL(a){return __awaiter$9(this,void 0,void 0,function*(){return a&&(yield this.getPartnerURL(a))||getPortalBaseURL(this.ctx)})}getCommonLoginQueryParams(a,o,c,h){return __awaiter$9(this,void 0,void 0,function*(){return toQueryString({newDeviceSessionId:o,newDeviceEncryptionKey:c,pregenWalletIds:Object.entries(this.wallets).filter(([d,_])=>this.isPregenWalletClaimable(_)&&_.partnerId===a).map(([d])=>d).join(","),isForKnownDeviceLogin:h?h.toString():void 0})})}getCommonQueryParams(a,o){var c,h,d,_,_e,tt;return __awaiter$9(this,void 0,void 0,function*(){const rt=a?(c=(yield this.ctx.capsuleClient.getPartner(a)).data)===null||c===void 0?void 0:c.partner:void 0;return toQueryString({apiKey:this.ctx.apiKey,partnerId:a,portalFont:rt==null?void 0:rt.font,portalBorderRadius:(h=this.portalTheme)===null||h===void 0?void 0:h.borderRadius,portalThemeMode:(rt==null?void 0:rt.themeMode)||((d=this.portalTheme)===null||d===void 0?void 0:d.mode),portalAccentColor:(rt==null?void 0:rt.accentColor)||((_=this.portalTheme)===null||_===void 0?void 0:_.accentColor),portalForegroundColor:(rt==null?void 0:rt.foregroundColor)||((_e=this.portalTheme)===null||_e===void 0?void 0:_e.foregroundColor),portalBackgroundColor:(rt==null?void 0:rt.backgroundColor)||this.portalBackgroundColor||((tt=this.portalTheme)===null||tt===void 0?void 0:tt.backgroundColor),portalPrimaryButtonColor:this.portalPrimaryButtonColor,portalTextColor:this.portalTextColor,portalPrimaryButtonTextColor:this.portalPrimaryButtonTextColor,isForNewDevice:o?o.toString():void 0,supportedWalletTypes:__classPrivateFieldGet(this,_CoreCapsule_supportedWalletTypesOpt,"f")?JSON.stringify(__classPrivateFieldGet(this,_CoreCapsule_supportedWalletTypesOpt,"f")):void 0})})}getWebAuthURLForCreate(a,o,c,h){return __awaiter$9(this,void 0,void 0,function*(){const d=yield this.getCommonQueryParams(c,h),_={email:`email=${encodeURIComponent(this.email)}`,phone:`phone=${encodeURIComponent(this.phone)}&countryCode=${encodeURIComponent(this.countryCode)}`,farcaster:`farcasterUsername=${encodeURIComponent(this.farcasterUsername)}`}[a];return`${c&&(yield this.getPartnerURL(c))||getPortalBaseURL(this.ctx)}/web/users/${this.userId}/biometrics/${o}?${_}${d}`})}getShortUrl(a){return`${getPortalBaseURL(this.ctx)}/short/${a}`}shortenLoginLink(a){return __awaiter$9(this,void 0,void 0,function*(){const o=yield upload(a,this.ctx.capsuleClient);return this.getShortUrl(o)})}getWebAuthURLForLogin(a,o,c,h,d,_="email",_e){return __awaiter$9(this,void 0,void 0,function*(){const tt=yield this.getCommonQueryParams(c),rt=yield this.getCommonLoginQueryParams(c,h,d,_e),it={email:`email=${encodeURIComponent(this.email)}`,phone:`phone=${encodeURIComponent(this.phone)}&countryCode=${encodeURIComponent(this.countryCode)}`,farcaster:`farcasterUsername=${encodeURIComponent(this.farcasterUsername)}`}[_];return`${c&&(yield this.getPartnerURL(c))||getPortalBaseURL(this.ctx)}/web/biometrics/login?${it}&sessionId=${a}&encryptionKey=${o}${rt}${tt}`})}getWebAuthURLForLoginForPhone(a,o,c,h,d){return __awaiter$9(this,void 0,void 0,function*(){const _=yield this.getCommonQueryParams(c),_e=yield this.getCommonLoginQueryParams(c,h,d);return`${c&&(yield this.getPartnerURL(c))||getPortalBaseURL(this.ctx)}/web/biometrics/login?phone=${encodeURIComponent(this.phone)}&countryCode=${encodeURIComponent(this.countryCode)}&sessionId=${a}&encryptionKey=${o}${_e}${_}`})}getPrivateKey(a){return __awaiter$9(this,void 0,void 0,function*(){const o=Object.values(this.wallets),c=a?this.wallets[a]:o==null?void 0:o[0];if(!c)throw new Error("wallet not found");if(c.scheme!==WalletScheme.DKLS)throw new Error("invalid wallet scheme");return yield this.platformUtils.getPrivateKey(this.ctx,this.userId,c.id,c.signer,this.retrieveSessionCookie())})}fetchWallets(){return __awaiter$9(this,void 0,void 0,function*(){return(yield this.isPortal()?this.ctx.capsuleClient.getAllWallets(this.userId):this.ctx.capsuleClient.getWallets(this.userId,!0)).data.wallets.filter(o=>!!o.address&&this.isWalletSupported(entityToWallet(o)))})}populateWalletAddresses(){return __awaiter$9(this,void 0,void 0,function*(){(yield this.ctx.capsuleClient.getWallets(this.userId,!0)).data.wallets.forEach(c=>{this.wallets[c.id]&&(this.wallets[c.id]=Object.assign(Object.assign({},entityToWallet(c)),this.wallets[c.id]))}),yield this.setWallets(this.wallets)})}populatePregenWalletAddresses(a,o){return __awaiter$9(this,void 0,void 0,function*(){(yield this.ctx.capsuleClient.getPregenWallets(a,o)).wallets.forEach(d=>{this.wallets[d.id]&&(this.wallets[d.id]=Object.assign(Object.assign({},entityToWallet(d)),this.wallets[d.id]))}),yield this.setWallets(this.wallets)})}checkIfUserExists(a){return __awaiter$9(this,void 0,void 0,function*(){return(yield this.ctx.capsuleClient.checkUserExists(a,null,null)).data.exists})}checkIfUserExistsByPhone(a,o){return __awaiter$9(this,void 0,void 0,function*(){return(yield this.ctx.capsuleClient.checkUserExists(null,a,o)).data.exists})}createUser(a){return __awaiter$9(this,void 0,void 0,function*(){this.requireApiKey(),yield this.setEmail(a);const{userId:o}=yield this.ctx.capsuleClient.createUser(Object.assign({email:this.email},this.getVerificationEmailProps()));yield this.setUserId(o)})}createUserByPhone(a,o){return __awaiter$9(this,void 0,void 0,function*(){this.requireApiKey(),yield this.setPhoneNumber(a,o);const{userId:c}=yield this.ctx.capsuleClient.createUser({phone:this.phone,countryCode:this.countryCode});yield this.setUserId(c)})}externalWalletLogin(a,o,c){return __awaiter$9(this,void 0,void 0,function*(){this.requireApiKey();const{userId:h}=yield this.ctx.capsuleClient.externalWalletLogin({externalAddress:a,type:o,externalWalletProvider:c});yield this.setExternalWallet(a,o,c),yield this.setUserId(h)})}isUsingExternalWallet(){return!!Object.keys(this.externalWallets).length}verifyEmail(a){return __awaiter$9(this,void 0,void 0,function*(){return yield this.ctx.capsuleClient.verifyEmail(this.userId,{verificationCode:a}),this.getSetUpBiometricsURL(!1)})}verifyPhone(a){return __awaiter$9(this,void 0,void 0,function*(){return yield this.ctx.capsuleClient.verifyPhone(this.userId,{verificationCode:a}),this.getSetUpBiometricsURLForPhone(!1)})}verify2FA(a,o){return __awaiter$9(this,void 0,void 0,function*(){const c=yield this.ctx.capsuleClient.verify2FA(a,o);return{address:c.data.address,initiatedAt:c.data.initiatedAt,status:c.data.status,userId:c.data.userId,walletId:c.data.walletId}})}verify2FAForPhone(a,o,c){return __awaiter$9(this,void 0,void 0,function*(){const h=yield this.ctx.capsuleClient.verify2FAForPhone(a,o,c);return{address:h.data.address,initiatedAt:h.data.initiatedAt,status:h.data.status,userId:h.data.userId,walletId:h.data.walletId}})}setup2FA(){return __awaiter$9(this,void 0,void 0,function*(){return{uri:(yield this.ctx.capsuleClient.setup2FA(this.userId)).data.uri}})}enable2FA(a){return __awaiter$9(this,void 0,void 0,function*(){yield this.ctx.capsuleClient.enable2FA(this.userId,a)})}check2FAStatus(){return __awaiter$9(this,void 0,void 0,function*(){return this.userId?{isSetup:(yield this.ctx.capsuleClient.check2FAStatus(this.userId)).data.isSetup}:{isSetup:!1}})}resendVerificationCode(){return __awaiter$9(this,void 0,void 0,function*(){yield this.ctx.capsuleClient.resendVerificationCode(Object.assign({userId:this.userId},this.getVerificationEmailProps()))})}resendVerificationCodeByPhone(){return __awaiter$9(this,void 0,void 0,function*(){yield this.ctx.capsuleClient.resendVerificationCodeByPhone({userId:this.userId})})}getSetUpBiometricsURL(a,o="email"){return __awaiter$9(this,void 0,void 0,function*(){const c=yield this.ctx.capsuleClient.addSessionPublicKey(this.userId,{status:PublicKeyStatus.PENDING,type:PublicKeyType.WEB});return this.getWebAuthURLForCreate(o,c.data.id,c.data.partnerId,a)})}getSetUpBiometricsURLForPhone(a){return __awaiter$9(this,void 0,void 0,function*(){const o=yield this.ctx.capsuleClient.addSessionPublicKey(this.userId,{status:PublicKeyStatus.PENDING,type:PublicKeyType.WEB});return this.getWebAuthURLForCreate("phone",o.data.id,o.data.partnerId,a)})}isSessionActive(){return __awaiter$9(this,void 0,void 0,function*(){return this.isUsingExternalWallet()?!0:!!(yield this.touchSession()).data.isAuthenticated})}isFullyLoggedIn(){return __awaiter$9(this,void 0,void 0,function*(){return this.isUsingExternalWallet()?!0:(yield this.isSessionActive())&&this.currentWalletIdsArray.length>0&&this.currentWalletIdsArray.reduce((o,[c])=>o&&!!this.wallets[c],!0)})}getUserBiometricLocationHints(){return __awaiter$9(this,void 0,void 0,function*(){if(!this.email&&!this.phone&&!this.farcasterUsername)throw new Error("one of email, phone or farcaster username are required to get biometric location hints");return yield this.ctx.capsuleClient.getBiometricLocationHints({email:this.email,phone:this.phone,countryCode:this.countryCode,farcasterUsername:this.farcasterUsername})})}initiateUserLogin(a,o,c="email",h){return __awaiter$9(this,void 0,void 0,function*(){c==="email"?yield this.setEmail(a):c==="phone"?yield this.setPhoneNumber(a,h):c==="farcaster"&&(yield this.setFarcasterUsername(a));const d=yield this.touchSession(!0);this.loginEncryptionKeyPair||(yield this.setLoginEncryptionKeyPair());const _=yield this.getWebAuthURLForLogin(d.data.sessionId,getPublicKeyHex(this.loginEncryptionKeyPair),d.data.partnerId,void 0,void 0,c);return o?this.shortenLoginLink(_):_})}initiateUserLoginForPhone(a,o,c){return __awaiter$9(this,void 0,void 0,function*(){yield this.setPhoneNumber(a,o);const h=yield this.touchSession(!0);this.loginEncryptionKeyPair||(yield this.setLoginEncryptionKeyPair());const d=yield this.getWebAuthURLForLoginForPhone(h.data.sessionId,getPublicKeyHex(this.loginEncryptionKeyPair),h.data.partnerId);return c?this.shortenLoginLink(d):d})}waitForAccountCreation(){return __awaiter$9(this,void 0,void 0,function*(){for(yield this.touchSession(),this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.isAwaitingAccountCreation=!0;this.isAwaitingAccountCreation;)try{if(yield new Promise(a=>setTimeout(a,POLLING_INTERVAL_MS)),yield this.isSessionActive())return this.isAwaitingAccountCreation=!1,!0}catch(a){console.error(a)}return!1})}waitForPasskeyAndCreateWallet(){return __awaiter$9(this,void 0,void 0,function*(){yield this.waitForAccountCreation();let a,o;this.email!=null?(a=this.email,o=PregenIdentifierType.EMAIL):(a=this.getPhoneNumber(),o=PregenIdentifierType.PHONE);const c=(yield this.ctx.capsuleClient.getPregenWallets(a,o)).wallets.filter(_e=>this.isWalletSupported(entityToWallet(_e)));let h,d={};c.length>0&&(h=yield this.claimPregenWallets(a,o),d=this.supportedWalletTypes.reduce((_e,{type:tt})=>{var rt;return Object.assign(Object.assign({},_e),{[tt]:[(rt=c.find(it=>!!WalletSchemeTypeMap[it.scheme][tt]))===null||rt===void 0?void 0:rt.id]})},{}));const _=yield this.createWalletPerType();return h=h??_.recoverySecret,d=Object.assign(Object.assign({},d),_.walletIds),{walletIds:d,recoverySecret:h}})}getFarcasterConnectURL(){return __awaiter$9(this,void 0,void 0,function*(){yield this.logout(!0),yield this.touchSession(!0);const{data:{connect_uri:a}}=yield this.ctx.capsuleClient.initializeFarcasterLogin();return a})}waitForFarcasterStatus(){return __awaiter$9(this,void 0,void 0,function*(){for(this.isAwaitingFarcaster=!0;this.isAwaitingFarcaster;)try{yield new Promise(o=>setTimeout(o,POLLING_INTERVAL_MS));const a=yield this.ctx.capsuleClient.getFarcasterAuthStatus();if(a.data.state==="completed"){const{userId:o,userExists:c,username:h}=a.data;return yield this.setUserId(o),yield this.setFarcasterUsername(h),{userExists:c,username:h}}}catch(a){console.error(a),this.isAwaitingFarcaster=!1}})}getOAuthURL(a){return __awaiter$9(this,void 0,void 0,function*(){yield this.logout(!0);const o=yield this.touchSession(!0);return`${getBaseUrl(this.ctx.env)}auth/${a.toLowerCase()}?sessionLookupId=${encodeURIComponent(o.data.sessionLookupId)}`})}waitForOAuth(){return __awaiter$9(this,void 0,void 0,function*(){for(this.isAwaitingOAuth=!0;this.isAwaitingOAuth;)try{yield new Promise(o=>setTimeout(o,POLLING_INTERVAL_MS));const a=yield this.touchSession();if(a.data.userId){const{userId:o,email:c}=a.data;return yield this.setUserId(o),yield this.setEmail(c),{userExists:yield this.checkIfUserExists(c),email:c}}}catch(a){console.error(a)}return{userExists:!1}})}waitForLoginAndSetup(a,o){var c;return __awaiter$9(this,void 0,void 0,function*(){for(this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.isAwaitingLogin=!0;this.isAwaitingLogin;)try{if(yield new Promise(tt=>setTimeout(tt,POLLING_INTERVAL_MS)),!(yield this.isSessionActive())){if(a!=null&&a.closed)return{isComplete:!1,isError:!0};continue}const h=yield this.userSetupAfterLogin(),d=(c=h.data.needsWallet)!==null&&c!==void 0?c:!1;if(!d&&this.currentWalletIdsArray.length===0){if(a!=null&&a.closed)return{isComplete:!1,isError:!0};continue}const _=yield this.fetchWallets(),_e=yield this.getTransmissionKeyShares();if(_e.data.temporaryShares.length===_.length){yield this.setupAfterLogin(_e.data.temporaryShares,o);const tt=Object.values(this.wallets).reduce((rt,it)=>(this.isPregenWalletClaimable(it)&&(rt[it.pregenIdentifier]=it.pregenIdentifierType),rt),{});for(const[rt,it]of Object.entries(tt))yield this.claimPregenWallets(rt,it);return{isComplete:!0,needsWallet:d||Object.values(this.wallets).length===0,partnerId:h.data.partnerId}}}catch(h){console.error(h)}return{isComplete:!1}})}refreshSession(a){return __awaiter$9(this,void 0,void 0,function*(){const o=yield this.touchSession(!0);this.loginEncryptionKeyPair||(yield this.setLoginEncryptionKeyPair());const c=yield this.getWebAuthURLForLogin(o.data.sessionId,getPublicKeyHex(this.loginEncryptionKeyPair));return a&&this.platformUtils.openPopup(c),c})}userSetupAfterLogin(){return __awaiter$9(this,void 0,void 0,function*(){const a=yield this.touchSession();return yield this.setUserId(a.data.userId),a.data.currentWalletIds&&a.data.currentWalletIds!==this.currentWalletIds&&(yield this.setCurrentWalletIds(a.data.currentWalletIds,this.isPortal()?a.data.sessionLookupId:void 0)),a})}getTransmissionKeyShares(a){return __awaiter$9(this,void 0,void 0,function*(){const o=yield this.touchSession(),c=a?`${o.data.sessionLookupId}-new-device`:o.data.sessionLookupId;return this.ctx.capsuleClient.getTransmissionKeyshares(this.userId,c)})}setupAfterLogin(a,o){return __awaiter$9(this,void 0,void 0,function*(){a||(a=(yield this.getTransmissionKeyShares()).data.temporaryShares),a.forEach(c=>{const h=decryptWithPrivateKey(this.loginEncryptionKeyPair.privateKey,c.encryptedShare,c.encryptedKey);this.wallets[c.walletId]={id:c.walletId,signer:h}}),yield this.deleteLoginEncryptionKeyPair(),yield this.populateWalletAddresses(),yield this.touchSession(!o)})}distributeNewWalletShare(a,o,c){return __awaiter$9(this,void 0,void 0,function*(){let h=o;return h||(h=this.wallets[a].signer),c?yield sendRecoveryForShare(this.ctx,this.userId,a,[],h,!1,this.getBackupKitEmailProps()):yield distributeNewShare(this.ctx,this.userId,a,h,!1,this.getBackupKitEmailProps())})}waitForWalletAddress(a){return __awaiter$9(this,void 0,void 0,function*(){let o=0;for(;;)try{if(o===10)break;++o;const h=(yield this.ctx.capsuleClient.getWallets(this.userId)).data.wallets.find(d=>d.id===a);if(h&&h.address)return;yield new Promise(d=>setTimeout(d,SHORT_POLLING_INTERVAL_MS))}catch(c){console.error(c)}throw new Error("timed out waiting for wallet address")})}waitForPregenWalletAddress(a,o=PregenIdentifierType.EMAIL,c){return __awaiter$9(this,void 0,void 0,function*(){let h=0;for(;;)try{if(h===10)break;++h;const _=(yield this.ctx.capsuleClient.getPregenWallets(a,o)).wallets.find(_e=>_e.id===c);if(_&&_.address)return;yield new Promise(_e=>setTimeout(_e,SHORT_POLLING_INTERVAL_MS))}catch(d){console.error(d)}throw new Error("timed out waiting for wallet address")})}createWalletPerType(a=!1,o){return __awaiter$9(this,void 0,void 0,function*(){const c=[],h={};let d;for(const _ of yield this.getTypesToCreate(o)){const[_e,tt]=yield this.createWallet(_,a);c.push(_e),getEquivalentTypes(_).filter(rt=>!!this.isWalletTypeEnabled[rt]).forEach(rt=>{h[rt]=[_e.id]}),tt&&(d=tt)}return{wallets:c,walletIds:h,recoverySecret:d}})}refreshShare({walletId:a,share:o,oldPartnerId:c,newPartnerId:h,redistributeBackupEncryptedShares:d}){return __awaiter$9(this,void 0,void 0,function*(){const{signer:_}=yield this.platformUtils.refresh(this.ctx,this.retrieveSessionCookie(),this.userId,a,o,c,h),_e=yield distributeNewShare(this.ctx,this.userId,a,_,!d,this.getBackupKitEmailProps(),h);return{signer:_,recoverySecret:_e}})}createWallet(a,o=!1,c){var h;return __awaiter$9(this,void 0,void 0,function*(){this.requireApiKey();const d=yield this.assertIsValidWalletType(a??((h=this.supportedWalletTypes.find(({optional:st})=>!st))===null||h===void 0?void 0:h.type));let _,_e,tt;switch(d){case WalletType.SOLANA:{tt=yield this.platformUtils.ed25519Keygen(this.ctx,this.userId,this.retrieveSessionCookie(),this.getBackupKitEmailProps());break}default:{tt=yield this.platformUtils.keygen(this.ctx,this.userId,d,null,this.retrieveSessionCookie(),this.getBackupKitEmailProps());break}}const rt=tt.walletId;_=tt.signer,this.wallets[rt]={id:rt,signer:_},_e=this.wallets[rt],yield this.waitForWalletAddress(_e.id),yield this.populateWalletAddresses();let it=null;return o||(it=yield distributeNewShare(this.ctx,this.userId,_e.id,_,!1,this.getBackupKitEmailProps())),[_e,it]})}createWalletPreGen(a,o,c){var h,d;return a===void 0&&(a=(h=this.supportedWalletTypes.find(({optional:_})=>!_))===null||h===void 0?void 0:h.type),c===void 0&&(c=PregenIdentifierType.EMAIL),__awaiter$9(this,void 0,void 0,function*(){this.requireApiKey();const _=yield this.assertIsValidWalletType(a??((d=this.supportedWalletTypes.find(({optional:it})=>!it))===null||d===void 0?void 0:d.type));let _e;switch(_){case WalletType.SOLANA:_e=yield this.platformUtils.ed25519PreKeygen(this.ctx,o,c,this.retrieveSessionCookie());break;default:_e=yield this.platformUtils.preKeygen(this.ctx,void 0,o,c,_,null,this.retrieveSessionCookie());break}const{signer:tt,walletId:rt}=_e;return this.wallets[rt]={id:rt,signer:tt},yield this.waitForPregenWalletAddress(o,c,rt),yield this.populatePregenWalletAddresses(o,c),this.wallets[rt]})}createPregenWalletPerType(a,o=PregenIdentifierType.EMAIL,c){return __awaiter$9(this,void 0,void 0,function*(){const h=[];for(const d of yield this.getTypesToCreate(c)){const _=yield this.createWalletPreGen(d,a,o);h.push(_)}return h})}claimPregenWallets(a,o=PregenIdentifierType.EMAIL){return __awaiter$9(this,void 0,void 0,function*(){if(this.requireApiKey(),o===PregenIdentifierType.EMAIL){if(!(yield this.checkIfUserExists(a)))throw new Error("user does not exist")}else{const d=parsePhoneNumber(a),_=d.formatNational(),_e=`+${d.countryCallingCode}`;if(!(yield this.checkIfUserExistsByPhone(_,_e)))throw new Error("user does not exist")}const c=(yield this.ctx.capsuleClient.getPregenWallets(a,o)).wallets.filter(d=>this.isWalletSupported(entityToWallet(d)));if(c.length===0)throw new Error("wallets not found");let h;for(const d of c){yield this.ctx.capsuleClient.claimPregenWallet({userId:this.userId,walletId:d.id});const{signer:_,recoverySecret:_e}=yield this.refreshShare({walletId:d.id,share:this.wallets[d.id].signer,oldPartnerId:d.partnerId,newPartnerId:d.partnerId,redistributeBackupEncryptedShares:!0});_e&&(h=_e),this.wallets[d.id]=Object.assign(Object.assign({},this.wallets[d.id]),{signer:_,userId:this.userId,pregenIdentifier:void 0,pregenIdentifierType:void 0}),yield this.setWallets(this.wallets)}return h})}updateWalletIdentifierPreGen(a,o,c=PregenIdentifierType.EMAIL){return __awaiter$9(this,void 0,void 0,function*(){this.requireApiKey(),yield this.ctx.capsuleClient.updatePregenWallet(o,{pregenIdentifier:a,pregenIdentifierType:c})})}hasPregenWallet(a,o=PregenIdentifierType.EMAIL){return __awaiter$9(this,void 0,void 0,function*(){return this.requireApiKey(),!!(yield this.ctx.capsuleClient.getPregenWallets(a,o)).wallets[0]})}getPregenWallets(a,o=PregenIdentifierType.EMAIL){return __awaiter$9(this,void 0,void 0,function*(){return this.requireApiKey(),(yield this.ctx.capsuleClient.getPregenWallets(a,o,this.isPortal())).wallets.filter(h=>this.isWalletSupported(entityToWallet(h)))})}encodeWalletBase64(a){const o=JSON.stringify(a);return Buffer$B.from(o).toString("base64")}getUserShare(){return Object.values(this.wallets).length===0?null:Object.values(this.wallets).map(a=>this.encodeWalletBase64(a)).join("-")}setUserShare(a){return __awaiter$9(this,void 0,void 0,function*(){if(!a)return;const o=a.split("-");for(const c of o){const h=Buffer$B.from(c,"base64").toString(),d=migrateWallet(JSON.parse(h));this.wallets[d.id]=d,yield this.setWallets(this.wallets)}})}getTransactionReviewUrl(a,o){return __awaiter$9(this,void 0,void 0,function*(){const c=yield this.touchSession(),h=yield this.getCommonQueryParams(c.data.partnerId);return`${getPortalBaseURL(this.ctx)}/web/users/${this.userId}/transaction-review/${a}?email=${encodeURIComponent(this.email)}${h}${o?`&timeoutMs=${o}`:""}`})}getOnRampTransactionUrl(a){var{purchaseId:o}=a,c=__rest$2(a,["purchaseId"]);return __awaiter$9(this,void 0,void 0,function*(){const h=yield this.ctx.capsuleClient.touchSession(),d=yield this.getCommonQueryParams(h.data.partnerId),[_,_e]=extractWalletRef(c),tt=qs.stringify({[_]:_e,currentWalletIds:JSON.stringify(this.currentWalletIds),sessionId:h.data.sessionId},{addQueryPrefix:!0});return`${getPortalBaseURL(this.ctx)}/web/users/${this.userId}/on-ramp-transaction/${o}${tt}${d}`})}signMessage(a,o,c=3e4,h){return __awaiter$9(this,void 0,void 0,function*(){this.assertIsValidWalletId(a);const d=this.wallets[a];let _=this.userId;d.partnerId&&!d.userId&&(_=d.partnerId);let _e=yield this.signMessageInner(d,_,o,h),tt=Date.now();if(_e.pendingTransactionId)this.platformUtils.openPopup(yield this.getTransactionReviewUrl(_e.pendingTransactionId,c),{type:h?PopupType.SIGN_TRANSACTION_REVIEW:PopupType.SIGN_MESSAGE_REVIEW});else return _e;for(yield new Promise(rt=>setTimeout(rt,POLLING_INTERVAL_MS));!(Date.now()-tt>c);){try{yield this.ctx.capsuleClient.getPendingTransaction(this.userId,_e.pendingTransactionId)}catch{throw new TransactionReviewDenied}if(_e=yield this.signMessageInner(d,_,o,h),_e.pendingTransactionId)yield new Promise(rt=>setTimeout(rt,POLLING_INTERVAL_MS));else break}if(_e.pendingTransactionId)throw new TransactionReviewTimeout(yield this.getTransactionReviewUrl(_e.pendingTransactionId),_e.pendingTransactionId);return _e})}signMessageInner(a,o,c,h){return __awaiter$9(this,void 0,void 0,function*(){let d;switch(a.scheme){case WalletScheme.ED25519:d=yield this.platformUtils.ed25519Sign(this.ctx,o,a.id,a.signer,c,this.retrieveSessionCookie());break;default:d=yield this.platformUtils.signMessage(this.ctx,o,a.id,a.signer,c,this.retrieveSessionCookie(),a.scheme===WalletScheme.DKLS,h);break}return d})}signTransaction(a,o,c,h=3e4){return __awaiter$9(this,void 0,void 0,function*(){this.assertIsValidWalletId(a);const d=this.wallets[a];let _=this.userId;d.partnerId&&!d.userId&&(_=d.partnerId);let _e=yield this.platformUtils.signTransaction(this.ctx,_,a,this.wallets[a].signer,o,c,this.retrieveSessionCookie(),d.scheme===WalletScheme.DKLS),tt=Date.now();if(_e.pendingTransactionId)this.platformUtils.openPopup(yield this.getTransactionReviewUrl(_e.pendingTransactionId,h),{type:PopupType.SIGN_TRANSACTION_REVIEW});else return _e;for(yield new Promise(rt=>setTimeout(rt,POLLING_INTERVAL_MS));!(Date.now()-tt>h);){try{yield this.ctx.capsuleClient.getPendingTransaction(this.userId,_e.pendingTransactionId)}catch{throw new TransactionReviewDenied}if(_e=yield this.platformUtils.signTransaction(this.ctx,_,a,this.wallets[a].signer,o,c,this.retrieveSessionCookie(),d.scheme===WalletScheme.DKLS),_e.pendingTransactionId)yield new Promise(rt=>setTimeout(rt,POLLING_INTERVAL_MS));else break}if(_e.pendingTransactionId)throw new TransactionReviewTimeout(yield this.getTransactionReviewUrl(_e.pendingTransactionId),_e.pendingTransactionId);return _e})}sendTransaction(a,o,c){return __awaiter$9(this,void 0,void 0,function*(){this.assertIsValidWalletId(a);const h=this.wallets[a],d=yield this.platformUtils.sendTransaction(this.ctx,this.userId,a,this.wallets[a].signer,o,c,this.retrieveSessionCookie(),h.scheme===WalletScheme.DKLS);if(d.pendingTransactionId)throw this.platformUtils.openPopup(yield this.getTransactionReviewUrl(d.pendingTransactionId),{type:PopupType.SIGN_TRANSACTION_REVIEW}),new TransactionReviewError(yield this.getTransactionReviewUrl(d.pendingTransactionId));return d})}isProviderModalDisabled(){return!!this.disableProviderModal}initiateOnRampTransaction(a){var o;return __awaiter$9(this,void 0,void 0,function*(){const{params:c,shouldOpenPopup:h}=a,d=__rest$2(a,["params","shouldOpenPopup"]),_=yield this.ctx.capsuleClient.createOnRampPurchase(Object.assign({userId:this.userId,params:Object.assign(Object.assign({},c),{address:(o=d.externalWalletAddress)!==null&&o!==void 0?o:this.getDisplayAddress(d.walletId,{addressType:c.walletType})})},d)),_e=yield this.getOnRampTransactionUrl(Object.assign({purchaseId:_.id},d));return h&&this.platformUtils.openPopup(_e,{type:PopupType.ON_RAMP_TRANSACTION}),{onRampPurchase:_,portalUrl:_e}})}keepSessionAlive(){return __awaiter$9(this,void 0,void 0,function*(){try{return yield this.ctx.capsuleClient.keepSessionAlive(this.userId),!0}catch{return!1}})}exportSession(){const a={email:this.email,userId:this.userId,wallets:this.wallets,currentWalletIds:this.currentWalletIds,sessionCookie:this.sessionCookie,phone:this.phone,countryCode:this.countryCode};return Buffer$B.from(JSON.stringify(a)).toString("base64")}importSession(a){return __awaiter$9(this,void 0,void 0,function*(){const o=Buffer$B.from(a,"base64").toString("utf8"),c=JSON.parse(o);yield this.setEmail(c.email),yield this.setUserId(c.userId),yield this.setWallets(c.wallets);for(const h of Object.keys(this.wallets))this.wallets[h].userId||(this.wallets[h].userId=this.userId);yield this.setCurrentWalletIds(c.currentWalletIds),this.persistSessionCookie(c.sessionCookie),yield this.setPhoneNumber(c.phone,c.countryCode)})}exitAccountCreation(){this.isAwaitingAccountCreation=!1}exitLogin(){this.isAwaitingLogin=!1}exitFarcaster(){this.isAwaitingFarcaster=!1}exitOAuth(){this.isAwaitingOAuth=!1}exitLoops(){this.exitAccountCreation(),this.exitLogin(),this.exitFarcaster(),this.exitOAuth()}logout(a){return __awaiter$9(this,void 0,void 0,function*(){yield this.ctx.capsuleClient.logout(),yield this.clearStorage(),a?(Object.entries(this.wallets).forEach(([o,c])=>{c.pregenIdentifier||delete this.wallets[o]}),yield this.setWallets(this.wallets)):this.wallets={},this.currentWalletIds={},this.currentExternalWalletAddresses=void 0,this.externalWallets={},this.loginEncryptionKeyPair=void 0,this.email=void 0,this.phone=void 0,this.countryCode=void 0,this.userId=void 0,this.sessionCookie=void 0})}toString(){const a=Object.keys(this.wallets).reduce((c,h)=>Object.assign(Object.assign({},c),{[h]:Object.assign(Object.assign({},this.wallets[h]),{signer:this.wallets[h].signer?"[REDACTED]":void 0})}),{}),o={supportedWalletTypes:this.supportedWalletTypes,cosmosPrefix:this.cosmosPrefix,email:this.email,phone:this.phone,countryCode:this.countryCode,userId:this.userId,currentWalletIds:this.currentWalletIds,wallets:a,loginEncryptionKeyPair:this.loginEncryptionKeyPair?"[REDACTED]":void 0,ctx:{apiKey:this.ctx.apiKey,disableWorkers:this.ctx.disableWorkers,disableWebSockets:this.ctx.disableWebSockets,env:this.ctx.env,offloadMPCComputationURL:this.ctx.offloadMPCComputationURL,useLocalFiles:this.ctx.useLocalFiles,useDKLS:this.ctx.useDKLS,cosmosPrefix:this.ctx.cosmosPrefix}};return`Capsule ${JSON.stringify(o,null,2)}`}}_CoreCapsule_supportedWalletTypes=new WeakMap,_CoreCapsule_supportedWalletTypesOpt=new WeakMap;CoreCapsule.version=CORE_CAPSULE_VERSION;var __awaiter$8=function(e,a,o,c){function h(d){return d instanceof o?d:new o(function(_){_(d)})}return new(o||(o=Promise))(function(d,_){function _e(it){try{rt(c.next(it))}catch(st){_(st)}}function tt(it){try{rt(c.throw(it))}catch(st){_(st)}}function rt(it){it.done?d(it.value):h(it.value).then(_e,tt)}rt((c=c.apply(e,a||[])).next())})};function waitUntilTrue(e,a,o){return __awaiter$8(this,void 0,void 0,function*(){const c=Date.now();for(;Date.now()-csetTimeout(h,o))}return!1})}const capsuleVersion=CoreCapsule.version;class LocalStorage{constructor(){this.get=a=>typeof window<"u"&&localStorage.getItem(a)||null,this.set=(a,o)=>{typeof window<"u"&&localStorage.setItem(a,o)},this.removeItem=a=>{typeof window<"u"&&localStorage.removeItem(a)},this.clear=a=>{if(typeof window<"u")for(let o=0;otypeof window<"u"&&sessionStorage.getItem(a)||null,this.set=(a,o)=>{typeof window<"u"&&sessionStorage.setItem(a,o)},this.removeItem=a=>{typeof window<"u"&&sessionStorage.removeItem(a)},this.clear=a=>{if(typeof window<"u")for(let o=0;o{const e=()=>{const c=new Error("not implemented");return c.code="ENOSYS",c};if(!globalThis.fs){let c="";globalThis.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1},writeSync(h,d){c+=o.decode(d);const _=c.lastIndexOf(` `);return _!=-1&&(console.log(c.substring(0,_)),c=c.substring(_+1)),d.length},write(h,d,_,_e,tt,rt){if(_!==0||_e!==d.length||tt!==null){rt(e());return}const it=this.writeSync(h,d);rt(null,it)},chmod(h,d,_){_(e())},chown(h,d,_,_e){_e(e())},close(h,d){d(e())},fchmod(h,d,_){_(e())},fchown(h,d,_,_e){_e(e())},fstat(h,d){d(e())},fsync(h,d){d(null)},ftruncate(h,d,_){_(e())},lchown(h,d,_,_e){_e(e())},link(h,d,_){_(e())},lstat(h,d){d(e())},mkdir(h,d,_){_(e())},open(h,d,_,_e){_e(e())},read(h,d,_,_e,tt,rt){rt(e())},readdir(h,d){d(e())},readlink(h,d){d(e())},rename(h,d,_){_(e())},rmdir(h,d){d(e())},stat(h,d){d(e())},symlink(h,d,_){_(e())},truncate(h,d,_){_(e())},unlink(h,d){d(e())},utimes(h,d,_,_e){_e(e())}}}if(globalThis.process||(globalThis.process={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw e()},pid:-1,ppid:-1,umask(){throw e()},cwd(){throw e()},chdir(){throw e()}}),!globalThis.crypto)throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");if(globalThis.performance||(globalThis.performance=Date),!globalThis.TextEncoder)throw new Error("globalThis.TextEncoder is not available, polyfill required");if(!globalThis.TextDecoder)throw new Error("globalThis.TextDecoder is not available, polyfill required");const a=new TextEncoder("utf-8"),o=new TextDecoder("utf-8");globalThis.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=st=>{st!==0&&console.warn("exit code:",st)},this._exitPromise=new Promise(st=>{this._resolveExitPromise=st}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;const c=(st,ht)=>{this.mem.setUint32(st+0,ht,!0),this.mem.setUint32(st+4,Math.floor(ht/4294967296),!0)},h=st=>{const ht=this.mem.getUint32(st+0,!0),mt=this.mem.getInt32(st+4,!0);return ht+mt*4294967296},d=st=>{const ht=this.mem.getFloat64(st,!0);if(ht===0)return;if(!isNaN(ht))return ht;const mt=this.mem.getUint32(st,!0);return this._values[mt]},_=(st,ht)=>{if(typeof ht=="number"&&ht!==0){if(isNaN(ht)){this.mem.setUint32(st+4,2146959360,!0),this.mem.setUint32(st,0,!0);return}this.mem.setFloat64(st,ht,!0);return}if(ht===void 0){this.mem.setFloat64(st,0,!0);return}let vt=this._ids.get(ht);vt===void 0&&(vt=this._idPool.pop(),vt===void 0&&(vt=this._values.length),this._values[vt]=ht,this._goRefCounts[vt]=0,this._ids.set(ht,vt)),this._goRefCounts[vt]++;let yt=0;switch(typeof ht){case"object":ht!==null&&(yt=1);break;case"string":yt=2;break;case"symbol":yt=3;break;case"function":yt=4;break}this.mem.setUint32(st+4,2146959360|yt,!0),this.mem.setUint32(st,vt,!0)},_e=st=>{const ht=h(st+0),mt=h(st+8);return new Uint8Array(this._inst.exports.mem.buffer,ht,mt)},tt=st=>{const ht=h(st+0),mt=h(st+8),vt=new Array(mt);for(let yt=0;yt{const ht=h(st+0),mt=h(st+8);return o.decode(new DataView(this._inst.exports.mem.buffer,ht,mt))},it=Date.now()-performance.now();this.importObject={_gotest:{add:(st,ht)=>st+ht},gojs:{"runtime.wasmExit":st=>{st>>>=0;const ht=this.mem.getInt32(st+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(ht)},"runtime.wasmWrite":st=>{st>>>=0;const ht=h(st+8),mt=h(st+16),vt=this.mem.getInt32(st+24,!0);fs.writeSync(ht,new Uint8Array(this._inst.exports.mem.buffer,mt,vt))},"runtime.resetMemoryDataView":st=>{this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":st=>{st>>>=0,c(st+8,(it+performance.now())*1e6)},"runtime.walltime":st=>{st>>>=0;const ht=new Date().getTime();c(st+8,ht/1e3),this.mem.setInt32(st+16,ht%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":st=>{st>>>=0;const ht=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(ht,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(ht);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()},h(st+8))),this.mem.setInt32(st+16,ht,!0)},"runtime.clearTimeoutEvent":st=>{st>>>=0;const ht=this.mem.getInt32(st+8,!0);clearTimeout(this._scheduledTimeouts.get(ht)),this._scheduledTimeouts.delete(ht)},"runtime.getRandomData":st=>{st>>>=0,crypto.getRandomValues(_e(st+8))},"syscall/js.finalizeRef":st=>{st>>>=0;const ht=this.mem.getUint32(st+8,!0);if(this._goRefCounts[ht]--,this._goRefCounts[ht]===0){const mt=this._values[ht];this._values[ht]=null,this._ids.delete(mt),this._idPool.push(ht)}},"syscall/js.stringVal":st=>{st>>>=0,_(st+24,rt(st+8))},"syscall/js.valueGet":st=>{st>>>=0;const ht=Reflect.get(d(st+8),rt(st+16));st=this._inst.exports.getsp()>>>0,_(st+32,ht)},"syscall/js.valueSet":st=>{st>>>=0,Reflect.set(d(st+8),rt(st+16),d(st+32))},"syscall/js.valueDelete":st=>{st>>>=0,Reflect.deleteProperty(d(st+8),rt(st+16))},"syscall/js.valueIndex":st=>{st>>>=0,_(st+24,Reflect.get(d(st+8),h(st+16)))},"syscall/js.valueSetIndex":st=>{st>>>=0,Reflect.set(d(st+8),h(st+16),d(st+24))},"syscall/js.valueCall":st=>{st>>>=0;try{const ht=d(st+8),mt=Reflect.get(ht,rt(st+16)),vt=tt(st+32),yt=Reflect.apply(mt,ht,vt);st=this._inst.exports.getsp()>>>0,_(st+56,yt),this.mem.setUint8(st+64,1)}catch(ht){st=this._inst.exports.getsp()>>>0,_(st+56,ht),this.mem.setUint8(st+64,0)}},"syscall/js.valueInvoke":st=>{st>>>=0;try{const ht=d(st+8),mt=tt(st+16),vt=Reflect.apply(ht,void 0,mt);st=this._inst.exports.getsp()>>>0,_(st+40,vt),this.mem.setUint8(st+48,1)}catch(ht){st=this._inst.exports.getsp()>>>0,_(st+40,ht),this.mem.setUint8(st+48,0)}},"syscall/js.valueNew":st=>{st>>>=0;try{const ht=d(st+8),mt=tt(st+16),vt=Reflect.construct(ht,mt);st=this._inst.exports.getsp()>>>0,_(st+40,vt),this.mem.setUint8(st+48,1)}catch(ht){st=this._inst.exports.getsp()>>>0,_(st+40,ht),this.mem.setUint8(st+48,0)}},"syscall/js.valueLength":st=>{st>>>=0,c(st+16,parseInt(d(st+8).length))},"syscall/js.valuePrepareString":st=>{st>>>=0;const ht=a.encode(String(d(st+8)));_(st+16,ht),c(st+24,ht.length)},"syscall/js.valueLoadString":st=>{st>>>=0;const ht=d(st+8);_e(st+16).set(ht)},"syscall/js.valueInstanceOf":st=>{st>>>=0,this.mem.setUint8(st+24,d(st+8)instanceof d(st+16)?1:0)},"syscall/js.copyBytesToGo":st=>{st>>>=0;const ht=_e(st+8),mt=d(st+32);if(!(mt instanceof Uint8Array||mt instanceof Uint8ClampedArray)){this.mem.setUint8(st+48,0);return}const vt=mt.subarray(0,ht.length);ht.set(vt),c(st+40,vt.length),this.mem.setUint8(st+48,1)},"syscall/js.copyBytesToJS":st=>{st>>>=0;const ht=d(st+8),mt=_e(st+16);if(!(ht instanceof Uint8Array||ht instanceof Uint8ClampedArray)){this.mem.setUint8(st+48,0);return}const vt=mt.subarray(0,ht.length);ht.set(vt),c(st+40,vt.length),this.mem.setUint8(st+48,1)},debug:st=>{console.log(st)}}}}run(c){return __awaiter$7(this,void 0,void 0,function*(){if(!(c instanceof WebAssembly.Instance))throw new Error("Go.run: WebAssembly.Instance expected");this._inst=c,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,globalThis,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[globalThis,5],[this,6]]),this._idPool=[],this.exited=!1;let h=4096;const d=st=>{const ht=h,mt=a.encode(st+"\0");return new Uint8Array(this.mem.buffer,h,mt.length).set(mt),h+=mt.length,h%8!==0&&(h+=8-h%8),ht},_=this.argv.length,_e=[];this.argv.forEach(st=>{_e.push(d(st))}),_e.push(0),Object.keys(this.env).sort().forEach(st=>{_e.push(d(`${st}=${this.env[st]}`))}),_e.push(0);const rt=h;if(_e.forEach(st=>{this.mem.setUint32(h,st,!0),this.mem.setUint32(h+4,0,!0),h+=8}),h>=12288)throw new Error("total length of command line and environment variables exceeds limit");this._inst.exports.run(_,rt),this.exited&&this._resolveExitPromise(),yield this._exitPromise})}_resume(){if(this.exited)throw new Error("Go program has already exited");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(c){const h=this;return function(){const d={id:c,this:this,args:arguments};return h._pendingEvent=d,h._resume(),d.result}}}})();var __awaiter$6=function(e,a,o,c){function h(d){return d instanceof o?d:new o(function(_){_(d)})}return new(o||(o=Promise))(function(d,_){function _e(it){try{rt(c.next(it))}catch(st){_(st)}}function tt(it){try{rt(c.throw(it))}catch(st){_(st)}}function rt(it){it.done?d(it.value):h(it.value).then(_e,tt)}rt((c=c.apply(e,a||[])).next())})};const configCGGMPBase=(e,a,o)=>`{"ServerUrl":"${e}", "WalletId": "${a}", "Id":"${o}", "Ids":["USER","CAPSULE"], "Threshold":1}`,configDKLSBase=(e,a,o)=>`{"walletId": "${e}", "id":"${a}", "otherId":"CAPSULE", "isReceiver": false, "disableWebSockets": ${o}}`;function keygenRequest(e,a,o,c){return __awaiter$6(this,void 0,void 0,function*(){const{data:h}=yield e.mpcComputationClient.post("/wallets",{userId:a,walletId:o,protocolId:c});return h})}function signMessageRequest(e,a,o,c,h,d){return __awaiter$6(this,void 0,void 0,function*(){const{data:_}=yield e.mpcComputationClient.post(`/wallets/${o}/messages/sign`,{userId:a,protocolId:c,message:h,signer:d});return _})}function sendTransactionRequest(e,a,o,c,h,d,_){return __awaiter$6(this,void 0,void 0,function*(){const{data:_e}=yield e.mpcComputationClient.post(`/wallets/${o}/transactions/send`,{userId:a,protocolId:c,transaction:h,signer:d,chainId:_});return _e})}function ed25519Keygen$1(e,a){return __awaiter$6(this,void 0,void 0,function*(){const{walletId:o,protocolId:c}=yield e.capsuleClient.createWallet(a,{scheme:WalletScheme.ED25519,type:WalletType.SOLANA}),h=getBaseMPCNetworkUrl(e.env,!e.disableWebSockets);return{signer:yield new Promise((_,_e)=>global$1.ed25519CreateAccount(h,o,c,(tt,rt)=>{tt&&_e(tt),_(rt)})),walletId:o}})}function ed25519PreKeygen$1(e,a,o){return __awaiter$6(this,void 0,void 0,function*(){const{walletId:c,protocolId:h}=yield e.capsuleClient.createWalletPreGen({pregenIdentifier:a,pregenIdentifierType:o,scheme:WalletScheme.ED25519,type:WalletType.SOLANA}),d=getBaseMPCNetworkUrl(e.env,!e.disableWebSockets);return{signer:yield new Promise((_e,tt)=>global$1.ed25519CreateAccount(d,c,h,(rt,it)=>{rt&&tt(rt),_e(it)})),walletId:c}})}function ed25519Sign$1(e,a,o,c,h){return __awaiter$6(this,void 0,void 0,function*(){const{protocolId:d}=yield e.capsuleClient.preSignMessage(o,c,h,WalletScheme.ED25519);return{signature:yield new Promise((_e,tt)=>global$1.ed25519Sign(a,d,h,(rt,it)=>{rt&&tt(rt),_e(it)}))}})}function keygen$1(e,a,o,c){return __awaiter$6(this,void 0,void 0,function*(){const{walletId:h,protocolId:d}=yield e.capsuleClient.createWallet(a,{useTwoSigners:!0,scheme:e.useDKLS?WalletScheme.DKLS:WalletScheme.CGGMP,type:o,cosmosPrefix:o===WalletType.COSMOS?e.cosmosPrefix:void 0});if(e.offloadMPCComputationURL&&!e.useDKLS)return{signer:(yield keygenRequest(e,a,h,d)).signer,walletId:h};const _=getBaseMPCNetworkUrl(e.env,!e.disableWebSockets),_e=e.useDKLS?configDKLSBase(h,"USER",e.disableWebSockets):configCGGMPBase(_,h,"USER"),tt=e.useDKLS?global$1.dklsCreateAccount:global$1.createAccountV2;return{signer:yield new Promise((it,st)=>tt(_e,_,d,c,()=>{},(ht,mt)=>{ht&&st(ht),it(mt)})),walletId:h}})}function preKeygen$1(e,a,o,c,h,d){return __awaiter$6(this,void 0,void 0,function*(){const{walletId:_,protocolId:_e}=yield e.capsuleClient.createWalletPreGen({pregenIdentifier:o,pregenIdentifierType:c,type:h,cosmosPrefix:h===WalletType.COSMOS?e.cosmosPrefix:void 0}),tt=getBaseMPCNetworkUrl(e.env,!e.disableWebSockets),rt=configDKLSBase(_,"USER",e.disableWebSockets);return{signer:yield new Promise((st,ht)=>global$1.dklsCreateAccount(rt,tt,_e,d,()=>{},(mt,vt)=>{mt&&ht(mt),st(vt)})),walletId:_}})}function signMessage$1(e,a,o,c,h,d){return __awaiter$6(this,void 0,void 0,function*(){const{protocolId:_,pendingTransactionId:_e}=yield e.capsuleClient.preSignMessage(c,o,h,null,d);if(_e)return{pendingTransactionId:_e};if(e.offloadMPCComputationURL&&!e.useDKLS)return signMessageRequest(e,c,o,_,h,a);const tt=getBaseMPCNetworkUrl(e.env,!e.disableWebSockets),rt=e.useDKLS?global$1.dklsSignMessage:global$1.signMessage,it=JSON.parse(a);return!it.disableWebSockets!=!e.disableWebSockets&&(it.disableWebSockets=e.disableWebSockets),a=JSON.stringify(it),new Promise((st,ht)=>rt(a,tt,h,_,(mt,vt)=>{mt&&ht(mt),st({signature:vt})}))})}function signTransaction$1(e,a,o,c,h,d){return __awaiter$6(this,void 0,void 0,function*(){const{data:{protocolId:_,pendingTransactionId:_e}}=yield e.capsuleClient.signTransaction(c,o,{transaction:h,chainId:d});if(_e)return{pendingTransactionId:_e};if(e.offloadMPCComputationURL&&!e.useDKLS)return sendTransactionRequest(e,c,o,_,h,a,d);const tt=getBaseMPCNetworkUrl(e.env,!e.disableWebSockets),rt=e.useDKLS?global$1.dklsSendTransaction:global$1.sendTransaction,it=JSON.parse(a);return!it.disableWebSockets!=!e.disableWebSockets&&(it.disableWebSockets=e.disableWebSockets),a=JSON.stringify(it),new Promise((st,ht)=>rt(a,tt,h,d,_,(mt,vt)=>{mt&&ht(mt),st({signature:vt})}))})}function sendTransaction$1(e,a,o,c,h,d){return __awaiter$6(this,void 0,void 0,function*(){const{data:{protocolId:_,pendingTransactionId:_e}}=yield e.capsuleClient.sendTransaction(c,o,{transaction:h,chainId:d});if(_e)return{pendingTransactionId:_e};if(e.offloadMPCComputationURL&&!e.useDKLS)return sendTransactionRequest(e,c,o,_,h,a,d);const tt=getBaseMPCNetworkUrl(e.env,!e.disableWebSockets),rt=e.useDKLS?global$1.dklsSendTransaction:global$1.sendTransaction,it=JSON.parse(a);return!it.disableWebSockets!=!e.disableWebSockets&&(it.disableWebSockets=e.disableWebSockets),a=JSON.stringify(it),new Promise((st,ht)=>rt(a,tt,h,d,_,(mt,vt)=>{mt&&ht(mt),st({signature:vt})}))})}function refresh$1(e,a,o,c,h,d){return __awaiter$6(this,void 0,void 0,function*(){const{data:{protocolId:_}}=yield e.capsuleClient.refreshKeys(c,o,h,d),_e=getBaseMPCNetworkUrl(e.env,!e.disableWebSockets),tt=e.useDKLS?global$1.dklsRefresh:global$1.refresh,rt=JSON.parse(a);return!rt.disableWebSockets!=!e.disableWebSockets&&(rt.disableWebSockets=e.disableWebSockets),a=JSON.stringify(rt),new Promise((it,st)=>tt(a,_e,_,(ht,mt)=>{ht&&st(ht),it(mt)}))})}function getPrivateKey$1(e,a,o,c){return __awaiter$6(this,void 0,void 0,function*(){const h=yield e.capsuleClient.getCapsuleShare(c,o);return h?new Promise((d,_)=>global$1.getPrivateKey(a,h,(_e,tt)=>{_e&&_(_e),d(tt)})):""})}var define_process_env_default={},__awaiter$5=function(e,a,o,c){function h(d){return d instanceof o?d:new o(function(_){_(d)})}return new(o||(o=Promise))(function(d,_){function _e(it){try{rt(c.next(it))}catch(st){_(st)}}function tt(it){try{rt(c.throw(it))}catch(st){_(st)}}function rt(it){it.done?d(it.value):h(it.value).then(_e,tt)}rt((c=c.apply(e,[])).next())})};function loadWasm(e,a){return __awaiter$5(this,void 0,void 0,function*(){const o=new self.Go;let c=a;if(!c){if(define_process_env_default.DISABLE_WASM_FETCH==="true")throw new Error("fetching wasm file is disabled");c=yield(yield fetch(`${getPortalBaseURL(e)}/static/js/main.wasm`,{mode:"cors"})).arrayBuffer()}const h=yield WebAssembly.instantiate(c,o.importObject);o.run(h.instance)})}function executeMessage(e,a){return __awaiter$5(this,void 0,void 0,function*(){const{functionType:o,params:c}=a;switch(o){case"KEYGEN":{const{userId:h,secretKey:d,type:_=WalletType.EVM}=c;return yield keygen$1(e,h,_,d)}case"SIGN_TRANSACTION":{const{share:h,walletId:d,userId:_,tx:_e,chainId:tt}=c;return signTransaction$1(e,h,d,_,_e,tt)}case"SEND_TRANSACTION":{const{share:h,walletId:d,userId:_,tx:_e,chainId:tt}=c;return sendTransaction$1(e,h,d,_,_e,tt)}case"SIGN_MESSAGE":{const{share:h,walletId:d,userId:_,message:_e,cosmosSignDoc:tt}=c;return signMessage$1(e,h,d,_,_e,tt)}case"REFRESH":{const{share:h,walletId:d,userId:_,oldPartnerId:_e,newPartnerId:tt}=c;return refresh$1(e,h,d,_,_e,tt)}case"PREKEYGEN":{const{email:h,partnerId:d,secretKey:_,type:_e=WalletType.EVM}=c;let{pregenIdentifier:tt,pregenIdentifierType:rt}=c;return h!=="null"&&h!=="undefined"&&h!==""&&h!=null&&(tt=h,rt=PregenIdentifierType.EMAIL),yield preKeygen$1(e,d,tt,rt,_e,_)}case"GET_PRIVATE_KEY":{const{share:h,walletId:d,userId:_}=c;return yield getPrivateKey$1(e,h,d,_)}case"ED25519_KEYGEN":{const{userId:h}=c;return ed25519Keygen$1(e,h)}case"ED25519_SIGN":{const{share:h,walletId:d,userId:_,base64Bytes:_e}=c;return ed25519Sign$1(e,h,_,d,_e)}case"ED25519_PREKEYGEN":{const{email:h}=c;let{pregenIdentifier:d,pregenIdentifierType:_}=c;return h!=="null"&&h!=="undefined"&&h!==""&&h!=null&&(d=h,_=PregenIdentifierType.EMAIL),ed25519PreKeygen$1(e,d,_)}default:throw new Error(`functionType: ${o} not supported`)}})}function handleMessage(e,a,o){return __awaiter$5(this,void 0,void 0,function*(){const{env:c,apiKey:h,cosmosPrefix:d="cosmos",offloadMPCComputationURL:_,disableWorkers:_e,sessionCookie:tt,useDKLS:rt,disableWebSockets:it,wasmOverride:st}=e.data;if(!c)return!0;const ht={env:c,apiKey:h,cosmosPrefix:d,capsuleClient:initClient$1(c,capsuleVersion,h,o,()=>tt),offloadMPCComputationURL:_,mpcComputationClient:_?initClient(_,!!_e):void 0,useDKLS:rt,disableWebSockets:!!it,wasmOverride:st};(!ht.offloadMPCComputationURL||ht.useDKLS)&&(yield loadWasm(ht,st));const mt=yield executeMessage(ht,e.data);return a(mt),!1})}var __awaiter$4=function(e,a,o,c){function h(d){return d instanceof o?d:new o(function(_){_(d)})}return new(o||(o=Promise))(function(d,_){function _e(it){try{rt(c.next(it))}catch(st){_(st)}}function tt(it){try{rt(c.throw(it))}catch(st){_(st)}}function rt(it){it.done?d(it.value):h(it.value).then(_e,tt)}rt((c=c.apply(e,a||[])).next())})};function setupWorker(e,a){return __awaiter$4(this,void 0,void 0,function*(){const o=h=>{h.data.functionType!=="CUSTOM"&&a(h.data)};if(e.disableWorkers)return{postMessage:function(d){(function(){return __awaiter$4(this,void 0,void 0,function*(){yield handleMessage({data:d},_=>o({data:_}),e.disableWorkers)})})()},terminate:()=>{}};let c;if(e.useLocalFiles)throw new Error("useLocalFiles only supported locally");{const h=yield fetch(`${getPortalBaseURL(e)}/static/js/mpcWorker-bundle.js`),d=new Blob([yield h.text()],{type:"application/javascript"}),_=URL.createObjectURL(d);c=new Worker(_)}return c.onmessage=o,c})}var __awaiter$3=function(e,a,o,c){function h(d){return d instanceof o?d:new o(function(_){_(d)})}return new(o||(o=Promise))(function(d,_){function _e(it){try{rt(c.next(it))}catch(st){_(st)}}function tt(it){try{rt(c.throw(it))}catch(st){_(st)}}function rt(it){it.done?d(it.value):h(it.value).then(_e,tt)}rt((c=c.apply(e,a||[])).next())})};function isKeygenComplete(e,a,o){return __awaiter$3(this,void 0,void 0,function*(){return!!(yield e.capsuleClient.getWallets(a)).data.wallets.find(d=>d.id===o).address})}function isRefreshComplete(e,a,o,c){return __awaiter$3(this,void 0,void 0,function*(){const{isDone:h}=yield e.capsuleClient.isRefreshDone(a,o,c);return h})}function isPreKeygenComplete(e,a,o,c){return __awaiter$3(this,void 0,void 0,function*(){return!!(yield e.capsuleClient.getPregenWallets(a,o)).wallets.find(_=>_.id===c).address})}function keygen(e,a,o,c,h=!1,d,_={}){return new Promise(_e=>__awaiter$3(this,void 0,void 0,function*(){const tt=yield setupWorker(e,rt=>__awaiter$3(this,void 0,void 0,function*(){if(yield waitUntilTrue(()=>__awaiter$3(this,void 0,void 0,function*(){return isKeygenComplete(e,a,rt.walletId)}),15e3,1e3),h){_e({signer:rt.signer,walletId:rt.walletId,recoveryShare:null}),tt.terminate();return}const it=yield distributeNewShare(e,a,rt.walletId,rt.signer,!1,_);_e({signer:rt.signer,walletId:rt.walletId,recoveryShare:it}),tt.terminate()}));tt.postMessage({env:e.env,apiKey:e.apiKey,cosmosPrefix:e.cosmosPrefix,params:{userId:a,secretKey:c,type:o},functionType:"KEYGEN",offloadMPCComputationURL:e.offloadMPCComputationURL,disableWorkers:e.disableWorkers,sessionCookie:d,useDKLS:e.useDKLS,disableWebSockets:e.disableWebSockets,wasmOverride:e.wasmOverride})}))}function preKeygen(e,a,o,c,h,d=!1,_,_e){return new Promise(tt=>__awaiter$3(this,void 0,void 0,function*(){const rt=yield setupWorker(e,ht=>__awaiter$3(this,void 0,void 0,function*(){yield waitUntilTrue(()=>__awaiter$3(this,void 0,void 0,function*(){return isPreKeygenComplete(e,a,o,ht.walletId)}),15e3,1e3),tt({signer:ht.signer,walletId:ht.walletId,recoveryShare:null}),rt.terminate()})),st={pregenIdentifier:a,pregenIdentifierType:o,type:c,secretKey:h,partnerId:_,email:void 0};o===PregenIdentifierType.EMAIL&&(st.email=a),rt.postMessage({env:e.env,apiKey:e.apiKey,cosmosPrefix:e.cosmosPrefix,params:st,functionType:"PREKEYGEN",offloadMPCComputationURL:e.offloadMPCComputationURL,disableWorkers:e.disableWorkers,sessionCookie:_e,useDKLS:e.useDKLS,disableWebSockets:e.disableWebSockets,wasmOverride:e.wasmOverride})}))}function refresh(e,a,o,c,h,d,_){return new Promise(_e=>__awaiter$3(this,void 0,void 0,function*(){const tt=yield setupWorker(e,rt=>__awaiter$3(this,void 0,void 0,function*(){yield waitUntilTrue(()=>__awaiter$3(this,void 0,void 0,function*(){return isRefreshComplete(e,o,c,_)}),15e3,1e3),_e({signer:rt}),tt.terminate()}));tt.postMessage({env:e.env,apiKey:e.apiKey,params:{userId:o,walletId:c,share:h,oldPartnerId:d,newPartnerId:_},functionType:"REFRESH",disableWorkers:e.disableWorkers,sessionCookie:a,useDKLS:e.useDKLS,disableWebSockets:e.disableWebSockets,wasmOverride:e.wasmOverride})}))}function ed25519Keygen(e,a,o,c={}){return new Promise(h=>__awaiter$3(this,void 0,void 0,function*(){const d=yield setupWorker(e,_=>__awaiter$3(this,void 0,void 0,function*(){yield waitUntilTrue(()=>__awaiter$3(this,void 0,void 0,function*(){return isKeygenComplete(e,a,_.walletId)}),15e3,1e3),h({signer:_.signer,walletId:_.walletId,recoveryShare:null}),d.terminate()}));d.postMessage({env:e.env,apiKey:e.apiKey,cosmosPrefix:e.cosmosPrefix,params:{userId:a},functionType:"ED25519_KEYGEN",disableWorkers:e.disableWorkers,sessionCookie:o,disableWebSockets:e.disableWebSockets,wasmOverride:e.wasmOverride})}))}function ed25519PreKeygen(e,a,o,c){return new Promise(h=>__awaiter$3(this,void 0,void 0,function*(){const d=yield setupWorker(e,tt=>__awaiter$3(this,void 0,void 0,function*(){yield waitUntilTrue(()=>__awaiter$3(this,void 0,void 0,function*(){return isPreKeygenComplete(e,a,o,tt.walletId)}),15e3,1e3),h({signer:tt.signer,walletId:tt.walletId,recoveryShare:null}),d.terminate()})),_e={pregenIdentifier:a,pregenIdentifierType:o,email:void 0};o===PregenIdentifierType.EMAIL&&(_e.email=a),d.postMessage({env:e.env,apiKey:e.apiKey,cosmosPrefix:e.cosmosPrefix,params:_e,functionType:"ED25519_PREKEYGEN",disableWorkers:e.disableWorkers,sessionCookie:c,disableWebSockets:e.disableWebSockets,wasmOverride:e.wasmOverride})}))}var __awaiter$2=function(e,a,o,c){function h(d){return d instanceof o?d:new o(function(_){_(d)})}return new(o||(o=Promise))(function(d,_){function _e(it){try{rt(c.next(it))}catch(st){_(st)}}function tt(it){try{rt(c.throw(it))}catch(st){_(st)}}function rt(it){it.done?d(it.value):h(it.value).then(_e,tt)}rt((c=c.apply(e,a||[])).next())})};function signTransaction(e,a,o,c,h,d,_,_e){return __awaiter$2(this,void 0,void 0,function*(){return yield new Promise(tt=>__awaiter$2(this,void 0,void 0,function*(){const rt=yield setupWorker(e,it=>__awaiter$2(this,void 0,void 0,function*(){tt(it),rt.terminate()}));rt.postMessage({env:e.env,apiKey:e.apiKey,cosmosPrefix:e.cosmosPrefix,params:{share:c,walletId:o,userId:a,tx:h,chainId:d},functionType:"SIGN_TRANSACTION",offloadMPCComputationURL:e.offloadMPCComputationURL,disableWorkers:e.disableWorkers,sessionCookie:_,useDKLS:_e,disableWebSockets:e.disableWebSockets,wasmOverride:e.wasmOverride})}))})}function sendTransaction(e,a,o,c,h,d,_,_e){return __awaiter$2(this,void 0,void 0,function*(){return yield new Promise(tt=>__awaiter$2(this,void 0,void 0,function*(){const rt=yield setupWorker(e,it=>__awaiter$2(this,void 0,void 0,function*(){tt(it),rt.terminate()}));rt.postMessage({env:e.env,apiKey:e.apiKey,cosmosPrefix:e.cosmosPrefix,params:{share:c,walletId:o,userId:a,tx:h,chainId:d},functionType:"SEND_TRANSACTION",offloadMPCComputationURL:e.offloadMPCComputationURL,disableWorkers:e.disableWorkers,sessionCookie:_,useDKLS:_e,disableWebSockets:e.disableWebSockets,wasmOverride:e.wasmOverride})}))})}function signMessage(e,a,o,c,h,d,_,_e){return __awaiter$2(this,void 0,void 0,function*(){return yield new Promise(tt=>__awaiter$2(this,void 0,void 0,function*(){const rt=yield setupWorker(e,it=>__awaiter$2(this,void 0,void 0,function*(){tt(it),rt.terminate()}));rt.postMessage({env:e.env,apiKey:e.apiKey,cosmosPrefix:e.cosmosPrefix,params:{share:c,walletId:o,userId:a,message:h,cosmosSignDoc:_e},functionType:"SIGN_MESSAGE",offloadMPCComputationURL:e.offloadMPCComputationURL,disableWorkers:e.disableWorkers,sessionCookie:d,useDKLS:_,disableWebSockets:e.disableWebSockets,wasmOverride:e.wasmOverride})}))})}function ed25519Sign(e,a,o,c,h,d){return __awaiter$2(this,void 0,void 0,function*(){return yield new Promise(_=>__awaiter$2(this,void 0,void 0,function*(){const _e=yield setupWorker(e,tt=>__awaiter$2(this,void 0,void 0,function*(){_(tt),_e.terminate()}));_e.postMessage({env:e.env,apiKey:e.apiKey,cosmosPrefix:e.cosmosPrefix,params:{share:c,walletId:o,userId:a,base64Bytes:h},functionType:"ED25519_SIGN",disableWorkers:e.disableWorkers,sessionCookie:d,disableWebSockets:e.disableWebSockets,wasmOverride:e.wasmOverride})}))})}var __awaiter$1=function(e,a,o,c){function h(d){return d instanceof o?d:new o(function(_){_(d)})}return new(o||(o=Promise))(function(d,_){function _e(it){try{rt(c.next(it))}catch(st){_(st)}}function tt(it){try{rt(c.throw(it))}catch(st){_(st)}}function rt(it){it.done?d(it.value):h(it.value).then(_e,tt)}rt((c=c.apply(e,a||[])).next())})};function getPrivateKey(e,a,o,c,h){return __awaiter$1(this,void 0,void 0,function*(){return yield new Promise(d=>__awaiter$1(this,void 0,void 0,function*(){const _=yield setupWorker(e,_e=>__awaiter$1(this,void 0,void 0,function*(){d(_e),_.terminate()}));_.postMessage({env:e.env,apiKey:e.apiKey,cosmosPrefix:e.cosmosPrefix,params:{share:c,walletId:o,userId:a},functionType:"GET_PRIVATE_KEY",offloadMPCComputationURL:e.offloadMPCComputationURL,disableWorkers:e.disableWorkers,sessionCookie:h,useDKLS:e.useDKLS,disableWebSockets:e.disableWebSockets,wasmOverride:e.wasmOverride})}))})}class WebUtils{constructor(){this.localStorage=new LocalStorage,this.sessionStorage=new SessionStorage,this.secureStorage=null,this.isSyncStorage=!0,this.disableProviderModal=!1}getPrivateKey(a,o,c,h,d){return getPrivateKey(a,o,c,h,d)}keygen(a,o,c,h,d,_={}){return keygen(a,o,c,h,!0,d,_)}refresh(a,o,c,h,d,_,_e){return refresh(a,o,c,h,d,_,_e)}preKeygen(a,o,c,h,d,_,_e){return preKeygen(a,c,h,d,_,!1,o,_e)}signMessage(a,o,c,h,d,_,_e,tt){return signMessage(a,o,c,h,d,_,_e,tt)}signTransaction(a,o,c,h,d,_,_e,tt){return signTransaction(a,o,c,h,d,_,_e,tt)}sendTransaction(a,o,c,h,d,_,_e,tt){return sendTransaction(a,o,c,h,d,_,_e,tt)}signHash(a,o){throw new Error("not implemented")}ed25519Keygen(a,o,c,h){return ed25519Keygen(a,o,c,h)}ed25519PreKeygen(a,o,c,h){return ed25519PreKeygen(a,o,c,h)}ed25519Sign(a,o,c,h,d,_){return ed25519Sign(a,o,c,h,d,_)}openPopup(a,o){if(o){const{type:c}=o,h=550;let d;switch(c){case PopupType.LOGIN_PASSKEY:{d=798;break}case PopupType.CREATE_PASSKEY:{d=464;break}case PopupType.SIGN_MESSAGE_REVIEW:{d=585;break}case PopupType.SIGN_TRANSACTION_REVIEW:{d=750;break}case PopupType.OAUTH:default:{d=768;break}}const _=window.screenLeft!==void 0?window.screenLeft:window.screenX,_e=window.screenTop!==void 0?window.screenTop:window.screenY,tt=window.innerWidth?window.innerWidth:document.documentElement.clientWidth?document.documentElement.clientWidth:screen.width,rt=window.innerHeight?window.innerHeight:document.documentElement.clientHeight?document.documentElement.clientHeight:screen.height,it=(tt-h)/2+_,st=(rt-d)/2+_e,ht=`toolbar=no, menubar=no, width=${h}, - height=${d}, top=${st}, left=${it}`;let mt=window.open(a,c.toString(),ht);return mt||setTimeout(()=>{mt=window.open(a,"_blank")},0),mt}else{const c=window.open(a,"popup","popup=true,width=400,height=500");return c||setTimeout(()=>{window.open(a,"_blank")},0),c}}}class Capsule extends CoreCapsule{getPlatformUtils(){return new WebUtils}}const CAPSULE_ENV="BETA",CAPSULE_API_KEY="9f96227082046e39bcaa5f996ba7b4bb",capsuleClient=new Capsule(CAPSULE_ENV,CAPSULE_API_KEY),OnboardingScreen=({onComplete:e})=>{const[a,o]=reactExports.useState(!1),[c,h]=reactExports.useState(""),[d,_]=reactExports.useState(null);reactExports.useEffect(()=>{_e()},[]);const _e=async()=>{var rt,it;o(!0),h("Starting the initialization of Capsule Telegram Mini App Demo..."),_(null);try{if(_default.ready(),!_default.initDataUnsafe.user){_("Error during initialization: User data not found");return}const st=(rt=_default.initDataUnsafe.user)==null?void 0:rt.username;if(!st){_("Error during initialization: Username not found");return}h(`User authenticated successfully: ${(it=_default.initDataUnsafe.user)==null?void 0:it.username}`),await new Promise(vt=>setTimeout(vt,500)),h(`Checking Telegram cloud storage for existing wallet data associated with user ${st}...`);const ht=await retrieveChunkedData("userShare",h,_),mt=await retrieveChunkedData("walletId",h,_);ht&&mt?(h(`Existing wallet data found: Wallet ID ${mt}. Setting up your wallet...`),await capsuleClient.setUserShare(ht)):(h(`No existing wallet data found for user ${st}. Proceeding with new wallet creation...`),await new Promise(vt=>setTimeout(vt,500))),h("Initialization complete. Redirecting to the app..."),await new Promise(vt=>setTimeout(vt,500)),e()}catch(st){_(`Initialization error: ${st instanceof Error?st.message:String(st)}. Please try again or contact support if the issue persists.`)}finally{o(!1),h("")}},tt=async()=>{var rt;o(!0),h("Generating a new wallet..."),_(null);try{const it=(rt=_default.initDataUnsafe.user)==null?void 0:rt.username;if(!it){_("Error: Username not found. Unable to create wallet.");return}const st=`${it+crypto.randomUUID().split("-")[0]}@test.usecapsule.com`;h("Creating wallet with pre-generated identifier...");const ht=await capsuleClient.createWalletPreGen(WalletType.EVM,st);h(`Wallet created successfully. Wallet ID: ${ht.id}, Address: ${ht.address||"N/A"}`),await new Promise(vt=>setTimeout(vt,500)),h("Retrieving user wallet share...");const mt=await capsuleClient.getUserShare()||"";h("Preparing to store wallet data in Telegram cloud storage..."),await new Promise(vt=>setTimeout(vt,500)),h("Storing wallet data. This may take a few seconds..."),await Promise.all([storeWithChunking("userShare",mt,h,_),storeWithChunking("walletId",ht.id,h,_)]),h("Wallet data stored successfully. Initialization complete. Redirecting to the app..."),await new Promise(vt=>setTimeout(vt,500)),e()}catch(it){_(`Error: ${it instanceof Error?it.message:String(it)}. Please try again or contact support.`)}finally{o(!1),h("")}};return d?jsxRuntimeExports.jsxs("div",{className:"h-full flex flex-col justify-between p-6",children:[jsxRuntimeExports.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("h1",{className:"text-4xl font-bold mb-4",children:"Oops!"}),jsxRuntimeExports.jsx("p",{className:"text-lg text-muted-foreground",children:d})]})}),jsxRuntimeExports.jsx(Button,{size:"lg",className:"w-full mt-6",onClick:_e,children:"Retry"})]}):a?jsxRuntimeExports.jsx("div",{className:"h-full flex flex-col justify-between p-6",children:jsxRuntimeExports.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:jsxRuntimeExports.jsx(Spinner,{message:c})})}):jsxRuntimeExports.jsxs("div",{className:"h-full flex flex-col justify-between p-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[jsxRuntimeExports.jsx("div",{className:"w-20 h-20 mb-6 text-primary",children:jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"w-full h-full",children:[jsxRuntimeExports.jsx("path",{d:"M21 12V7H5a2 2 0 0 1 0-4h14v4"}),jsxRuntimeExports.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h16v-5"}),jsxRuntimeExports.jsx("path",{d:"M18 12a2 2 0 0 0 0 4h4v-4Z"})]})}),jsxRuntimeExports.jsx("h1",{className:"text-4xl font-bold mb-4",children:"Welcome"}),jsxRuntimeExports.jsx("p",{className:"text-lg text-muted-foreground text-center",children:"Create your secure wallet to start exploring web3"})]}),jsxRuntimeExports.jsx(Button,{size:"lg",className:"w-full",onClick:tt,children:"Create Wallet"})]})};function composeEventHandlers(e,a,{checkForDefaultPrevented:o=!0}={}){return function(h){if(e==null||e(h),o===!1||!h.defaultPrevented)return a==null?void 0:a(h)}}function createContext2(e,a){const o=reactExports.createContext(a),c=d=>{const{children:_,..._e}=d,tt=reactExports.useMemo(()=>_e,Object.values(_e));return jsxRuntimeExports.jsx(o.Provider,{value:tt,children:_})};c.displayName=e+"Provider";function h(d){const _=reactExports.useContext(o);if(_)return _;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${e}\``)}return[c,h]}function createContextScope(e,a=[]){let o=[];function c(d,_){const _e=reactExports.createContext(_),tt=o.length;o=[...o,_];const rt=st=>{var $t;const{scope:ht,children:mt,...vt}=st,yt=(($t=ht==null?void 0:ht[e])==null?void 0:$t[tt])||_e,_t=reactExports.useMemo(()=>vt,Object.values(vt));return jsxRuntimeExports.jsx(yt.Provider,{value:_t,children:mt})};rt.displayName=d+"Provider";function it(st,ht){var yt;const mt=((yt=ht==null?void 0:ht[e])==null?void 0:yt[tt])||_e,vt=reactExports.useContext(mt);if(vt)return vt;if(_!==void 0)return _;throw new Error(`\`${st}\` must be used within \`${d}\``)}return[rt,it]}const h=()=>{const d=o.map(_=>reactExports.createContext(_));return function(_e){const tt=(_e==null?void 0:_e[e])||d;return reactExports.useMemo(()=>({[`__scope${e}`]:{..._e,[e]:tt}}),[_e,tt])}};return h.scopeName=e,[c,composeContextScopes(h,...a)]}function composeContextScopes(...e){const a=e[0];if(e.length===1)return a;const o=()=>{const c=e.map(h=>({useScope:h(),scopeName:h.scopeName}));return function(d){const _=c.reduce((_e,{useScope:tt,scopeName:rt})=>{const st=tt(d)[`__scope${rt}`];return{..._e,...st}},{});return reactExports.useMemo(()=>({[`__scope${a.scopeName}`]:_}),[_])}};return o.scopeName=a.scopeName,o}var useLayoutEffect2=globalThis!=null&&globalThis.document?reactExports.useLayoutEffect:()=>{},useReactId=React$1.useId||(()=>{}),count$1=0;function useId(e){const[a,o]=reactExports.useState(useReactId());return useLayoutEffect2(()=>{e||o(c=>c??String(count$1++))},[e]),e||(a?`radix-${a}`:"")}function useCallbackRef$1(e){const a=reactExports.useRef(e);return reactExports.useEffect(()=>{a.current=e}),reactExports.useMemo(()=>(...o)=>{var c;return(c=a.current)==null?void 0:c.call(a,...o)},[])}function useControllableState({prop:e,defaultProp:a,onChange:o=()=>{}}){const[c,h]=useUncontrolledState({defaultProp:a,onChange:o}),d=e!==void 0,_=d?e:c,_e=useCallbackRef$1(o),tt=reactExports.useCallback(rt=>{if(d){const st=typeof rt=="function"?rt(e):rt;st!==e&&_e(st)}else h(rt)},[d,e,h,_e]);return[_,tt]}function useUncontrolledState({defaultProp:e,onChange:a}){const o=reactExports.useState(e),[c]=o,h=reactExports.useRef(c),d=useCallbackRef$1(a);return reactExports.useEffect(()=>{h.current!==c&&(d(c),h.current=c)},[c,h,d]),o}var NODES=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Primitive$1=NODES.reduce((e,a)=>{const o=reactExports.forwardRef((c,h)=>{const{asChild:d,..._}=c,_e=d?Slot:a;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),jsxRuntimeExports.jsx(_e,{..._,ref:h})});return o.displayName=`Primitive.${a}`,{...e,[a]:o}},{});function dispatchDiscreteCustomEvent(e,a){e&&reactDomExports.flushSync(()=>e.dispatchEvent(a))}function useEscapeKeydown(e,a=globalThis==null?void 0:globalThis.document){const o=useCallbackRef$1(e);reactExports.useEffect(()=>{const c=h=>{h.key==="Escape"&&o(h)};return a.addEventListener("keydown",c,{capture:!0}),()=>a.removeEventListener("keydown",c,{capture:!0})},[o,a])}var DISMISSABLE_LAYER_NAME="DismissableLayer",CONTEXT_UPDATE="dismissableLayer.update",POINTER_DOWN_OUTSIDE="dismissableLayer.pointerDownOutside",FOCUS_OUTSIDE="dismissableLayer.focusOutside",originalBodyPointerEvents,DismissableLayerContext=reactExports.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),DismissableLayer=reactExports.forwardRef((e,a)=>{const{disableOutsidePointerEvents:o=!1,onEscapeKeyDown:c,onPointerDownOutside:h,onFocusOutside:d,onInteractOutside:_,onDismiss:_e,...tt}=e,rt=reactExports.useContext(DismissableLayerContext),[it,st]=reactExports.useState(null),ht=(it==null?void 0:it.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,mt]=reactExports.useState({}),vt=useComposedRefs(a,Vt=>st(Vt)),yt=Array.from(rt.layers),[_t]=[...rt.layersWithOutsidePointerEventsDisabled].slice(-1),$t=yt.indexOf(_t),bt=it?yt.indexOf(it):-1,xt=rt.layersWithOutsidePointerEventsDisabled.size>0,St=bt>=$t,Rt=usePointerDownOutside(Vt=>{const Wt=Vt.target,Ft=[...rt.branches].some(Zt=>Zt.contains(Wt));!St||Ft||(h==null||h(Vt),_==null||_(Vt),Vt.defaultPrevented||_e==null||_e())},ht),Ot=useFocusOutside(Vt=>{const Wt=Vt.target;[...rt.branches].some(Zt=>Zt.contains(Wt))||(d==null||d(Vt),_==null||_(Vt),Vt.defaultPrevented||_e==null||_e())},ht);return useEscapeKeydown(Vt=>{bt===rt.layers.size-1&&(c==null||c(Vt),!Vt.defaultPrevented&&_e&&(Vt.preventDefault(),_e()))},ht),reactExports.useEffect(()=>{if(it)return o&&(rt.layersWithOutsidePointerEventsDisabled.size===0&&(originalBodyPointerEvents=ht.body.style.pointerEvents,ht.body.style.pointerEvents="none"),rt.layersWithOutsidePointerEventsDisabled.add(it)),rt.layers.add(it),dispatchUpdate(),()=>{o&&rt.layersWithOutsidePointerEventsDisabled.size===1&&(ht.body.style.pointerEvents=originalBodyPointerEvents)}},[it,ht,o,rt]),reactExports.useEffect(()=>()=>{it&&(rt.layers.delete(it),rt.layersWithOutsidePointerEventsDisabled.delete(it),dispatchUpdate())},[it,rt]),reactExports.useEffect(()=>{const Vt=()=>mt({});return document.addEventListener(CONTEXT_UPDATE,Vt),()=>document.removeEventListener(CONTEXT_UPDATE,Vt)},[]),jsxRuntimeExports.jsx(Primitive$1.div,{...tt,ref:vt,style:{pointerEvents:xt?St?"auto":"none":void 0,...e.style},onFocusCapture:composeEventHandlers(e.onFocusCapture,Ot.onFocusCapture),onBlurCapture:composeEventHandlers(e.onBlurCapture,Ot.onBlurCapture),onPointerDownCapture:composeEventHandlers(e.onPointerDownCapture,Rt.onPointerDownCapture)})});DismissableLayer.displayName=DISMISSABLE_LAYER_NAME;var BRANCH_NAME="DismissableLayerBranch",DismissableLayerBranch=reactExports.forwardRef((e,a)=>{const o=reactExports.useContext(DismissableLayerContext),c=reactExports.useRef(null),h=useComposedRefs(a,c);return reactExports.useEffect(()=>{const d=c.current;if(d)return o.branches.add(d),()=>{o.branches.delete(d)}},[o.branches]),jsxRuntimeExports.jsx(Primitive$1.div,{...e,ref:h})});DismissableLayerBranch.displayName=BRANCH_NAME;function usePointerDownOutside(e,a=globalThis==null?void 0:globalThis.document){const o=useCallbackRef$1(e),c=reactExports.useRef(!1),h=reactExports.useRef(()=>{});return reactExports.useEffect(()=>{const d=_e=>{if(_e.target&&!c.current){let tt=function(){handleAndDispatchCustomEvent(POINTER_DOWN_OUTSIDE,o,rt,{discrete:!0})};const rt={originalEvent:_e};_e.pointerType==="touch"?(a.removeEventListener("click",h.current),h.current=tt,a.addEventListener("click",h.current,{once:!0})):tt()}else a.removeEventListener("click",h.current);c.current=!1},_=window.setTimeout(()=>{a.addEventListener("pointerdown",d)},0);return()=>{window.clearTimeout(_),a.removeEventListener("pointerdown",d),a.removeEventListener("click",h.current)}},[a,o]),{onPointerDownCapture:()=>c.current=!0}}function useFocusOutside(e,a=globalThis==null?void 0:globalThis.document){const o=useCallbackRef$1(e),c=reactExports.useRef(!1);return reactExports.useEffect(()=>{const h=d=>{d.target&&!c.current&&handleAndDispatchCustomEvent(FOCUS_OUTSIDE,o,{originalEvent:d},{discrete:!1})};return a.addEventListener("focusin",h),()=>a.removeEventListener("focusin",h)},[a,o]),{onFocusCapture:()=>c.current=!0,onBlurCapture:()=>c.current=!1}}function dispatchUpdate(){const e=new CustomEvent(CONTEXT_UPDATE);document.dispatchEvent(e)}function handleAndDispatchCustomEvent(e,a,o,{discrete:c}){const h=o.originalEvent.target,d=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:o});a&&h.addEventListener(e,a,{once:!0}),c?dispatchDiscreteCustomEvent(h,d):h.dispatchEvent(d)}var AUTOFOCUS_ON_MOUNT="focusScope.autoFocusOnMount",AUTOFOCUS_ON_UNMOUNT="focusScope.autoFocusOnUnmount",EVENT_OPTIONS={bubbles:!1,cancelable:!0},FOCUS_SCOPE_NAME="FocusScope",FocusScope=reactExports.forwardRef((e,a)=>{const{loop:o=!1,trapped:c=!1,onMountAutoFocus:h,onUnmountAutoFocus:d,..._}=e,[_e,tt]=reactExports.useState(null),rt=useCallbackRef$1(h),it=useCallbackRef$1(d),st=reactExports.useRef(null),ht=useComposedRefs(a,yt=>tt(yt)),mt=reactExports.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;reactExports.useEffect(()=>{if(c){let yt=function(xt){if(mt.paused||!_e)return;const St=xt.target;_e.contains(St)?st.current=St:focus(st.current,{select:!0})},_t=function(xt){if(mt.paused||!_e)return;const St=xt.relatedTarget;St!==null&&(_e.contains(St)||focus(st.current,{select:!0}))},$t=function(xt){if(document.activeElement===document.body)for(const Rt of xt)Rt.removedNodes.length>0&&focus(_e)};document.addEventListener("focusin",yt),document.addEventListener("focusout",_t);const bt=new MutationObserver($t);return _e&&bt.observe(_e,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",yt),document.removeEventListener("focusout",_t),bt.disconnect()}}},[c,_e,mt.paused]),reactExports.useEffect(()=>{if(_e){focusScopesStack.add(mt);const yt=document.activeElement;if(!_e.contains(yt)){const $t=new CustomEvent(AUTOFOCUS_ON_MOUNT,EVENT_OPTIONS);_e.addEventListener(AUTOFOCUS_ON_MOUNT,rt),_e.dispatchEvent($t),$t.defaultPrevented||(focusFirst(removeLinks(getTabbableCandidates(_e)),{select:!0}),document.activeElement===yt&&focus(_e))}return()=>{_e.removeEventListener(AUTOFOCUS_ON_MOUNT,rt),setTimeout(()=>{const $t=new CustomEvent(AUTOFOCUS_ON_UNMOUNT,EVENT_OPTIONS);_e.addEventListener(AUTOFOCUS_ON_UNMOUNT,it),_e.dispatchEvent($t),$t.defaultPrevented||focus(yt??document.body,{select:!0}),_e.removeEventListener(AUTOFOCUS_ON_UNMOUNT,it),focusScopesStack.remove(mt)},0)}}},[_e,rt,it,mt]);const vt=reactExports.useCallback(yt=>{if(!o&&!c||mt.paused)return;const _t=yt.key==="Tab"&&!yt.altKey&&!yt.ctrlKey&&!yt.metaKey,$t=document.activeElement;if(_t&&$t){const bt=yt.currentTarget,[xt,St]=getTabbableEdges(bt);xt&&St?!yt.shiftKey&&$t===St?(yt.preventDefault(),o&&focus(xt,{select:!0})):yt.shiftKey&&$t===xt&&(yt.preventDefault(),o&&focus(St,{select:!0})):$t===bt&&yt.preventDefault()}},[o,c,mt.paused]);return jsxRuntimeExports.jsx(Primitive$1.div,{tabIndex:-1,..._,ref:ht,onKeyDown:vt})});FocusScope.displayName=FOCUS_SCOPE_NAME;function focusFirst(e,{select:a=!1}={}){const o=document.activeElement;for(const c of e)if(focus(c,{select:a}),document.activeElement!==o)return}function getTabbableEdges(e){const a=getTabbableCandidates(e),o=findVisible(a,e),c=findVisible(a.reverse(),e);return[o,c]}function getTabbableCandidates(e){const a=[],o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:c=>{const h=c.tagName==="INPUT"&&c.type==="hidden";return c.disabled||c.hidden||h?NodeFilter.FILTER_SKIP:c.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;o.nextNode();)a.push(o.currentNode);return a}function findVisible(e,a){for(const o of e)if(!isHidden(o,{upTo:a}))return o}function isHidden(e,{upTo:a}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(a!==void 0&&e===a)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function isSelectableInput(e){return e instanceof HTMLInputElement&&"select"in e}function focus(e,{select:a=!1}={}){if(e&&e.focus){const o=document.activeElement;e.focus({preventScroll:!0}),e!==o&&isSelectableInput(e)&&a&&e.select()}}var focusScopesStack=createFocusScopesStack();function createFocusScopesStack(){let e=[];return{add(a){const o=e[0];a!==o&&(o==null||o.pause()),e=arrayRemove(e,a),e.unshift(a)},remove(a){var o;e=arrayRemove(e,a),(o=e[0])==null||o.resume()}}}function arrayRemove(e,a){const o=[...e],c=o.indexOf(a);return c!==-1&&o.splice(c,1),o}function removeLinks(e){return e.filter(a=>a.tagName!=="A")}var PORTAL_NAME$1="Portal",Portal$1=reactExports.forwardRef((e,a)=>{var _e;const{container:o,...c}=e,[h,d]=reactExports.useState(!1);useLayoutEffect2(()=>d(!0),[]);const _=o||h&&((_e=globalThis==null?void 0:globalThis.document)==null?void 0:_e.body);return _?ReactDOM.createPortal(jsxRuntimeExports.jsx(Primitive$1.div,{...c,ref:a}),_):null});Portal$1.displayName=PORTAL_NAME$1;function useStateMachine(e,a){return reactExports.useReducer((o,c)=>a[o][c]??o,e)}var Presence=e=>{const{present:a,children:o}=e,c=usePresence(a),h=typeof o=="function"?o({present:c.isPresent}):reactExports.Children.only(o),d=useComposedRefs(c.ref,getElementRef(h));return typeof o=="function"||c.isPresent?reactExports.cloneElement(h,{ref:d}):null};Presence.displayName="Presence";function usePresence(e){const[a,o]=reactExports.useState(),c=reactExports.useRef({}),h=reactExports.useRef(e),d=reactExports.useRef("none"),_=e?"mounted":"unmounted",[_e,tt]=useStateMachine(_,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return reactExports.useEffect(()=>{const rt=getAnimationName(c.current);d.current=_e==="mounted"?rt:"none"},[_e]),useLayoutEffect2(()=>{const rt=c.current,it=h.current;if(it!==e){const ht=d.current,mt=getAnimationName(rt);e?tt("MOUNT"):mt==="none"||(rt==null?void 0:rt.display)==="none"?tt("UNMOUNT"):tt(it&&ht!==mt?"ANIMATION_OUT":"UNMOUNT"),h.current=e}},[e,tt]),useLayoutEffect2(()=>{if(a){let rt;const it=a.ownerDocument.defaultView??window,st=mt=>{const yt=getAnimationName(c.current).includes(mt.animationName);if(mt.target===a&&yt&&(tt("ANIMATION_END"),!h.current)){const _t=a.style.animationFillMode;a.style.animationFillMode="forwards",rt=it.setTimeout(()=>{a.style.animationFillMode==="forwards"&&(a.style.animationFillMode=_t)})}},ht=mt=>{mt.target===a&&(d.current=getAnimationName(c.current))};return a.addEventListener("animationstart",ht),a.addEventListener("animationcancel",st),a.addEventListener("animationend",st),()=>{it.clearTimeout(rt),a.removeEventListener("animationstart",ht),a.removeEventListener("animationcancel",st),a.removeEventListener("animationend",st)}}else tt("ANIMATION_END")},[a,tt]),{isPresent:["mounted","unmountSuspended"].includes(_e),ref:reactExports.useCallback(rt=>{rt&&(c.current=getComputedStyle(rt)),o(rt)},[])}}function getAnimationName(e){return(e==null?void 0:e.animationName)||"none"}function getElementRef(e){var c,h;let a=(c=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:c.get,o=a&&"isReactWarning"in a&&a.isReactWarning;return o?e.ref:(a=(h=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:h.get,o=a&&"isReactWarning"in a&&a.isReactWarning,o?e.props.ref:e.props.ref||e.ref)}var count=0;function useFocusGuards(){reactExports.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??createFocusGuard()),document.body.insertAdjacentElement("beforeend",e[1]??createFocusGuard()),count++,()=>{count===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(a=>a.remove()),count--}},[])}function createFocusGuard(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var __assign$1=function(){return __assign$1=Object.assign||function(a){for(var o,c=1,h=arguments.length;c"u")return zeroGap;var a=getOffset(e),o=document.documentElement.clientWidth,c=window.innerWidth;return{left:a[0],top:a[1],right:a[2],gap:Math.max(0,c-o+a[2]-a[0])}},Style=styleSingleton(),lockAttribute="data-scroll-locked",getStyles=function(e,a,o,c){var h=e.left,d=e.top,_=e.right,_e=e.gap;return o===void 0&&(o="margin"),` + height=${d}, top=${st}, left=${it}`;let mt=window.open(a,c.toString(),ht);return mt||setTimeout(()=>{mt=window.open(a,"_blank")},0),mt}else{const c=window.open(a,"popup","popup=true,width=400,height=500");return c||setTimeout(()=>{window.open(a,"_blank")},0),c}}}class Capsule extends CoreCapsule{getPlatformUtils(){return new WebUtils}}const CAPSULE_ENV="BETA",CAPSULE_API_KEY="9f96227082046e39bcaa5f996ba7b4bb",capsuleClient=new Capsule(CAPSULE_ENV,CAPSULE_API_KEY),OnboardingScreen=({onComplete:e})=>{const[a,o]=reactExports.useState(!1),[c,h]=reactExports.useState(""),[d,_]=reactExports.useState(null);reactExports.useEffect(()=>{_e()},[]);const _e=async()=>{var rt,it;o(!0),h("Starting the initialization of Capsule Telegram Mini App Demo..."),_(null);try{if(_default.ready(),!_default.initDataUnsafe.user){_("Error during initialization: User data not found");return}const st=(rt=_default.initDataUnsafe.user)==null?void 0:rt.username;if(!st){_("Error during initialization: Username not found");return}h(`User authenticated successfully: ${(it=_default.initDataUnsafe.user)==null?void 0:it.username}`),await new Promise(vt=>setTimeout(vt,1e3)),h(`Checking Telegram cloud storage for existing wallet data associated with user ${st}...`);const ht=await retrieveChunkedData("userShare",h,_),mt=await retrieveChunkedData("walletId",h,_);ht&&mt?(h(`Existing wallet data found: Wallet ID ${mt}. Setting up your wallet...`),await capsuleClient.setUserShare(ht)):(h(`No existing wallet data found for user ${st}. Proceeding with new wallet creation...`),await new Promise(vt=>setTimeout(vt,1e3))),h("Initialization complete. Redirecting to the app..."),await new Promise(vt=>setTimeout(vt,1e3)),e()}catch(st){_(`Initialization error: ${st instanceof Error?st.message:String(st)}. Please try again or contact support if the issue persists.`)}finally{o(!1),h("")}},tt=async()=>{var rt;o(!0),h("Generating a new wallet..."),_(null);try{const it=(rt=_default.initDataUnsafe.user)==null?void 0:rt.username;if(!it){_("Error: Username not found. Unable to create wallet.");return}const st=`${it+crypto.randomUUID().split("-")[0]}@test.usecapsule.com`;h("Creating wallet with pre-generated identifier...");const ht=await capsuleClient.createWalletPreGen(WalletType.EVM,st);h(`Wallet created successfully. Wallet ID: ${ht.id}, Address: ${ht.address||"N/A"}`),await new Promise(vt=>setTimeout(vt,1e3)),h("Retrieving user wallet share...");const mt=await capsuleClient.getUserShare()||"";h("Preparing to store wallet data in Telegram cloud storage..."),await new Promise(vt=>setTimeout(vt,1e3)),h("Storing wallet data. This may take a few seconds..."),await Promise.all([storeWithChunking("userShare",mt,h,_),storeWithChunking("walletId",ht.id,h,_)]),h("Wallet data stored successfully. Initialization complete. Redirecting to the app..."),await new Promise(vt=>setTimeout(vt,1e3)),e()}catch(it){_(`Error: ${it instanceof Error?it.message:String(it)}. Please try again or contact support.`)}finally{o(!1),h("")}};return d?jsxRuntimeExports.jsxs("div",{className:"h-full flex flex-col justify-between p-6",children:[jsxRuntimeExports.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("h1",{className:"text-4xl font-bold mb-4",children:"Oops!"}),jsxRuntimeExports.jsx("p",{className:"text-lg text-muted-foreground",children:d})]})}),jsxRuntimeExports.jsx(Button,{size:"lg",className:"w-full mt-6",onClick:_e,children:"Retry"})]}):a?jsxRuntimeExports.jsx("div",{className:"h-full flex flex-col justify-between p-6",children:jsxRuntimeExports.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:jsxRuntimeExports.jsx(Spinner,{message:c})})}):jsxRuntimeExports.jsxs("div",{className:"h-full flex flex-col justify-between p-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[jsxRuntimeExports.jsx("div",{className:"w-20 h-20 mb-6 text-primary",children:jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"w-full h-full",children:[jsxRuntimeExports.jsx("path",{d:"M21 12V7H5a2 2 0 0 1 0-4h14v4"}),jsxRuntimeExports.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h16v-5"}),jsxRuntimeExports.jsx("path",{d:"M18 12a2 2 0 0 0 0 4h4v-4Z"})]})}),jsxRuntimeExports.jsx("h1",{className:"text-4xl font-bold mb-4",children:"Welcome"}),jsxRuntimeExports.jsx("p",{className:"text-lg text-muted-foreground text-center",children:"Create your secure wallet to start exploring web3"})]}),jsxRuntimeExports.jsx(Button,{size:"lg",className:"w-full",onClick:tt,children:"Create Wallet"})]})};function composeEventHandlers(e,a,{checkForDefaultPrevented:o=!0}={}){return function(h){if(e==null||e(h),o===!1||!h.defaultPrevented)return a==null?void 0:a(h)}}function createContext2(e,a){const o=reactExports.createContext(a),c=d=>{const{children:_,..._e}=d,tt=reactExports.useMemo(()=>_e,Object.values(_e));return jsxRuntimeExports.jsx(o.Provider,{value:tt,children:_})};c.displayName=e+"Provider";function h(d){const _=reactExports.useContext(o);if(_)return _;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${e}\``)}return[c,h]}function createContextScope(e,a=[]){let o=[];function c(d,_){const _e=reactExports.createContext(_),tt=o.length;o=[...o,_];const rt=st=>{var $t;const{scope:ht,children:mt,...vt}=st,yt=(($t=ht==null?void 0:ht[e])==null?void 0:$t[tt])||_e,_t=reactExports.useMemo(()=>vt,Object.values(vt));return jsxRuntimeExports.jsx(yt.Provider,{value:_t,children:mt})};rt.displayName=d+"Provider";function it(st,ht){var yt;const mt=((yt=ht==null?void 0:ht[e])==null?void 0:yt[tt])||_e,vt=reactExports.useContext(mt);if(vt)return vt;if(_!==void 0)return _;throw new Error(`\`${st}\` must be used within \`${d}\``)}return[rt,it]}const h=()=>{const d=o.map(_=>reactExports.createContext(_));return function(_e){const tt=(_e==null?void 0:_e[e])||d;return reactExports.useMemo(()=>({[`__scope${e}`]:{..._e,[e]:tt}}),[_e,tt])}};return h.scopeName=e,[c,composeContextScopes(h,...a)]}function composeContextScopes(...e){const a=e[0];if(e.length===1)return a;const o=()=>{const c=e.map(h=>({useScope:h(),scopeName:h.scopeName}));return function(d){const _=c.reduce((_e,{useScope:tt,scopeName:rt})=>{const st=tt(d)[`__scope${rt}`];return{..._e,...st}},{});return reactExports.useMemo(()=>({[`__scope${a.scopeName}`]:_}),[_])}};return o.scopeName=a.scopeName,o}var useLayoutEffect2=globalThis!=null&&globalThis.document?reactExports.useLayoutEffect:()=>{},useReactId=React$1.useId||(()=>{}),count$1=0;function useId(e){const[a,o]=reactExports.useState(useReactId());return useLayoutEffect2(()=>{e||o(c=>c??String(count$1++))},[e]),e||(a?`radix-${a}`:"")}function useCallbackRef$1(e){const a=reactExports.useRef(e);return reactExports.useEffect(()=>{a.current=e}),reactExports.useMemo(()=>(...o)=>{var c;return(c=a.current)==null?void 0:c.call(a,...o)},[])}function useControllableState({prop:e,defaultProp:a,onChange:o=()=>{}}){const[c,h]=useUncontrolledState({defaultProp:a,onChange:o}),d=e!==void 0,_=d?e:c,_e=useCallbackRef$1(o),tt=reactExports.useCallback(rt=>{if(d){const st=typeof rt=="function"?rt(e):rt;st!==e&&_e(st)}else h(rt)},[d,e,h,_e]);return[_,tt]}function useUncontrolledState({defaultProp:e,onChange:a}){const o=reactExports.useState(e),[c]=o,h=reactExports.useRef(c),d=useCallbackRef$1(a);return reactExports.useEffect(()=>{h.current!==c&&(d(c),h.current=c)},[c,h,d]),o}var NODES=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Primitive$1=NODES.reduce((e,a)=>{const o=reactExports.forwardRef((c,h)=>{const{asChild:d,..._}=c,_e=d?Slot:a;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),jsxRuntimeExports.jsx(_e,{..._,ref:h})});return o.displayName=`Primitive.${a}`,{...e,[a]:o}},{});function dispatchDiscreteCustomEvent(e,a){e&&reactDomExports.flushSync(()=>e.dispatchEvent(a))}function useEscapeKeydown(e,a=globalThis==null?void 0:globalThis.document){const o=useCallbackRef$1(e);reactExports.useEffect(()=>{const c=h=>{h.key==="Escape"&&o(h)};return a.addEventListener("keydown",c,{capture:!0}),()=>a.removeEventListener("keydown",c,{capture:!0})},[o,a])}var DISMISSABLE_LAYER_NAME="DismissableLayer",CONTEXT_UPDATE="dismissableLayer.update",POINTER_DOWN_OUTSIDE="dismissableLayer.pointerDownOutside",FOCUS_OUTSIDE="dismissableLayer.focusOutside",originalBodyPointerEvents,DismissableLayerContext=reactExports.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),DismissableLayer=reactExports.forwardRef((e,a)=>{const{disableOutsidePointerEvents:o=!1,onEscapeKeyDown:c,onPointerDownOutside:h,onFocusOutside:d,onInteractOutside:_,onDismiss:_e,...tt}=e,rt=reactExports.useContext(DismissableLayerContext),[it,st]=reactExports.useState(null),ht=(it==null?void 0:it.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,mt]=reactExports.useState({}),vt=useComposedRefs(a,Vt=>st(Vt)),yt=Array.from(rt.layers),[_t]=[...rt.layersWithOutsidePointerEventsDisabled].slice(-1),$t=yt.indexOf(_t),bt=it?yt.indexOf(it):-1,xt=rt.layersWithOutsidePointerEventsDisabled.size>0,St=bt>=$t,Rt=usePointerDownOutside(Vt=>{const Wt=Vt.target,Ft=[...rt.branches].some(Zt=>Zt.contains(Wt));!St||Ft||(h==null||h(Vt),_==null||_(Vt),Vt.defaultPrevented||_e==null||_e())},ht),Ot=useFocusOutside(Vt=>{const Wt=Vt.target;[...rt.branches].some(Zt=>Zt.contains(Wt))||(d==null||d(Vt),_==null||_(Vt),Vt.defaultPrevented||_e==null||_e())},ht);return useEscapeKeydown(Vt=>{bt===rt.layers.size-1&&(c==null||c(Vt),!Vt.defaultPrevented&&_e&&(Vt.preventDefault(),_e()))},ht),reactExports.useEffect(()=>{if(it)return o&&(rt.layersWithOutsidePointerEventsDisabled.size===0&&(originalBodyPointerEvents=ht.body.style.pointerEvents,ht.body.style.pointerEvents="none"),rt.layersWithOutsidePointerEventsDisabled.add(it)),rt.layers.add(it),dispatchUpdate(),()=>{o&&rt.layersWithOutsidePointerEventsDisabled.size===1&&(ht.body.style.pointerEvents=originalBodyPointerEvents)}},[it,ht,o,rt]),reactExports.useEffect(()=>()=>{it&&(rt.layers.delete(it),rt.layersWithOutsidePointerEventsDisabled.delete(it),dispatchUpdate())},[it,rt]),reactExports.useEffect(()=>{const Vt=()=>mt({});return document.addEventListener(CONTEXT_UPDATE,Vt),()=>document.removeEventListener(CONTEXT_UPDATE,Vt)},[]),jsxRuntimeExports.jsx(Primitive$1.div,{...tt,ref:vt,style:{pointerEvents:xt?St?"auto":"none":void 0,...e.style},onFocusCapture:composeEventHandlers(e.onFocusCapture,Ot.onFocusCapture),onBlurCapture:composeEventHandlers(e.onBlurCapture,Ot.onBlurCapture),onPointerDownCapture:composeEventHandlers(e.onPointerDownCapture,Rt.onPointerDownCapture)})});DismissableLayer.displayName=DISMISSABLE_LAYER_NAME;var BRANCH_NAME="DismissableLayerBranch",DismissableLayerBranch=reactExports.forwardRef((e,a)=>{const o=reactExports.useContext(DismissableLayerContext),c=reactExports.useRef(null),h=useComposedRefs(a,c);return reactExports.useEffect(()=>{const d=c.current;if(d)return o.branches.add(d),()=>{o.branches.delete(d)}},[o.branches]),jsxRuntimeExports.jsx(Primitive$1.div,{...e,ref:h})});DismissableLayerBranch.displayName=BRANCH_NAME;function usePointerDownOutside(e,a=globalThis==null?void 0:globalThis.document){const o=useCallbackRef$1(e),c=reactExports.useRef(!1),h=reactExports.useRef(()=>{});return reactExports.useEffect(()=>{const d=_e=>{if(_e.target&&!c.current){let tt=function(){handleAndDispatchCustomEvent(POINTER_DOWN_OUTSIDE,o,rt,{discrete:!0})};const rt={originalEvent:_e};_e.pointerType==="touch"?(a.removeEventListener("click",h.current),h.current=tt,a.addEventListener("click",h.current,{once:!0})):tt()}else a.removeEventListener("click",h.current);c.current=!1},_=window.setTimeout(()=>{a.addEventListener("pointerdown",d)},0);return()=>{window.clearTimeout(_),a.removeEventListener("pointerdown",d),a.removeEventListener("click",h.current)}},[a,o]),{onPointerDownCapture:()=>c.current=!0}}function useFocusOutside(e,a=globalThis==null?void 0:globalThis.document){const o=useCallbackRef$1(e),c=reactExports.useRef(!1);return reactExports.useEffect(()=>{const h=d=>{d.target&&!c.current&&handleAndDispatchCustomEvent(FOCUS_OUTSIDE,o,{originalEvent:d},{discrete:!1})};return a.addEventListener("focusin",h),()=>a.removeEventListener("focusin",h)},[a,o]),{onFocusCapture:()=>c.current=!0,onBlurCapture:()=>c.current=!1}}function dispatchUpdate(){const e=new CustomEvent(CONTEXT_UPDATE);document.dispatchEvent(e)}function handleAndDispatchCustomEvent(e,a,o,{discrete:c}){const h=o.originalEvent.target,d=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:o});a&&h.addEventListener(e,a,{once:!0}),c?dispatchDiscreteCustomEvent(h,d):h.dispatchEvent(d)}var AUTOFOCUS_ON_MOUNT="focusScope.autoFocusOnMount",AUTOFOCUS_ON_UNMOUNT="focusScope.autoFocusOnUnmount",EVENT_OPTIONS={bubbles:!1,cancelable:!0},FOCUS_SCOPE_NAME="FocusScope",FocusScope=reactExports.forwardRef((e,a)=>{const{loop:o=!1,trapped:c=!1,onMountAutoFocus:h,onUnmountAutoFocus:d,..._}=e,[_e,tt]=reactExports.useState(null),rt=useCallbackRef$1(h),it=useCallbackRef$1(d),st=reactExports.useRef(null),ht=useComposedRefs(a,yt=>tt(yt)),mt=reactExports.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;reactExports.useEffect(()=>{if(c){let yt=function(xt){if(mt.paused||!_e)return;const St=xt.target;_e.contains(St)?st.current=St:focus(st.current,{select:!0})},_t=function(xt){if(mt.paused||!_e)return;const St=xt.relatedTarget;St!==null&&(_e.contains(St)||focus(st.current,{select:!0}))},$t=function(xt){if(document.activeElement===document.body)for(const Rt of xt)Rt.removedNodes.length>0&&focus(_e)};document.addEventListener("focusin",yt),document.addEventListener("focusout",_t);const bt=new MutationObserver($t);return _e&&bt.observe(_e,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",yt),document.removeEventListener("focusout",_t),bt.disconnect()}}},[c,_e,mt.paused]),reactExports.useEffect(()=>{if(_e){focusScopesStack.add(mt);const yt=document.activeElement;if(!_e.contains(yt)){const $t=new CustomEvent(AUTOFOCUS_ON_MOUNT,EVENT_OPTIONS);_e.addEventListener(AUTOFOCUS_ON_MOUNT,rt),_e.dispatchEvent($t),$t.defaultPrevented||(focusFirst(removeLinks(getTabbableCandidates(_e)),{select:!0}),document.activeElement===yt&&focus(_e))}return()=>{_e.removeEventListener(AUTOFOCUS_ON_MOUNT,rt),setTimeout(()=>{const $t=new CustomEvent(AUTOFOCUS_ON_UNMOUNT,EVENT_OPTIONS);_e.addEventListener(AUTOFOCUS_ON_UNMOUNT,it),_e.dispatchEvent($t),$t.defaultPrevented||focus(yt??document.body,{select:!0}),_e.removeEventListener(AUTOFOCUS_ON_UNMOUNT,it),focusScopesStack.remove(mt)},0)}}},[_e,rt,it,mt]);const vt=reactExports.useCallback(yt=>{if(!o&&!c||mt.paused)return;const _t=yt.key==="Tab"&&!yt.altKey&&!yt.ctrlKey&&!yt.metaKey,$t=document.activeElement;if(_t&&$t){const bt=yt.currentTarget,[xt,St]=getTabbableEdges(bt);xt&&St?!yt.shiftKey&&$t===St?(yt.preventDefault(),o&&focus(xt,{select:!0})):yt.shiftKey&&$t===xt&&(yt.preventDefault(),o&&focus(St,{select:!0})):$t===bt&&yt.preventDefault()}},[o,c,mt.paused]);return jsxRuntimeExports.jsx(Primitive$1.div,{tabIndex:-1,..._,ref:ht,onKeyDown:vt})});FocusScope.displayName=FOCUS_SCOPE_NAME;function focusFirst(e,{select:a=!1}={}){const o=document.activeElement;for(const c of e)if(focus(c,{select:a}),document.activeElement!==o)return}function getTabbableEdges(e){const a=getTabbableCandidates(e),o=findVisible(a,e),c=findVisible(a.reverse(),e);return[o,c]}function getTabbableCandidates(e){const a=[],o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:c=>{const h=c.tagName==="INPUT"&&c.type==="hidden";return c.disabled||c.hidden||h?NodeFilter.FILTER_SKIP:c.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;o.nextNode();)a.push(o.currentNode);return a}function findVisible(e,a){for(const o of e)if(!isHidden(o,{upTo:a}))return o}function isHidden(e,{upTo:a}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(a!==void 0&&e===a)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function isSelectableInput(e){return e instanceof HTMLInputElement&&"select"in e}function focus(e,{select:a=!1}={}){if(e&&e.focus){const o=document.activeElement;e.focus({preventScroll:!0}),e!==o&&isSelectableInput(e)&&a&&e.select()}}var focusScopesStack=createFocusScopesStack();function createFocusScopesStack(){let e=[];return{add(a){const o=e[0];a!==o&&(o==null||o.pause()),e=arrayRemove(e,a),e.unshift(a)},remove(a){var o;e=arrayRemove(e,a),(o=e[0])==null||o.resume()}}}function arrayRemove(e,a){const o=[...e],c=o.indexOf(a);return c!==-1&&o.splice(c,1),o}function removeLinks(e){return e.filter(a=>a.tagName!=="A")}var PORTAL_NAME$1="Portal",Portal$1=reactExports.forwardRef((e,a)=>{var _e;const{container:o,...c}=e,[h,d]=reactExports.useState(!1);useLayoutEffect2(()=>d(!0),[]);const _=o||h&&((_e=globalThis==null?void 0:globalThis.document)==null?void 0:_e.body);return _?ReactDOM.createPortal(jsxRuntimeExports.jsx(Primitive$1.div,{...c,ref:a}),_):null});Portal$1.displayName=PORTAL_NAME$1;function useStateMachine(e,a){return reactExports.useReducer((o,c)=>a[o][c]??o,e)}var Presence=e=>{const{present:a,children:o}=e,c=usePresence(a),h=typeof o=="function"?o({present:c.isPresent}):reactExports.Children.only(o),d=useComposedRefs(c.ref,getElementRef(h));return typeof o=="function"||c.isPresent?reactExports.cloneElement(h,{ref:d}):null};Presence.displayName="Presence";function usePresence(e){const[a,o]=reactExports.useState(),c=reactExports.useRef({}),h=reactExports.useRef(e),d=reactExports.useRef("none"),_=e?"mounted":"unmounted",[_e,tt]=useStateMachine(_,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return reactExports.useEffect(()=>{const rt=getAnimationName(c.current);d.current=_e==="mounted"?rt:"none"},[_e]),useLayoutEffect2(()=>{const rt=c.current,it=h.current;if(it!==e){const ht=d.current,mt=getAnimationName(rt);e?tt("MOUNT"):mt==="none"||(rt==null?void 0:rt.display)==="none"?tt("UNMOUNT"):tt(it&&ht!==mt?"ANIMATION_OUT":"UNMOUNT"),h.current=e}},[e,tt]),useLayoutEffect2(()=>{if(a){let rt;const it=a.ownerDocument.defaultView??window,st=mt=>{const yt=getAnimationName(c.current).includes(mt.animationName);if(mt.target===a&&yt&&(tt("ANIMATION_END"),!h.current)){const _t=a.style.animationFillMode;a.style.animationFillMode="forwards",rt=it.setTimeout(()=>{a.style.animationFillMode==="forwards"&&(a.style.animationFillMode=_t)})}},ht=mt=>{mt.target===a&&(d.current=getAnimationName(c.current))};return a.addEventListener("animationstart",ht),a.addEventListener("animationcancel",st),a.addEventListener("animationend",st),()=>{it.clearTimeout(rt),a.removeEventListener("animationstart",ht),a.removeEventListener("animationcancel",st),a.removeEventListener("animationend",st)}}else tt("ANIMATION_END")},[a,tt]),{isPresent:["mounted","unmountSuspended"].includes(_e),ref:reactExports.useCallback(rt=>{rt&&(c.current=getComputedStyle(rt)),o(rt)},[])}}function getAnimationName(e){return(e==null?void 0:e.animationName)||"none"}function getElementRef(e){var c,h;let a=(c=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:c.get,o=a&&"isReactWarning"in a&&a.isReactWarning;return o?e.ref:(a=(h=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:h.get,o=a&&"isReactWarning"in a&&a.isReactWarning,o?e.props.ref:e.props.ref||e.ref)}var count=0;function useFocusGuards(){reactExports.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??createFocusGuard()),document.body.insertAdjacentElement("beforeend",e[1]??createFocusGuard()),count++,()=>{count===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(a=>a.remove()),count--}},[])}function createFocusGuard(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var __assign$1=function(){return __assign$1=Object.assign||function(a){for(var o,c=1,h=arguments.length;c"u")return zeroGap;var a=getOffset(e),o=document.documentElement.clientWidth,c=window.innerWidth;return{left:a[0],top:a[1],right:a[2],gap:Math.max(0,c-o+a[2]-a[0])}},Style=styleSingleton(),lockAttribute="data-scroll-locked",getStyles=function(e,a,o,c){var h=e.left,d=e.top,_=e.right,_e=e.gap;return o===void 0&&(o="margin"),` .`.concat(noScrollbarsClassName,` { overflow: hidden `).concat(c,`; padding-right: `).concat(_e,"px ").concat(c,`; diff --git a/index.html b/index.html index f7ae16e..a45b5bb 100644 --- a/index.html +++ b/index.html @@ -11,7 +11,7 @@ content="width=device-width, initial-scale=1.0" /> Capsule Telegram Mini App - +