@privy-io/react-auth 2.6.2 → 2.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/abstract-smart-wallets.js +1 -1
- package/dist/cjs/farcaster.js +1 -1
- package/dist/cjs/getEmbeddedConnectedWallet-DTU4T9TJ.js +1 -0
- package/dist/cjs/index.js +1 -5
- package/dist/cjs/internal-context-HesndSYh.js +1 -0
- package/dist/cjs/privy-provider-CWADob3g.js +27 -0
- package/dist/cjs/smart-wallets-Dsq1trqs.js +1 -0
- package/dist/cjs/smart-wallets.js +1 -1
- package/dist/cjs/solana.js +1 -1
- package/dist/cjs/ui.js +2 -2
- package/dist/cjs/useActiveWallet-D5FyaqZJ.js +1 -0
- package/dist/cjs/useFundWallet-BsBuslJV.js +1 -0
- package/dist/dts/farcaster.d.mts +1 -1
- package/dist/dts/farcaster.d.ts +1 -1
- package/dist/dts/index.d.mts +12 -8
- package/dist/dts/index.d.ts +12 -8
- package/dist/dts/smart-wallets.d.mts +1 -1
- package/dist/dts/smart-wallets.d.ts +1 -1
- package/dist/dts/solana.d.mts +6 -6
- package/dist/dts/solana.d.ts +6 -6
- package/dist/dts/{types-CcosPsy6.d.mts → types-CsAGoXth.d.mts} +9 -9
- package/dist/dts/{types-CcosPsy6.d.ts → types-CsAGoXth.d.ts} +9 -9
- package/dist/dts/ui.d.mts +1 -1
- package/dist/dts/ui.d.ts +1 -1
- package/dist/dts/{useSolanaWallets-BHduxJmW.d.mts → useSolanaWallets-CFgYdjDv.d.mts} +18 -1
- package/dist/dts/{useSolanaWallets-BHduxJmW.d.ts → useSolanaWallets-CFgYdjDv.d.ts} +18 -1
- package/dist/esm/abstract-smart-wallets.mjs +1 -1
- package/dist/esm/farcaster.mjs +1 -1
- package/dist/esm/getEmbeddedConnectedWallet-CSSBWE2p.mjs +1 -0
- package/dist/esm/index.mjs +1 -5
- package/dist/esm/{internal-context-CL_EG4e1.mjs → internal-context-O3TPYUku.mjs} +1 -1
- package/dist/esm/privy-provider-u_cmfixS.mjs +27 -0
- package/dist/esm/smart-wallets-vK26EMrU.mjs +1 -0
- package/dist/esm/smart-wallets.mjs +1 -1
- package/dist/esm/solana.mjs +1 -1
- package/dist/esm/ui.mjs +2 -2
- package/dist/esm/useActiveWallet-Cwj5v4eK.mjs +1 -0
- package/dist/esm/useFundWallet-BPk4tVPS.mjs +1 -0
- package/package.json +4 -4
- package/dist/cjs/AwaitingEvmToSolBridgingScreen-pmGmvR1q.js +0 -22
- package/dist/cjs/getEmbeddedConnectedWallet-CGj_I0cc.js +0 -2
- package/dist/cjs/importWallet-Du1BO6qb.js +0 -1
- package/dist/cjs/internal-context-D5TgeQk8.js +0 -1
- package/dist/cjs/prepareFundingModalData-C2_ED32S.js +0 -1
- package/dist/cjs/smart-wallets-CoYci1bf.js +0 -1
- package/dist/cjs/useActiveWallet-CaLK0Ao4.js +0 -1
- package/dist/cjs/useFundWallet-92y-LJjK.js +0 -1
- package/dist/esm/AwaitingEvmToSolBridgingScreen-DnBONxHo.mjs +0 -22
- package/dist/esm/getEmbeddedConnectedWallet-Cyt02rK3.mjs +0 -2
- package/dist/esm/importWallet-Bqr-aqzk.mjs +0 -1
- package/dist/esm/prepareFundingModalData-Bkg2jc5P.mjs +0 -1
- package/dist/esm/smart-wallets-KrlR2oLu.mjs +0 -1
- package/dist/esm/useActiveWallet-SKrFBYMY.mjs +0 -1
- package/dist/esm/useFundWallet-BvMwnH48.mjs +0 -1
package/dist/cjs/index.js
CHANGED
|
@@ -1,5 +1 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),t=require("mipd"),r=require("react"),n=require("react-device-detect"),i=require("viem/utils"),a=require("./internal-context-D5TgeQk8.js"),o=require("./AwaitingEvmToSolBridgingScreen-pmGmvR1q.js"),s=require("jose"),l=require("uuid"),c=require("eventemitter3"),d=require("@coinbase/wallet-sdk"),u=require("./prepareFundingModalData-C2_ED32S.js"),h=require("ofetch"),p=require("js-cookie"),y=require("zustand"),m=require("@marsidev/react-turnstile"),w=require("styled-components"),g=require("./useActiveWallet-CaLK0Ao4.js"),v=require("@heroicons/react/24/outline/DevicePhoneMobileIcon"),f=require("@heroicons/react/24/outline/FingerPrintIcon"),E=require("@heroicons/react/24/outline/PhoneIcon"),C=require("@heroicons/react/24/outline/ShieldCheckIcon"),P=require("viem"),A=require("@heroicons/react/24/outline/CalendarIcon"),x=require("@heroicons/react/24/outline/ExclamationTriangleIcon"),T=require("@headlessui/react"),k=require("@heroicons/react/24/outline/CheckCircleIcon"),_=require("@heroicons/react/24/outline/CloudArrowUpIcon"),S=require("@heroicons/react/24/outline/ExclamationCircleIcon"),I=require("@heroicons/react/24/outline/NoSymbolIcon"),b=require("./getEmbeddedConnectedWallet-CGj_I0cc.js"),W=require("@heroicons/react/24/outline/ArrowTopRightOnSquareIcon"),j=require("@heroicons/react/24/outline/EnvelopeIcon"),O=require("@heroicons/react/24/outline/ClockIcon"),R=require("@heroicons/react/24/outline/TrashIcon"),U=require("@heroicons/react/24/solid/CheckBadgeIcon"),N=require("@heroicons/react/24/solid/LockClosedIcon"),M=require("@heroicons/react/24/outline/QuestionMarkCircleIcon"),F=require("@heroicons/react/24/solid/IdentificationIcon"),L=require("@heroicons/react/24/outline/ChevronRightIcon"),D=require("@heroicons/react/24/outline/MinusCircleIcon"),B=require("@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon"),q=require("@privy-io/js-sdk-core"),H=require("@heroicons/react/24/solid/ShieldCheckIcon"),z=require("@heroicons/react/24/outline/GlobeAltIcon"),V=require("@heroicons/react/24/outline/ChevronDownIcon"),K=require("./importWallet-Du1BO6qb.js"),$=require("viem/experimental");function Y(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function G(e){if(e&&"object"==typeof e&&"default"in e)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}require("tinycolor2"),require("@heroicons/react/24/outline/ArrowLeftIcon"),require("@heroicons/react/24/outline/ArrowRightIcon"),require("@heroicons/react/24/outline/XMarkIcon"),require("@heroicons/react/24/outline/CheckIcon"),require("@heroicons/react/24/outline/Square2StackIcon"),require("@heroicons/react/24/outline/WalletIcon"),require("@walletconnect/ethereum-provider"),require("@heroicons/react/24/outline/UserCircleIcon"),require("@heroicons/react/20/solid/CheckIcon"),require("@heroicons/react/24/solid/DocumentCheckIcon"),require("@heroicons/react/24/solid/XCircleIcon"),require("fast-password-entropy"),require("secure-password-utilities"),require("secure-password-utilities/wordlists"),require("@heroicons/react/24/outline/LockClosedIcon"),require("@heroicons/react/24/outline/PencilSquareIcon"),require("@heroicons/react/24/solid/CheckCircleIcon"),require("@heroicons/react/24/outline/ArrowPathIcon"),require("@heroicons/react/24/outline/EyeIcon"),require("@heroicons/react/24/outline/EyeSlashIcon"),require("@heroicons/react/24/outline/KeyIcon"),require("@heroicons/react/24/outline/ArrowDownTrayIcon"),require("@heroicons/react/24/outline/ClipboardDocumentCheckIcon"),require("@heroicons/react/24/outline/DocumentDuplicateIcon"),require("qrcode"),require("@heroicons/react/24/outline/InformationCircleIcon"),require("@heroicons/react/24/outline/CreditCardIcon"),require("@heroicons/react/24/outline/QrCodeIcon"),require("@heroicons/react/24/solid/ArrowsRightLeftIcon"),require("@heroicons/react/24/outline"),require("@heroicons/react/24/outline/ClipboardDocumentIcon"),require("zustand/shallow"),require("zustand/traditional");var X=/*#__PURE__*/Y(r),J=/*#__PURE__*/G(s),Q=/*#__PURE__*/Y(c),Z=/*#__PURE__*/Y(p),ee=/*#__PURE__*/Y(v),te=/*#__PURE__*/Y(f),re=/*#__PURE__*/Y(E),ne=/*#__PURE__*/Y(C),ie=/*#__PURE__*/Y(A),ae=/*#__PURE__*/Y(x),oe=/*#__PURE__*/Y(k),se=/*#__PURE__*/Y(_),le=/*#__PURE__*/Y(S),ce=/*#__PURE__*/Y(I),de=/*#__PURE__*/Y(W),ue=/*#__PURE__*/Y(j),he=/*#__PURE__*/Y(O),pe=/*#__PURE__*/Y(R),ye=/*#__PURE__*/Y(U),me=/*#__PURE__*/Y(N),we=/*#__PURE__*/Y(M),ge=/*#__PURE__*/Y(F),ve=/*#__PURE__*/Y(L),fe=/*#__PURE__*/Y(D),Ee=/*#__PURE__*/Y(B),Ce=/*#__PURE__*/Y(H),Pe=/*#__PURE__*/Y(z),Ae=/*#__PURE__*/Y(V);class xe{async authenticate(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(a.customJwtAccountAuthenticatePath,{token:this.meta.token})}catch(e){throw a.formatApiError(e)}}async link(){throw Error("Unimplemented")}constructor(e){this.meta={token:e}}}function Te(e){return e?{"privy-ui":"t"}:void 0}class ke{async authenticate(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new a.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(a.passwordlessAuthenticatePath,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw a.formatApiError(e)}}async link(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new a.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(a.passwordlessLinkPath,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw a.formatApiError(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new a.PrivyClientError("Email must be set when initialzing authentication.");let n=Te(r);try{return await this.api.post(a.passwordlessInitPath,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw a.formatApiError(e)}}constructor({email:e,captchaToken:t,disableSignup:r}){this.meta={email:e,captchaToken:t,disableSignup:r??!1}}}class _e extends ke{async link(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new a.PrivyClientError("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(a.updateEmailPath,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw a.formatApiError(e)}}constructor(e,t,r){super({email:t,captchaToken:r}),this.meta={email:t,captchaToken:r,oldAddress:e,disableSignup:!1}}}class Se{get meta(){return this._meta}async authenticate(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new a.PrivyClientError("Auth flow must be initialized first");try{let e=await this.api.post(a.farcasterAuthenticatePath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});if(!e)throw new a.PrivyClientError("No response from authentication");return e}catch(e){throw a.formatApiError(e)}}async link(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(a.farcasterLinkPath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(e){throw a.formatApiError(e)}}async _startChannelOnce(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");let e=await this.api.post(a.farcasterInitPath,{token:this.captchaToken});n.isMobile&&!n.isIOS&&e.connect_uri&&o.openHref(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new a.PrivyClientError("Auth flow must be initialized first");let e=await this.api.get(a.farcasterStatusPath,{headers:{"farcaster-channel-token":this.meta.channelToken}});return"completed"===e.state&&(this.message=e.message,this.signature=e.signature,this.fid=e.fid,!0)}constructor(e,t=!1){this._meta={disableSignup:!1},this.captchaToken=e,this.startChannelOnce=new o.RunEffectOnce(this._startChannelOnce.bind(this)),this.pollForReady=new o.RunEffectOnce(this._pollForReady.bind(this)),this._meta.disableSignup=t}}class Ie{getOrCreateGuestCredential(e){let t=o.getGuestCredentialStorageKey(e);if(o.e()){if(o.s.get(t))return o.s.get(t);{let e=s.base64url.encode(o.randomBytes(32));return o.s.put(t,e),e}}return s.base64url.encode(o.randomBytes(32))}async authenticate(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(a.guestAccountAuthenticatePath,{guest_credential:this.meta.guestCredential})}catch(e){throw a.formatApiError(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}class be{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new a.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new a.PrivyClientError("User denied confirmation during OAuth flow");let e=o.getCodeVerifier();try{let t=await this.api.post(a.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});return o.s.del(o.CODE_VERIFIER_KEY),o.s.del(o.HEADLESS_OAUTH_KEY),o.s.del(o.OAUTH_DISABLE_SIGNUP_KEY),t}catch(e){let t=a.formatApiError(e);if(t.privyErrorCode)throw new a.PrivyClientError(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new a.PrivyClientError("Invalid code during oauth flow.",void 0,a.PrivyErrorCode.OAUTH_USER_DENIED);throw new a.PrivyClientError("Invalid code during OAuth flow.",void 0,a.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new a.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new a.PrivyClientError("User denied confirmation during OAuth flow");let e=o.s.get(o.CODE_VERIFIER_KEY);if(!e)throw new a.PrivyClientError("Authentication error.");try{let t=await this.api.post(a.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return o.s.del(o.CODE_VERIFIER_KEY),t}catch(e){throw a.formatApiError(e)}}async getAuthorizationUrl(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.provider)throw new a.PrivyClientError("Provider must be set when initializing OAuth authentication.");let e=o.createCodeVerifier();o.s.put(o.CODE_VERIFIER_KEY,e);let t=o.createStateCode();o.s.put(o.STATE_CODE_KEY,t);let r=await o.deriveCodeChallengeFromCodeVerifier(e);this.meta.withPrivyUi||o.s.put(o.HEADLESS_OAUTH_KEY,!0),this.meta.disableSignup&&o.s.put(o.OAUTH_DISABLE_SIGNUP_KEY,!0);let n=Te(this.meta.withPrivyUi);try{return await this.api.post(a.oAuthInitPath,{provider:this.meta.provider,redirect_to:window.location.href,token:this.meta.captchaToken,code_challenge:r,state_code:t},{headers:{...n}})}catch(e){throw a.formatApiError(e)}}constructor(e){this.meta=e}}const We=({style:t})=>/*#__PURE__*/e.jsx(Pe.default,{style:{color:"var(--privy-color-error)",...t}});let je={google:{name:"Google",component:o.Google},discord:{name:"Discord",component:o.Discord},github:{name:"Github",component:o.Github},linkedin:{name:"LinkedIn",component:o.LinkedIn},twitter:{name:"Twitter",component:o.Twitter},spotify:{name:"Spotify",component:o.Spotify},instagram:{name:"Instagram",component:o.Instagram},tiktok:{name:"Tiktok",component:o.Tiktok},apple:{name:"Apple",component:o.Apple}};const Oe=e=>e in je?je[e]:{name:"Unknown",component:We};function Re(){let e=new URLSearchParams(window.location.search),t=e.get("privy_oauth_code"),r=e.get("privy_oauth_state"),n=e.get("privy_oauth_provider");if(!t||!r||!n)return{inProgress:!1};let i=!1;try{i=!!window.opener.location.origin}catch{}return{inProgress:!0,authorizationCode:t,stateCode:r,provider:n,withPrivyUi:!o.s.get(o.HEADLESS_OAUTH_KEY),popupFlow:null!==window.opener&&i,disableSignup:!!o.s.get(o.OAUTH_DISABLE_SIGNUP_KEY)}}class Ue{async initRegisterFlow(e){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");this.authenticateForRegistration=!0,this.meta.initRegisterResponse=await this.initRegisterOnce.execute(e)}async initAuthenticationFlow(e){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");this.authenticateForRegistration=!1,this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute(e)}async initLinkFlow(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");this.meta.initLinkResponse=await this.initLinkOnce.execute()}async register(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new a.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initRegisterResponse||(this.meta.initRegisterResponse=await this.initRegisterOnce.execute());try{let t=this.meta.initRegisterResponse.options,r=await e.startRegistration(this._transformInitLinkOptionsToCamelCase(t));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(a.passkeyRegisterPath,{relying_party:this.meta.initRegisterResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new a.PrivyClientError("Passkey request timed out or rejected by user.",void 0,a.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw a.formatApiError(e)}}async authenticate(){if(this.authenticateForRegistration)return this.register();let e=await import("@simplewebauthn/browser");if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new a.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initAuthenticateResponse||(this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute());let t=this.meta.allowedCredentialsIds?.map((e=>({type:"public-key",id:e})))??this.meta.initAuthenticateResponse.options.allow_credentials;try{let r=await e.startAuthentication(this._transformInitAuthenticateOptionsToCamelCase({...this.meta.initAuthenticateResponse.options,allow_credentials:t}));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(a.passkeyAuthenticatePath,{relying_party:this.meta.initAuthenticateResponse.relying_party,challenge:this.meta.initAuthenticateResponse.options.challenge,authenticator_response:this._transformAuthenticationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new a.PrivyClientError("Passkey request timed out or rejected by user.",void 0,a.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw a.formatApiError(e)}}async link(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new a.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initLinkResponse||(this.meta.initLinkResponse=await this.initLinkOnce.execute());try{let t=this.meta.initLinkResponse.options,r=await e.startRegistration(this._transformInitLinkOptionsToCamelCase(t));return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(a.passkeyLinkPath,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new a.PrivyClientError("Passkey request timed out or rejected by user.",void 0,a.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw a.formatApiError(e)}}async _initRegisterOnce(e){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");let t=Te(e);return await this.api.post(a.passkeyInitRegisterPath,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");let t=Te(e);return await this.api.post(a.passkeyInitAuthenticatePath,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");return await this.api.post(a.passkeyInitLinkPath,{})}_transformInitLinkOptionsToCamelCase(e){return{rp:e.rp,user:{id:e.user.id,name:e.user.name,displayName:e.user.display_name},challenge:e.challenge,pubKeyCredParams:e.pub_key_cred_params.map((e=>({type:e.type,alg:e.alg}))),timeout:e.timeout,excludeCredentials:e.exclude_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports}))),authenticatorSelection:{authenticatorAttachment:e.authenticator_selection?.authenticator_attachment,requireResidentKey:e.authenticator_selection?.require_resident_key,residentKey:e.authenticator_selection?.resident_key,userVerification:e.authenticator_selection?.user_verification},attestation:e.attestation,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props?.rk,hmacCreateSecret:e.extensions?.hmac_create_secret}}}_transformRegistrationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,attestation_object:e.response.attestationObject,authenticator_data:e.response.authenticatorData},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}_transformInitAuthenticateOptionsToCamelCase(e){return{rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}}_transformAuthenticationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}constructor({captchaToken:e,setPasskeyAuthState:t}){this.authenticateForRegistration=!1,this.initRegisterOnce=new o.RunEffectOnce(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new o.RunEffectOnce(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new o.RunEffectOnce(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t}}}class Ne{async authenticate(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new a.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(a.passwordlessSmsAuthenticatePath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw a.formatApiError(e)}}async link(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new a.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(a.passwordlessSmsLinkPath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw a.formatApiError(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new a.PrivyClientError("phone nNumber must be set when initialzing authentication.");let n=Te(r);try{return await this.api.post(a.passwordlessSmsInitPath,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw a.formatApiError(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:r}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:r??!1}}}class Me extends Ne{async link(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new a.PrivyClientError("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(a.updatePhonePath,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw a.formatApiError(e)}}constructor(e,t,r){super({phoneNumber:t,captchaToken:r}),this.meta={phoneNumber:t,captchaToken:r,oldPhoneNumber:e,disableSignup:!1}}}class Fe{static parse(e){try{return new Fe(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return J.decodeJwt(e),e}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){return Date.now()>=1e3*(this.expiration-e)}constructor(e){this.value=e,this._decoded=J.decodeJwt(e)}}class Le extends Fe{static parse(e){try{return new Le(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}let De,Be=[1,11155111,137,10,8453,84532,42161,7777777,43114,56],qe=(e,t)=>e.makeWeb3Provider({options:t});class He extends o.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:o.COINBASE_WALLET_DATA_URI,id:"com.coinbase.wallet"}}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new a.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw o.formatConnectorError(e)}}updateConnectionPreference(e){this.connectionOptions=e,this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",this.proxyProvider.setWalletProvider(qe(De,this.connectionOptions))}constructor(e,t,r,n,i,a){if(super("coinbase_wallet",e,t,r),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new o.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.connectionOptions=n.coinbaseWallet.connectionOptions??"all",this.walletClientType="smartWalletOnly"===this.connectionOptions?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!De){let r=[t.id].concat(e.map((e=>e.id))),n="eoaOnly"!==this.connectionOptions?r.filter((e=>!Be.includes(e))):[];n.length>0&&!n.every((e=>o.DEFAULT_SUPPORTED_CHAIN_IDS.has(e)))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${n.join(", ")}`),De=new d.CoinbaseWalletSDK({appName:i,appLogoUrl:a,appChainIds:r})}this.proxyProvider.setWalletProvider(qe(De,this.connectionOptions))}}class ze extends o.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return await this.isConnected()?(await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[o.toHex(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:o.Blobby,id:"io.privy.wallet"}}disconnect(){this.connected=!1}async promptConnection(){}constructor({provider:e,chains:t,defaultChain:r,rpcConfig:n,imported:i,walletIndex:a}){super("privy",t,r,n),this.connectorType="embedded",this.proxyProvider=e,this.walletIndex=a,i&&(this.connectorType="embedded_imported"),this.subscribeListeners()}}const Ve=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];class Ke extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class $e extends Q.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Ke(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Kn()||!this.address)throw new Ke("Disconnected",4900);let{hash:r}=await Xn(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Ke(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await Kn()||!this.address)throw new Ke("Disconnected",4900);let{signature:r}=await Gn(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new Ke(`Invalid params for ${e.method}`,4200);if("string"==typeof e.params[0])t=e.params[0];else{if(!("chainId"in e.params[0])||"string"!=typeof e.params[0].chainId)throw new Ke(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=o.getPublicClient(this.chainId,this.chains,this.rpcConfig,{appId:this.appId}),this.emit("chainChanged",t)}async handlePersonalSign(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for personal_sign");let t=e.params[0],r=e.params[1],{signature:n}=await $n({message:t},{address:r});return n}async handleSignedTypedData(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_signTypedData_v4");let t=e.params[0],r="string"==typeof e.params[1]?JSON.parse(e.params[1]):e.params[1],{signature:n}=await Yn(o.generateTypedDataWithDomainType(r),{address:t});return n}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_estimateGas");delete e.params[0].gasPrice,delete e.params[0].maxFeePerGas,delete e.params[0].maxPriorityFeePerGas;let t={...e.params[0],chainId:o.toHex(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...o.toViemTransactionSerializable(t)})}async request(e){switch(console.debug("Embedded1193Provider.request() called with args",e),e.method){case"eth_accounts":case"eth_requestAccounts":return this.address?[this.address]:[];case"eth_chainId":return o.toHex(this.chainId);case"eth_estimateGas":return this.handleEstimateGas(e);case"eth_sendTransaction":return this.handleSendTransaction(e);case"eth_signTransaction":return this.handleSignTransaction(e);case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(e);case"personal_sign":return this.handlePersonalSign(e);case"eth_signTypedData_v4":return this.handleSignedTypedData(e)}if(!(e=>Ve.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await Kn();if(await Jn(),!t||!this.address)throw new Ke("Disconnected",4900);try{return(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:{method:e.method,params:e.params}})).response.data}catch(e){throw console.error(e),new Ke("Disconnected",4900)}}}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:n,rpcConfig:i,chains:a,appId:s,chainId:l=1,walletIndex:c}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=n,this.chainId=l,this.rpcConfig=i,this.chains=a,this.publicClient=o.getPublicClient(l,this.chains,i,{appId:s}),this.rpcTimeoutDuration=o.getRpcTimeout(i,"privy"),this.appId=s,this.walletIndex=c}}class Ye extends o.EthereumWalletConnector{get walletBranding(){return{id:this.id,name:this.name,icon:this.icon}}async initialize(){this.initialized=!0,this.emit("initialized")}async connect(){throw Error("connect called for an uninstalled wallet via the EthereumNullConnector")}disconnect(){throw Error("disconnect called for an uninstalled wallet via the EthereumNullConnector")}promptConnection(e){throw Error(`promptConnection called for an uninstalled wallet via the EthereumNullConnector for ${e}`)}constructor({id:e,name:t,icon:r,walletClientType:n,defaultChain:i}){super(n,[],i,{}),this.connectorType="null",this.proxyProvider=new o.PrivyProxyProvider(void 0,o.DEFAULT_RPC_TIMEOUT),this.id=e,this.name=t,this.icon=r,this.connectorType=n}}const Ge=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlSpace:"preserve",x:0,y:0,viewBox:"0 0 318.6 318.6",width:"28",height:"28",style:{height:"28px",width:"28px",...t},...r,children:[/*#__PURE__*/e.jsx("style",{children:".s1{stroke-linecap:round;stroke-linejoin:round}.s2{fill:#e4761b;stroke:#e4761b}.s3{fill:#f6851b;stroke:#f6851b}"}),/*#__PURE__*/e.jsx("path",{fill:"#e2761b",stroke:"#e2761b",className:"s1",d:"m274.1 35.5-99.5 73.9L193 65.8z"}),/*#__PURE__*/e.jsx("path",{d:"m44.4 35.5 98.7 74.6-17.5-44.3zm193.9 171.3-26.5 40.6 56.7 15.6 16.3-55.3zm-204.4.9L50.1 263l56.7-15.6-26.5-40.6z",className:"s1 s2"}),/*#__PURE__*/e.jsx("path",{d:"m103.6 138.2-15.8 23.9 56.3 2.5-2-60.5zm111.3 0-39-34.8-1.3 61.2 56.2-2.5zM106.8 247.4l33.8-16.5-29.2-22.8zm71.1-16.5 33.9 16.5-4.7-39.3z",className:"s1 s2"}),/*#__PURE__*/e.jsx("path",{fill:"#d7c1b3",stroke:"#d7c1b3",className:"s1",d:"m211.8 247.4-33.9-16.5 2.7 22.1-.3 9.3zm-105 0 31.5 14.9-.2-9.3 2.5-22.1z"}),/*#__PURE__*/e.jsx("path",{fill:"#233447",stroke:"#233447",className:"s1",d:"m138.8 193.5-28.2-8.3 19.9-9.1zm40.9 0 8.3-17.4 20 9.1z"}),/*#__PURE__*/e.jsx("path",{fill:"#cd6116",stroke:"#cd6116",className:"s1",d:"m106.8 247.4 4.8-40.6-31.3.9zM207 206.8l4.8 40.6 26.5-39.7zm23.8-44.7-56.2 2.5 5.2 28.9 8.3-17.4 20 9.1zm-120.2 23.1 20-9.1 8.2 17.4 5.3-28.9-56.3-2.5z"}),/*#__PURE__*/e.jsx("path",{fill:"#e4751f",stroke:"#e4751f",className:"s1",d:"m87.8 162.1 23.6 46-.8-22.9zm120.3 23.1-1 22.9 23.7-46zm-64-20.6-5.3 28.9 6.6 34.1 1.5-44.9zm30.5 0-2.7 18 1.2 45 6.7-34.1z"}),/*#__PURE__*/e.jsx("path",{d:"m179.8 193.5-6.7 34.1 4.8 3.3 29.2-22.8 1-22.9zm-69.2-8.3.8 22.9 29.2 22.8 4.8-3.3-6.6-34.1z",className:"s3"}),/*#__PURE__*/e.jsx("path",{fill:"#c0ad9e",stroke:"#c0ad9e",className:"s1",d:"m180.3 262.3.3-9.3-2.5-2.2h-37.7l-2.3 2.2.2 9.3-31.5-14.9 11 9 22.3 15.5h38.3l22.4-15.5 11-9z"}),/*#__PURE__*/e.jsx("path",{fill:"#161616",stroke:"#161616",className:"s1",d:"m177.9 230.9-4.8-3.3h-27.7l-4.8 3.3-2.5 22.1 2.3-2.2h37.7l2.5 2.2z"}),/*#__PURE__*/e.jsx("path",{fill:"#763d16",stroke:"#763d16",className:"s1",d:"m278.3 114.2 8.5-40.8-12.7-37.9-96.2 71.4 37 31.3 52.3 15.3 11.6-13.5-5-3.6 8-7.3-6.2-4.8 8-6.1zM31.8 73.4l8.5 40.8-5.4 4 8 6.1-6.1 4.8 8 7.3-5 3.6 11.5 13.5 52.3-15.3 37-31.3-96.2-71.4z"}),/*#__PURE__*/e.jsx("path",{d:"m267.2 153.5-52.3-15.3 15.9 23.9-23.7 46 31.2-.4h46.5zm-163.6-15.3-52.3 15.3-17.4 54.2h46.4l31.1.4-23.6-46zm71 26.4 3.3-57.7 15.2-41.1h-67.5l15 41.1 3.5 57.7 1.2 18.2.1 44.8h27.7l.2-44.8z",className:"s3"})]}),Xe=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"108",height:"108",viewBox:"0 0 108 108",fill:"none",style:{height:"28px",width:"28px",...t},...r,children:[/*#__PURE__*/e.jsx("rect",{width:"108",height:"108",rx:"23",fill:"#AB9FF2"}),/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M46.5267 69.9229C42.0054 76.8509 34.4292 85.6182 24.348 85.6182C19.5824 85.6182 15 83.6563 15 75.1342C15 53.4305 44.6326 19.8327 72.1268 19.8327C87.768 19.8327 94 30.6846 94 43.0079C94 58.8258 83.7355 76.9122 73.5321 76.9122C70.2939 76.9122 68.7053 75.1342 68.7053 72.314C68.7053 71.5783 68.8275 70.7812 69.0719 69.9229C65.5893 75.8699 58.8685 81.3878 52.5754 81.3878C47.993 81.3878 45.6713 78.5063 45.6713 74.4598C45.6713 72.9884 45.9768 71.4556 46.5267 69.9229ZM83.6761 42.5794C83.6761 46.1704 81.5575 47.9658 79.1875 47.9658C76.7816 47.9658 74.6989 46.1704 74.6989 42.5794C74.6989 38.9885 76.7816 37.1931 79.1875 37.1931C81.5575 37.1931 83.6761 38.9885 83.6761 42.5794ZM70.2103 42.5795C70.2103 46.1704 68.0916 47.9658 65.7216 47.9658C63.3157 47.9658 61.233 46.1704 61.233 42.5795C61.233 38.9885 63.3157 37.1931 65.7216 37.1931C68.0916 37.1931 70.2103 38.9885 70.2103 42.5795Z",fill:"#FFFDF8"})]});function Je(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var Qe=0;class Ze extends o.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return{name:this.providerDetail.info.name,icon:this.providerDetail.info.icon,id:this.providerDetail.info.rdns}}disconnect(){console.warn(`Programmatic disconnect with ${this.providerDetail.info.name} is not yet supported.`)}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new a.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw o.formatConnectorError(e)}}constructor(e,t,r,n,i){super(i||"unknown",e,t,r),this.connectorType="injected",this.proxyProvider=new o.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=n;let a=n.provider;this.proxyProvider.setWalletProvider(a)}}var et="__private_"+Qe+++"__walletBranding";class tt extends o.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return Je(this,et)[et]??{name:"Browser Extension",icon:o.BrowserExtensionWallet,id:"extension"}}disconnect(){console.warn("Programmatic disconnect with browser wallets is not yet supported.")}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new a.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw o.formatConnectorError(e)}}constructor(e,t,r,n,i){super(i??"unknown",e,t,r),Object.defineProperty(this,et,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new o.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(n),"metamask"===i?Je(this,et)[et]={name:"MetaMask",icon:Ge,id:"io.metamask"}:"phantom"===i&&(Je(this,et)[et]={name:"Phantom",icon:Xe,id:"phantom"})}}class rt extends Ze{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){try{n.isMobile||await this.proxyProvider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new a.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw o.formatConnectorError(e)}}}class nt extends u.SolanaWalletConnector{get walletBranding(){return{id:this.id,name:this.name,icon:this.icon}}async initialize(){this.initialized=!0,this.emit("initialized")}async connect(){throw Error("connect called for an uninstalled wallet via the SolanaNullConnector")}constructor({id:e,name:t,icon:r}){super({name:t},!1),this.connectorType="null",this.proxyProvider=new o.PrivyProxyProvider(void 0,o.DEFAULT_RPC_TIMEOUT),this.disconnect=async()=>{throw Error("disconnect called for an uninstalled wallet via the SolanaNullConnector")},this.promptConnection=async()=>{throw Error("promptConnection called for an uninstalled wallet via the SolanaNullConnector")},this.id=e,this.name=t,this.icon=r}}class it extends Q.default{get wallets(){let e=new Set,t=this.walletConnectors.flatMap((e=>e.wallets)).sort(((e,t)=>e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0)).filter((t=>{let r=`${t.address}${t.walletClientType}${t.connectorType}${t.meta.id}`;return!e.has(r)&&(e.add(r),!0)})),r=t.findIndex((e=>e.address===(this.activeWallet?this.activeWallet:"unknown")));return r>=0&&t.unshift(t.splice(r,1)[0]),t}async initialize(e){if(this.initialized&&!e)return;e&&this.removeAllConnectors(),o.s.get(o.CONNECTORS_STATE_KEY)&&(o.s.getKeys().forEach((e=>{e.startsWith("walletconnect")&&o.s.del(e)})),o.s.del(o.CONNECTORS_STATE_KEY));let t=o.detectInjectedConnectors({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:r})=>{this.createEthereumWalletConnector({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:r}})}))}));for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),Object.values(o.mobileWalletsConfig)))!e.isInstalled&&this.walletList.includes(e.client)&&(["ethereum-only","ethereum-and-solana"].includes(this.walletChainType)&&e.chainTypes.includes("ethereum")&&this.createEthereumWalletConnector({connectorType:"null",walletClientType:e.client,walletConfig:e}),["ethereum-and-solana","solana-only"].includes(this.walletChainType)&&e.chainTypes.includes("solana")&&this.addSolanaWalletConnector(new nt({id:e.client,name:e.name})));this.externalWalletConfig.walletConnect.enabled&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"unknown"}),this.externalWalletConfig.solana.connectors?.get().forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{e?.forEach(this.addSolanaWalletConnector)})),await t,this.initialized=!0}findWalletConnector(e,t){return"wallet_connect_v2"===e?this.walletConnectors.filter(o.isEthereumWalletConnector).find((t=>t.connectorType===e))??null:this.walletConnectors.filter(o.isEthereumWalletConnector).find((r=>r.connectorType===e&&r.walletClientType===t))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(u.isSolanaWalletConnector).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}onInitialized(e){e.wallets.forEach((e=>{let t=this.storedConnections.find((t=>t.address===e.address&&t.connectorType===e.connectorType&&("solana"===e.type&&"unknown"===t.walletClientType&&"unknown"===e.walletClientType?e.meta.id===t.id:t.walletClientType===e.walletClientType)));t&&(e.connectedAt=t.connectedAt)})),this.saveConnectionHistory(),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&(this.saveConnectionHistory(),this.emit("walletsUpdated"))}addEmbeddedWalletConnectors({walletProxy:e,rootWallet:t,embeddedWallets:r,defaultChain:n,appId:i}){for(let a of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===a.walletIndex));if(r&&o.isEthereumWalletConnector(r))r.proxyProvider.walletProxy=e;else{let{entropyId:r,entropyIdVerifier:s}=o.getEntropyDetailsFromAccount(t),l=new ze({provider:new $e({walletProxy:e,address:a.address,entropyId:r,entropyIdVerifier:s,rpcConfig:this.rpcConfig,chains:this.chains,appId:i,chainId:n.id,walletIndex:a.walletIndex}),chains:this.chains,defaultChain:n,rpcConfig:this.rpcConfig,imported:!1,walletIndex:a.walletIndex});this.addWalletConnector(l)}}}addImportedWalletConnector(e,t,r,n){let i=this.findWalletConnector("embedded_imported","privy");if(i&&o.isEthereumWalletConnector(i))i.proxyProvider.walletProxy=e;else{let i=new ze({provider:new $e({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(i)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.saveConnectionHistory(),this.storedConnections=u.loadConnectionHistory(),this.emit("walletsUpdated")}removeImportedWalletConnector(){let e=this.findWalletConnector("embedded_imported","privy");if(e){let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1),this.saveConnectionHistory(),this.storedConnections=u.loadConnectionHistory(),this.emit("walletsUpdated")}}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:n}){let i=this.findWalletConnector(e,t);if(i&&o.isEthereumWalletConnector(i))return i instanceof o.WalletConnectV2WalletConnector&&i.resetConnection(t),i;let a=(()=>"injected"!==e?"coinbase_wallet"===e?new He(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):"null"!==e?new o.WalletConnectV2WalletConnector(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,t):n?new Ye({id:n.client,name:n.name,defaultChain:this.defaultChain,walletClientType:n.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new rt(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new tt(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new tt(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new tt(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new Ze(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,t):void 0)();return a&&this.addWalletConnector(a),a||null}addWalletConnector(e){this.walletConnectors.push(e),e.on("initialized",(()=>this.onInitialized(e))),e.on("walletsUpdated",(()=>this.onWalletsUpdated(e))),e.initialize().catch((e=>{console.debug("Failed to initialize connector",e)}))}saveConnectionHistory(){let e=this.wallets.map((e=>({address:e.address,connectorType:e.connectorType,walletClientType:e.walletClientType,connectedAt:e.connectedAt,id:e.meta.id})));o.s.put(o.CONNECTIONS_HISTORY_KEY,e)}async activeWalletSign(e){let t=this.wallets,r=t.length>0?t[0]:null;return r&&o.isBaseConnectedEthereumWallet(r)?r.sign(e):null}setActiveWallet(e){this.activeWallet=i.getAddress(e),this.emit("walletsUpdated")}setWalletList(e){this.walletList=e,this.initialized&&this.initialize(!0).catch(console.error)}removeAllConnectors(){for(let e of this.walletConnectors)e.removeAllListeners();this.walletConnectors=[]}constructor(e,t,r,n,i,a,s,l,c,d,h,p){super(),this.addSolanaWalletConnector=async e=>{let t=this.findSolanaWalletConnector(e.walletClientType);if(!t||"null"===t.connectorType){if("null"===t?.connectorType){let e=this.walletConnectors.indexOf(t);this.walletConnectors.splice(e,1)}this.addWalletConnector(e)}},this.getEthereumProvider=()=>{let e=this.wallets[0],t=this.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return e&&t?t.proxyProvider:new o.PrivyProxyProvider},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=n,this.defaultChain=i,this.walletConnectors=[],this.initialized=!1,this.store=a,this.walletList=s,this.shouldEnforceDefaultChainOnConnect=l,this.externalWalletConfig=c,this.privyAppName=d,this.privyAppLogo=h,this.walletChainType=p||"ethereum-only",this.storedConnections=u.loadConnectionHistory()}}let at=[a.sessionsRefreshPath,a.sessionsLogoutPath,a.analyticsEventsPath];class ot{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw a.formatApiError(e)}}async post(e,t,r){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...r})}catch(e){throw a.formatApiError(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw a.formatApiError(e)}}constructor({appId:e,appClientId:t,client:r,defaults:n}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=r.clientAnalyticsId,this.sdkVersion=o.VERSION,this.client=r,this.defaults=n,this.fallbackApiUrl=r.fallbackApiUrl,this.baseFetch=h.ofetch.create({baseURL:this.defaults.baseURL,timeout:this.defaults.timeout,retry:3,retryDelay:500,retryStatusCodes:[408,409,425,500,502,503,504],credentials:"include",onRequest:async({request:e,options:t})=>{let r=new Headers(t.headers);r.set("privy-app-id",this.appId),this.appClientId&&r.set("privy-client-id",this.appClientId),r.set("privy-ca-id",this.clientAnalyticsId||""),r.set("privy-client",`react-auth:${this.sdkVersion}`);let n=at.includes(e.toString());if(!r.has("authorization")){let e=await this.client.getAccessToken({disableAutoRefresh:n});null!==e&&r.set("authorization",`Bearer ${e}`)}t.headers=r,t.retryDelay&&"number"==typeof t.retryDelay&&(t.retryDelay=3*t.retryDelay)},onRequestError:({error:e})=>{if(e instanceof DOMException&&"AbortError"===e.name)throw new a.PrivyTimeoutError}})}}let st=/paymaster\.biconomy\.io\/api/i,lt={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const ct=(e,t)=>e&&st.test(e)?lt:t&&t.policy_id?{policyId:t.policy_id}:void 0;function dt(){return!(n.isSafari&&window.location.origin.startsWith("http://localhost"))}const ut=y.create((()=>({identityToken:null})));var ht,pt=((ht={}).PRIVY="privy_access_token",ht.CUSTOMER="customer_access_token",ht);class yt{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(o.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)}get privyAccessToken(){return this._getToken(o.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}_getToken(e){try{let t=o.s.get(e);return"string"==typeof t?Fe.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=o.s.get(o.REFRESH_TOKEN_STORAGE_KEY);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=o.s.get(o.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return null;{let r=new Fe(t);return r.isExpired()?(o.s.del(o.getProviderAccessTokenStorageKey(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=Z.default.get(o.SESSION_COOKIE_KEY);return void 0!==e&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(e="privy_access_token"){let t="string"==typeof this.getToken(e),r="string"==typeof this.refreshToken&&this.refreshToken!==o.DEPRECATED_REFRESH_TOKEN;return this.mightHaveServerCookies||t&&r}hasActiveAccessToken(e){let t=Fe.parse(this.getToken(e));return null!==t&&!t.isExpired(30)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}destroy(){return this.destroyOnce.execute()}storeProviderAccessToken(e,t){"string"==typeof t?o.s.put(o.getProviderAccessTokenStorageKey(e),t):o.s.del(o.getProviderAccessTokenStorageKey(e))}updateIdentityToken(e){"string"==typeof e?this.storeIdentityToken(e):this.clearIdentityToken()}async _authenticate(e){try{let t=await e.authenticate(),{user:r,is_new_user:n,oauth_tokens:i}=t;this.handleTokenResponse(t);let a=i?{provider:i.provider,accessToken:i.access_token,accessTokenExpiresInSeconds:i.access_token_expires_in_seconds,refreshToken:i.refresh_token,refreshTokenExpiresInSeconds:i.refresh_token_expires_in_seconds,scopes:i.scopes}:void 0;return this._trackAuthenticateEvents(e,n),{user:o.convertUserResponseToUser(r),isNewUser:n,oAuthTokens:a}}catch(e){throw console.warn("Error authenticating session"),a.formatPrivyError(e)}}_trackAuthenticateEvents(e,t){let r=function(e){return e instanceof ke?"email":e instanceof Ne?"sms":e instanceof o.SiweFlow?"siwe":e instanceof Ie?"guest":e instanceof xe?"custom_auth":e instanceof be?e.meta.provider:null}(e);r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:r,isNewUser:t}}),"siwe"===r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate_siwe",payload:{connectorType:e.meta.connectorType,walletClientType:e.meta.walletClientType}})}async _link(e){try{let t=await e.link(),r=t.oauth_tokens,n=r?{provider:r.provider,accessToken:r.access_token,accessTokenExpiresInSeconds:r.access_token_expires_in_seconds,refreshToken:r.refresh_token,refreshTokenExpiresInSeconds:r.refresh_token_expires_in_seconds,scopes:r.scopes}:void 0;return{user:o.convertUserResponseToUser(t),oAuthTokens:n}}catch(e){throw console.warn("Error linking account"),a.formatPrivyError(e)}}async _refresh(){if(!this.api)throw new a.PrivyClientError("Session has no API instance");if(!this.client)throw new a.PrivyClientError("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let e=this.token,t=this.refreshToken;if(this.client.useServerCookies&&!this.mightHaveServerCookies&&this.token&&window.location.origin===this.client.apiUrl)return this.destroyLocalState(),null;try{let r;if(!(e&&t||this.mightHaveServerCookies))return null;{let n={};e&&(n.authorization=`Bearer ${e}`),r=await this.api.post(a.sessionsRefreshPath,t?{refresh_token:t}:{},{headers:n})}return this.handleTokenResponse(r),o.convertUserResponseToUser(r.user)}catch(e){if(e instanceof a.PrivyApiError&&e.privyErrorCode===a.PrivyErrorCode.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw a.formatPrivyError(e)}}handleTokenResponse(e){e.session_update_action&&"set"!==e.session_update_action?"clear"===e.session_update_action?this.destroyLocalState():"ignore"===e.session_update_action&&(e.token&&(this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token)),e.identity_token&&this.storeIdentityToken(e.identity_token)):this._storeAllTokens(e)}_storeAllTokens(e){this.storeRefreshToken(e.refresh_token),this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token),e.identity_token&&this.storeIdentityToken(e.identity_token)}async _destroy(){try{await(this.api?.post(a.sessionsLogoutPath,{refresh_token:this.refreshToken}))}catch(e){console.warn("Error destroying session")}this.destroyLocalState()}destroyLocalState(){this.storeRefreshToken(null),this.storeCustomerAccessToken(null),this.storePrivyAccessToken(null),this.clearIdentityToken()}storeCustomerAccessToken(e){if("string"==typeof e){let t=o.s.get(o.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY);if(o.s.put(o.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY,e),!this.client?.useServerCookies){let t=Fe.parse(e)?.expiration;Z.default.set(o.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:dt(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else o.s.del(o.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY),Z.default.remove(o.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(o.s.put(o.REFRESH_TOKEN_STORAGE_KEY,e),this.client?.useServerCookies||Z.default.set(o.SESSION_COOKIE_KEY,"t",{sameSite:"Strict",secure:dt(),expires:30})):(o.s.del(o.REFRESH_TOKEN_STORAGE_KEY),Z.default.remove(o.REFRESH_TOKEN_COOKIE_KEY),Z.default.remove(o.SESSION_COOKIE_KEY))}storePrivyAccessToken(e){"string"==typeof e?o.s.put(o.PRIVY_ACCESS_TOKEN_STORAGE_KEY,e):o.s.del(o.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}storeIdentityToken(e){if(ut.setState({identityToken:e}),this.client?.useServerCookies)return;o.s.put(o.IDENTITY_TOKEN_STORAGE_KEY,e);let t=Fe.parse(e)?.expiration;Z.default.set(o.IDENTITY_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:dt(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){o.s.del(o.IDENTITY_TOKEN_STORAGE_KEY),ut.setState({identityToken:null}),Z.default.remove(o.IDENTITY_TOKEN_COOKIE_KEY)}constructor(){this.authenticateOnce=new o.RunEffectOnce((async e=>this._authenticate(e))),this.linkOnce=new o.RunEffectOnce((async e=>this._link(e))),this.refreshOnce=new o.RunEffectOnce(this._refresh.bind(this)),this.destroyOnce=new o.RunEffectOnce(this._destroy.bind(this))}}let mt;var wt=0,gt="__private_"+wt+++"__getOrGenerateClientAnalyticsId";class vt{initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:n,store:i,walletList:a,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c}){this.connectors||(this.connectors=new it(this.appId,e,t,r,n,i,a,o,s,l,void 0,c))}generateApi(){let e=new ot({appId:this.appId,appClientId:this.appClientId,client:this,defaults:{baseURL:this.apiUrl,timeout:this.timeout}});return this.session.api=e,e}updateApiUrl(e){this.apiUrl=e||this.fallbackApiUrl,this.api=this.generateApi(),e&&(this.useServerCookies=!0)}authenticate(){if(!this.authFlow)throw new a.PrivyClientError("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new a.PrivyClientError("No auth flow in progress.");let{oAuthTokens:e}=await this.session.link(this.authFlow);return{user:await this.getAuthenticatedUser(),oAuthTokens:e}}storeProviderAccessToken(e,t){this.session.storeProviderAccessToken(e,t)}getProviderAccessToken(e){return this.session.getProviderAccessToken(e)}async logout(){await this.session.destroy(),this.authFlow=void 0}clearProviderAcccessTokens(e){e.linkedAccounts.filter((e=>"cross_app"===e.type)).forEach((e=>{this.storeProviderAccessToken(e.providerApp.id,null)}))}startAuthFlow(e){return e.api=this.api,this.authFlow=e,this.authFlow}async initMfaSmsVerification(){try{await this.api.post(a.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw a.formatApiError(e)}}async initMfaPasskeyVerification(){try{return(e=>({rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}))((await this.api.post(a.mfaPasskeyInitPath,{})).options)}catch(e){throw a.formatApiError(e)}}async getCrossAppProviderDetails(e){try{return this._cachedProviderAppDetails[e]||(this._cachedProviderAppDetails[e]=await this.api.get(`/api/v1/apps/${e}/cross-app/details`)),this._cachedProviderAppDetails[e]}catch(e){console.error("Error fetching cross app provider details",e)}}async acceptTerms(){try{let e=await this.api.post(a.acceptTermsPath,{});return o.convertUserResponseToUser(e)}catch(e){throw a.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(a.unlinkEmailPath,{address:e});return await this.getAuthenticatedUser()??o.convertUserResponseToUser(t)}catch(e){throw a.formatPrivyError(e)}}async unlinkPhone(e){try{let t=await this.api.post(a.unlinkPhonePath,{phoneNumber:e});return await this.getAuthenticatedUser()??o.convertUserResponseToUser(t)}catch(e){throw a.formatPrivyError(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(a.unlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??o.convertUserResponseToUser(t)}catch(e){throw a.formatPrivyError(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(a.siwsUnlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??o.convertUserResponseToUser(t)}catch(e){throw a.formatPrivyError(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(a.unlinkOAuthPath,{provider:e,subject:t});return await this.getAuthenticatedUser()??o.convertUserResponseToUser(r)}catch(e){throw a.formatPrivyError(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(a.unlinkFarcasterPath,{fid:e});return await this.getAuthenticatedUser()??o.convertUserResponseToUser(t)}catch(e){throw a.formatPrivyError(e)}}async unlinkTelegram(e){try{let t=await this.api.post(a.telegramAccountUnlinkPath,{telegram_user_id:e});return await this.getAuthenticatedUser()??o.convertUserResponseToUser(t)}catch(e){throw a.formatPrivyError(e)}}async revokeDelegatedWallet(){try{await this.api.post(a.delegatedActionsRevokePath,{})}catch(e){throw a.formatPrivyError(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:r,options:n}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(a.analyticsEventsPath,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:r?r.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:n?.keepAlive??!1})}catch(e){console.log("Unable to submit event. This is not an issue.")}}async signMoonpayOnRampUrl(e){try{return this.api.post(a.moonpayPluginOnRampPath,e)}catch(e){throw a.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(a.coinbaseOnRampInitPath,e)}catch(e){throw a.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${a.coinbaseOnRampStatusPath}?partnerUserId=${e}`)}catch(e){throw a.formatPrivyError(e)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(e){return await this.getPrivyAccessToken(e)||await this.getCustomerAccessToken(e)}async getCustomerAccessToken(e){return await this._getToken(pt.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(pt.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?Le.parse(this.session.getToken(e))?.appId!==this.appId?(await this.logout(),null):this.session.getToken(e):(this.session.destroyLocalState(),null):!t?.disableAutoRefresh&&this.session.hasRefreshCredentials(e)?(await this.session.refresh(),this.session.getToken(e)):null:null}async getSmartWalletsConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}/smart_wallets`,{baseURL:this.fallbackApiUrl,headers:e});return r.enabled?{enabled:r.enabled,smartWalletType:r.smart_wallet_type,configuredNetworks:r.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:ct(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw a.formatPrivyError(e)}}async getServerConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}`,{baseURL:this.fallbackApiUrl,headers:e}),n=r.telegram_auth_config?{botId:r.telegram_auth_config.bot_id,botName:r.telegram_auth_config.bot_name,linkEnabled:r.telegram_auth_config.link_enabled,seamlessAuthEnabled:r.telegram_auth_config.seamless_auth_enabled}:void 0,i=r.funding_config?{methods:r.funding_config.methods,options:r.funding_config.options,defaultRecommendedAmount:r.funding_config.default_recommended_amount,defaultRecommendedCurrency:r.funding_config.default_recommended_currency,promptFundingOnWalletCreation:r.funding_config.prompt_funding_on_wallet_creation,crossChainBridgingEnabled:r.funding_config.cross_chain_bridging_enabled}:void 0;return{id:r.id,name:r.name,verificationKey:r.verification_key,logoUrl:r.logo_url||void 0,accentColor:r.accent_color||void 0,showWalletLoginFirst:r.show_wallet_login_first,allowlistConfig:{errorTitle:r.allowlist_config.error_title,errorDetail:r.allowlist_config.error_detail,errorCtaText:r.allowlist_config.cta_text,errorCtaLink:r.allowlist_config.cta_link},walletAuth:r.wallet_auth,solanaWalletAuth:r.solana_wallet_auth,emailAuth:r.email_auth,smsAuth:r.sms_auth,googleOAuth:r.google_oauth,twitterOAuth:r.twitter_oauth,discordOAuth:r.discord_oauth,githubOAuth:r.github_oauth,spotifyOAuth:r.spotify_oauth,instagramOAuth:r.instagram_oauth,tiktokOAuth:r.tiktok_oauth,linkedinOAuth:r.linkedin_oauth,appleOAuth:r.apple_oauth,farcasterAuth:r.farcaster_auth,passkeyAuth:r.passkey_auth,passkeysForSignupEnabled:r.passkeys_for_signup_enabled,telegramAuth:r.telegram_auth,disablePlusEmails:r.disable_plus_emails,termsAndConditionsUrl:r.terms_and_conditions_url,embeddedWalletConfig:{ethereum:{createOnLogin:r.embedded_wallet_config.ethereum?.create_on_login??r.embedded_wallet_config.create_on_login},solana:{createOnLogin:r.embedded_wallet_config.solana?.create_on_login??"off"},userOwnedRecoveryOptions:r.embedded_wallet_config.user_owned_recovery_options,requireUserOwnedRecoveryOnCreate:r.embedded_wallet_config.require_user_owned_recovery_on_create},privacyPolicyUrl:r.privacy_policy_url,requireUsersAcceptTerms:r.require_users_accept_terms,customApiUrl:r.custom_api_url,walletConnectCloudProjectId:r.wallet_connect_cloud_project_id,fiatOnRampEnabled:r.fiat_on_ramp_enabled,captchaEnabled:r.captcha_enabled,captchaSiteKey:r.captcha_site_key,createdAt:new Date(1e3*r.created_at),updatedAt:new Date(1e3*r.updated_at),mfaMethods:r.mfa_methods,enforceWalletUis:r.enforce_wallet_uis,legacyWalletUiConfig:r.legacy_wallet_ui_config,telegramAuthConfiguration:n,fundingConfig:i}}catch(e){throw a.formatPrivyError(e)}}async getUsdTokenPrice(e){try{return(await this.api.get(`/api/v1/token_price?chainId=${e.id}&tokenSymbol=${e.nativeCurrency.symbol}`)).usd}catch(t){return void console.error(`Unable to fetch token price for chain with id ${e.id}`)}}async getUsdPriceForSol(){try{return(await this.api.get("/api/v1/token_price?chainId=0&tokenSymbol=SOL")).usd}catch(e){return void console.error("Unable to fetch token price for SOL")}}async getSplTokenMetadata({mintAddress:e,cluster:t}){try{return await this.api.get(`/api/v1/spl_token_info?mint_address=${e}&cluster=${t}`)}catch(r){return void console.error(`Unable to fetch token metadata for ${t}:${e}`)}}async requestFarcasterSignerStatus(e){try{return await this.api.post("/api/v1/farcaster/signer/status",{ed25519_public_key:e})}catch(e){throw console.error("Unable to fetch Farcaster signer status"),e}}async generateSiweNonce({address:e,captchaToken:t}){try{return(await this.api.post(a.siweInitPath,{address:e,token:t})).nonce}catch(e){throw a.formatPrivyError(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i,mode:o}){return await this.api.post(a.siweAuthenticatePath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:i,mode:o})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}){return await this.api.post(a.siweLinkPath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})}async linkSmartWallet({message:e,signature:t,smartWalletType:r}){try{let n=await this.api.post(a.smartWalletLinkPath,{message:e,signature:t,smart_wallet_type:r});return o.convertUserResponseToUser(n)}catch(e){throw a.formatPrivyError(e)}}async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}){try{let a=await this.linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i});return o.convertUserResponseToUser(a)}catch(e){throw a.formatPrivyError(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(a.siwsInitPath,{address:e,token:t})).nonce}catch(e){throw a.formatPrivyError(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:i}){return await this.api.post(a.siwsAuthenticatePath,{message:e,signature:t,walletClientType:r,connectorType:n,mode:i})}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,telegramWebAppData:s,farcasterEmbeddedAddress:l,oAuthUserInfo:c}){try{let d,u;switch(r){case"email":d=a.transferEmailPath,u={nonce:e,email:t};break;case"sms":d=a.transferPhonePath,u={nonce:e,phoneNumber:t};break;case"siwe":if(d=a.transferWalletPath,!n)throw Error("Wallet parameters must be defined");u={nonce:e,address:t,...n};break;case"farcaster":d=a.transferFarcasterPath,u={nonce:e,farcaster_id:t,farcaster_embedded_address:l};break;case"telegram":d=a.telegramAccountTransferPath,u={nonce:e,telegram_auth_result:i,telegram_web_app_data:s};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:d=a.transferOAuthPath,u={nonce:e,userInfo:c}}let h=await this.api.post(d,u);return await this.getAuthenticatedUser()??o.convertUserResponseToUser(h)}catch(e){throw a.formatPrivyError(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n}){return await this.api.post(a.siwsLinkPath,{message:e,signature:t,walletClientType:r,connectorType:n})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:n}){try{let i=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n});return o.convertUserResponseToUser(i)}catch(e){throw a.formatPrivyError(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(a.usersMePath);return this.session.updateIdentityToken(e.identity_token),o.convertUserResponseToUser(e.user)}catch(e){throw a.formatPrivyError(e)}}async scanTransaction(e){try{return await this.api.post(a.transactionScanningPath,e)}catch(e){throw a.formatPrivyError(e)}}constructor({apiUrl:e=o.DEFAULT_PRIVY_API_URL,appId:t,appClientId:r,timeout:n=o.DEFAULT_API_TIMEOUT_MS}){Object.defineProperty(this,gt,{value:ft}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==o.DEFAULT_PRIVY_API_URL&&e.startsWith("https://privy."),this.timeout=n,this.appId=t,this.appClientId=r,this.clientAnalyticsId=function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}(this,gt)[gt](),mt||(mt=new yt),this.session=mt,this.api=this.generateApi(),this.session.client=this}}function ft(){if("undefined"==typeof window)return null;try{let e=o.s.get(o.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=l.v4();try{return o.s.put(o.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}const Et=t=>{let{enabled:n,siteKey:i,appId:a,setError:s,setToken:l,setExecuting:c,ref:d}=o.useCaptcha(),[,u]=r.useMemo((()=>i?.split("t:")||[]),[i]);if(r.useEffect((()=>d.current?.remove),[]),!n)return null;if(!u)throw Error("Unsupported captcha site key");/*#__PURE__*/return e.jsx("div",{className:"hidden h-0 w-0",children:/*#__PURE__*/e.jsx(m.Turnstile,{...t,ref:d,siteKey:u,options:{action:a,size:"invisible",...t.delayedExecution?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{t.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:()=>{t.onError?.(),s("Captcha failed"),c(!1)},onSuccess:e=>{t.onSuccess?.(e),l(e),c(!1)},onExpire:()=>{t.onExpire?.();try{d.current?.reset(),s(void 0),l(void 0)}catch(e){s("expired_and_failed_reset")}}})})};function Ct(e){o.usePrivyEventSubscription("configureMfa",e)}let Pt=Array(6).fill("");var At,xt=((At=xt||{})[At.RESET_AFTER_DELAY=0]="RESET_AFTER_DELAY",At[At.CLEAR_ON_NEXT_VALID_INPUT=1]="CLEAR_ON_NEXT_VALID_INPUT",At);function Tt(e){return/^[0-9]{1}$/.test(e)}function kt(e){return 6===e.length&&e.every(Tt)}const _t=({onChange:t,disabled:i,errorReasonOverride:a,success:o})=>{let[s,l]=r.useState(Pt),[c,d]=r.useState(null),[u,h]=r.useState(null),p=async e=>{e.preventDefault();let r=e.currentTarget.value.replace(/\s+/g,"");if(""===r)return;let n=s.reduce(((e,t)=>e+Number(Tt(t))),0),i=r.split(""),a=!i.every(Tt),o=i.length+n>6;if(a)return d("Passcode can only be numbers"),void h(1);if(o)return d("Passcode must be exactly 6 numbers"),void h(1);d(null),h(null);let c=Number(e.currentTarget.name?.charAt(4)),u=[...r||[""]].slice(0,6-c),p=[...s.slice(0,c),...u,...s.slice(c+u.length)];l(p);let y=Math.min(Math.max(c+u.length,0),5),m=document.querySelector(`input[name=pin-${y}]`);if(m?.focus(),kt(p))try{await t(p.join(""));let e=document.querySelector(`input[name=pin-${y}]`);e?.blur()}catch(e){h(1),d(e.message)}else try{await t(null)}catch(e){h(1),d(e.message)}},y=o?"success":!(!a&&!c)?"fail":"";/*#__PURE__*/return e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsxs(St,{children:[/*#__PURE__*/e.jsx("div",{children:s.map(((r,a)=>/*#__PURE__*/e.jsx("input",{name:`pin-${a}`,type:"text",value:s[a],onChange:p,onKeyUp:e=>{"Backspace"===e.key&&(e=>{1===u&&(d(null),h(null));let r=[...s.slice(0,e),"",...s.slice(e+1)];if(l(r),e>0){let t=document.querySelector(`input[name=pin-${e-1}]`);t?.focus()}kt(r)?t(r.join("")):t(null)})(a)},inputMode:"numeric",autoFocus:0===a,pattern:"[0-9]",className:y,autoComplete:n.isMobile?"one-time-code":"off",disabled:i},a)))}),/*#__PURE__*/e.jsx("div",{children:/*#__PURE__*/e.jsx(It,{$fail:!!a||!!c,children:a||c})})]})})};let St=/*#__PURE__*/w.styled.div.withConfig({displayName:"PinInputContainer",componentId:"sc-7a171f6-0"})(["display:flex;flex-direction:column;width:100%;gap:8px;@media (max-width:440px){margin-top:8px;margin-bottom:8px;}> div:nth-child(1){display:flex;justify-content:center;gap:0.5rem;width:100%;border-radius:var(--privy-border-radius-md);> input{border:1px solid var(--privy-color-foreground-4);background:var(--privy-color-background);border-radius:var(--privy-border-radius-md);padding:8px 10px;height:58px;width:46px;text-align:center;font-size:18px;}> input:disabled{background:var(--privy-color-background-2);}> input:focus{border:1px solid var(--privy-color-accent);}> input:invalid{border:1px solid var(--privy-color-error);}> input.success{border:1px solid var(--privy-color-success);}> input.fail{border:1px solid var(--privy-color-error);animation:shake 180ms;animation-iteration-count:2;}}@keyframes shake{0%{transform:translate(1px,0px);}33%{transform:translate(-1px,0px);}67%{transform:translate(-1px,0px);}100%{transform:translate(1px,0px);}}"]),It=/*#__PURE__*/w.styled.div.withConfig({displayName:"InputHelp",componentId:"sc-7a171f6-1"})(["line-height:20px;font-size:13px;display:flex;justify-content:flex-start;width:100%;color:",";"],(e=>e.$fail?"var(--privy-color-error)":"var(--privy-color-foreground-3)"));const bt=({pendingTransaction:t})=>{let{getAccessToken:n}=o.usePrivyContext(),{wallets:i}=o.useWallets(),{walletProxy:s,rpcConfig:l,chains:c,appId:d,nativeTokenSymbolForChainId:u}=a.usePrivyInternal(),[h,p]=r.useState(null),[y,m]=r.useState(t),{tokenPrice:w}=o.useGetTokenPrice(y.chainId),g=u(t.chainId)||"ETH",v=r.useMemo((()=>i.find((e=>"privy"===e.walletClientType))),[i]);return r.useEffect((()=>{(async function(){if(!await n()||!s||!v)return y;let e=o.getPublicClient(y.chainId,c,l,{appId:d}),t=await o.prepareTransactionRequest(y,e,v.address);return p(P.toHex(BigInt(t.gas??0))),t})().then(m).catch(console.error)}),[s]),v?/*#__PURE__*/e.jsx(Wt,{children:/*#__PURE__*/e.jsx(o.TransactionDetails,{from:v.address,to:y.to,txn:y,gas:h??void 0,tokenPrice:w,tokenSymbol:g})}):null};let Wt=/*#__PURE__*/w.styled.div.withConfig({displayName:"TransactionInfoWrapper",componentId:"sc-731f1950-0"})(["width:100%;padding:1rem 0;"]);function jt(){let{promptMfa:e,init:t,submit:n,cancel:i,mfaMethods:a}=r.useContext(o.PrivyContext);return{promptMfa:e,init:t,submit:n,cancel:i,mfaMethods:a}}const Ot=({hasBlockingError:t,error:r,onClose:n,onBack:i,handleSubmit:s,account:l,submitSuccess:c})=>{let{pendingTransaction:d}=a.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:n},"header"),/*#__PURE__*/e.jsx(o.e$2,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(o.ConnectionLoader,{success:c,fail:!!r}),r?/*#__PURE__*/e.jsx(ae.default,{style:{width:"38px",height:"38px"}}):/*#__PURE__*/e.jsx(o.FaceId,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsx(o.Title,{style:{marginTop:"1rem"},children:"Verifying with passkey"}),/*#__PURE__*/e.jsxs(o.List,{children:[/*#__PURE__*/e.jsxs(o.ListItem,{children:[/*#__PURE__*/e.jsx(o.ListItemIcon,{children:/*#__PURE__*/e.jsx(ne.default,{})}),"Approve this action using your touch, face, PIN, or hardware key."]}),/*#__PURE__*/e.jsxs(o.ListItem,{children:[/*#__PURE__*/e.jsx(o.ListItemIcon,{children:/*#__PURE__*/e.jsx(ie.default,{})}),"You last added a passkey on"," ",l?.firstVerifiedAt?.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),"."]})]}),d&&/*#__PURE__*/e.jsx(o.Container,{children:/*#__PURE__*/e.jsx(bt,{pendingTransaction:d})}),r&&/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ErrorMessage,{style:{marginTop:"1.25rem"},children:r.message}),/*#__PURE__*/e.jsx(o.PrimaryButton,{disabled:t,onClick:s,style:{marginTop:"1.25rem"},children:"Try again"})]}),i&&/*#__PURE__*/e.jsx(o.PrimaryTextButton,{style:{marginTop:"1rem"},onClick:i,children:"Choose another method"}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]})},Rt=({open:t,onClose:n})=>{let{user:i}=o.usePrivyContext(),[a,s]=r.useState(i?.mfaMethods[0]??null),{init:l,cancel:c,submit:d}=jt(),[u,h]=r.useState(!1),[p,y]=r.useState(!1),[m,w]=r.useState(null),[g,v]=r.useState(null);r.useEffect((()=>{s(i?.mfaMethods[0]??null)}),[i?.mfaMethods]);let f=r.useRef(!1);r.useEffect((()=>{!f.current&&a&&t&&(f.current=!0,P(a).finally((()=>{f.current=!1})))}),[t]);let E=e=>o.errorIndicatesMaxMfaRetries(e)?(h(!0),Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.")):o.errorIndicatesMfaVerificationFailed(e)?(h(!1),Error("The code you entered is not valid")):o.errorIndicatesMfaTimeout(e)?(h(!0),Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.")):(console.error(e),h(!1),Error("Something went wrong."));async function C(e){v(null);try{if(!e||!a)return;await d(a,e),y(!0),h(!1),n()}catch(e){throw E(e)}}async function P(e){if("passkey"!==e)try{s(e),await l(e)}catch(e){console.error(e)}else try{s(e);let t=await l(e);if(!t)throw Error("something went wrong");w(t),await d(e,t),y(!0),h(!1),n()}catch(e){v(E(e))}}let A=()=>{s(null),v(null),c(),n()};return t&&i?"passkey"===a?/*#__PURE__*/e.jsx(Ot,{account:i.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],selectedMethod:a,submitSuccess:p,hasBlockingError:u,error:g,onClose:A,onBack:()=>{s(null),v(null)},handleSubmit:()=>C(m).catch(v)}):a?/*#__PURE__*/e.jsx(Ut,{submitSuccess:p,hasBlockingError:u,handleSubmitCode:C,selectedMethod:a,onClose:A,onBack:i.mfaMethods.length>1?()=>s(null):void 0}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:A},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ne.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Verify your identity"}),/*#__PURE__*/e.jsx(o.SubTitle,{children:"Choose a verification method"}),/*#__PURE__*/e.jsxs(o.MethodList,{children:[i.mfaMethods.includes("totp")&&/*#__PURE__*/e.jsxs(o.LoginMethodButton,{onClick:()=>P("totp"),children:[/*#__PURE__*/e.jsx(ee.default,{}),"Authenticator App"]},"totp"),i.mfaMethods.includes("sms")&&/*#__PURE__*/e.jsxs(o.LoginMethodButton,{onClick:()=>P("sms"),children:[/*#__PURE__*/e.jsx(re.default,{}),"SMS"]},"sms"),i.mfaMethods.includes("passkey")&&/*#__PURE__*/e.jsxs(o.LoginMethodButton,{onClick:()=>P("passkey"),children:[/*#__PURE__*/e.jsx(te.default,{}),"Passkey"]},"passkey")]}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}):null};let Ut=({selectedMethod:t,submitSuccess:r,hasBlockingError:n,onClose:i,onBack:s,handleSubmitCode:l})=>{let{app:c}=o.usePrivyModal(),{pendingTransaction:d}=a.usePrivyInternal();switch(t){case"sms":/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:i},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(re.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Enter verification code"}),/*#__PURE__*/e.jsxs(o.Container,{children:[/*#__PURE__*/e.jsx(_t,{success:r,disabled:n,onChange:l}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["To continue, please enter the 6-digit code sent to your ",/*#__PURE__*/e.jsx("strong",{children:"mobile device"})]}),d&&/*#__PURE__*/e.jsx(bt,{pendingTransaction:d})]}),s&&/*#__PURE__*/e.jsx(o.PrimaryTextButton,{theme:c?.appearance.palette.colorScheme,onClick:s,children:"Choose another method"}),/*#__PURE__*/e.jsx(o.SecondaryButton,{onClick:i,children:"Not now"}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]});case"totp":/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:i},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ee.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Enter verification code"}),/*#__PURE__*/e.jsxs(o.Container,{children:[/*#__PURE__*/e.jsx(_t,{success:r,disabled:n,onChange:l}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["To continue, please enter the 6-digit code generated from your"," ",/*#__PURE__*/e.jsx("strong",{children:"authenticator app"})]}),d&&/*#__PURE__*/e.jsx(bt,{pendingTransaction:d})]}),s&&/*#__PURE__*/e.jsx(o.PrimaryTextButton,{theme:c?.appearance.palette.colorScheme,onClick:s,children:"Choose another method"}),/*#__PURE__*/e.jsx(o.SecondaryButton,{onClick:i,children:"Not now"}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]});default:return null}};const Nt=/*#__PURE__*/w.createGlobalStyle([":root{--privy-border-radius-sm:6px;--privy-border-radius-md:12px;--privy-border-radius-mdlg:16px;--privy-border-radius-lg:24px;--privy-border-radius-full:9999px;--privy-color-background:",";--privy-color-background-2:",";--privy-color-background-3:",";--privy-color-foreground:",";--privy-color-foreground-2:",";--privy-color-foreground-3:",";--privy-color-foreground-4:",";--privy-color-foreground-accent:",";--privy-color-accent:",";--privy-color-accent-light:",";--privy-color-accent-lightest:",";--privy-color-accent-dark:",";--privy-color-accent-darkest:",";--privy-color-success:",";--privy-color-success-dark:",";--privy-color-success-light:",";--privy-color-error:",";--privy-color-error-light:",";--privy-color-warn:",";--privy-color-warn-light:",";--privy-height-modal-full:620px;--privy-height-modal-compact:480px;};"],(e=>e.theme.background),(e=>e.theme.background2),(e=>e.theme.background3),(e=>e.theme.foreground),(e=>e.theme.foreground2),(e=>e.theme.foreground3),(e=>e.theme.foreground4),(e=>e.theme.foregroundAccent),(e=>e.theme.accent),(e=>e.theme.accentLight),(e=>e.theme.accentLightest),(e=>e.theme.accentDark),(e=>e.theme.accentDarkest),(e=>e.theme.success),(e=>e.theme.successDark),(e=>e.theme.successLight),(e=>e.theme.error),(e=>e.theme.errorLight),(e=>e.theme.warn),(e=>e.theme.warnLight)),Mt=/*#__PURE__*/w.styled.div.withConfig({displayName:"StylesWrapper",componentId:"sc-bc1e45b4-0"})([""," color:var(--privy-color-foreground-2);h3{font-size:16px;line-height:24px;font-weight:500;color:var(--privy-color-foreground-2);}h4{font-size:14px;line-height:20px;font-weight:500;color:var(--privy-color-foreground);}p{font-size:13px;line-height:20px;color:var(--privy-color-foreground-2);}button:focus,input:focus,optgroup:focus,select:focus,textarea:focus{outline:none;border-color:var(--privy-color-accent-light);box-shadow:0 0 0 1px var(--privy-color-accent-light);}.mobile-only{@media (min-width:441px){display:none;}}@keyframes fadein{0%{opacity:0;}100%{opacity:1;}}"],"\n *,\n ::before,\n ::after {\n box-sizing: border-box;\n border-width: 0;\n border-style: solid;\n }\n\n line-height: 1.15;\n -webkit-text-size-adjust: 100%;\n -moz-tab-size: 4;\n tab-size: 4;\n font-feature-settings: normal;\n\n margin: 0;\n font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif,\n 'Apple Color Emoji', 'Segoe UI Emoji';\n\n hr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n }\n\n abbr:where([title]) {\n text-decoration: underline dotted;\n }\n\n h1,\n h2,\n h3,\n h4,\n h5,\n h6 {\n font-size: inherit;\n font-weight: inherit;\n font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif,\n 'Apple Color Emoji', 'Segoe UI Emoji';\n display: inline;\n }\n\n a {\n color: inherit;\n text-decoration: inherit;\n }\n\n b,\n strong {\n font-weight: bolder;\n }\n\n code,\n kbd,\n samp,\n pre {\n font-family: ui-monospace, SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 1em;\n }\n\n small {\n font-size: 80%;\n }\n\n sub,\n sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n }\n\n sub {\n bottom: -0.25em;\n }\n\n sup {\n top: -0.5em;\n }\n\n table {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n }\n\n button,\n input,\n optgroup,\n select,\n textarea {\n font-family: inherit;\n font-size: 100%;\n font-weight: inherit;\n line-height: inherit;\n color: inherit;\n margin: 0;\n padding: 0;\n }\n\n button,\n select {\n text-transform: none;\n }\n\n button,\n [type='button'],\n [type='reset'],\n [type='submit'] {\n -webkit-appearance: button;\n background-color: transparent;\n background-image: none;\n }\n\n ::-moz-focus-inner {\n border-style: none;\n padding: 0;\n }\n\n :-moz-focusring {\n outline: 1px dotted ButtonText;\n }\n\n :-moz-ui-invalid {\n box-shadow: none;\n }\n\n legend {\n padding: 0;\n }\n\n progress {\n vertical-align: baseline;\n }\n\n ::-webkit-inner-spin-button,\n ::-webkit-outer-spin-button {\n height: auto;\n }\n\n [type='search'] {\n -webkit-appearance: textfield;\n outline-offset: -2px;\n }\n\n ::-webkit-search-decoration {\n -webkit-appearance: none;\n }\n\n ::-webkit-file-upload-button {\n -webkit-appearance: button;\n font: inherit;\n }\n\n summary {\n display: list-item;\n }\n\n blockquote,\n dl,\n dd,\n h1,\n h2,\n h3,\n h4,\n h5,\n h6,\n hr,\n figure,\n p,\n pre {\n margin: 0;\n }\n\n fieldset {\n margin: 0;\n padding: 0;\n }\n\n legend {\n padding: 0;\n }\n\n ol,\n ul,\n menu {\n list-style: none;\n margin: 0;\n padding: 0;\n }\n\n textarea {\n resize: vertical;\n }\n\n input::placeholder,\n textarea::placeholder {\n opacity: 1;\n color: #9ca3af;\n }\n\n button,\n [role='button'] {\n cursor: pointer;\n }\n\n :disabled {\n cursor: default;\n }\n\n img,\n svg,\n video,\n canvas,\n audio,\n iframe,\n embed,\n object {\n display: block;\n }\n\n img,\n video {\n max-width: 100%;\n height: auto;\n }\n\n [hidden] {\n display: none;\n }\n"),Ft=({children:t,open:r,onClick:n,...i})=>/*#__PURE__*/e.jsx(T.Transition,{show:r,as:X.default.Fragment,children:/*#__PURE__*/e.jsxs(T.Dialog,{onClose:n,...i,as:Dt,children:[/*#__PURE__*/e.jsx(T.TransitionChild,{as:X.default.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/e.jsx(Lt,{id:"privy-dialog-backdrop","aria-hidden":"true"})}),/*#__PURE__*/e.jsx(Bt,{children:/*#__PURE__*/e.jsx(T.TransitionChild,{as:X.default.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/e.jsx(T.DialogPanel,{as:qt,children:t})})})]})});let Lt=/*#__PURE__*/w.styled.div.withConfig({displayName:"Backdrop",componentId:"sc-3cfde0b5-0"})(["position:fixed;inset:0;transition:backdrop-filter 100ms ease;backdrop-filter:blur(3px);-webkit-backdrop-filter:blur(3px);&.entering,&.leaving{backdrop-filter:unset;-webkit-backdrop-filter:unset;}"]),Dt=/*#__PURE__*/w.styled.div.withConfig({displayName:"DialogWrapper",componentId:"sc-3cfde0b5-1"})(["position:relative;z-index:999999;"]),Bt=/*#__PURE__*/w.styled.div.withConfig({displayName:"DialogContainer",componentId:"sc-3cfde0b5-2"})(["position:fixed;inset:0;display:flex;align-items:center;justify-content:center;width:100vw;min-height:100vh;"]);const qt=/*#__PURE__*/w.styled.div.withConfig({displayName:"Panel",componentId:"sc-3cfde0b5-3"})(["padding:0;background:transparent;border:none;width:100%;pointer-events:auto;outline:none;display:block;@media (max-width:440px){opacity:1;transform:translate3d(0,0,0);transition:transform 200ms ease-in;position:fixed;bottom:0;&.entering,&.leaving{opacity:0;transform:translate3d(0,100%,0);transition:transform 150ms ease-in 0ms,opacity 0ms ease 150ms;}}@media (min-width:441px){opacity:1;transition:opacity 100ms ease-in;&.entering,&.leaving{opacity:0;transition-delay:5ms;}margin:auto;width:360px;box-shadow:0px 8px 36px rgba(55,65,81,0.15);border-radius:var(--privy-border-radius-lg);}"]),Ht=/*#__PURE__*/w.styled.div.withConfig({displayName:"CenterItem",componentId:"sc-3cfde0b5-4"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;"]);let zt=({isMfaVerifying:t,onMfaVerificationComplete:n})=>{let{ready:i,isModalOpen:a}=o.usePrivyContext(),{headless:s}=o.useAppConfig(),{currentScreen:l}=o.usePrivyModal(),{status:c,execute:d,reset:u,enabled:h}=o.useCaptcha(),p=a&&l&&l.isCaptchaRequired&&!s&&"ready"===c;return r.useEffect((()=>{p&&d()}),[p]),r.useEffect((()=>{!a&&h&&u()}),[a,h]),l&&!i&&l.isShownBeforeReady?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{}),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(Ht,{children:/*#__PURE__*/e.jsx(o.Loader,{})}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}):!l&&t?/*#__PURE__*/e.jsx(Rt,{open:t,onClose:n}):l?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.Hide,{$if:!!t,children:/*#__PURE__*/e.jsx(l.component,{})}),/*#__PURE__*/e.jsx(o.Hide,{$if:!t,children:/*#__PURE__*/e.jsx(Rt,{open:t,onClose:n})})]}):null},Vt=({isMfaVerifying:t,onMfaVerificationComplete:n})=>{let i=r.useRef(null);/*#__PURE__*/return e.jsx(Yt,{style:{height:g.useElementHeight(i)},id:"privy-modal-content",children:/*#__PURE__*/e.jsx("div",{ref:i,children:/*#__PURE__*/e.jsx(zt,{isMfaVerifying:t,onMfaVerificationComplete:n})})})};const Kt=({open:t})=>{let n=o.useAppConfig(),{gracefulClosePrivyModal:i}=(()=>{let{closePrivyModal:e}=a.usePrivyInternal(),{onUserCloseViaDialogOrKeybindRef:t}=o.usePrivyModal();return{gracefulClosePrivyModal:r.useCallback((()=>{if(!t?.current)return e({shouldCallAuthOnSuccess:!1});t.current()}),[e])}})(),[s,l]=r.useState(!1);Ct({onMfaRequired:()=>{n.mfa.noPromptOnMfaRequired||l(!0)}});let c=t||s;return n.render.standalone?/*#__PURE__*/e.jsx(Mt,{children:/*#__PURE__*/e.jsx($t,{id:"privy-modal-content",children:/*#__PURE__*/e.jsx(zt,{isMfaVerifying:s,onMfaVerificationComplete:()=>l(!1)})})}):/*#__PURE__*/e.jsx(Ft,{open:c,id:"privy-dialog","aria-label":"log in or sign up","aria-labelledby":"privy-dialog-title",onClick:()=>i(),children:/*#__PURE__*/e.jsx(Mt,{children:/*#__PURE__*/e.jsx(Vt,{isMfaVerifying:s,onMfaVerificationComplete:()=>l(!1)})})})};let $t=/*#__PURE__*/w.styled.div.withConfig({displayName:"ContentWrapper",componentId:"sc-df48cc55-0"})(["display:flex;flex-direction:column;text-align:center;font-size:14px;line-height:20px;width:100%;background:var(--privy-color-background);padding:0 16px;"]),Yt=/*#__PURE__*/w.styled($t).withConfig({displayName:"BaseModal",componentId:"sc-df48cc55-1"})(["transition:height 150ms ease-out;overflow-x:hidden;overflow-y:auto;scrollbar-width:none;max-height:calc(100svh - 32px);border-radius:var(--privy-border-radius-lg) var(--privy-border-radius-lg) 0 0;box-shadow:0px 0px 36px rgba(55,65,81,0.15);@media (min-width:441px){box-shadow:0px 8px 36px rgba(55,65,81,0.15);border-radius:var(--privy-border-radius-lg);}"]);function Gt(t){let n=r.useRef(null),i=r.useRef();return r.useEffect((()=>{i.current?.remove(),i.current=function({botUsername:e,scriptHost:t}){let r=document.createElement("script"),{origin:n}=new URL(t);return r.async=!0,r.src=`${n}/js/telegram-login.js`,r.setAttribute("data-telegram-login",e),r.setAttribute("data-request-access","write"),r.setAttribute("data-lang","en"),r}(t),n.current?.after(i.current)}),[t]),/*#__PURE__*/e.jsx("div",{ref:n,hidden:!0})}async function Xt(e,t,r,n,i,a=!1){let s=a,l=async l=>{if(s&&t&&t.length>0){l===(a?0:1)?i("configureMfa","onMfaRequired",{mfaMethods:t}):n.current?.reject(new o.PrivyIframeError("missing_or_invalid_mfa","MFA verification failed, retry."));let s=await new Promise(((e,t)=>{r.current={resolve:e,reject:t},setTimeout((()=>{let e=new o.PrivyIframeError("mfa_timeout","Timed out waiting for MFA code");n.current?.reject(e),t(e)}),3e5)}));return await e(s)}return await e()},c=null;for(let e=0;e<4;e++)try{c=await l(e),n.current?.resolve(void 0);break}catch(e){if("missing_or_invalid_mfa"!==e.type)throw n.current?.resolve(void 0),e;s=!0}if(null===c){let e=new o.PrivyIframeError("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw n.current?.reject(e),e}return c}var Jt;let Qt=(Jt=0,()=>"id-"+Jt++);function Zt(e){return void 0!==e.error}let er=new class{enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){let r=this.callbacks[t];if(!r)throw Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":case"privy:signer:create":case"privy:wallets:add":case"privy:wallets:import":case"privy:wallets:set-recovery":case"privy:wallets:connect":case"privy:wallets:recover":case"privy:wallets:rpc":case"privy:wallet:create":case"privy:mfa:verify":case"privy:mfa:init-enrollment":case"privy:mfa:submit-enrollment":case"privy:mfa:unenroll":case"privy:mfa:clear":case"privy:auth:unlink-passkey":case"privy:farcaster:init-signer":case"privy:farcaster:sign":case"privy:solana-wallet:create":case"privy:delegated-actions:consent":return r;default:throw Error(`invalid wallet event type ${e}`)}}constructor(){this.callbacks={}}},tr=new Map,rr=(e,t)=>"bigint"==typeof t?t.toString():t;function nr(e,t,r,n){let i=r.contentWindow;if(!i)throw Error("iframe not initialized");let a=((e,t)=>`${e}${JSON.stringify(t,rr)}`)(e,t);if("privy:wallet:create"===e){let e=tr.get(a);if(e)return e}let o=new Promise(((r,a)=>{let o=Qt();er.enqueue(o,{resolve:r,reject:a}),i.postMessage({id:o,event:e,data:t},n)})).finally((()=>{tr.delete(a)}));return tr.set(a,o),o}function ir(t){let n=o.useIsServerConfigLoaded(),i=r.useRef(null),a=r.useRef(t.mfaMethods),s=o.useEmitPrivyEvent(),[l,c]=r.useState(!1);return r.useEffect((()=>{a.current=t.mfaMethods}),[t.mfaMethods]),r.useEffect((()=>{if(!l)return;let e=i.current;if(!e)return;function r(e){var r;e&&e.origin===t.origin&&"string"==typeof(r=e.data).event&&/^privy:.+/.test(r.event)&&function(e){switch(e.event){case"privy:iframe:ready":let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data);case"privy:signer:create":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:add":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:set-recovery":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:connect":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:recover":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:rpc":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallet:create":let r=er.dequeue(e.event,e.id);return Zt(e)?r.reject(new o.PrivyIframeError(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallets:import":let n=er.dequeue(e.event,e.id);return Zt(e)?n.reject(new o.PrivyIframeError(e.error.type,e.error.message)):n.resolve(e.data);case"privy:mfa:verify":let i=er.dequeue(e.event,e.id);return Zt(e)?i.reject(new o.PrivyIframeError(e.error.type,e.error.message)):i.resolve(e.data);case"privy:mfa:init-enrollment":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:submit-enrollment":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:unenroll":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:clear":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:auth:unlink-passkey":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:solana-wallet:create":let a=er.dequeue(e.event,e.id);return Zt(e)?a.reject(new o.PrivyIframeError(e.error.type,e.error.message)):a.resolve(e.data);case"privy:farcaster:init-signer":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:sign":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:delegated-actions:consent":{let t=er.dequeue(e.event,e.id);return Zt(e)?t.reject(new o.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}(e.data)}let n={createSigner:r=>Xt((n=>nr("privy:signer:create",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s),addWallet:r=>Xt((n=>nr("privy:wallets:add",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s),setRecovery:r=>Xt((n=>nr("privy:wallets:set-recovery",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s),connect:r=>Xt((n=>nr("privy:wallets:connect",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s),recover:r=>Xt((n=>nr("privy:wallets:recover",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s,!r.recoveryAccessToken&&!r.recoveryPassword&&!r.recoverySecretOverride),rpc:r=>Xt((n=>nr("privy:wallets:rpc",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s),create:r=>nr("privy:wallet:create",r,e,t.origin),importWallet:r=>nr("privy:wallets:import",r,e,t.origin),createSolana:r=>Xt((n=>nr("privy:solana-wallet:create",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s),createDelegatedAction:r=>nr("privy:delegated-actions:consent",r,e,t.origin),verifyMfa:r=>Xt((n=>nr("privy:mfa:verify",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s,!0),initEnrollMfa:r=>Xt((n=>nr("privy:mfa:init-enrollment",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s),submitEnrollMfa:r=>Xt((n=>nr("privy:mfa:submit-enrollment",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s),unenrollMfa:r=>Xt((n=>nr("privy:mfa:unenroll",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s),clearMfa:r=>nr("privy:mfa:clear",r,e,t.origin),unlinkPasskeyAccount:r=>Xt((n=>nr("privy:auth:unlink-passkey",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,s),initFarcasterSigner:r=>nr("privy:farcaster:init-signer",r,e,t.origin),signFarcasterMessage:r=>nr("privy:farcaster:sign",r,e,t.origin)};window.addEventListener("message",r);let c=new AbortController;return o.invokeUntilSettled((()=>nr("privy:iframe:ready",{},e,t.origin)),{abortSignal:c.signal}).then((()=>t.onLoad(n)),((...e)=>{console.warn("Privy iframe failed to load: ",...e),t.onLoadFailed()})),()=>{window.removeEventListener("message",r),c.abort()}}),[l]),n?
|
|
2
|
-
/*#__PURE__*/e.jsx("iframe",{ref:i,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>c(!0),src:o.constructURL(t.origin,`/apps/${t.appId}/embedded-wallets`,{caid:t.clientAnalyticsId,client_id:t.appClientId})}):null}const ar=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&e.delegated));class or{async handleSignMessage(e){if(!e.params||"string"!=typeof e.params.message)throw Error("Message must be provided as a string for Solana signMessage RPC");return await Zn({message:e.params.message,options:{address:this.address,uiOptions:{}}})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await Kn())throw Error("User must be authenticated to use embedded Solana wallet");if(!await Qn())throw new a.PrivyClientError("Unable to connect to Solana embedded wallet");if("signMessage"===e.method)return await this.handleSignMessage(e);throw Error("Embedded Solana provider does not yet support this RPC method.")}constructor(e,t){this.walletProxy=e,this.address=t}}async function sr({tx:e,accessToken:t,walletProxy:r,entropyId:n,entropyIdVerifier:i,transactingWalletAddress:a,transactingWalletIndex:s}){let l=o.getWalletPublicKeyFromTransaction(e,a),c=o.isVersionedTransaction(e)?Buffer.from(e.message.serialize()):e.serializeMessage(),{response:d}=await r.rpc({accessToken:t,entropyId:n,entropyIdVerifier:i,chainType:"solana",hdWalletIndex:s,request:{method:"signMessage",params:{message:c.toString("base64")}}}),u=d.data.signature,h=Buffer.from(u,"base64");e.addSignature(l,h)}async function lr({tx:e,connection:t,accessToken:r,walletProxy:n,entropyId:i,entropyIdVerifier:a,transactingWalletAddress:o,transactingWalletIndex:s,transactionOptions:l}){let c;try{await sr({tx:e,accessToken:r,walletProxy:n,entropyId:i,entropyIdVerifier:a,transactingWalletAddress:o,transactingWalletIndex:s});let d=e.serialize();c=await t.sendRawTransaction(d,l);let u=await t.confirmTransaction(c);if(u.value.err||u.value.err){let e=u.value.err||u.value.err;if("string"==typeof e)throw Error(e);throw e}return{signature:c,signedTransaction:e,receipt:await t.getParsedTransaction(c,{maxSupportedTransactionVersion:0})}}catch(e){throw e.txSignature=c,e}}const cr=()=>{let e=o.useAppConfig();r.useEffect((()=>{(async e=>{let t=new URL("v3/wallets","https://explorer-api.walletconnect.com");t.searchParams.append("projectId",e);let r=await fetch(t);return r.ok?Object.values((await r.json()).listings).sort((({slug:e},{slug:t})=>"rainbow"===e&&"metamask"===t?1:"metamask"===e||"rainbow"===e?-1:1)):(console.debug(`Failed to fetch WalletConnect listings: ${await r.text().catch((()=>"No response."))}`),[])})(e.walletConnectCloudProjectId).then((e=>o.setExternalWalletState({listings:e}))).catch(console.error)}),[e.walletConnectCloudProjectId])},dr="popup-privy-oauth",ur="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";class hr{async authenticate(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(a.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw a.formatApiError(e)}}async link(){if(!this.api)throw new a.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(a.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw a.formatApiError(e)}}constructor({authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}){this.meta={authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}}}async function pr({api:e,requesterAppId:t,providerAppId:r}){let n=(await e.get(`/api/v1/apps/${t}/cross-app/connections`)).connections.find((e=>e.provider_app_id===r));if(!n)throw new a.PrivyClientError("Invalid connected app");return{name:n.provider_app_name,logoUrl:n.provider_app_icon_url||void 0,apiUrl:n.provider_app_custom_api_url,readOnly:n.read_only}}const yr=async({user:e,address:t,client:r,request:n,requesterAppId:i,reconnect:s})=>{r.createAnalyticsEvent({eventName:"cross_app_request_started",payload:{address:t,method:n.method}});let l=e?.linkedAccounts.find((e=>"cross_app"===e.type&&(e.embeddedWallets.some((e=>e.address===t))||e.smartWallets.some((e=>e.address===t)))));if(!e||!l)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Cannot request a signature with this wallet address",address:t}}),new a.PrivyClientError("Cannot request a signature with this wallet address");let c=r.getProviderAccessToken(l.providerApp.id),d=await pr({api:r.api,requesterAppId:i,providerAppId:l.providerApp.id});if(!c){if(d.readOnly)throw console.error("cannot transact against a read-only provider app"),new a.PrivyClientError("Cannot transact against a read-only provider app");await s({appId:l.providerApp.id,action:"link"})&&(c=r.getProviderAccessToken(l.providerApp.id))}if(!c)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Transactions require a valid token",address:t}}),new a.PrivyClientError("Transactions require a valid token");let u=o.triggerPopup();if(!u)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Missing token",address:t}}),new a.PrivyClientError("Failed to initialize signature request");let h=new URL(`${d.apiUrl}/oauth/transact`);return h.searchParams.set("token",c||""),h.searchParams.set("request",mr(n)),u.location=h.href,new Promise(((e,i)=>{let o=setTimeout((()=>{d(),i(new a.PrivyClientError("Request timeout")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Request timeout",address:t}})}),12e4),s=setInterval((()=>{u.closed&&(d(),i(new a.PrivyClientError("User rejected request")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"User rejected request",address:t}}))}),300),c=a=>{a.data&&("set"===a.data.token?.action&&void 0!==a.data.token?.value?r.storeProviderAccessToken(l.providerApp.id,a.data.token.value):"clear"===a.data.token?.action&&r.storeProviderAccessToken(l.providerApp.id,null),"PRIVY_CROSS_APP_ACTION_RESPONSE"===a.data.type&&a.data.result&&(d(),e(a.data.result),r.createAnalyticsEvent({eventName:"cross_app_request_success",payload:{address:t,method:n.method}})),"PRIVY_CROSS_APP_ACTION_ERROR"===a.data.type&&a.data.error&&(d(),i(a.data.error),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:a.data.error,address:t}})))};window.addEventListener("message",c);let d=()=>{u.close(),clearInterval(s),clearTimeout(o),window.removeEventListener("message",c)}}))};let mr=e=>JSON.stringify({content:{request:{request:wr(e,P.toHex)}},timestamp:Date.now(),callbackUrl:window.origin});const wr=(e,t)=>"bigint"==typeof e?t(e):Array.isArray(e)?e.map((e=>wr(e,t))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,r])=>[e,wr(r,t)]))):e;let gr=({passkeys:t,expanded:n,onUnlink:i,onExpand:a})=>{let[s,l]=r.useState([]),c=n?t.length:2,d=e=>e.authenticatorName?e.createdWithBrowser?`${e.authenticatorName} on ${e.createdWithBrowser}`:e.authenticatorName:e.createdWithBrowser?e.createdWithOs?`${e.createdWithBrowser} on ${e.createdWithOs}`:`${e.createdWithBrowser}`:"Unknown device";/*#__PURE__*/return e.jsxs("div",{children:[/*#__PURE__*/e.jsx(Sr,{children:"Your passkeys"}),/*#__PURE__*/e.jsxs(xr,{children:[t.slice(0,c).map((t=>/*#__PURE__*/e.jsxs(Wr,{children:[/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(Ir,{children:d(t)}),/*#__PURE__*/e.jsxs(br,{children:["Last used: ",(t.latestVerifiedAt??t.verifiedAt).toLocaleString()]})]}),/*#__PURE__*/e.jsx(Or,{disabled:s.includes(t.credentialId),onClick:()=>(async e=>{l((t=>t.concat([e]))),await i(e),l((t=>t.filter((t=>t!==e))))})(t.credentialId),children:s.includes(t.credentialId)?/*#__PURE__*/e.jsx(o.ButtonLoader,{}):/*#__PURE__*/e.jsx(pe.default,{height:"1.6em"})})]},t.credentialId))),t.length>2&&!n&&/*#__PURE__*/e.jsx(Ar,{onClick:a,children:"View all"})]})]})},vr=()=>/*#__PURE__*/e.jsxs(xr,{children:[/*#__PURE__*/e.jsxs(o.ListItem,{children:[/*#__PURE__*/e.jsx(o.ListItemIcon,{children:/*#__PURE__*/e.jsx(ye.default,{})}),"Log in with Touch ID, Face ID, or a security key."]}),/*#__PURE__*/e.jsxs(o.ListItem,{children:[/*#__PURE__*/e.jsx(o.ListItemIcon,{children:/*#__PURE__*/e.jsx(me.default,{})}),"More secure than a password."]}),/*#__PURE__*/e.jsxs(o.ListItem,{children:[/*#__PURE__*/e.jsx(o.ListItemIcon,{children:/*#__PURE__*/e.jsx(he.default,{})}),"Takes seconds to set up and use."]})]});const fr={component:()=>{let{user:t,unlinkPasskey:n}=o.usePrivyContext(),{linkWithPasskey:i,closePrivyModal:s}=a.usePrivyInternal(),l=t?.linkedAccounts.filter((e=>"passkey"===e.type)),[c,d]=r.useState(!1),[u,h]=r.useState(""),[p,y]=r.useState(!1),[m,w]=r.useState(!1);r.useEffect((()=>{0===l.length&&w(!1)}),[l.length]);let g=async e=>(d(!0),await n(e).then((()=>y(!0))).catch((e=>{e instanceof a.PrivyError&&e.privyErrorCode===a.PrivyErrorCode.MISSING_MFA_CREDENTIALS?h("Cannot unlink a passkey enrolled in MFA"):h("Unknown error occurred.")})).finally((()=>{d(!1)})));return p?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:()=>s()},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(oe.default,{})}),/*#__PURE__*/e.jsx(Tr,{style:{marginBottom:"1.5rem"},children:"Passkeys updated"}),/*#__PURE__*/e.jsx(kr,{children:" "}),/*#__PURE__*/e.jsx(o.BottomSection,{children:/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:()=>s(),children:"Done"})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}):m?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:()=>w(!1),onClose:()=>s()},"header"),/*#__PURE__*/e.jsx(gr,{passkeys:l,expanded:m,onUnlink:g,onExpand:()=>w(!0)}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:()=>s()},"header"),/*#__PURE__*/e.jsx(o.AppLogoContainer,{children:/*#__PURE__*/e.jsxs(Er,{children:[/*#__PURE__*/e.jsx(o.FaceId,{}),/*#__PURE__*/e.jsx(o.FingerPrint,{})]})}),/*#__PURE__*/e.jsx(Tr,{children:"Secure your account with a passkey"}),/*#__PURE__*/e.jsx(_r,{}),0===l.length?/*#__PURE__*/e.jsx(vr,{}):/*#__PURE__*/e.jsx(gr,{passkeys:l,expanded:m,onUnlink:g,onExpand:()=>w(!0)}),/*#__PURE__*/e.jsxs(o.BottomSection,{style:{marginTop:"12px"},children:[u&&/*#__PURE__*/e.jsx(Cr,{$fail:!0,children:u}),/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:()=>{d(!0),i().then((()=>y(!0))).catch((e=>{if(e instanceof a.PrivyError){if(e.privyErrorCode===a.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE)return void h("Cannot link more passkeys to account.");if(e.privyErrorCode===a.PrivyErrorCode.PASSKEY_NOT_ALLOWED)return void h("Passkey request timed out or rejected by user.")}h("Unknown error occurred.")})).finally((()=>{d(!1)}))},loading:c,children:"Add new passkey"})]}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]})}},Er=/*#__PURE__*/w.styled.div.withConfig({displayName:"DoubleIconWrapper",componentId:"sc-d6832d36-0"})(["display:flex;align-items:center;justify-content:center;width:180px;height:90px;border-radius:50%;svg + svg{margin-left:12px;}> svg{z-index:2;color:var(--privy-color-accent) !important;stroke:var(--privy-color-accent) !important;fill:var(--privy-color-accent) !important;}"]);let Cr=/*#__PURE__*/w.styled.div.withConfig({displayName:"InputHelp",componentId:"sc-d6832d36-1"})(["line-height:20px;height:20px;font-size:13px;color:",";display:flex;justify-content:flex-beginngin;width:100%;"],(e=>e.$fail?"var(--privy-color-error)":"var(--privy-color-foreground-3)")),Pr=/*#__PURE__*/w.css(["&&{width:100%;font-size:0.875rem;line-height:1rem;@media (min-width:440px){font-size:14px;}display:flex;gap:12px;justify-content:center;padding:6px 8px;background-color:var(--privy-color-background);transition:background-color 200ms ease;color:var(--privy-color-accent) !important;:focus{outline:none;box-shadow:none;}}"]);const Ar=/*#__PURE__*/w.styled.button.withConfig({displayName:"LinkButton",componentId:"sc-d6832d36-2"})(["",""],Pr);let xr=/*#__PURE__*/w.styled.div.withConfig({displayName:"List",componentId:"sc-d6832d36-3"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.8rem;padding:0.5rem 0rem 0rem;flex-grow:1;width:100%;"]),Tr=/*#__PURE__*/w.styled.div.withConfig({displayName:"ModalTitle",componentId:"sc-d6832d36-4"})(["font-size:18px;line-height:18px;text-align:center;font-weight:600;"]),kr=/*#__PURE__*/w.styled.div.withConfig({displayName:"ModalSubTitle",componentId:"sc-d6832d36-5"})(["font-size:0.875rem;text-align:center;margin-top:10px;"]),_r=/*#__PURE__*/w.styled.div.withConfig({displayName:"SectionSpacer",componentId:"sc-d6832d36-6"})(["height:32px;"]),Sr=/*#__PURE__*/w.styled.div.withConfig({displayName:"PasskeyListTitle",componentId:"sc-d6832d36-7"})(["line-height:20px;height:20px;font-size:1em;font-weight:450;display:flex;justify-content:flex-beginning;width:100%;"]),Ir=/*#__PURE__*/w.styled.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-d6832d36-8"})(["font-size:1em;line-height:1.3em;font-weight:500;color:var(--privy-color-foreground-2);padding:0.2em 0;"]),br=/*#__PURE__*/w.styled.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-d6832d36-9"})(["font-size:0.875rem;line-height:1rem;color:#64668b;padding:0.2em 0;"]),Wr=/*#__PURE__*/w.styled.div.withConfig({displayName:"PasskeyListItem",componentId:"sc-d6832d36-10"})(["display:flex;align-items:center;justify-content:space-between;padding:1em;gap:10px;font-size:0.875rem;line-height:1rem;text-align:left;border-radius:8px;border:1px solid #e2e3f0 !important;width:100%;height:5em;"]),jr=/*#__PURE__*/w.css([":focus,:hover,:active{outline:none;}display:flex;width:2em;height:2em;justify-content:center;align-items:center;svg{color:var(--privy-color-error);}svg:hover{color:var(--privy-color-foreground-3);}"]),Or=/*#__PURE__*/w.styled.button.withConfig({displayName:"PasskeyItemUnlinkButton",componentId:"sc-d6832d36-11"})(["",""],jr);const Rr=new Map([[o.FundingMethodSelectionScreen,null],[o.TransferFromWalletScreen,"external"],[o.AwaitingExternalTransferScreen,"external"],[o.AwaitingExternalSolanaTransferScreen,"external"],[o.AwaitingEvmToSolBridgingScreen,"external"],[o.AwaitingSolToEvmBridgingScreen,"external"],[o.ManualTransferScreen,"manual"],[o.MoonpayStatusScreen,"moonpay"]]),Ur=e=>!!e.fundingConfig&&u.filterSupportedOptions(e.fundingConfig.options).length>=1;async function Nr({url:e,popup:t,provider:r}){return t.location=e,new Promise(((e,r)=>{function n(){t?.close(),window.removeEventListener("message",i)}function i(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(e(t.data),n()),"https://cdn.apple-cloudkit.com"===t.origin&&t.data.ckSession&&(e({type:"PRIVY_OAUTH_RESPONSE",ckWebAuthToken:t.data.ckSession}),n()),"PRIVY_OAUTH_ERROR"===t.data.type&&(r(t.data.error),n()))}window.addEventListener("message",i)}))}const Mr={component:()=>{let{app:t,data:r}=o.usePrivyModal(),n=o.useAppConfig(),i=r?.externalConnectWallet?.suggestedAddress,s=i?`Connect the wallet with address ${o.formatWalletAddress(i)} ${t?.name?`to ${t.name}.`:"."}`:`Connect a wallet to ${t?.name}`,{connectors:l}=a.usePrivyInternal(),c=o.toWalletButtons({walletList:r?.externalConnectWallet?.walletList??t.appearance.walletList,walletChainType:r?.externalConnectWallet?.walletChainType??t.appearance.walletChainType,connectors:l,connectOnly:!0,ignore:t.appearance.walletList,walletConnectEnabled:t.externalWallets.walletConnect.enabled});/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{},"header"),c.length>0&&/*#__PURE__*/e.jsx(o.PaddedScreenHeader,{title:"Connect your wallet",description:s}),/*#__PURE__*/e.jsx(o.LoginMethodContainerWithScrollShadows,{$colorScheme:n.appearance.palette.colorScheme,children:/*#__PURE__*/e.jsx(o.WalletButtonList,{wallets:c})}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]})}},Fr={component:()=>{let t=o.useAppConfig(),{data:n,navigate:i,setModalData:s,onUserCloseViaDialogOrKeybindRef:l}=o.usePrivyModal(),{crossAppAuthFlow:c,updateWallets:d,closePrivyModal:u,createAnalyticsEvent:h}=a.usePrivyInternal(),{logout:p}=g.useLogout(),[y,m]=r.useState({}),w=n?.crossAppAuth,v={id:w.appId,name:w.name,logoUrl:w.logoUrl},f=new a.PrivyClientError(`There was an issue connecting your ${v.name} account. Please try again.`),E=new o.RunEffectOnce((async e=>{if(w.popup)try{let t=await c({appId:e,popup:w.popup,action:w.action});m({data:t})}catch(e){e instanceof a.PrivyClientError?m({error:e}):(e instanceof a.PrivyApiError&&w.popup&&w.popup.close(),m({error:f}))}else m({error:f})})),C=()=>{y.data&&(d(),w.onSuccess(y.data),u({shouldCallAuthOnSuccess:!0,isSuccess:!0})),w.onError(y.error??new a.PrivyClientError("User canceled flow")),u({shouldCallAuthOnSuccess:!1,isSuccess:!1})};l.current=C,r.useEffect((()=>{v.id.length&&E.execute(v.id)}),[v.id]),r.useEffect((()=>{if(!y.data)return;let e=y.data;if(t.legal.requireUsersAcceptTerms&&!e.hasAcceptedTerms){let e=setTimeout((()=>{i(o.AffirmativeConsentScreen)}),o.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(o.shouldProceedtoEmbeddedWalletCreationFlow(e,t.embeddedWallets)){let e=setTimeout((()=>{s({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),h({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:`privy:${v.id}`,screen:"CrossAppAuthScreen"}}),p()},callAuthOnSuccessOnClose:!0}}),i(o.EmbeddedWalletOnAccountCreateScreen)}),o.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}let r=setTimeout(C,o.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(r)}),[y.data]);let{title:P,subtitle:A}=r.useMemo((()=>y.data?{title:`Successfully connected with ${v.name}`,subtitle:"You're good to go!"}:y.error?{title:"Authentication failed",subtitle:y.error.message}:{title:`Connecting to ${v.name}`,subtitle:`Please check the pop-up from ${v.name} to continue`}),[y,v.name]);/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:C}),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(Lr,{children:[/*#__PURE__*/e.jsx(o.e$2,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(o.ConnectionLoader,{success:!!y.data,fail:!!y.error}),/*#__PURE__*/e.jsx(o.ProviderAppLogo,{name:v.name,logoUrl:v.logoUrl})]})}),/*#__PURE__*/e.jsxs(o.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx("h3",{children:P}),/*#__PURE__*/e.jsx("p",{children:A})]})]}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]})}};let Lr=/*#__PURE__*/w.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-33c02367-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin-left:27px;margin-right:27px;gap:24px;"]);const Dr={component:()=>{let{app:t,data:n}=o.usePrivyModal(),{closePrivyModal:i}=a.usePrivyInternal(),[s,l]=r.useState(!1),[c,d]=r.useState(),{address:u,onDelegate:h,onSuccess:p,onError:y}=n.delegatedActions.consent,m=async()=>{s?p():y(c??new a.PrivyClientError("User declined delegating actions.")),i({shouldCallAuthOnSuccess:!1})};return r.useEffect((()=>{if(!s&&!c)return;let e=setTimeout(m,o.DEFAULT_SUCCESS_SCREEN_LONG_DURATION_MS);return()=>clearTimeout(e)}),[s,c]),s||c?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:m}),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(o.HorizontallyCenteredItem,{children:[c?/*#__PURE__*/e.jsx(le.default,{stroke:"var(--privy-color-error)",width:"64px",height:"64px"}):/*#__PURE__*/e.jsx(oe.default,{stroke:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(o.ConfigurableSpacer,{height:20}),/*#__PURE__*/e.jsx(o.CenteredScreenHeader,{title:c?"Something went wrong":"Success!",description:c?"Please try again.":`You’ve successfully granted delegated action permissions to ${t.name}.`})]}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{closeable:!0,onClose:m}),/*#__PURE__*/e.jsx(se.default,{width:56,height:56,style:{margin:"auto"}}),/*#__PURE__*/e.jsx(o.Title,{style:{marginTop:24,color:"var(--privy-color-foreground)"},children:"Enable offline access"}),/*#__PURE__*/e.jsxs(o.SubTitle,{style:{marginBottom:24,textWrap:"pretty"},children:["By confirming, ",t.name," will be able to use your wallet for you even when you're not around. You can revoke this later."]}),/*#__PURE__*/e.jsx(qr,{showIcon:!0,address:u,title:"Wallet",isLoading:!1}),/*#__PURE__*/e.jsxs(Br,{style:{marginTop:24},children:[/*#__PURE__*/e.jsx(o.SecondaryButton,{onClick:m,children:"Not now"}),/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:async()=>{try{await h(),l(!0)}catch(e){d(e)}},children:"Accept"})]}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]})}};let Br=/*#__PURE__*/w.styled.div.withConfig({displayName:"ButtonsContainer",componentId:"sc-bdb7bc51-0"})(["display:flex;gap:10px;"]),qr=/*#__PURE__*/w.styled(o.WalletInfoCard).withConfig({displayName:"StyledWalletInfoCard",componentId:"sc-bdb7bc51-1"})(["margin-top:1.5rem;"]);const Hr={component:()=>{let{app:t,data:n}=o.usePrivyModal(),{closePrivyModal:i}=a.usePrivyInternal(),[s,l]=r.useState(!1),[c,d]=r.useState(),{onRevoke:u,onSuccess:h,onError:p}=n.delegatedActions.revoke,y=async()=>{s?h():p(c??new a.PrivyClientError("User declined revoking access to their delegated wallet.")),i({shouldCallAuthOnSuccess:!1})};return r.useEffect((()=>{if(!s&&!c)return;let e=setTimeout(y,o.DEFAULT_SUCCESS_SCREEN_LONG_DURATION_MS);return()=>clearTimeout(e)}),[s,c]),s||c?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:y}),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(o.HorizontallyCenteredItem,{children:[c?/*#__PURE__*/e.jsx(le.default,{stroke:"var(--privy-color-error)",width:"64px",height:"64px"}):/*#__PURE__*/e.jsx(oe.default,{stroke:"var(--privy-color-success)",width:"64px",height:"64px"}),/*#__PURE__*/e.jsx(o.ConfigurableSpacer,{height:20}),/*#__PURE__*/e.jsx(o.CenteredScreenHeader,{title:c?"Something went wrong":"Success!",description:c?"Please try again.":"You've successfully revoked permissions."})]}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{closeable:!0,onClose:y}),/*#__PURE__*/e.jsx(ce.default,{width:56,height:56,style:{margin:"auto"}}),/*#__PURE__*/e.jsx(o.Title,{style:{marginTop:24},children:"Revoke offline access to wallet"}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["By confirming, ",t.name," will no longer be able to use this wallet on your behalf when you are not online."]}),/*#__PURE__*/e.jsxs(zr,{style:{marginTop:24},children:[/*#__PURE__*/e.jsx(o.SecondaryButton,{onClick:y,children:"Deny"}),/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:async()=>{try{await u(),l(!0)}catch(e){d(e)}},children:"Confirm"})]}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]})}};let zr=/*#__PURE__*/w.styled.div.withConfig({displayName:"ButtonsContainer",componentId:"sc-993a839-0"})(["display:flex;gap:10px;"]),Vr="#8a63d2";const Kr={component:()=>{let{lastScreen:t,navigateBack:i,data:s,app:l}=o.usePrivyModal(),{requestFarcasterSignerStatus:c,closePrivyModal:d}=a.usePrivyInternal(),[u,h]=r.useState(void 0),[p,y]=r.useState(!1),[m,w]=r.useState(!1),g=r.useRef([]),v=s?.farcasterSigner;r.useEffect((()=>{let e=Date.now(),t=setInterval((async()=>{if(!v?.public_key)return clearInterval(t),void h({retryable:!0,message:"Connect failed",detail:"Something went wrong. Please try again."});"approved"===v.status&&(clearInterval(t),y(!1),w(!0),g.current.push(setTimeout((()=>d({shouldCallAuthOnSuccess:!1,isSuccess:!0})),o.DEFAULT_SUCCESS_SCREEN_DURATION_MS)));let r=await c(v?.public_key),n=Date.now()-e;"approved"===r.status?(clearInterval(t),y(!1),w(!0),g.current.push(setTimeout((()=>d({shouldCallAuthOnSuccess:!1,isSuccess:!0})),o.DEFAULT_SUCCESS_SCREEN_DURATION_MS))):n>3e5?(clearInterval(t),h({retryable:!0,message:"Connect failed",detail:"The request timed out. Try again."})):"revoked"===r.status&&(clearInterval(t),h({retryable:!0,message:"Request rejected",detail:"The request was rejected. Please try again."}))}),2e3);return()=>{clearInterval(t),g.current.forEach((e=>clearTimeout(e)))}}),[]);let f="pending_approval"===v?.status?v.signer_approval_url:void 0;return n.isMobile||p?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:t?i:void 0,onClose:d},"header"),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),n.isIOS?
|
|
3
|
-
/*#__PURE__*/e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsxs(Yr,{children:[/*#__PURE__*/e.jsx(o.e$2,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(o.ConnectionLoader,{success:m,fail:!!u}),/*#__PURE__*/e.jsx(o.Farcaster,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(o.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx(o.Title,{children:u?u.message:"Add a signer to Farcaster"}),/*#__PURE__*/e.jsx(o.SubTitle,{children:u?u.detail:"This will allow "+l.name+" to add casts, likes, follows, and more on your behalf."})]}),f&&/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:e=>{e.preventDefault(),window.location.href=f},children:"Open Warpcast app"})]})}):/*#__PURE__*/e.jsx(e.Fragment,{children:/*#__PURE__*/e.jsxs($r,{children:[/*#__PURE__*/e.jsx(o.e$2,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(o.ConnectionLoader,{success:m,fail:!!u}),/*#__PURE__*/e.jsx(o.Farcaster,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(o.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx(o.Title,{children:u?u.message:"Requesting signer from Farcaster"}),/*#__PURE__*/e.jsx(o.SubTitle,{children:u?u.detail:"This should only take a moment"}),/*#__PURE__*/e.jsx(o.CenteredItem,{children:f&&n.isMobile&&/*#__PURE__*/e.jsx(o.OpenLinkButton,{text:"Take me to Warpcast",url:f,color:Vr})})]})]})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:t?i:void 0,onClose:d},"header"),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx($r,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(o.Title,{children:"Add a signer to Farcaster"}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["This will allow ",l.name," to add casts, likes, follows, and more on your behalf."]}),/*#__PURE__*/e.jsx(o.CenteredItemWithPadding,{children:"pending_approval"===v?.status?/*#__PURE__*/e.jsx(o.QrCode,{url:v.signer_approval_url,size:275,squareLogoElement:o.Farcaster}):/*#__PURE__*/e.jsx(o.Loader,{})}),/*#__PURE__*/e.jsxs(o.CenteredItem,{children:[/*#__PURE__*/e.jsx(o.SubTitle,{children:"Or copy this link and paste it into a phone browser to open the Warpcast app."}),"pending_approval"===v?.status&&/*#__PURE__*/e.jsx(o.CopytoClipboardButton,{text:v.signer_approval_url,itemName:"link",color:Vr})]})]})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]})}};let $r=/*#__PURE__*/w.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-6e8f76e5-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin-left:27px;margin-right:27px;gap:24px;"]),Yr=/*#__PURE__*/w.styled.div.withConfig({displayName:"ConnectContainerButton",componentId:"sc-6e8f76e5-1"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;gap:24px;width:100%;"]);const Gr={component:()=>{let{closePrivyModal:t}=a.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(Xr,{children:/*#__PURE__*/e.jsx(de.default,{style:{width:32,height:32}})}),/*#__PURE__*/e.jsx(o.PaddedScreenHeader,{title:"Could not log in with provider",description:"It looks like you're using an in-app browser. To log in, please try again using an external browser.",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",textAlign:"center"}}),/*#__PURE__*/e.jsx(o.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:()=>t(),children:"Close"})}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]})}};let Xr=/*#__PURE__*/w.styled.div.withConfig({displayName:"StyledCircle",componentId:"sc-7bde5742-0"})(["border-radius:50%;height:68px;width:68px;display:flex;align-items:center;justify-content:center;background-color:var(--privy-color-accent);color:white;margin:0 auto 24px auto;"]);const Jr={component:()=>{let{app:t}=o.usePrivyModal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(o.CenteredScreenHeader,{title:"Connect your email",description:`Add your email to your ${t?.name} account`,icon:/*#__PURE__*/e.jsx(ue.default,{color:"var(--privy-color-accent)",strokeWidth:2,height:"48px",width:"48px"})}),/*#__PURE__*/e.jsx(o.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(o.ConnectEmailForm,{stacked:!0})}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]})}},Qr={component:()=>{let{app:t,currentScreen:r,data:n,navigate:i,setModalData:s}=o.usePrivyModal(),{initLoginWithSms:l}=a.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(o.CenteredScreenHeader,{title:"Connect your phone",description:`Add your number to your ${t?.name} account`,icon:/*#__PURE__*/e.jsx(re.default,{color:"var(--privy-color-accent)",strokeWidth:2,height:"40px",width:"40px"})}),/*#__PURE__*/e.jsx(o.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(o.ConnectPhoneNumberForm,{stacked:!0,onSubmit:async function({qualifiedPhoneNumber:e}){try{await l({phoneNumber:e,withPrivyUi:!0}),i(o.AwaitingPasswordlessCodeScreen)}catch(e){s({errorModalData:{error:e,previousScreen:n?.errorModalData?.previousScreen||r||Qr}}),i(o.ErrorScreen)}},hideRecent:!0})}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]})}},Zr={component:()=>{let{app:t,data:r}=o.usePrivyModal(),n=r?.externalConnectWallet?.suggestedAddress,i=n?/*#__PURE__*/e.jsxs("span",{children:["Link the wallet with address ",/*#__PURE__*/e.jsx(o.Address,{showCopyIcon:!1,address:n})," ",t?.name?`to ${t.name}.`:"."]}):`Link a wallet to your ${t?.name} account`,{connectors:s}=a.usePrivyInternal(),l=o.toWalletButtons({walletList:r?.externalConnectWallet?.walletList??t.appearance.walletList,walletChainType:r?.externalConnectWallet?.walletChainType??t.appearance.walletChainType,connectors:s,connectOnly:!1,ignore:t.appearance.walletList,walletConnectEnabled:t.externalWallets.walletConnect.enabled});/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{},"header"),l.length>0&&/*#__PURE__*/e.jsx(o.PaddedScreenHeader,{title:"Link your wallet",description:i}),/*#__PURE__*/e.jsx(o.LoginMethodContainer,{children:/*#__PURE__*/e.jsx(o.WalletButtonList,{wallets:l})}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]})}},en=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{width:"164",height:"164",viewBox:"0 0 164 164",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"26px",width:"26px",...t},...r,children:[/*#__PURE__*/e.jsx("circle",{cx:"82",cy:"82",r:"80",stroke:"#EC6351","stroke-width":"4","stroke-linecap":"round"}),/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M81.9999 100.788C93.3288 100.788 102.513 91.6043 102.513 80.2754C102.513 68.9465 93.3288 59.7626 81.9999 59.7626C70.671 59.7626 61.4871 68.9465 61.4871 80.2754C61.4871 91.6043 70.671 100.788 81.9999 100.788ZM88.3236 71.8304C88.9093 71.2446 89.8591 71.2446 90.4449 71.8304C91.0307 72.4161 91.0307 73.3659 90.4449 73.9517L84.121 80.2756L90.445 86.5996C91.0308 87.1854 91.0308 88.1351 90.445 88.7209C89.8592 89.3067 88.9095 89.3067 88.3237 88.7209L81.9997 82.3969L75.6756 88.7209C75.0899 89.3067 74.1401 89.3067 73.5543 88.7209C72.9685 88.1351 72.9685 87.1854 73.5543 86.5996L79.8783 80.2756L73.5544 73.9517C72.9686 73.3659 72.9686 72.4161 73.5544 71.8304C74.1402 71.2446 75.09 71.2446 75.6758 71.8304L81.9997 78.1543L88.3236 71.8304Z",fill:"#EC6351"})]}),tn={component:()=>{let{closePrivyModal:t}=a.usePrivyInternal(),{navigate:r}=o.usePrivyModal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(en,{style:{width:"160px",height:"160px",margin:"0 auto 20px"}}),/*#__PURE__*/e.jsx(o.PaddedScreenHeader,{title:"Could not connect with wallet",description:"Please check that Phantom multichain is enabled and try again.",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",textAlign:"center"}}),/*#__PURE__*/e.jsxs(o.BottomPusherContainer,{children:[/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:()=>r(o.LandingScreen),children:"Try again"}),/*#__PURE__*/e.jsx(o.SecondaryButton,{onClick:()=>t(),children:"Cancel"})]}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]})}};function rn(){let{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:n,submitEnrollmentWithSms:i,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:s,unenroll:l,enrollInMfa:c}=r.useContext(o.PrivyContext);return{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:n,submitEnrollmentWithSms:i,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:s,unenrollWithSms:()=>l("sms"),unenrollWithTotp:()=>l("totp"),unenrollWithPasskey:e=>l("passkey",e),showMfaEnrollmentModal:()=>c(!0),closeMfaEnrollmentModal:()=>c(!1)}}const nn=t=>/*#__PURE__*/e.jsxs(an,{xmlns:"http://www.w3.org/2000/svg",fill:"none",width:"88",height:"89",viewBox:"0 0 88 89",...t,children:[/*#__PURE__*/e.jsx("rect",{y:"0.666016",width:"88",height:"88",rx:"44"}),/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M45.2463 20.9106C44.5473 20.2486 43.4527 20.2486 42.7537 20.9106C37.8798 25.5263 31.3034 28.3546 24.0625 28.3546C23.9473 28.3546 23.8323 28.3539 23.7174 28.3525C22.9263 28.3427 22.2202 28.8471 21.9731 29.5987C20.9761 32.6311 20.4375 35.8693 20.4375 39.2297C20.4375 53.5896 30.259 65.651 43.5482 69.0714C43.8446 69.1477 44.1554 69.1477 44.4518 69.0714C57.741 65.651 67.5625 53.5896 67.5625 39.2297C67.5625 35.8693 67.0239 32.6311 66.0269 29.5987C65.7798 28.8471 65.0737 28.3427 64.2826 28.3525C64.1677 28.3539 64.0527 28.3546 63.9375 28.3546C56.6966 28.3546 50.1202 25.5263 45.2463 20.9106ZM52.7249 40.2829C53.3067 39.4683 53.1181 38.3363 52.3035 37.7545C51.4889 37.1726 50.3569 37.3613 49.7751 38.1759L41.9562 49.1223L38.0316 45.1977C37.3238 44.4899 36.1762 44.4899 35.4684 45.1977C34.7605 45.9056 34.7605 47.0532 35.4684 47.761L40.9059 53.1985C41.2826 53.5752 41.806 53.7671 42.337 53.7232C42.868 53.6792 43.3527 53.4039 43.6624 52.9704L52.7249 40.2829Z"})]});let an=/*#__PURE__*/w.styled.svg.withConfig({displayName:"StyledSvg",componentId:"sc-59fa943f-0"})(["height:90px;width:90px;> rect{","}> path{fill:white;}"],(e=>"success"===e.color?"fill: var(--privy-color-success);":"fill: var(--privy-color-accent);"));const on=({showIntro:t,userMfaMethods:r,appMfaMethods:n,userHasAuthSms:i,isTotpLoading:a,isPasskeyLoading:s,error:l,onClose:c,onBackToIntro:d,handleSelectMethod:u,setRemovingMfaMethod:h})=>{let p=r.reduce(((e,t)=>({...e,[t]:!0})),{}),y=n.reduce(((e,t)=>({...e,[t]:!0})),{});/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:t?d:void 0,onClose:c},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ne.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Choose a verification method"}),r.length>0?/*#__PURE__*/e.jsx(o.SubTitle,{children:"To add or delete verification methods, verification is required."}):/*#__PURE__*/e.jsx(o.SubTitle,{children:"How would you like to verify your identity? You can change this later."}),l&&/*#__PURE__*/e.jsx(o.ErrorMessage,{style:{marginTop:"1.25rem"},children:l.message}),/*#__PURE__*/e.jsxs(o.MethodList,{children:[(y.totp||p.totp)&&/*#__PURE__*/e.jsxs(o.MethodListItem,{children:[/*#__PURE__*/e.jsx(o.LoginMethodButton,{style:{justifyContent:"center"},disabled:p.totp||a,onClick:()=>u("totp"),children:a?/*#__PURE__*/e.jsx(o.Loader,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/e.jsxs(o.SmsInsecureText,{children:[/*#__PURE__*/e.jsxs(o.MethodText,{children:[/*#__PURE__*/e.jsx(ee.default,{}),"Authenticator app"]}),p.totp?/*#__PURE__*/e.jsx(sn,{color:"green",children:"Enabled"}):/*#__PURE__*/e.jsx(o.ExtraText,{children:"Recommended"})]})}),p.totp&&/*#__PURE__*/e.jsx(o.RemoveMethodButton,{style:{position:"absolute",right:0},onClick:()=>h("totp"),children:/*#__PURE__*/e.jsx(fe.default,{})})]},"totp"),(y.sms||p.sms)&&/*#__PURE__*/e.jsxs(o.MethodListItem,{children:[/*#__PURE__*/e.jsx(o.LoginMethodButton,{disabled:p.sms||i,onClick:()=>u("sms"),children:/*#__PURE__*/e.jsxs(o.SmsInsecureText,{children:[/*#__PURE__*/e.jsxs(o.MethodText,{children:[/*#__PURE__*/e.jsx(re.default,{}),"SMS"]}),p.sms&&/*#__PURE__*/e.jsx(sn,{color:"green",children:"Enabled"}),i&&/*#__PURE__*/e.jsx(o.ExtraText,{children:"Disabled"})]})}),p.sms&&/*#__PURE__*/e.jsx(o.RemoveMethodButton,{style:{position:"absolute",right:0},onClick:()=>h("sms"),children:/*#__PURE__*/e.jsx(fe.default,{})})]},"sms"),(y.passkey||p.passkey)&&/*#__PURE__*/e.jsxs(o.MethodListItem,{children:[/*#__PURE__*/e.jsx(o.LoginMethodButton,{style:{justifyContent:"center"},onClick:()=>u("passkey"),disabled:p.passkey||s,children:s?/*#__PURE__*/e.jsx(o.Loader,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/e.jsxs(o.SmsInsecureText,{children:[/*#__PURE__*/e.jsxs(o.MethodText,{children:[/*#__PURE__*/e.jsx(te.default,{}),"Passkey"]}),p.passkey?/*#__PURE__*/e.jsx(sn,{color:"green",children:"Enabled"}):/*#__PURE__*/e.jsx(o.ExtraText,{isAccent:!0,children:/*#__PURE__*/e.jsx(ve.default,{})})]})}),p.passkey&&/*#__PURE__*/e.jsx(o.RemoveMethodButton,{style:{position:"absolute",right:0},onClick:()=>h("passkey"),children:/*#__PURE__*/e.jsx(fe.default,{})})]},"passkey")]}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]})};let sn=/*#__PURE__*/w.styled(o.Chip).withConfig({displayName:"StyledChip",componentId:"sc-998ca5bc-0"})(["margin-right:1.5rem;"]);const ln=({appName:t,onComplete:n,onClose:i,onReset:s})=>{let{user:l}=o.usePrivyContext(),{data:c}=o.usePrivyModal(),{initLinkWithPasskey:d,linkWithPasskey:u}=a.usePrivyInternal(),{initEnrollmentWithPasskey:h,submitEnrollmentWithPasskey:p}=rn(),[y,m]=r.useState(!1),[w,g]=r.useState(!1),[v,f]=r.useState(!1),[E,C]=r.useState(null),P=r.useMemo((()=>l?.linkedAccounts.filter((e=>"passkey"===e.type))??[]),[l]),A=()=>{c?.mfaEnrollmentFlow?.onSuccess(),n()},x=async e=>{m(!0);try{await h(),await p({credentialIds:e},{removeForLogin:c?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa}),f(!0)}catch(e){C(e)}finally{m(!1)}},T=async()=>{g(!0),C(null);try{await d();let e=await u(),t=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];await x(t)}catch(e){C(e)}finally{g(!1)}};return 0===P.length||w?/*#__PURE__*/e.jsx(cn,{onReset:s,onClose:i,onClick:T,isCreating:w}):v?/*#__PURE__*/e.jsx(un,{appName:t,onClick:A,onClose:A}):E?/*#__PURE__*/e.jsx(o.ErrorScreenView,{error:E,backFn:()=>C(null),onClick:()=>C(null)}):/*#__PURE__*/e.jsx(dn,{passkeys:P,isSubmitting:y,isCreating:w,onReset:s,onClose:i,onSubmitEnrollment:()=>x(P.map((e=>e.credentialId))),onAddPasskey:T})};let cn=({onReset:t,onClose:r,onClick:n,isCreating:i})=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:t,onClose:r},"header"),/*#__PURE__*/e.jsx(o.AppLogoContainer,{children:/*#__PURE__*/e.jsxs(Er,{children:[/*#__PURE__*/e.jsx(o.FaceId,{}),/*#__PURE__*/e.jsx(o.FingerPrint,{})]})}),/*#__PURE__*/e.jsx(o.Title,{children:"Set up passkey verification"}),/*#__PURE__*/e.jsxs(o.List,{children:[/*#__PURE__*/e.jsxs(o.ListItem,{children:[/*#__PURE__*/e.jsx(o.ListItemIcon,{children:/*#__PURE__*/e.jsx(ne.default,{})}),"Verify with Touch ID, Face ID, PIN, or hardware key"]}),/*#__PURE__*/e.jsxs(o.ListItem,{children:[/*#__PURE__*/e.jsx(o.ListItemIcon,{children:/*#__PURE__*/e.jsx(he.default,{})}),"Takes seconds to set up and use"]}),/*#__PURE__*/e.jsxs(o.ListItem,{children:[/*#__PURE__*/e.jsx(o.ListItemIcon,{children:/*#__PURE__*/e.jsx(Ee.default,{})}),"Use your passkey to verify transactions and login to your account"]})]}),/*#__PURE__*/e.jsx(o.PrimaryButton,{style:{marginTop:"2.25rem"},onClick:n,loading:i,children:"Add a new passkey"}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}),dn=({onReset:t,onClose:n,onAddPasskey:i,onSubmitEnrollment:a,passkeys:s,isSubmitting:l,isCreating:c})=>{let[d,u]=r.useState(!1),h=d?s.length:s.length>3?2:3;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:d?()=>u(!1):t,onClose:n},"header"),!d&&/*#__PURE__*/e.jsx(o.AppLogoContainer,{children:/*#__PURE__*/e.jsxs(Er,{children:[/*#__PURE__*/e.jsx(o.FaceId,{}),/*#__PURE__*/e.jsx(o.FingerPrint,{})]})}),/*#__PURE__*/e.jsx(o.Title,{children:"Enable your passkeys for verification"}),/*#__PURE__*/e.jsxs(o.List,{children:[s.slice(0,h).map((t=>/*#__PURE__*/e.jsxs(hn,{children:[/*#__PURE__*/e.jsx(pn,{children:mn(t)}),/*#__PURE__*/e.jsxs(yn,{children:["Last used: ",t.latestVerifiedAt?.toLocaleString()]})]},t.credentialId))),!d&&s.length>3&&/*#__PURE__*/e.jsx(wn,{onClick:()=>u(!0),children:"View All"})]}),/*#__PURE__*/e.jsx(o.PrimaryButton,{style:{marginTop:"1.5rem"},onClick:a,loading:l,children:"Enable passkeys"}),s.length<5&&/*#__PURE__*/e.jsx(wn,{style:{marginTop:"0.5rem"},onClick:i,disabled:c,children:c?/*#__PURE__*/e.jsx(o.Loader,{style:{height:"1rem",width:"1rem",borderWidth:2}}):"Add new passkey"}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]})},un=({appName:t,onClick:r,onClose:n})=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:n},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(oe.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Passkey verification added"}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["From now on, you'll use the passkey whenever you use your ",t," wallet."]}),/*#__PURE__*/e.jsx(o.BottomSection,{children:/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:r,children:"Done"})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}),hn=/*#__PURE__*/w.styled.div.withConfig({displayName:"PasskeyItem",componentId:"sc-d5b2bf9c-0"})(["&&{padding:0.75rem 1rem;text-align:left;border-radius:0.5rem;border:1px solid var(--privy-color-foreground-4);width:100%;}"]),pn=/*#__PURE__*/w.styled.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-d5b2bf9c-1"})(["font-size:0.875rem;line-height:1.375rem;font-weight:500;color:var(--privy-color-foreground-1);"]),yn=/*#__PURE__*/w.styled.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-d5b2bf9c-2"})(["font-size:0.75rem;font-weight:400;line-height:1.125rem;color:var(--privy-color-foreground-2);"]),mn=e=>e.authenticatorName?e.createdWithBrowser?`${e.authenticatorName} on ${e.createdWithBrowser}`:e.authenticatorName:e.createdWithBrowser?e.createdWithOs?`${e.createdWithBrowser} on ${e.createdWithOs}`:`${e.createdWithBrowser}`:"Unknown device";const wn=/*#__PURE__*/w.styled.button.withConfig({displayName:"StyledLink",componentId:"sc-d5b2bf9c-3"})(["&&{width:100%;font-size:0.875rem;line-height:1rem;@media (min-width:440px){font-size:14px;}display:flex;gap:12px;justify-content:center;padding:0.75rem 1rem;background-color:var(--privy-color-background);transition:background-color 200ms ease;color:var(--privy-color-accent);:focus{outline:none;box-shadow:none;}}"]),gn=({appName:t,onComplete:n,onReset:i,onClose:a})=>{let[s,l]=r.useState(""),[c,d]=r.useState(!1),[u,h]=r.useState(null),[p,y]=r.useState("enroll"),{initEnrollmentWithSms:m,submitEnrollmentWithSms:w}=rn(),{app:g,data:v}=o.usePrivyModal();function f(){v?.mfaEnrollmentFlow?.onSuccess(),n()}return u?/*#__PURE__*/e.jsx(o.ErrorScreenView,{error:u,backFn:()=>h(null),onClick:()=>h(null)}):"enroll"===p?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:i,onClose:a},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(re.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Set up SMS verification"}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["We'll text a verification code to this mobile device whenever you use your ",t," ","wallet."]}),/*#__PURE__*/e.jsxs(o.Container,{children:[/*#__PURE__*/e.jsx(o.ConnectPhoneNumberForm,{onSubmit:async function({qualifiedPhoneNumber:e}){try{await m({phoneNumber:e}),l(e),y("verify")}catch(e){h(e)}},hideRecent:!0}),/*#__PURE__*/e.jsxs(o.TermsText,{children:["By providing your mobile number, you agree to receive text messages from ",g?.name,". Some carrier charges may apply"]})]}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}):c?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:f},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(oe.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"SMS verification added"}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["From now on, you'll enter the verification code sent to your mobile device whenever you use your ",t," wallet."]}),/*#__PURE__*/e.jsx(o.BottomSection,{children:/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:f,children:"Done"})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:function(){"verify"===p?y("enroll"):i()},onClose:a},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(re.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Enter enrollment code"}),/*#__PURE__*/e.jsxs(o.Container,{children:[/*#__PURE__*/e.jsx(_t,{onChange:async function(e){try{if(!e)return;await w({phoneNumber:s,mfaCode:e}),d(!0)}catch(e){if(o.errorIndicatesMfaRateLimit(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(o.errorIndicatesMfaVerificationFailed(e))throw Error("The code you entered is not valid");if(o.errorIndicatesMfaTimeout(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw o.errorIndicatesMfaCanceled(e)?Error("Verification canceled"):Error("Unknown error")}}}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["To continue, enter the 6-digit code sent to ",/*#__PURE__*/e.jsx("strong",{children:q.lastFourDigits(s)})]})]}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]})},vn=({size:t,authUrl:r})=>/*#__PURE__*/e.jsx(o.QrCode,{url:r,squareLogoElement:Ce.default,size:t,fgColor:"#1F1F1F"}),fn=({onComplete:t,onClose:n,onReset:i,totpInfo:a})=>{let[s,l]=r.useState("enroll"),[c,d]=r.useState(!1),{submitEnrollmentWithTotp:u}=rn(),{data:h}=o.usePrivyModal();function p(){h?.mfaEnrollmentFlow?.onSuccess(),t()}return"enroll"===s?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:i,onClose:n},"header"),/*#__PURE__*/e.jsx(o.Title,{children:"Scan QR code"}),/*#__PURE__*/e.jsx(o.SubTitle,{children:"Open your authenticator app and scan the QR code to continue."}),/*#__PURE__*/e.jsx(o.CenteredItemWithPadding,{children:/*#__PURE__*/e.jsx(vn,{authUrl:a.authUrl,size:200})}),/*#__PURE__*/e.jsxs(o.BottomSection,{children:[/*#__PURE__*/e.jsx(o.CenteredItem,{children:/*#__PURE__*/e.jsx(o.CopytoClipboardButton,{itemName:"setup key",text:a.secret})}),/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:function(){l("verify")},children:"Continue"})]}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}):c?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:p},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(oe.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Authenticator app verification added"}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["From now on, you'll enter the verification code generated by your authenticator app whenever you use your ",a.appName," wallet."]}),/*#__PURE__*/e.jsx(o.BottomSection,{children:/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:p,children:"Done"})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:function(){"verify"===s?l("enroll"):i()},onClose:n},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ee.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Enter enrollment code"}),/*#__PURE__*/e.jsx(o.Container,{children:/*#__PURE__*/e.jsx(_t,{onChange:async function(e){try{if(!e)return;await u({mfaCode:e}),d(!0)}catch(e){if(o.errorIndicatesMfaRateLimit(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(o.errorIndicatesMfaVerificationFailed(e))throw Error("The code you entered is not valid");if(o.errorIndicatesMfaTimeout(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw o.errorIndicatesMfaCanceled(e)?Error("Verification canceled"):Error("Unknown error")}}})}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["To continue, enter the 6-digit code generated from your ",/*#__PURE__*/e.jsx("strong",{children:"authenticator app"})]}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]})},En={component:()=>{let{user:t,enrollInMfa:n,ready:i}=o.usePrivyContext(),[s,l]=r.useState(null),{unenrollWithSms:c,unenrollWithTotp:d,unenrollWithPasskey:u}=rn(),{app:h,data:p,onUserCloseViaDialogOrKeybindRef:y}=o.usePrivyModal(),{closePrivyModal:m}=a.usePrivyInternal(),{promptMfa:w}=jt(),{initEnrollmentWithTotp:g}=rn(),[v,f]=r.useState(!1),[E,C]=r.useState(null),[P,A]=r.useState(null),x=()=>{m({shouldCallAuthOnSuccess:!0}),n(!1),setTimeout((()=>{l(null),C(null)}),500)},{initEnrollmentWithPasskey:T,submitEnrollmentWithPasskey:k}=rn(),[_,S]=r.useState(!1),[I,b]=r.useState(null);y.current=x;let W=t?.mfaMethods.includes("sms"),j=!!t?.phone,O=t?.mfaMethods.includes("totp"),R=t?.mfaMethods.includes("passkey"),U=W||O||R,N=t?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function M(){l(null),C(null)}if(r.useEffect((()=>{U&&f(!0)}),[U]),!i||!t||!h/*#__PURE__*/)return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:x},"header"),/*#__PURE__*/e.jsx(o.AppLogoContainer,{children:/*#__PURE__*/e.jsx(nn,{})}),/*#__PURE__*/e.jsx(o.Container,{children:/*#__PURE__*/e.jsx(o.Loader,{})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]});if("sms"===s)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:M,onClose:x},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(we.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Remove SMS verification?"}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["MFA adds an extra layer of security to your ",h?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/e.jsx(o.BottomSection,{children:/*#__PURE__*/e.jsx(o.PrimaryButton,{warn:!0,onClick:async function(){l(null);try{await c()}catch(e){l(null)}},children:"Remove SMS for MFA"})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]});if("totp"===s)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:M,onClose:x},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(we.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Remove Authenticator App verification?"}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:["MFA adds an extra layer of security to your ",h?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/e.jsx(o.BottomSection,{children:/*#__PURE__*/e.jsx(o.PrimaryButton,{warn:!0,onClick:async function(){l(null);try{await d()}catch(e){l(null)}},children:"Remove Authenticator App for MFA"})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]});if("passkey"===s){let t=p?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{backFn:M,onClose:x},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(we.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/e.jsx(o.SubTitle,{children:t?"Removing your passkey will remove as both a verification method and a login method.":"Removing your passkey will remove as a verification method."}),/*#__PURE__*/e.jsx(o.BottomSection,{children:/*#__PURE__*/e.jsx(o.PrimaryButton,{warn:!0,onClick:async function(){l(null);try{await u({removeForLogin:p?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa})}catch(e){l(null)}},children:"Yes, remove"})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]})}if(0===p.mfaEnrollmentFlow.mfaMethods.length&&!U)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:x},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ne.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Add more security"}),/*#__PURE__*/e.jsxs(o.SubTitle,{children:[h?.name," does not have any verification methods enabled."]}),/*#__PURE__*/e.jsx(o.BottomSection,{children:/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:x,children:"Close"})}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]});let F=!U&&!v;return F?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:x},"header"),/*#__PURE__*/e.jsx(o.IconWrapper,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ne.default,{})}),/*#__PURE__*/e.jsx(o.Title,{children:"Transaction Protection"}),/*#__PURE__*/e.jsx(o.SubTitle,{children:"Set up transaction protection to add an extra layer of security to your account"}),/*#__PURE__*/e.jsxs(o.List,{children:[/*#__PURE__*/e.jsxs(o.ListItem,{children:[/*#__PURE__*/e.jsx(o.ListItemIcon,{children:/*#__PURE__*/e.jsx(ye.default,{})}),"Enable 2-Step verification for your ",h?.name," wallet."]}),/*#__PURE__*/e.jsxs(o.ListItem,{children:[/*#__PURE__*/e.jsx(o.ListItemIcon,{children:/*#__PURE__*/e.jsx(ge.default,{})}),"You'll be prompted to authenticate to complete transactions."]})]}),/*#__PURE__*/e.jsxs(o.BottomSection,{children:[/*#__PURE__*/e.jsx(o.PrimaryButton,{onClick:()=>f(!0),children:"Continue"}),/*#__PURE__*/e.jsx(o.SecondaryButton,{onClick:x,children:"Not now"})]}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]}):"sms"===E?/*#__PURE__*/e.jsx(gn,{appName:h?.name||"Privy",onComplete:x,onReset:M,onClose:x}):"totp"===E&&P?/*#__PURE__*/e.jsx(fn,{onComplete:x,onClose:x,onReset:M,totpInfo:{...P,appName:h?.name||"Privy"}}):"passkey"===E?/*#__PURE__*/e.jsx(ln,{appName:h?.name||"Privy",onComplete:x,onReset:M,onClose:x}):/*#__PURE__*/e.jsx(on,{showIntro:F,userMfaMethods:t.mfaMethods,appMfaMethods:h.mfa.methods,userHasAuthSms:j,onBackToIntro:function(){f(!1)},handleSelectMethod:async function(e){return await w().catch(b),"totp"===e?(C(e),A(null),void g().then((e=>{A(e)})).catch((()=>{A(null),M()}))):"passkey"===e&&1===N.length?await async function(){S(!0);try{await T(),await k({credentialIds:N},{removeForLogin:p?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa})}catch(e){b(e)}finally{S(!1)}}():void C(e)},isTotpLoading:"totp"===E&&!P,isPasskeyLoading:_,error:I,onClose:x,setRemovingMfaMethod:async e=>{await w().catch(b),l(e)}})}},Cn={component:()=>{let{authenticated:t,logout:n,ready:i,user:s}=o.usePrivyContext(),{app:l,setModalData:c,navigate:d,resetNavigation:u}=o.usePrivyModal(),{getAuthMeta:h,initLoginWithOAuth:p,loginWithOAuth:y,updateWallets:m,setReadyToTrue:w,closePrivyModal:g,createAnalyticsEvent:v}=a.usePrivyInternal(),[f,E]=r.useState(!1),[C,P]=r.useState(void 0),A=h()?.provider||"google",{name:x,component:T}=Oe(A);r.useEffect((()=>{y(A).then((()=>{E(!0),w(!0)})).catch((e=>{if(w(!1),e?.privyErrorCode===a.PrivyErrorCode.ALLOWLIST_REJECTED)return P(void 0),u(),void d(o.AllowlistRejectionScreen);if(e?.privyErrorCode===a.PrivyErrorCode.USER_LIMIT_REACHED)return console.error(new a.PrivyUserLimitReachedError(e).toString()),P(void 0),u(),void d(o.UserLimitReachedScreen);if(e?.privyErrorCode===a.PrivyErrorCode.USER_DOES_NOT_EXIST)return P(void 0),u(),void d(o.AccountNotFoundScreen);if(e?.privyErrorCode===a.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return P(void 0),u(),c({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:h()?.provider,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void d(o.LinkConflictScreen);let{retryable:t,detail:r}=function(e,t){let r={detail:"",retryable:!1},n=o.e$1(t);if(e?.privyErrorCode===a.PrivyErrorCode.LINKED_TO_ANOTHER_USER&&(r.detail="This account has already been linked to another user."),e?.privyErrorCode===a.PrivyErrorCode.INVALID_CREDENTIALS&&(r.retryable=!0,r.detail="Something went wrong. Try again."),e.privyErrorCode===a.PrivyErrorCode.OAUTH_USER_DENIED&&(r.detail=`Retry and check ${n} to finish connecting your account.`,r.retryable=!0),e?.privyErrorCode===a.PrivyErrorCode.TOO_MANY_REQUESTS&&(r.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===a.PrivyErrorCode.TOO_MANY_REQUESTS&&e.message.includes("provider rate limit")){let e=Oe(t).name;r.detail=`Request limit reached for ${e}. Please wait a moment and try again.`}if(e?.privyErrorCode===a.PrivyErrorCode.OAUTH_ACCOUNT_SUSPENDED){let e=Oe(t).name;r.detail=`Your ${e} account is suspended. Please try another login method.`}return e?.privyErrorCode===a.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE&&(r.detail="You cannot authorize more than one account for this user."),e?.privyErrorCode===a.PrivyErrorCode.OAUTH_UNEXPECTED&&t.startsWith("privy:")&&(r.detail="Something went wrong. Please try again."),r}(e,A);P({retryable:t,detail:r,message:"Authentication failed"})})).finally((()=>{o.stripUrlOAuthParamsAndRemoveStateCode()}))}),[x,A]),r.useEffect((()=>{if(i&&t&&f&&s){if(l?.legal.requireUsersAcceptTerms&&!s.hasAcceptedTerms){let e=setTimeout((()=>{d(o.AffirmativeConsentScreen)}),o.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(o.shouldProceedtoEmbeddedWalletCreationFlow(s,l.embeddedWallets)){let e=setTimeout((()=>{c({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),v({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:A,screen:"OAuthStatusScreen"}}),n()},callAuthOnSuccessOnClose:!0}}),d(o.EmbeddedWalletOnAccountCreateScreen)}),o.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}{let e=setTimeout((()=>g({shouldCallAuthOnSuccess:!0,isSuccess:!0})),o.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return m(),()=>clearTimeout(e)}}}),[i,t,f,s]);let k=f?`Successfully connected with ${x}`:C?C.message:`Verifying connection to ${x}`,_="";return _=f?"You’re good to go!":C?C.detail:"Just a few moments more",/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{}),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsxs(Pn,{children:[/*#__PURE__*/e.jsx(o.e$2,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(o.ConnectionLoader,{success:f,fail:!!C}),/*#__PURE__*/e.jsx(T,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsxs(o.FixedGappedContainer,{children:[/*#__PURE__*/e.jsx("h3",{children:k}),/*#__PURE__*/e.jsx("p",{children:_})]}),C&&C?.retryable?/*#__PURE__*/e.jsx(o.SoftCtaButton,{onClick:()=>{o.stripUrlOAuthParamsAndRemoveStateCode(),p(A),P(void 0)},disabled:!f&&!C?.retryable,children:"Retry"}):null]}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.ModalFooter,{})]})}};let Pn=/*#__PURE__*/w.styled.div.withConfig({displayName:"ConnectContainer",componentId:"sc-89bb91a9-0"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;margin-left:27px;margin-right:27px;gap:24px;"]);const An=({instructions:t,fees:n,transactionInfo:i,solPrice:a,rpcEndpoint:s})=>{let l=t.reduce(((e,{amount:t,token:r})=>t&&"SOL"===r?.symbol?e+t:e),0n),[c,d]=r.useState(0),[u,h]=r.useState(!1),p=t[c];/*#__PURE__*/return e.jsxs(o.Rows,{children:[/*#__PURE__*/e.jsxs(o.Row,{children:[/*#__PURE__*/e.jsx(o.LabelSm,{children:"Total"}),/*#__PURE__*/e.jsx(o.Value,{children:/*#__PURE__*/e.jsx(o.SolanaPriceDisplay,{quantities:[l,n],tokenPrice:a})})]}),i&&i.action&&/*#__PURE__*/e.jsxs(o.Row,{children:[/*#__PURE__*/e.jsx(o.LabelSm,{children:"Action"}),/*#__PURE__*/e.jsx(o.Value,{children:i.action})]}),/*#__PURE__*/e.jsxs(o.Row,{children:[/*#__PURE__*/e.jsx(o.LabelSm,{children:"Fees"}),/*#__PURE__*/e.jsx(o.Value,{children:/*#__PURE__*/e.jsx(o.SolanaPriceDisplay,{quantities:[n||0n],tokenPrice:a})})]}),t.length>1?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.Row,{children:/*#__PURE__*/e.jsxs(o.InteractiveLabel,{onClick:()=>h((e=>!e)),children:[/*#__PURE__*/e.jsx("span",{children:"Details"}),/*#__PURE__*/e.jsx(Ae.default,{height:"16px",width:"16px",strokeWidth:"2",style:{transition:"all 300ms",transform:u?"rotate(180deg)":void 0}})]})}),u&&/*#__PURE__*/e.jsx(o.Row,{children:/*#__PURE__*/e.jsxs(Tn,{children:[/*#__PURE__*/e.jsxs(kn,{children:[/*#__PURE__*/e.jsxs(_n,{children:[c+1," of ",t.length," instructions"]}),/*#__PURE__*/e.jsxs(In,{children:[c>0&&/*#__PURE__*/e.jsx(o.BackButton,{backFn:()=>d((e=>e-1))}),c<t.length-1&&/*#__PURE__*/e.jsx(o.NextButton,{nextFn:()=>d((e=>e+1))})]})]}),/*#__PURE__*/e.jsx(Sn,{children:/*#__PURE__*/e.jsx(xn,{instruction:p,rpcEndpoint:s,solPrice:a})})]})})]}):/*#__PURE__*/e.jsx(xn,{instruction:p,rpcEndpoint:s,solPrice:a,hideAmount:!0})]})};function xn({instruction:t,rpcEndpoint:r,solPrice:n,hideAmount:i}){return t?/*#__PURE__*/e.jsxs(o.Rows,{children:[!i&&!!t.amount&&/*#__PURE__*/e.jsxs(o.Row,{children:[/*#__PURE__*/e.jsx(o.LabelSm,{children:"Amount"}),/*#__PURE__*/e.jsx(o.Value,{children:/*#__PURE__*/e.jsx(o.SolanaPriceDisplay,{quantities:[t.amount],tokenPrice:n,tokenSymbol:t.token?.symbol??"SOL",tokenDecimals:t.token?.decimals??9})})]}),t.to&&/*#__PURE__*/e.jsxs(o.Row,{children:[/*#__PURE__*/e.jsx(o.LabelSm,{children:"To"}),/*#__PURE__*/e.jsx(o.Value,{children:/*#__PURE__*/e.jsx(o.WalletLink,{walletAddress:t.to,rpcEndpoint:r,network:"solana"})})]}),t.tokenAccount&&/*#__PURE__*/e.jsxs(o.Row,{children:[/*#__PURE__*/e.jsx(o.LabelSm,{children:"Token account"}),/*#__PURE__*/e.jsx(o.Value,{children:/*#__PURE__*/e.jsx(o.WalletLink,{walletAddress:t.tokenAccount,rpcEndpoint:r,network:"solana"})})]}),t.tokenAccountOwner&&/*#__PURE__*/e.jsxs(o.Row,{children:[/*#__PURE__*/e.jsx(o.LabelSm,{children:"Token account owner"}),/*#__PURE__*/e.jsx(o.Value,{children:/*#__PURE__*/e.jsx(o.WalletLink,{walletAddress:t.tokenAccountOwner,rpcEndpoint:r,network:"solana"})})]}),t.from&&/*#__PURE__*/e.jsxs(o.Row,{children:[/*#__PURE__*/e.jsx(o.LabelSm,{children:"From"}),/*#__PURE__*/e.jsx(o.Value,{children:/*#__PURE__*/e.jsx(o.WalletLink,{walletAddress:t.from,rpcEndpoint:r,network:"solana"})})]})]}):null}let Tn=/*#__PURE__*/w.styled.div.withConfig({displayName:"InstructionsBox",componentId:"sc-5a140027-0"})(["display:flex;flex-direction:column;width:100%;overflow:hidden;&&{border:1px solid;border-color:var(--privy-color-foreground-4);border-radius:var(--privy-border-radius-md);}"]),kn=/*#__PURE__*/w.styled.header.withConfig({displayName:"InstructionsBoxHeader",componentId:"sc-5a140027-1"})(["display:flex;justify-content:space-between;align-items:center;padding:12px;background-color:var(--privy-color-background-2);"]),_n=/*#__PURE__*/w.styled.h4.withConfig({displayName:"HeaderTitle",componentId:"sc-5a140027-2"})(["font-size:14px;font-weight:500;line-height:19.6px;"]),Sn=/*#__PURE__*/w.styled.div.withConfig({displayName:"InstructionsBoxContent",componentId:"sc-5a140027-3"})(["padding:12px;"]),In=/*#__PURE__*/w.styled.div.withConfig({displayName:"NavigationButtonsConatiner",componentId:"sc-5a140027-4"})(["display:flex;gap:8px;align-items:center;"]);const bn=({instructions:t,fees:r,onClose:n,receiptHeader:i,receiptDescription:a,transactionInfo:s,solPrice:l,rpcEndpoint:c,signOnly:d})=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{onClose:n}),/*#__PURE__*/e.jsx(o.e$2,{style:{marginBottom:"16px"},children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(o.CircleBackground,{color:"var(--privy-color-success-light)"}),/*#__PURE__*/e.jsx(oe.default,{height:38,width:38,strokeWidth:2,stroke:"var(--privy-color-success)"})]})}),/*#__PURE__*/e.jsx(o.CenteredScreenHeader,{title:i??`Transaction ${d?"signed":"complete"}!`,description:a??"You're all set."}),/*#__PURE__*/e.jsx(An,{solPrice:l,instructions:t,fees:r,transactionInfo:s,rpcEndpoint:c}),/*#__PURE__*/e.jsx(o.Grow,{}),/*#__PURE__*/e.jsx(Wn,{loading:!1,onClick:n,children:"Close"}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]});let Wn=/*#__PURE__*/w.styled(o.PrimaryButton).withConfig({displayName:"SubmitButton",componentId:"sc-6f95cdcf-0"})(["&&{margin-top:24px;}transition:color 350ms ease,background-color 350ms ease;"]);const jn={component:()=>{let{data:t,onUserCloseViaDialogOrKeybindRef:n,setModalData:i,navigate:s}=o.usePrivyModal(),{client:l,closePrivyModal:c,walletProxy:d,showFiatPrices:u}=a.usePrivyInternal(),h=o.useAppConfig(),{user:p,getAccessToken:y}=o.usePrivyContext(),[m,w]=r.useState(t?.sendSolanaTransaction?.transactionRequest),[g,v]=r.useState(),[f,E]=r.useState(),[C,A]=r.useState(0),[x,T]=r.useState({value:0n,isLoading:!1}),[k,_]=r.useState(!1),[S,I]=r.useState(),[b,W]=r.useState(),j=t?.sendSolanaTransaction?.connection,O=t?.sendSolanaTransaction?.transactingWallet,R=t?.sendSolanaTransaction?.signOnly??!1,U=g?.instructions.length??1,N=O?.imported?o.getImportedPrivySolanaWallet(p):o.getPrivyPrimaryWallet(p),M=o.getSolanaNetworkFromRpcEndpoint(j?.rpcEndpoint||""),{solPrice:F,isSolPriceLoading:L}=o.useGetSolPrice({enabled:u}),D=r.useMemo((()=>{let e,t;if(!g)return;let r=g.spender;0===C&&O?.address===r&&(e=o.getNativeCurrencyFromLamports(g.fee));let n=o.getNativeCurrencyFromLamports(x.value,3,!0),i=g.instructions[C];if(!i)return{fee:e,spender:r,balance:n};if("unknown"===i.type)return{fee:e,spender:r,program:i.program,balance:n};if("ata-creation"===i.type)return{fee:e,spender:r,balance:n,tokenAccountOwner:i.owner,tokenAccount:i.ata,tokenAddress:i.mint};let a=i.fromAccount,s="sol-transfer"===i.type?i.toAccount:i.toAccount||i.toAta,l="spl-transfer"===i.type?i.token.address:void 0;return null!=e&&"SOL"===i.token.symbol&&(t=o.getNativeCurrencyFromLamports(i.value+g.fee)),{fee:e,spender:r,from:a,to:s,tokenAddress:l,amount:`${P.formatUnits(i.value,i.token.decimals)} ${i.token.symbol}`.trim(),total:t,balance:n}}),[g,C,O?.address,x]),B=r.useMemo((()=>{let e,t;if(!g||!u||!F||L)return;function r(...e){return o.getDollarsFromLamport(e.reduce(((e,t)=>e+t),0n),F??0)}0===C&&O?.address===g.spender&&(e=r(g.fee));let n=r(x.value),i=g.instructions[C];return i&&"unknown"!==i.type&&"ata-creation"!==i.type?(null!=e&&"SOL"===i.token.symbol&&(t=r(i.value,g.fee)),{fee:e,amount:"SOL"===i.token.symbol?r(i.value):`${P.formatUnits(i.value,i.token.decimals)} ${i.token.symbol}`.trim(),total:t,balance:n}):{fee:e,balance:n}}),[g,u,F,L,O?.address,C,x]),H=r.useMemo((()=>{if(R||!g||x.isLoading||C>0)return!1;let e=g.instructions[C];if(!e)return!1;let t=0n;return O?.address===g.spender&&(t+=g.fee),"value"in e&&O?.address===e.fromAccount&&"SOL"===e.token.symbol&&(t+=e.value),x.value<t}),[g,x,C,R]);if(r.useEffect((()=>{!async function(){if(m&&j&&l)try{E(void 0);let e=await o.parseSolanaTransaction({tx:m,connection:j,client:l});v(e),A(0)}catch(e){console.error("Failed to prepare transaction",e),E(e)}}()}),[m,j,l]),r.useEffect((()=>{(async function(){if(!O||!j)return;T({value:x.value,isLoading:!0});let e=new q.SolanaClient({name:"mainnet-beta",rpcUrl:j.rpcEndpoint});T({value:await e.getBalance(O.address).catch((()=>0n))??0n,isLoading:!1})})().catch(console.error)}),[g,j]),!(m&&t?.sendSolanaTransaction&&O&&j)){let r=Error("Invalid transaction request");/*#__PURE__*/return e.jsx(o.ErrorScreenView,{error:r,onClick:()=>{t?.sendSolanaTransaction?.onFailure(r),c({shouldCallAuthOnSuccess:!1})}})}let z=()=>{if(!k)return S?t?.sendSolanaTransaction?.onSuccess(S):(t?.sendSolanaTransaction?.onFailure(b??f??Error("User exited the modal before submitting the transaction")),A(0)),c({shouldCallAuthOnSuccess:!1})};n.current=z;let V=t.sendSolanaTransaction?.uiOptions?.transactionInfo?.contractInfo?.imgUrl?/*#__PURE__*/e.jsx("img",{src:t.sendSolanaTransaction.uiOptions.transactionInfo.contractInfo.imgUrl,alt:t.sendSolanaTransaction.uiOptions.transactionInfo.contractInfo.imgAltText}):null,K=!!(t.funding&&t.funding.supportedOptions.length>0),$=H&&K;return S?/*#__PURE__*/e.jsx(bn,{instructions:g?.instructions.reduce(((e,t)=>("ata-creation"===t.type&&e.push({tokenAccountOwner:t.owner,tokenAccount:t.ata}),"spl-transfer"===t.type&&e.push({from:t.fromAccount,to:t.toAccount||t.toAta,amount:t.value,token:t.token}),"sol-transfer"===t.type&&e.push({from:t.fromAccount,to:t.toAccount,amount:t.value,token:t.token}),e)),[])??[],fees:0===C?S.fees:0n,onClose:z,transactionInfo:t.sendSolanaTransaction?.uiOptions.transactionInfo,solPrice:F,receiptHeader:t.sendSolanaTransaction?.uiOptions.successHeader,receiptDescription:t.sendSolanaTransaction?.uiOptions.successDescription,rpcEndpoint:j.rpcEndpoint,signOnly:R}):b?/*#__PURE__*/e.jsx(o.TransactionErrorView,{transactionError:b,connection:j,onClose:z,network:"solana",onRetry:async()=>{W(void 0);let{blockhash:e}=await j.getLatestBlockhash();o.isVersionedTransaction(m)?m.message.recentBlockhash=e:m.recentBlockhash=e,w(m)}}):/*#__PURE__*/e.jsx(o.SendSolanaTransactionScreenView,{img:V,title:t.sendSolanaTransaction?.uiOptions?.transactionInfo?.title||"Confirm transaction",subtitle:t.sendSolanaTransaction?.uiOptions?.description||`${h.name} wants your permission to approve the following transaction.`,cta:$?"Add funds":t.sendSolanaTransaction?.uiOptions?.buttonText||"Approve",transactionIndex:C,maxIndex:U-1,network:"mainnet-beta"==M?"Solana":M,blockExplorerUrl:"https://explorer.solana.com",total:u?B?.total:D?.total,amount:u?B?.amount:D?.amount,fee:u?B?.fee:D?.fee,balance:u?B?.balance:D?.balance,from:D?.from,to:D?.to,tokenAccount:D?.tokenAccount,tokenAccountOwner:D?.tokenAccountOwner,tokenAddress:D?.tokenAddress,transactingWalletAddress:O.address,programAddress:D?.program,disabled:H&&!K,isSubmitting:k,isPreparing:!g||x.isLoading,isTokenPriceLoading:u&&L,isMissingFunds:H,submitError:b??void 0,parseError:f,onClick:$?async()=>{if(O){if(!K)throw Error("Funding wallet is not enabled");i({...t,funding:{...t.funding,methodScreen:o.FundingMethodSelectionScreen}}),s(o.FundingMethodSelectionScreen)}}:async()=>{if(C<(g?.instructions.length??1)-1)A(C+1);else try{_(!0);let e=await y();if(k||!e||!O||!d||!p||!N)return;let{rootWallet:r}=o.getSolanaSigningAndRootWallet(p,O.address);if(!r)throw Error("No root wallet for transacting wallet found");let{entropyId:n,entropyIdVerifier:i}=o.getEntropyDetailsFromAccount(r);if(R)await sr({tx:m,accessToken:e,walletProxy:d,entropyId:n,entropyIdVerifier:i,transactingWalletAddress:O.address,transactingWalletIndex:O.walletIndex??0}),I(o.createSolanaTransactionReceipt("",m,null));else{let{signature:r,receipt:a}=await lr({tx:m,accessToken:e,connection:j,walletProxy:d,entropyId:n,entropyIdVerifier:i,transactingWalletAddress:O.address,transactingWalletIndex:O.walletIndex??0,transactionOptions:t.sendSolanaTransaction?.transactionOptions});I(o.createSolanaTransactionReceipt(r,m,a))}}catch(e){console.warn({transaction:m,error:e}),W(e)}finally{_(!1)}},onClose:z,onBack:C>0&&U>1?()=>A(C-1):void 0})}},On=/*#__PURE__*/r.forwardRef(((t,n)=>{let[i,s]=r.useState(""),[l,c]=r.useState(""),[d,u]=r.useState(!1),{authenticated:h,user:p}=o.usePrivyContext(),{initUpdateEmail:y}=a.usePrivyInternal(),{navigate:m,setModalData:w,currentScreen:g}=o.usePrivyModal(),{enabled:v,token:f}=o.useCaptcha(),E=o.useAppConfig(),C=o.validateEmail(i)&&(E.disablePlusEmails&&i.includes("+")?(l||c("Please enter a valid email address without a '+'."),!1):(l&&c(""),!0)),P=d||!C,A=()=>{!v||f||h?(async e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");u(!0);try{await y(p.email.address,i,e),m(o.AwaitingPasswordlessCodeScreen)}catch(e){w({errorModalData:{error:e,previousScreen:g||o.LandingScreen}})}u(!1)})(f):(w({captchaModalData:{callback:e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");return y(p.email.address,i,e)},userIntentRequired:!1,onSuccessNavigateTo:o.AwaitingPasswordlessCodeScreen,onErrorNavigateTo:o.ErrorScreen}}),m(o.CaptchaScreen))};/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsxs(Rn,{children:[l&&/*#__PURE__*/e.jsx(o.ErrorMessage$1,{style:{marginTop:"0.25rem",textAlign:"left"},children:l}),/*#__PURE__*/e.jsxs(Un,{$error:!!l,children:[/*#__PURE__*/e.jsx(ue.default,{}),/*#__PURE__*/e.jsx("input",{ref:n,id:"email-input",type:"email",placeholder:"your@email.com",onChange:e=>s(e.target.value),onKeyUp:e=>{"Enter"===e.key&&A()},value:i,autoComplete:"email"}),t.stacked?null:/*#__PURE__*/e.jsx(o.EmbeddedButton,{isSubmitting:d,onClick:A,disabled:P,children:"Submit"})]})]}),t.stacked?/*#__PURE__*/e.jsx(o.PrimaryButton,{loadingText:null,loading:d,disabled:P,onClick:A,children:"Submit"}):null]})}));let Rn=o.InputContainerForm,Un=o.EmailUpdateForm;const Nn={component:()=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(o.CenteredScreenHeader,{title:"Update your email",description:"Add the email address you'd like to use going forward. We'll send you a confirmation code",icon:/*#__PURE__*/e.jsx(ue.default,{color:"var(--privy-color-accent)",strokeWidth:2,height:"48px",width:"48px"})}),/*#__PURE__*/e.jsx(o.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(On,{stacked:!0})}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]})},Mn={component:()=>{let{currentScreen:t,data:r,navigate:n,setModalData:i}=o.usePrivyModal(),{user:s}=o.usePrivyContext(),{initUpdatePhone:l}=a.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.ModalHeader,{},"header"),/*#__PURE__*/e.jsx(o.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(o.CenteredScreenHeader,{title:"Update your phone number",description:"Add the phone number you'd like to use going forward. We'll send you a confirmation code",icon:/*#__PURE__*/e.jsx(re.default,{color:"var(--privy-color-accent)",strokeWidth:2,height:"48px",width:"48px"})}),/*#__PURE__*/e.jsx(o.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(o.ConnectPhoneNumberForm,{stacked:!0,onSubmit:async function({qualifiedPhoneNumber:e}){try{if(!s?.phone?.number)throw Error("User is required to have an phone number to update it.");await l(s?.phone?.number,e),n(o.AwaitingPasswordlessCodeScreen)}catch(e){i({errorModalData:{error:e,previousScreen:r?.errorModalData?.previousScreen||t||Qr}}),n(o.ErrorScreen)}},hideRecent:!0})}),/*#__PURE__*/e.jsx(o.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(o.BlobbyFooter,{})]})}};let Fn,Ln,Dn,Bn,qn,Hn,zn,Vn;async function Kn(){return Fn?Fn.getAccessToken():Promise.resolve(o.s.get(o.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||o.s.get(o.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const $n=(e,t)=>Ln(e,t),Yn=(e,t)=>Dn(e,t),Gn=(e,t)=>Bn(e,t),Xn=(e,t)=>qn(e,t),Jn=()=>Hn(),Qn=()=>zn(),Zn=({message:e,options:t})=>Vn({message:e,options:t});let ei=s=>{let l=s.client,c=o.usePlugins();cr();let[d,h]=r.useState(!1),[p,y]=r.useState(!1),[m,w]=r.useState(!1),[g,v]=r.useState(null),[f,E]=r.useState([]),[C,P]=r.useState([]),[A,x]=r.useState([]),[T,k]=r.useState(!1),[_,S]=r.useState(null),[I,W]=r.useState(!1),[j,O]=r.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:a.notImplemented}),[R,U]=r.useState({status:"initial"}),[N,M]=r.useState({status:"initial"}),[F,L]=r.useState({status:"initial"}),[D,B]=r.useState({status:"initial"}),[q,H]=r.useState({status:"initial"}),[z,V]=r.useState({status:"initial"}),[K,$]=r.useState(null),Y=o.useAppConfig(),G=o.useIsServerConfigLoaded(),[X,J]=r.useState({}),[Q,Z]=r.useState(null),[ee,te]=r.useState(null),[re,ne]=r.useState(!1),[ie,ae]=r.useState(!1),[oe,se]=r.useState(Y.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),le=r.useRef(null),ce=r.useRef(null),de=r.useRef(o.privyEventsDefault),[ue,he]=r.useState(!1);l.onStoreCustomerAccessToken=e=>{e&&o.emitPrivyEvent(de,"accessToken","onAccessTokenGranted",{accessToken:e})},l.onDeleteCustomerAccessToken=()=>{v(null),w(!1),o.emitPrivyEvent(de,"accessToken","onAccessTokenRemoved")};let pe=r.useRef(null),ye=r.useRef(null),me=r.useRef(!1),we=({showWalletUIs:e})=>me.current?me.current:void 0!==e?!e:!Y.embeddedWallets.showWalletUIs,ge=e=>{S(e),setTimeout((()=>{h(!0)}),15)};r.useEffect((()=>{let e=[...o.getPrivySolanaHDWallets(g),o.getImportedPrivySolanaWallet(g)].filter((e=>!!e));K&&x(e.map((e=>({type:"solana",imported:e.imported,address:e.address,connectedAt:Date.now(),walletClientType:"privy",connectorType:"embedded",walletIndex:e.walletIndex??void 0,meta:{name:"Privy Wallet",icon:void 0,id:"io.privy.solana.wallet"},linked:!0,fund(){throw new a.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:()=>{throw new a.PrivyClientError("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new or(K,e.address),async signMessage(t){let r=await Kn();if(!r||!K)throw new a.PrivyClientError("Must have valid access token and Privy wallet to send transaction",a.PrivyErrorCode.MUST_BE_AUTHENTICATED);let n=e.imported?o.getImportedPrivySolanaWallet(g):o.getPrivyPrimaryWallet(g);if(!n)throw new a.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:i,entropyIdVerifier:s}=o.getEntropyDetailsFromAccount(n);if(!await Ze.recoverPrimaryWallet().catch((()=>!1)))throw new a.PrivyClientError("Wallet couldn't be connected",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);if(!g)throw new a.PrivyClientError("Attempting to sign a transaction with no user initialized");let{response:l}=await K.rpc({accessToken:r,entropyId:i,entropyIdVerifier:s,chainType:"solana",hdWalletIndex:e.walletIndex??0,request:{method:"signMessage",params:{message:Buffer.from(t).toString("base64")}}});return Buffer.from(l.data.signature,"base64")},async sendTransaction(e,t,r){let{signature:n}=await Ke({transaction:e,connection:t,transactionOptions:r,wallet:this,signOnly:!1});return n},async signTransaction(t){let r=await Kn();if(!r||!K)throw new a.PrivyClientError("Must have valid access token and Privy wallet to send transaction",a.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await Ze.recoverPrimaryWallet().catch((()=>!1)))throw new a.PrivyClientError("Wallet couldn't be connected",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let n=e.imported?e:o.getPrivyPrimaryWallet(g);if(!n)throw new a.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:i,entropyIdVerifier:s}=o.getEntropyDetailsFromAccount(n);return await sr({tx:t,accessToken:r,walletProxy:K,entropyId:i,entropyIdVerifier:s,transactingWalletAddress:e.address,transactingWalletIndex:e.walletIndex??0}),t},async signAllTransactions(t){let r=await Kn();if(!r||!K)throw new a.PrivyClientError("Must have valid access token and Privy wallet to send transaction",a.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await Ze.recoverPrimaryWallet().catch((()=>!1)))throw new a.PrivyClientError("Wallet couldn't be connected",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let n=e.imported?e:o.getPrivyPrimaryWallet(g);if(!n)throw new a.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:i,entropyIdVerifier:s}=o.getEntropyDetailsFromAccount(n);for(let n of t)await sr({tx:n,accessToken:r,walletProxy:K,entropyId:i,entropyIdVerifier:s,transactingWalletAddress:e.address,transactingWalletIndex:e.walletIndex??0});return t},loginOrLink:async()=>{throw new a.PrivyClientError("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{},isConnected:async()=>!0}))))}),[K,g]),r.useEffect((()=>{if(!g)return void l.connectors?.removeEmbeddedWalletConnectors();let e=o.getPrivyEthereumWallet(g),t=o.getPrivyEthereumHDWallets(g),r=o.getImportedPrivyEthereumWallet(g);e&&t.length||l.connectors?.removeEmbeddedWalletConnectors(),r||l.connectors?.removeImportedWalletConnector(),l.connectors?K?(e&&l.connectors.addEmbeddedWalletConnectors({walletProxy:K,rootWallet:e,embeddedWallets:t,defaultChain:Y.defaultChain,appId:s.appId}),r&&l.connectors.addImportedWalletConnector(K,r.address,Y.defaultChain,s.appId)):console.debug("Failed to add embedded wallet connector: Wallet proxy not initialized"):console.debug("Failed to add embedded wallet connector: Client connectors not initialized")}),[K,g]),r.useEffect((()=>{K&&ee?.(K)}),[K]);let ve=r.useRef();r.useEffect((()=>{(async()=>{if(!Y.customAuth?.enabled)return void se({status:"not-enabled"});let{getCustomAccessToken:e,isLoading:t}=Y.customAuth;if(p&&!t&&"loading"!==oe.status){se({status:"loading"});try{let t=await e();if(t===ve.current)return void se({status:"done"});if(!t&&m)return ve.current=t,await Qe.logout(),se({status:"done"}),void o.emitPrivyEvent(de,"customAuth","onUnauthenticated");if(!t)return ve.current=t,void se({status:"done"});l.startAuthFlow(new xe(t));let{user:r,isNewUser:n}=await l.authenticate();if(!r)return await Qe.logout(),se({status:"error",error:new a.PrivyClientError("Failed to sync with custom auth provider")}),void o.emitPrivyEvent(de,"customAuth","onUnauthenticated");void 0!==n&&o.emitPrivyEvent(de,"login","onComplete",{user:r,isNewUser:n,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),ve.current=t,o.emitPrivyEvent(de,"customAuth","onAuthenticated",{user:r}),se({status:"done"}),v(r||null),k(n||!1),w(!0),ae(!0)}catch(e){if(console.warn(e),await Qe.logout(),o.emitPrivyEvent(de,"customAuth","onUnauthenticated"),"User already exists with provided custom JWT account."===e.message)return void se({status:"initial"});o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),se({status:"error",error:e})}}})()}),["initial"===oe.status,Y.customAuth?.enabled,Y.customAuth?.getCustomAccessToken,Y.customAuth?.isLoading,p,m]),r.useEffect((()=>{ie&&K&&g&&(async()=>{let e=o.shouldCreateEmbeddedEthWallet(g,Y.embeddedWallets.ethereum.createOnLogin),t=o.shouldCreateEmbeddedSolWallet(g,Y.embeddedWallets.solana.createOnLogin),r=await Kn();if(r){if(e&&t){let e=await De(g,o.WALLET_PROXY_TIMEOUT);return await K.createSolana({accessToken:r,ethereumAddress:e?.address}),void ae(!1)}if(t)return await K.createSolana({accessToken:r,ethereumAddress:o.getPrivyEthereumWallet(g)?.address}),await Ze.refreshSessionAndUser(),void ae(!1);if(e)return await De(g,o.WALLET_PROXY_TIMEOUT),void ae(!1)}})().catch(console.error)}),[ie&&K&&g]),r.useEffect((()=>{if(Y.externalWallets.solana.connectors)return Y.externalWallets.solana.connectors.onMount(),()=>Y.externalWallets.solana.connectors?.onUnmount()}),[Y.externalWallets.solana.connectors]),r.useEffect((()=>{!p&&G&&async function(){let e,r=fe(),n=Ee(),i=t.createStore();l.initializeConnectorManager({walletConnectCloudProjectId:Y.walletConnectCloudProjectId,rpcConfig:Y.rpcConfig,chains:Y.chains,defaultChain:Y.defaultChain,store:i,walletList:Y.appearance.walletList,shouldEnforceDefaultChainOnConnect:Y.shouldEnforceDefaultChainOnConnect,externalWalletConfig:Y.externalWallets,appName:Y.name??"Privy",walletChainType:Y.appearance.walletChainType}),l.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=l.connectors.walletConnectors.length,r=l.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?he(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),he(!0)}),1500)})),l.connectors?.initialize().then((()=>{We()}));let a=await l.getAuthenticatedUser(),s=!!a;Y.legal.requireUsersAcceptTerms&&a&&!a.hasAcceptedTerms?(await l.logout(),Ze.setReadyToTrue(!0),o.emitPrivyEvent(de,"logout","onSuccess")):(Y.customAuth?.enabled||(w(!!a),a&&o.emitPrivyEvent(de,"login","onComplete",{user:a,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),v(a)),r?ye.current=s?"link":"login":n&&!s?(ye.current="login",J({telegramAuthModalData:{seamlessAuth:!0}}),ge(o.TelegramAuthScreen)):Ze.setReadyToTrue(!!a))}()}),[l,Q,p,G]),r.useEffect((()=>{if(p){if(!g||!g.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void ne(!0);ne([...f,...A].some((e=>"privy"===e.walletClientType)))}}),[p,g,f,A]),r.useEffect((()=>{l.connectors?.setWalletList(Y.appearance.walletList)}),[Y.appearance.walletList.join()]);let fe=()=>{let e=Re();return e.inProgress&&e.popupFlow?window.opener.location.origin!==window.location.origin?void window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Origins between parent and child windows do not match."}):"error"===e.authorizationCode?void window.opener.postMessage({type:"PRIVY_OAUTH_ERROR",error:"Something went wrong. Try again."}):void window.opener.postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}):(e.inProgress&&function(e){return e.startsWith("privy:")}(e.provider)&&!e.popupFlow&&(new BroadcastChannel(dr).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(l.startAuthFlow(new be(e)),ge(Cn),!0))},Ee=()=>{let e=o.detectCompletingTelegramFlow();if(!e||!Y.loginMethods.telegram||!Y.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new o.TelegramAuthFlow;return l.startAuthFlow(t),"login-url"===e.flowType&&(t.meta.telegramWebAppData=void 0,t.meta.telegramAuthResult=e.authData),"web-app"===e.flowType&&(t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=e.authData),!0},Ce=async(e,t,r,n)=>{if("solana_adapter"!==e)Pe(await(l.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,n);else{let e=l.connectors?.findSolanaWalletConnector(t);if(!e)return;Pe(e,t,r,n)}};async function Pe(e,t,r,n){if(!e)return O({status:"disconnected",connectedWallet:null,connectError:new a.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:a.notImplemented}),n?.(null,r);O({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:a.notImplemented}),e instanceof o.WalletConnectV2WalletConnector&&t&&await e.resetConnection(t),O({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Pe(e,t,r,n)});try{let t=await e.connect({showPrompt:!0});if((!t||o.isBaseConnectedEthereumWallet(t))&&Y.shouldEnforceDefaultChainOnConnect&&!Y.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){O((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:a.notImplemented})));try{await(t?.switchChain(Y.defaultChain.id)),t&&(t.chainId=o.formatChainIdToCAIP2(o.toHex(Y.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${Y.defaultChain.id}`)}}return O((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:a.notImplemented}))),t&&o.emitPrivyEvent(de,"connectWallet","onSuccess",{wallet:t}),n?.(t,r)}catch(e){return e instanceof a.PrivyError?(console.warn(e.cause?e.cause:e.message),o.emitPrivyEvent(de,"connectWallet","onError",e.privyErrorCode||a.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),o.emitPrivyEvent(de,"connectWallet","onError",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),O((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Ae=async(e,t,r)=>{if(null===e||!o.isBaseConnectedEthereumWallet(e))return;let n=new o.SiweFlow(e,l,t,r);l.startAuthFlow(n)},Te=async(e,t,r)=>{if(null===e||!u.isBaseConnectedSolanaWallet(e))return;let n=new o.SiwsFlow(e,l,t,r);l.startAuthFlow(n)},We=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client"),n="true"===e.get("privy_connect_only");if(!t||!r)return;let i=o.getWalletConfigForConnector({connectorType:t,walletClientType:r});if(!i||!i.isInstalled)return ge(tn);if(!l.connectors)throw new a.PrivyClientError("Connector not initialized");ge(n?o.ConnectOnlyStatusScreen:o.ConnectionStatusScreen);let s=new URL(window.location.href);s.searchParams.delete("privy_connector"),s.searchParams.delete("privy_wallet_client"),s.searchParams.delete("privy_connect_only"),window.history.pushState({},"",s),Ce(t,r,void 0,n?void 0:"solana_adapter"===t?Te:Ae)};r.useEffect((()=>{p&&m&&null===g&&l.getAuthenticatedUser().then(v)}),[p,m,g,l]);let je=e=>{if(!m)throw o.emitPrivyEvent(de,"linkAccount","onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new a.PrivyClientError("User must be authenticated before linking an account.")},Oe=e=>{if(!m||!g)return!1;if("privy"===e.walletClientType)return!0;for(let t of g.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},Fe=async e=>{let t;if(!l.connectors)throw new a.PrivyClientError("Connector not initialized");t="ethereum"===e.type?l.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:l.connectors.findSolanaWalletConnector(e.walletClientType)||null,O((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:a.notImplemented}))),Y.captchaEnabled&&!m?(J({captchaModalData:{callback:t=>o.isBaseConnectedEthereumWallet(e)?Ae(e,t):Te(e,t),userIntentRequired:!1,onSuccessNavigateTo:o.ConnectionStatusScreen,onErrorNavigateTo:o.ErrorScreen}}),ge(o.CaptchaScreen)):(o.isBaseConnectedEthereumWallet(e)?await Ae(e):await Te(e),ge(o.ConnectionStatusScreen))},Le=()=>{E((e=>{let t=l.connectors?.wallets.filter(o.isBaseConnectedEthereumWallet).map((e=>({...e,linked:Oe(e),loginOrLink:async()=>{if(!await e.isConnected())throw new a.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new a.PrivyClientError("Cannot link or login with embedded wallet");Fe(e)},fund:async t=>{await Ze.fundWallet(e.address,t)},unlink:async()=>{if(!m)throw new a.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new a.PrivyClientError("Cannot unlink an embedded wallet");v(await l.unlinkEthereumWallet(e.address))}})))||[];return o.areWalletArraysEqual(e,t)?e:t})),P((e=>{let t=(l.connectors?.wallets??[]).filter(u.isBaseConnectedSolanaWallet).map((e=>({...e,linked:Oe(e),loginOrLink:async()=>{if(!await e.isConnected())throw new a.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new a.PrivyClientError("Cannot link or login with embedded wallet");Fe(e)},fund:async()=>{throw new a.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:async()=>{if(!m)throw new a.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new a.PrivyClientError("Cannot unlink an embedded wallet");v(await l.unlinkSolanaWallet(e.address))}})));return o.areWalletArraysEqual(e,t)?e:t}))};r.useEffect((()=>{Le()}),[g?.linkedAccounts,m,p]),r.useEffect((()=>{if(p){if(!l.connectors)throw new a.PrivyClientError("Connector not initialized");Le(),l.connectors.on("walletsUpdated",Le)}}),[p]),r.useEffect((()=>{[...Y.loginMethodsAndOrder?.primary??[],...Y.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>l.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!l]);let De=async(e,t,r)=>{let n=o.getPrivyEthereumWallet(e),i=o.getPrivySolanaWallet(e);if(r&&"walletIndex"in r&&"number"==typeof r.walletIndex)return qe(e,t,r.walletIndex,n,i);let s=r&&"createAdditional"in r&&r.createAdditional;if(n&&!s)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[l,c]=await Promise.all([Ze.initializeWalletProxy(t),Kn()]);if(!l&&Y.customAuth?.enabled)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!l||!c||Y.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return Be();if(!n)return i&&await Ze.recoverPrimaryWallet(),await l.create({accessToken:c,solanaAddress:i?.address}),ze(0,"ethereum");{let t=(o.getLatestPrivyEthereumWallet(e)?.walletIndex??0)+1,{entropyId:r,entropyIdVerifier:n}=o.getEntropyDetailsFromAccount(o.getPrivyPrimaryWallet(e));return await Ze.recoverPrimaryWallet(),await l.addWallet({accessToken:c,entropyId:r,entropyIdVerifier:n,chainType:"ethereum",hdWalletIndex:t}),ze(t,"ethereum")}},Be=async()=>new Promise(((e,t)=>{J({createWallet:{onSuccess:t=>{o.emitPrivyEvent(de,"createWallet","onSuccess",{wallet:t}),e(t)},onFailure:e=>{o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),ge(o.EmbeddedWalletOnAccountCreateScreen)})),qe=async(e,t,r,n,i)=>{if(r<0)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${r}) is invalid.`);let[s,l]=await Promise.all([Ze.initializeWalletProxy(t),Kn()]);if(!s&&Y.customAuth?.enabled)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!s||!l||Y.embeddedWallets?.requireUserOwnedRecoveryOnCreate){if(0==r)return Be();throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Create wallet UI can only be displayed when walletIndex is 0.")}if(0==r){if(n)return n;await s.create({accessToken:l,solanaAddress:i?.address})}else{if(!n)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error("A user must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let t=o.getPrivyEthereumHDWallets(e).find((e=>e.walletIndex===r));if(t)return t;let{entropyId:i,entropyIdVerifier:c}=o.getEntropyDetailsFromAccount(o.getPrivyPrimaryWallet(e));await Ze.recoverPrimaryWallet(),await s.addWallet({accessToken:l,entropyId:i,entropyIdVerifier:c,chainType:"ethereum",hdWalletIndex:r})}return ze(r,"ethereum")},He=async({user:e,wp:t,accessToken:r,walletIndex:n,ethereumWallet:i})=>{let s=o.getPrivySolanaHDWallets(e).find((e=>e.walletIndex===n));if(s)return s;if(0===n)i&&await Ze.recoverPrimaryWallet(),await t.createSolana({accessToken:r,ethereumAddress:i?.address});else{let i=o.getPrivyPrimaryWallet(e);if(!i)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error("User must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let{entropyId:s,entropyIdVerifier:l}=o.getEntropyDetailsFromAccount(i);await Ze.recoverPrimaryWallet(),await t.addWallet({accessToken:r,entropyId:s,entropyIdVerifier:l,chainType:"solana",hdWalletIndex:n})}return ze(n,"solana")},ze=async(e,t)=>{let r=await Ze.refreshSessionAndUser(),n=("ethereum"===t?o.getPrivyEthereumHDWallets(r):o.getPrivySolanaHDWallets(r)).find((t=>t.walletIndex===e));if(!n)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return o.emitPrivyEvent(de,"createWallet","onSuccess",{wallet:n}),n},Ve=({transaction:e,uiOptions:t,fundWalletConfig:r,address:n,signOnly:l})=>new Promise((async(c,d)=>{let{requesterAppId:h}=t||{},p=l?"signTransaction":"sendTransaction";if(!m||!g)return o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED),void d(Error("User must be authenticated before signing with a Privy wallet"));let y=n??o.getPrivyEthereumWallet(g)?.address;if(!y)throw new a.PrivyClientError("User must have an embedded wallet to send a transaction.");let{signingWallet:w,rootWallet:v}=o.getEthereumSigningAndRootWallet(g,y);if(!v||!w)return o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void d(Error("Must have a Privy wallet before signing"));let f=et.wallets.find((e=>"privy"===e.walletClientType&&i.getAddress(e.address)===i.getAddress(w.address))),E=await(f?.getEthereumProvider());if(!f||!E)throw new a.PrivyClientError(`Cannot sendTransaction before embedded wallet ${w.address} is connected`);let C=e.chainId?Number(e.chainId):u.extractChainIdFromCAIP2(f.chainId);(e=>{if(!Y.chains.map((e=>e.id)).includes(e))throw new a.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,a.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(C);let P={...e,from:e.from??w.address,chainId:C},A=await Kn();if(!A||!K)return o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void d(Error("Must have valid access token and Privy wallet to send transaction"));let x=o.getPublicClient(P.chainId,Y.chains,Y.rpcConfig,{appId:s.appId});if(we({showWalletUIs:t?.showWalletUIs}))(async()=>{try{if(!await Ze.recoverPrimaryWallet())return o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void d(Error("Unable to connect to wallet"));let e=await o.prepareTransactionRequest(P,x,P.from),{entropyId:t,entropyIdVerifier:r}=o.getEntropyDetailsFromAccount(v),n=l?await o.signTransaction({accessToken:A,entropyId:t,entropyIdVerifier:r,transactingWallet:w,walletProxy:K,transactionRequest:P,requesterAppId:h}):await o.sendTransaction({accessToken:A,entropyId:t,entropyIdVerifier:r,transactingWallet:w,walletProxy:K,transactionRequest:e,publicClient:x,requesterAppId:h});l?o.emitPrivyEvent(de,"signTransaction","onSuccess",{signature:n}):o.emitPrivyEvent(de,"sendTransaction","onSuccess",{hash:n}),c({hash:n})}catch(e){o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.TRANSACTION_FAILURE),d(e)}})();else{let{entropyId:e,entropyIdVerifier:n}=o.getEntropyDetailsFromAccount(v),i=Ur(Y)?u.prepareFundingModalData({address:w.address,appConfig:Y,fundWalletConfig:r,methodScreen:o.FundingMethodSelectionScreen,chainIdOverride:P.chainId,comingFromSendTransactionScreen:!0}):void 0;J({connectWallet:{entropyId:e,entropyIdVerifier:n,onCompleteNavigateTo:o.SendTransactionScreen,onFailure:e=>{o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),d(e)}},sendTransaction:{transactionRequest:P,transactingWallet:w,entropyId:e,entropyIdVerifier:n,signOnly:l,onConfirm:l?async()=>await o.signTransaction({accessToken:A,entropyId:e,entropyIdVerifier:n,transactingWallet:w,walletProxy:K,transactionRequest:P,requesterAppId:h}):void 0,onSuccess:e=>{l?o.emitPrivyEvent(de,"signTransaction","onSuccess",{signature:e.hash}):o.emitPrivyEvent(de,"sendTransaction","onSuccess",{hash:e.hash}),c(e)},onFailure:e=>{o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.TRANSACTION_FAILURE),d(e)},uiOptions:t||{},fundWalletConfig:r,requesterAppId:h},funding:i}),ge(b.EmbeddedWalletConnectingScreen)}})),Ke=({transaction:e,connection:t,transactionOptions:r,fundWalletConfig:n,uiOptions:i,wallet:s,signOnly:l})=>new Promise((async(c,d)=>{let{requesterAppId:h}=i||{},p=l?"signSolanaTransaction":"sendSolanaTransaction";if(!m||!g)return o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED),void d(new a.PrivyClientError("User must be authenticated before signing with a Privy wallet",a.PrivyErrorCode.MUST_BE_AUTHENTICATED));let y=s?g.linkedAccounts.find((e=>"wallet"===e.type&&e.address===s.address)):o.getPrivySolanaWallet(g);if(!y)return o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void d(new a.PrivyClientError("Must have a Privy wallet before signing",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));let{rootWallet:w}=o.getSolanaSigningAndRootWallet(g,y.address);if(!await Ze.recoverPrimaryWallet().catch((()=>!1))||!w)throw o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new a.PrivyClientError(`Cannot sendSolanaTransaction before embedded wallet ${y.address} is connected`,a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);if(we({showWalletUIs:i?.showWalletUIs}))(async()=>{let n=await Kn();if(!n||!K)return o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void d(new a.PrivyClientError("Must have valid access token and Privy wallet to send transaction",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));try{let s;if(!await Ze.recoverPrimaryWallet())return o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void d(new a.PrivyClientError("Unable to connect to wallet",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR));if(we({showWalletUIs:i?.showWalletUIs})&&!l)try{if(!await o.hasSufficientFunds(e,t))return o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.INSUFFICIENT_BALANCE),void d(new a.PrivyClientError("Solana wallet has insufficient funds for this transaction.",a.PrivyErrorCode.INSUFFICIENT_BALANCE))}catch(e){return console.error(e),o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.TRANSACTION_FAILURE),void d(new a.PrivyClientError(e instanceof Error?e.message:"Transaction failed.",a.PrivyErrorCode.TRANSACTION_FAILURE))}let{entropyId:u,entropyIdVerifier:h}=o.getEntropyDetailsFromUser(g);if(l)await sr({accessToken:n,tx:e,walletProxy:K,entropyId:u,entropyIdVerifier:h,transactingWalletAddress:y.address,transactingWalletIndex:y.walletIndex??0}),s=o.createSolanaTransactionReceipt("",e,null),o.emitPrivyEvent(de,"signSolanaTransaction","onSuccess",{signedTransaction:e});else{let{signature:i,receipt:a}=await lr({accessToken:n,tx:e,connection:t,walletProxy:K,transactionOptions:r,entropyId:u,entropyIdVerifier:h,transactingWalletAddress:y.address,transactingWalletIndex:y.walletIndex??0});s=o.createSolanaTransactionReceipt(i,e,a),o.emitPrivyEvent(de,"sendSolanaTransaction","onSuccess",{response:s})}c(s)}catch(e){o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.TRANSACTION_FAILURE),d(e)}})();else{let{entropyId:s,entropyIdVerifier:m}=o.getEntropyDetailsFromAccount(w),g=Ur(Y)?u.prepareSolanaFundingModalData({address:y.address,appConfig:Y,methodScreen:o.FundingMethodSelectionScreen,fundWalletConfig:n,comingFromSendTransactionScreen:!0}):void 0;J({connectWallet:{entropyId:s,entropyIdVerifier:m,onCompleteNavigateTo:jn,onFailure:e=>{o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),d(e)}},sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:r,transactingWallet:y,onSuccess:e=>{l?o.emitPrivyEvent(de,"signSolanaTransaction","onSuccess",{signedTransaction:e.signedTransaction}):o.emitPrivyEvent(de,"sendSolanaTransaction","onSuccess",{response:e}),c(e)},onFailure:e=>{o.emitPrivyEvent(de,p,"onError",a.PrivyErrorCode.TRANSACTION_FAILURE),d(e)},uiOptions:i||{},requesterAppId:h,signOnly:l},funding:g}),ge(b.EmbeddedWalletConnectingScreen)}}));function $e(){return new Promise((async(e,t)=>{let r=await Kn();if(!r||!K)throw Error("Must have valid access token to enroll in MFA");try{await K.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let Ye=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],Ge=e=>{let t=g?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=o.toDisplayFromAccountType(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw o.emitPrivyEvent(de,"linkAccount","onError",a.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:n}),new a.PrivyClientError(`User already has an account of type ${r} linked.`)};async function Xe({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){S(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!m||!g)throw o.emitPrivyEvent(de,r,"onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=o.getPrivyPrimaryWallet(g);if(!n||!K)throw o.emitPrivyEvent(de,r,"onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");try{await $e()}catch(e){throw o.emitPrivyEvent(de,r,"onError",a.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((i,s)=>{let l={onSuccess:e=>{o.emitPrivyEvent(de,r,"onSuccess",{method:"user-passcode",wallet:e}),i(e)},onFailure:e=>{o.emitPrivyEvent(de,r,"onError",a.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),s(e)},callAuthOnSuccessOnClose:!1},c="user-passcode"===n.recoveryMethod,d=o.toEmbeddedWalletSetRecoveryScreen({walletAction:"update",availableRecoveryMethods:Y.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:c,showAutomaticRecovery:e}),{entropyId:u,entropyIdVerifier:h}=o.getEntropyDetailsFromAccount(n);J({setWalletPassword:l,recoverWallet:{entropyId:u,entropyIdVerifier:h,onFailure:s},createWallet:l,connectWallet:{onCompleteNavigateTo:d,shouldForceMFA:!1,entropyId:u,entropyIdVerifier:h,onFailure:e=>{o.emitPrivyEvent(de,r,"onError",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:c}}),ge(b.EmbeddedWalletConnectingScreen)}))}async function Je({appId:e,action:t}){let r=await Kn();if("link"===t&&!r)throw o.emitPrivyEvent(de,"linkAccount","onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new a.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw o.emitPrivyEvent(de,"login","onError",a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new a.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");pe.current=`privy:${e}`,ye.current=t;let n=o.triggerPopup();return l.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,i)=>{let{name:a,logoUrl:o}=await pr({api:l.api,providerAppId:e,requesterAppId:Y.id});J({crossAppAuth:{appId:e,name:a,logoUrl:o,action:t,popup:n,onSuccess:r,onError:i}}),ge(Fr)}))}let Qe={ready:p,authenticated:m,user:g,walletConnectors:l.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),J({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress,walletChainType:e?.walletChainType}}),ge(m?Mr:o.ConnectOnlyLandingScreen)},linkWallet:e=>{e&&"target"in e&&e&&(e=void 0),je("siwe"),pe.current="siwe",ye.current="link",J({...X,externalConnectWallet:{...X.externalConnectWallet,suggestedAddress:e?.suggestedAddress,walletList:e?.walletList,walletChainType:e?.walletChainType}}),ge(Zr)},startCrossAppAuthFlow:Je,linkEmail:()=>{je("email"),Ge("email"),pe.current="email",ye.current="link",ge(Jr)},linkPhone:()=>{je("sms"),Ge("phone"),pe.current="sms",ye.current="link",ge(Qr)},linkGoogle:async()=>{je("google"),Ge("google_oauth"),ye.current="link",await Ze.initLoginWithOAuth("google")},linkTwitter:async()=>{je("twitter"),Ge("twitter_oauth"),ye.current="link",await Ze.initLoginWithOAuth("twitter")},linkDiscord:async()=>{je("discord"),Ge("discord_oauth"),ye.current="link",await Ze.initLoginWithOAuth("discord")},linkGithub:async()=>{je("github"),Ge("github_oauth"),ye.current="link",await Ze.initLoginWithOAuth("github")},linkSpotify:async()=>{je("spotify"),Ge("spotify_oauth"),ye.current="link",await Ze.initLoginWithOAuth("spotify")},linkInstagram:async()=>{je("instagram"),Ge("instagram_oauth"),ye.current="link",await Ze.initLoginWithOAuth("instagram")},linkTiktok:async()=>{je("tiktok"),Ge("tiktok_oauth"),ye.current="link",await Ze.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{je("linkedin"),Ge("linkedin_oauth"),ye.current="link",await Ze.initLoginWithOAuth("linkedin")},linkApple:async()=>{je("apple"),Ge("apple_oauth"),ye.current="link",await Ze.initLoginWithOAuth("apple")},linkPasskey:async()=>{je("passkey"),Ge("passkey"),await Ze.initLinkWithPasskey(),ge(fr)},linkTelegram:async e=>{if(je("telegram"),Ge("telegram"),ye.current="link",pe.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new o.TelegramAuthFlow;l.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=o.convertInitDataRawToTelegramWebAppData(e.launchParams.initDataRaw),J({telegramAuthModalData:{seamlessAuth:!0}}),ge(o.TelegramAuthScreen)}else o.emitPrivyEvent(de,"linkAccount","onError",a.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await Ze.initLoginWithTelegram();ge(o.TelegramAuthScreen)},linkFarcaster:async()=>{je("farcaster"),Ge("farcaster"),await Ze.initLoginWithFarcaster(),ye.current="link",pe.current="farcaster",ge(o.FarcasterConnectStatusScreen)},updateEmail:()=>{if(je("email"),!g?.email)throw new a.PrivyClientError("User does not have an email linked to their account.");ye.current="update",pe.current="email",ge(Nn)},updatePhone:()=>{if(je("sms"),!g?.phone)throw new a.PrivyClientError("User does not have a phone number linked to their account.");ye.current="update",pe.current="sms",ge(Mn)},login:async e=>{e&&"target"in e&&e&&(e=void 0);let t="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!p){let e=await new Promise((e=>{Z((t=>e.bind(t)))}));if(Z(null),e)return void console.warn(t)}!g||g.isGuest?(ye.current="login",J({login:e}),ge(o.LandingScreen)):console.warn(t)},connectOrCreateWallet:async()=>{p||(await new Promise((e=>{Z((()=>e))})),Z(null)),m?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(ye.current="login",ge(o.ConnectOrCreateScreen))},logout:async()=>{if(ye.current=null,pe.current=null,g&&l.clearProviderAcccessTokens(g),S(null),await l.logout(),g&&K)try{await K.clearMfa({userId:g.id})}catch(e){}v(null),w(!1),o.emitPrivyEvent(de,"logout","onSuccess"),h(!1),o.s.del(o.CLIENT_ANALYTICS_ID_KEY),o.s.del(o.getGuestCredentialStorageKey(Y.id))},getAccessToken:r.useCallback((()=>l.getCustomerAccessToken()),[l]),unlinkWallet:async e=>{let t;return v(t=e.startsWith("0x")?await l.unlinkEthereumWallet(e):await l.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await l.unlinkEmail(e);return v(t),t},unlinkPhone:async e=>{let t=await l.unlinkPhone(e);return v(t),t},unlinkGoogle:async e=>{let t=await l.unlinkOAuth("google",e);return v(t),t},unlinkTwitter:async e=>{let t=await l.unlinkOAuth("twitter",e);return v(t),t},unlinkDiscord:async e=>{let t=await l.unlinkOAuth("discord",e);return v(t),t},unlinkGithub:async e=>{let t=await l.unlinkOAuth("github",e);return v(t),t},unlinkSpotify:async e=>{let t=await l.unlinkOAuth("spotify",e);return v(t),t},unlinkInstagram:async e=>{let t=await l.unlinkOAuth("instagram",e);return v(t),t},unlinkTiktok:async e=>{let t=await l.unlinkOAuth("tiktok",e);return v(t),t},unlinkLinkedIn:async e=>{let t=await l.unlinkOAuth("linkedin",e);return v(t),t},unlinkApple:async e=>{let t=await l.unlinkOAuth("apple",e);return v(t),t},unlinkFarcaster:async e=>{let t=await l.unlinkFarcaster(e);return v(t),t},unlinkTelegram:async e=>{let t=await l.unlinkTelegram(e);return v(t),t},unlinkPasskey:async e=>{let t=await Kn();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!K)throw Error("Wallet proxy not initialized.");let r=Y.passkeys.shouldUnenrollMfaOnUnlink;await K.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let n=await l.getAuthenticatedUser();return v(n),n},unlinkCrossAppAccount:async({subject:e})=>{let t=g?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new a.PrivyClientError("Invalid subject");l.storeProviderAccessToken(t.id,null);let r=await l.unlinkOAuth(`privy:${t.id}`,e);return v(r),r},createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let t=await Ze.refreshSessionAndUser();if(!t)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return De(t,15e3,e)},setWalletRecovery:async e=>Xe({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>Xe({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(r,n)=>{let{requesterAppId:i}=t?.uiOptions||{},s=e.message;if(!m||!g)return o.emitPrivyEvent(de,"signMessage","onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let c=t?.address??o.getPrivyEthereumWallet(g)?.address;if(!c)throw new a.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:d,rootWallet:u}=o.getEthereumSigningAndRootWallet(g,c);if(!d||!u)return o.emitPrivyEvent(de,"signMessage","onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));if("string"!=typeof s||s.length<1)return o.emitPrivyEvent(de,"signMessage","onError",a.PrivyErrorCode.INVALID_MESSAGE),void n(Error("Message must be a non-empty string"));let h=async()=>{if(!m)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Kn();if(!K||!e||!await Ze.recoverPrimaryWallet())throw Error("Unable to connect to wallet");l.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:d.address,requesterAppId:i}});let{entropyId:t,entropyIdVerifier:r}=o.getEntropyDetailsFromAccount(u),{response:n}=await K.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:d.walletIndex??0,requesterAppId:i,request:{method:"personal_sign",params:[s,d.address]}}),a=n.data;return l.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:d.address,requesterAppId:i}}),a};if(we({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await h();o.emitPrivyEvent(de,"signMessage","onSuccess",{signature:e}),r({signature:e})}catch(e){o.emitPrivyEvent(de,"signMessage","onError",a.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new o.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"personal_sign",data:s,confirmAndSign:h,onSuccess:e=>{o.emitPrivyEvent(de,"signMessage","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{o.emitPrivyEvent(de,"signMessage","onError",a.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t?.uiOptions||{}},{entropyId:i,entropyIdVerifier:l}=o.getEntropyDetailsFromAccount(u);J({signMessage:e,connectWallet:{entropyId:i,entropyIdVerifier:l,onCompleteNavigateTo:b.SignRequestScreen,onFailure:e=>{o.emitPrivyEvent(de,"signMessage","onError",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),ge(b.EmbeddedWalletConnectingScreen)}})),signTypedData:(e,t)=>new Promise((async(r,n)=>{let{requesterAppId:i}=t?.uiOptions||{};if(!m||!g)return o.emitPrivyEvent(de,"signTypedData","onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let s=t?.address??o.getPrivyEthereumWallet(g)?.address;if(!s)throw new a.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:c,rootWallet:d}=o.getEthereumSigningAndRootWallet(g,s);if(!d||!c)return o.emitPrivyEvent(de,"signTypedData","onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));let u=o.generateTypedDataWithDomainType(e),h=async()=>{if(!m)throw Error("User must be authenticated before signing with a Privy wallet");let e=await Kn();if(!K||!e||!await Ze.recoverPrimaryWallet())throw Error("Unable to connect to wallet");l.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:c.address,requesterAppId:i}});let{entropyId:t,entropyIdVerifier:r}=o.getEntropyDetailsFromAccount(d),{response:n}=await K.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:c.walletIndex??0,requesterAppId:i,request:{method:"eth_signTypedData_v4",params:[c.address,u]}}),a=n.data;return l.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:c.address,requesterAppId:i}}),a};if(we({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await h();o.emitPrivyEvent(de,"signTypedData","onSuccess",{signature:e}),r({signature:e})}catch(e){o.emitPrivyEvent(de,"signTypedData","onError",a.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new o.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"eth_signTypedData_v4",data:u,confirmAndSign:h,onSuccess:e=>{o.emitPrivyEvent(de,"signTypedData","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{o.emitPrivyEvent(de,"signTypedData","onError",a.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t?.uiOptions||{}},{entropyId:i,entropyIdVerifier:s}=o.getEntropyDetailsFromAccount(d);J({signMessage:e,connectWallet:{entropyId:i,entropyIdVerifier:s,onCompleteNavigateTo:b.SignRequestScreen,onFailure:e=>{o.emitPrivyEvent(de,"signMessage","onError",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),ge(b.EmbeddedWalletConnectingScreen)}})),sendTransaction:async(e,t)=>await Ve({transaction:e,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await Ve({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:e=>new Promise((async(t,r)=>{if(!m||!g)return void r(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let n=e?.address??o.getPrivyEthereumWallet(g)?.address;if(!n)return void r(Error("User does not have an HD Ethereum wallet. To export an imported wallet, pass the `address` of the wallet to `exportWallet`."));if(!i.isAddress(n))return void r(Error("Must provide a valid Ethereum address."));let{signingWallet:a,rootWallet:c}=o.getEthereumSigningAndRootWallet(g,n);if(!a||!c)return void r(Error("Must have a Privy wallet before exporting"));let{entropyId:d,entropyIdVerifier:u}=o.getEntropyDetailsFromAccount(c);J(X),await Kn()&&K?K?(J({keyExport:{appId:s.appId,appClientId:s.clientId,origin:l.apiUrl,walletToExport:a,primaryWallet:c,onSuccess:t,onFailure:r},connectWallet:{entropyId:d,entropyIdVerifier:u,onCompleteNavigateTo:b.EmbeddedWalletKeyExportScreen,onFailure:r,shouldForceMFA:!0}}),ge(b.EmbeddedWalletConnectingScreen)):r(Error("Must have a Privy wallet before exporting")):r(Error("Must have valid access token to enroll in MFA"))})),promptMfa:$e,async init(e){switch(e){case"sms":return void await l.initMfaSmsVerification();case"passkey":return await l.initMfaPasskeyVerification();case"totp":return;default:throw Error(`Unsupported MFA method: ${e}`)}},async submit(e,t){switch(e){case"totp":case"sms":if("string"!=typeof t)throw new a.PrivyClientError("Invalid MFA code");le.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{ce.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new a.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),n=(e=>({id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}))(await r.startAuthentication(t));le.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{ce.current={resolve:e,reject:t}}));break;default:throw le.current?.reject(new a.PrivyClientError("Unsupported MFA method")),new a.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){le.current?.reject(new a.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await Kn();if(!t||!K)throw Error("Must have valid access token to enroll in MFA");await K.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return Ze.closePrivyModal(),void t();Y.mfa.noPromptOnMfaRequired&&console.warn("[Privy Warning] Triggering the 'showMfaEnrollmentModal' function when 'noPromptOnMfaRequired' is set to true is unexpected. If this is intentional, ensure that you are building custom UIs for MFA verification."),J({mfaEnrollmentFlow:{mfaMethods:Y.mfa.methods,shouldUnlinkOnUnenrollMfa:Y.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),ge(En)})),async initEnrollmentWithTotp(){let e=await Kn();if(!e||!K)throw Error("Must have valid access token to enroll in MFA");let t=await K.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await Kn();if(!t||!K)throw Error("Must have valid access token to enroll in MFA");await K.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),v(await l.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await Kn();if(!t||!K)throw Error("Must have valid access token to enroll in MFA");await K.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),v(await l.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await Kn();if(!r||!K)throw Error("Must have valid access token to enroll in MFA");await K.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),v(await l.getAuthenticatedUser())},async unenroll(e,t={}){let r=await Kn();if(!r||!K)throw Error("Must have valid access token to remove MFA");"passkey"===e?await K.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await K.unenrollMfa({method:e,accessToken:r}),v(await l.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await Kn(),t=g?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!K||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(!g?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ze.recoverPrimaryWallet())throw Error("Unable to connect to wallet");let r=await K.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&v(await l.getAuthenticatedUser()||g||null),J({farcasterSigner:r}),ge(Kr)},getFarcasterSignerPublicKey:async()=>{let e,t=await Kn(),r=g?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!K||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!g?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ze.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!g.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=g.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await Kn(),r=g?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!K||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!g?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ze.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!g.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let n=await import("@simplewebauthn/browser"),i=await K.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:n.bufferToBase64URLString(e)},fid:BigInt(g.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(i.signature))},createGuestAccount:async()=>{if(g&&!g.isGuest)throw Error("User cannot already be authenticated to create a guest account");return g?.isGuest?g:Ze.loginWithGuestAccountFlow()},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let n=g?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return yr({user:g,client:l,address:t,requesterAppId:Y.id,request:{method:n?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:Je})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let n=g?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),i=o.generateTypedDataWithDomainType(e);return yr({user:g,client:l,address:t,requesterAppId:Y.id,request:{method:n?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,i],chainId:r},reconnect:Je})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=g?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return yr({user:g,client:l,address:t,requesterAppId:Y.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:Je})},isModalOpen:d,mfaMethods:Y.mfa.methods};Ln=Qe.signMessage,Dn=Qe.signTypedData,qn=async(e,t)=>await Ve({transaction:e,...t,signOnly:!1}),Bn=async(e,t)=>({signature:(await Ve({transaction:e,...t,signOnly:!0})).hash});let Ze={setAuthenticated:w,setUser:v,isNewUserThisSession:T,pendingTransaction:null,walletConnectionStatus:j,connectors:l.connectors?.walletConnectors??[],solanaWallets:C,rpcConfig:Y.rpcConfig,chains:Y.chains,appId:s.appId,showFiatPrices:"native-token"!==Y.embeddedWallets.priceDisplay.primary,clientAnalyticsId:l.clientAnalyticsId,customAuthStatus:oe,hideWalletUIs:me,isHeadlessSigning:r.useCallback(we,[Y.embeddedWallets.showWalletUIs]),emailOtpState:N,setEmailOtpState:M,smsOtpState:F,setSmsOtpState:L,oAuthState:q,setOAuthState:H,telegramAuthState:z,setTelegramAuthState:V,siweState:D,setSiweState:B,isHeadlessOAuthLoading:I,nativeTokenSymbolForChainId:e=>Y.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(K)return K;let t=new Promise((e=>{te((()=>t=>e(t)))})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return te(null),n},getAuthFlow:()=>l.authFlow,getAuthMeta:()=>l.authFlow?.meta,client:l,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=p&&m&&g;r&&pe.current&&(t=Ye(g)),"login"===ye.current?e.shouldCallAuthOnSuccess&&r&&pe.current?o.emitPrivyEvent(de,"login","onComplete",{user:g,isNewUser:T,wasAlreadyAuthenticated:!1,loginMethod:pe.current,loginAccount:t??null}):o.emitPrivyEvent(de,"login","onError",a.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===ye.current&&t?e.isSuccess&&r&&pe.current?o.emitPrivyEvent(de,"linkAccount","onSuccess",{user:g,linkMethod:pe.current,linkedAccount:t}):pe.current&&o.emitPrivyEvent(de,"linkAccount","onError",a.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:pe.current}):"update"===ye.current&&t&&(e.isSuccess&&r&&pe.current?o.emitPrivyEvent(de,"update","onSuccess",{user:g,updateMethod:pe.current,updatedAccount:t}):pe.current&&o.emitPrivyEvent(de,"update","onError",a.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:pe.current}));let n=_&&Rr.has(_),i=_===o.ErrorScreen&&X.errorModalData&&Rr.has(X.errorModalData.previousScreen);if((n||i)&&X.funding){let e,t=Rr.get(_)??null;if("solana"===X.funding.chainType){let r=c(o.SOLANA_FUNDING_PLUGIN_ID);if(r)try{e=BigInt(await r.getBalance({address:X.funding.address,cluster:X.funding.cluster}))}catch{console.error("Unable to pull wallet balance")}else console.warn("Unable to load solana plugin, skipping balance");o.emitPrivyEvent(de,"fundSolanaWallet","onUserExited",{address:X.funding.address,cluster:X.funding.cluster,fundingMethod:t,balance:e})}else{let r=o.getPublicClient(X.funding.chain.id,Y.chains,Y.rpcConfig,{appId:s.appId});try{e=await r.getBalance({address:X.funding.address})}catch{console.error("Unable to pull wallet balance")}o.emitPrivyEvent(de,"fundWallet","onUserExited",{address:X.funding.address,chain:X.funding.chain,fundingMethod:t,balance:e})}}J({...X,externalConnectWallet:{suggestedAddress:void 0}}),ye.current=null,pe.current=null,k(!1),h(!1),setTimeout((()=>{l.authFlow=void 0}),200)},solanaSignMessage:({message:e,options:t})=>new Promise((async(r,n)=>{if(!m||!g)return o.emitPrivyEvent(de,"signSolanaMessage","onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let i=t?.address??o.getPrivySolanaWallet(g)?.address;if(!i)throw new a.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:s,rootWallet:c}=o.getSolanaSigningAndRootWallet(g,i);if(!s||!c)return o.emitPrivyEvent(de,"signSolanaMessage","onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void n(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return o.emitPrivyEvent(de,"signMessage","onError",a.PrivyErrorCode.INVALID_MESSAGE),void n(Error("Message must be a non-empty string"));let d=async()=>{if(!m)throw Error("User must be authenticated before signing with a Privy wallet");let t=await l.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");let r=Ze.walletProxy??await Ze.initializeWalletProxy(15e3);if(!r)throw Error("Failed to initialize embedded wallet proxy.");if(!await Ze.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!c)throw Error("No root wallet for signing wallet found");let{entropyId:n,entropyIdVerifier:i}=o.getEntropyDetailsFromUser(g),{response:a}=await r.rpc({accessToken:t,entropyId:n,entropyIdVerifier:i,chainType:"solana",hdWalletIndex:s.walletIndex??0,request:{method:"signMessage",params:{message:e}}});return a.data.signature};if(we({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await d();o.emitPrivyEvent(de,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),r({signature:e})}catch(e){n(e)}else{let i={method:"solana_signMessage",data:e,confirmAndSign:d,onSuccess:e=>{o.emitPrivyEvent(de,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),r({signature:e})},onFailure:e=>{n(e)},uiOptions:t?.uiOptions},{entropyId:s,entropyIdVerifier:l}=o.getEntropyDetailsFromAccount(c);J({signMessage:i,connectWallet:{entropyId:s,entropyIdVerifier:l,onCompleteNavigateTo:b.SignRequestScreen,onFailure:e=>{o.emitPrivyEvent(de,"signSolanaMessage","onError",a.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),ge(b.EmbeddedWalletConnectingScreen)}})),signSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:n,address:i})=>{let s=i?A.find((e=>e.address===i)):A.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!s)throw o.emitPrivyEvent(de,"signSolanaTransaction","onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new a.PrivyClientError("Embedded wallet not found",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);let{signedTransaction:l}=await Ke({transaction:e,connection:t,transactionOptions:n,uiOptions:r,wallet:s,signOnly:!0});return l},sendSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:n,fundWalletConfig:i,address:s})=>{let l=s?A.find((e=>e.address===s)):A.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!l)throw o.emitPrivyEvent(de,"sendSolanaTransaction","onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new a.PrivyClientError("Embedded wallet not found",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);return await Ke({transaction:e,connection:t,transactionOptions:n,uiOptions:r,fundWalletConfig:i,wallet:l,signOnly:!1})},openPrivyModal:ge,connectWallet:Pe,initLoginWithWallet:async(e,t,r)=>{o.isBaseConnectedEthereumWallet(e)?(pe.current="siwe",Ae(e,t,r)):(pe.current="siws",Te(e,t,r))},loginWithWallet:async()=>{let e,t,r;if(!p)throw new a.PrivyNotReadyError;if(l.authFlow instanceof o.SiweFlow?e="siwe":l.authFlow instanceof o.SiwsFlow&&(e="siws"),!e)throw new a.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await l.getAccessToken())try{({user:t}=await l.link()),pe.current=e}catch(t){throw o.emitPrivyEvent(de,"linkAccount","onError",t.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await l.authenticate()),pe.current=e}catch(e){throw o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}v(t||g||null),k(r||!1),w(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(n,i)=>{let s=await Kn();if(!m||!g||!s)throw new a.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new a.PrivyClientError("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let l=Ze.walletProxy??await Ze.initializeWalletProxy(15e3);if(!l)throw new a.PrivyClientError("Wallet proxy not initialized.");if((({address:e,chainType:t,user:r})=>!!ar(r).find((r=>r.address===e&&r.chainType===t)))({address:e,chainType:t,user:g}))return n();let c=(({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new a.PrivyClientError("Address to delegate is not associated with current user.");return{address:r.address,chainType:r.chainType,walletIndex:r.walletIndex??0}})({address:e,user:g}),d=(({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new a.PrivyClientError("Address to delegate is not associated with current user.");let n=r.imported?r:o.getPrivyPrimaryWallet(t);if(!n)throw new a.PrivyClientError("Unable to determine root address for delegated address.");return{address:n.address,chainType:n.chainType,imported:n.imported}})({address:e,user:g}),u=async()=>{await l.createDelegatedAction({accessToken:s,rootWallet:d,delegatedWallets:[c]}),await Ze.refreshSessionAndUser()};if(await Ze.recoverPrimaryWallet(),r)J({delegatedActions:{consent:{address:e,onDelegate:u,onSuccess:async()=>{n()},onError:async e=>{i(e)}}}}),ge(Dr);else try{await u(),n()}catch(e){i(e)}})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!m||!g)throw new a.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");if(0===ar(g).length)throw new a.PrivyClientError("User has no delegated wallets to revoke.");let n=async()=>{await l.revokeDelegatedWallet(),await Ze.refreshSessionAndUser()};if(e)J({delegatedActions:{revoke:{onRevoke:n,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),ge(Hr);else try{await n(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new Se(e,t);l.startAuthFlow(r);try{pe.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===ye.current?o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ye.current&&o.emitPrivyEvent(de,"linkAccount","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!p)throw new a.PrivyNotReadyError;if(!(l.authFlow instanceof Se))throw new a.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await l.getAccessToken())try{({user:e}=await l.link()),pe.current="farcaster"}catch(e){throw o.emitPrivyEvent(de,"linkAccount","onError",e.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await l.authenticate()),pe.current="farcaster"}catch(e){throw o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}v(e||null),k(t||!1),w(!0)},async loginWithGuestAccountFlow(){let e=new Ie(this.appId);l.startAuthFlow(e);try{ye.current="login",pe.current="guest";let{user:e,isNewUser:t}=await l.authenticate();if(t=t||!1,!e)throw new a.PrivyClientError("Unable to authenticate guest account");let r=await Kn(),n=await Ze.initializeWalletProxy(o.WALLET_PROXY_TIMEOUT);if(r&&n)try{let t=o.shouldCreateEmbeddedEthWallet(e,Y.embeddedWallets.ethereum.createOnLogin),i=o.shouldCreateEmbeddedSolWallet(e,Y.embeddedWallets.solana.createOnLogin);if(t&&i){let t=await De(e,o.WALLET_PROXY_TIMEOUT);await n.createSolana({accessToken:r,ethereumAddress:t?.address}),e=await Ze.refreshSessionAndUser()}else i?(await n.createSolana({accessToken:r,ethereumAddress:o.getPrivyEthereumWallet(e)?.address}),e=await Ze.refreshSessionAndUser()):t?(await De(e,o.WALLET_PROXY_TIMEOUT),e=await Ze.refreshSessionAndUser()):v(e)}catch(t){v(e),console.warn("Unable to create embedded wallet for guest account")}return k(t),w(!0),o.emitPrivyEvent(de,"login","onComplete",{user:e,isNewUser:t,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),e}catch(e){throw o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:r}){let n=`privy:${e}`;pe.current=n;let{url:i,stateCode:s,codeVerifier:c}=await async function({api:e,appId:t}){let r=o.createCodeVerifier(),n=o.createStateCode(),i=await o.deriveCodeChallengeFromCodeVerifier(r);try{let{url:o}=await e.post(a.oAuthInitPath,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:i,state_code:n});return{url:o,stateCode:n,codeVerifier:r}}catch(e){throw a.formatApiError(e)}}({api:l.api,appId:e});if(!i)throw l.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new a.PrivyClientError("No authorization URL returned for cross-app auth.");try{let o=await async function({url:e,popup:t}){return t.location=e,new Promise(((e,r)=>{let n,i=setTimeout((()=>{r(new a.PrivyClientError("Authorization request timed out after 2 minutes.")),o()}),12e4);function o(){t?.close(),window.removeEventListener("message",l)}let s=setInterval((()=>{t?.closed&&!n&&(o(),clearInterval(s),clearTimeout(i),r(new a.PrivyClientError("User rejected request")))}),300);function l(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(clearTimeout(i),e(t.data),o()),"PRIVY_OAUTH_ERROR"===t.data.type&&(clearTimeout(i),r(new a.PrivyClientError(t.data.error)),o()),t.data.type===ur&&((n=new BroadcastChannel(dr)).onmessage=l))}window.addEventListener("message",l)}))}({url:i,popup:t,provider:n}),d=o.stateCode,u=o.authorizationCode;if(d!==s)throw l.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:n,storedStateCode:s??"",returnedStateCode:d??""}}),new a.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,a.PrivyErrorCode.OAUTH_UNEXPECTED);let h=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:i,client:o}){if(!n||!t)throw new a.PrivyClientError("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===n)throw new a.PrivyClientError("User denied confirmation during cross-app auth flow");try{let a=new hr({authorizationCode:n,stateCode:t,codeVerifier:r,provider:`privy:${e}`});o.startAuthFlow(a);let s="link"===i?await o.link():await o.authenticate(),l=s.oAuthTokens?.accessToken;return console.debug(),l}catch(e){let t=a.formatApiError(e);if(t.privyErrorCode)throw new a.PrivyClientError(t.message||"Invalid code during cross-app auth flow.",void 0,t.privyErrorCode);if("User denied confirmation during cross-app auth flow"===t.message)throw new a.PrivyClientError("Invalid code during cross-app auth flow.",void 0,a.PrivyErrorCode.OAUTH_USER_DENIED);throw new a.PrivyClientError("Invalid code during cross-app auth flow.",void 0,a.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:c,stateCode:d,authorizationCode:u,action:r,client:l});h&&l.storeProviderAccessToken(e,h);let p=await Ze.refreshSessionAndUser();if(!p)throw new a.PrivyClientError("Unable to update user");return l.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),p}catch(e){throw l.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:n}}),e}},async initLoginWithOAuth(e,t,r){if(pe.current=e,!o.e())return void ge(Gr);if("google"===e&&o.e$3(window.navigator.userAgent))return void ge(Gr);"twitter"===e&&window.opener&&window.opener.postMessage({type:ur},"*"),o.s.del(o.HEADLESS_OAUTH_KEY),o.s.del(o.OAUTH_DISABLE_SIGNUP_KEY);let i=new be({provider:e,disableSignup:!!r,withPrivyUi:!0});t&&i.addCaptchaToken(t),l.startAuthFlow(i);let a=await l.authFlow.getAuthorizationUrl();a&&a.url&&("twitter"===e&&n.isAndroid&&(a.url=a.url.replace("x.com","twitter.com")),window.location.assign(a.url))},async initLoginWithTelegram(e,t){if(!p)throw new a.PrivyNotReadyError;pe.current="telegram";let r=new o.TelegramAuthFlow(e,t);l.startAuthFlow(r),V({status:"loading"}),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>Y.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:Y.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):t(new a.PrivyClientError("Telegram auth failed or was canceled by the client")))):t(new a.PrivyClientError("Telegram was not initialized")):t(new a.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(l.authFlow instanceof o.TelegramAuthFlow))throw new a.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");l.authFlow.meta.captchaToken||=e?.captchaToken;let n=await Kn(),i=e?.intent||ye.current;if("login"===i)try{let e=await l.authenticate();t=e.user,r=e.isNewUser,pe.current="telegram"}catch(e){throw o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==i)throw new a.PrivyClientError("Unknown auth intent");try{t=(await l.link()).user,pe.current="telegram"}catch(e){throw o.emitPrivyEvent(de,"linkAccount","onError",e.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}v(t),k(r||!1),w(!0),V({status:"done"});let s=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,loginAccount:s}},async recoveryOAuthFlow(e,t,r){let n,i;function s(t){if(!t)throw l.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new a.PrivyClientError("Recovery OAuth failed")}switch(e){case"google-drive":{let t,c,{url:d,codeVerifier:u,stateCode:h}=await o.getRecoveryAuthorizationUrl({api:Fn.api,provider:e});s(d);try{let n=await Nr({url:d,popup:r,provider:e});if(t=n.stateCode,c=n.authorizationCode,t!==h)throw l.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:h??"",returnedStateCode:t??""}}),new a.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,a.PrivyErrorCode.OAUTH_UNEXPECTED)}catch(t){throw l.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new a.PrivyClientError("Recovery OAuth failed")}[n,i]=await Promise.all([Kn(),o.authenticateRecovery({api:Fn.api,provider:e,codeVerifier:u,stateCode:t,authorizationCode:c})]);break}case"icloud":{let{url:t}=await o.getRecoveryAuthorizationUrl({api:Fn.api,provider:e});s(t);let{ckWebAuthToken:a}=await Nr({url:t,popup:r,provider:e});i=a,n=await Kn()}}if(!K)throw new a.PrivyClientError("Cannot connect to wallet proxy");if(!n)throw new a.PrivyClientError("Unable to authorize user");switch(t){case"recover":{let t=X.recoverWallet?.entropyId,r=X.recoverWallet?.entropyIdVerifier;if(!t||!r)throw new a.PrivyClientError("Recovery OAuth failed");l.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await K.recover({accessToken:n,entropyId:t,entropyIdVerifier:r,recoveryAccessToken:i}),l.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break}case"create-wallet":{l.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await K.create({accessToken:n,recoveryAccessToken:i,recoveryMethod:e});let t=o.getPrivyEthereumWallet(await Ze.refreshSessionAndUser());if(!t)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");l.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.address}}),o.emitPrivyEvent(de,"createWallet","onSuccess",{wallet:t});break}case"set-recovery":{let t=o.getPrivyPrimaryWallet(g);if(!t)throw o.emitPrivyEvent(de,"setWalletRecovery","onError",a.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");l.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}});let{entropyId:r,entropyIdVerifier:s}=o.getEntropyDetailsFromAccount(t);await K.setRecovery({accessToken:n,entropyId:r,entropyIdVerifier:s,recoveryMethod:e,recoveryAccessToken:i});let c=o.getPrivyPrimaryWallet(await Ze.refreshSessionAndUser());if(!c)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");l.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}}),o.emitPrivyEvent(de,"setWalletRecovery","onSuccess",{method:e,wallet:c});break}default:throw new a.PrivyClientError("Unsupported recovery action")}},async loginWithOAuth(e){let t,r,n;if(!(l.authFlow instanceof be))throw new a.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let i=o.s.get(o.STATE_CODE_KEY),s=l.authFlow.meta.stateCode;if(i!==s)throw l.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:i??"",returnedStateCode:s??""}}),new a.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,a.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await l.getAccessToken())try{let r=await l.link();t=r.user,n=r.oAuthTokens,pe.current=e}catch(t){throw o.emitPrivyEvent(de,"linkAccount","onError",t.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let i=await l.authenticate();t=i.user,r=i.isNewUser,n=i.oAuthTokens,pe.current=e}catch(t){throw"login"===ye.current?o.emitPrivyEvent(de,"login","onError",t.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ye.current&&o.emitPrivyEvent(de,"linkAccount","onError",t.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return v(t),k(r||!1),w(!0),n&&t&&o.emitPrivyEvent(de,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),n},passkeyAuthState:R,setPasskeyAuthState:U,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new Ue({captchaToken:e,setPasskeyAuthState:U});l.startAuthFlow(r),ye.current="login";try{pe.current="passkey",U({status:"generating-challenge"}),await r.initRegisterFlow(t),U({status:"awaiting-passkey"})}catch(e){throw U({status:"error",error:e}),o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!p)throw new a.PrivyNotReadyError;if(!(l.authFlow instanceof Ue))throw new a.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==pe.current){let e=new a.PrivyClientError("Must init login with Passkey flow first.");throw U({status:"error",error:e}),e}let r=await Kn();try{pe.current="passkey",U({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await l.authenticate())}catch(e){throw U({status:"error",error:e}),o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}v(e),k(t||!1),w(!0),U({status:"done"});let n=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:n}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new Ue({captchaToken:e,setPasskeyAuthState:U});l.startAuthFlow(r),ye.current="login";try{pe.current="passkey",U({status:"generating-challenge"}),await r.initAuthenticationFlow(t),U({status:"awaiting-passkey"})}catch(e){throw U({status:"error",error:e}),o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,r;if(!p)throw new a.PrivyNotReadyError;if(!(l.authFlow instanceof Ue))throw new a.PrivyClientError("Must initialize Passkey flow first.");if(e?.credentialIds&&(l.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==pe.current){let e=new a.PrivyClientError("Must init login with Passkey flow first.");throw U({status:"error",error:e}),e}let n=await Kn();try{pe.current="passkey",U({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await l.authenticate())}catch(e){throw U({status:"error",error:e}),o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}v(t),k(r||!1),w(!0),U({status:"done"});let i=t?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,loginAccount:i}},async initLinkWithPasskey(e){let t=new Ue({captchaToken:e});l.startAuthFlow(t),ye.current="link",pe.current="passkey",U({status:"generating-challenge"});try{await t.initLinkFlow(),U({status:"awaiting-passkey"})}catch(e){throw o.emitPrivyEvent(de,"linkAccount","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),U({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!p)throw new a.PrivyNotReadyError;if(!(l.authFlow instanceof Ue))throw new a.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==pe.current)throw new a.PrivyClientError("Must init login with Passkey flow first.");try{pe.current="passkey",({user:e}=await l.link())}catch(e){throw o.emitPrivyEvent(de,"linkAccount","onError",e.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return v(e||g||null),U({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!o.e())throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");if("google"===e&&o.e$3(window.navigator.userAgent))throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");let n=new be({provider:e,withPrivyUi:!1,disableSignup:r??!1});t&&n.addCaptchaToken(t),H({status:"loading"});let i=await l.startAuthFlow(n).getAuthorizationUrl();i?.url&&window.location.assign(i.url)},async loginWithHeadlessOAuth(e){let t,r,n;W(!0),H({status:"loading"}),l.startAuthFlow(new be(e));let i=o.s.get(o.STATE_CODE_KEY),s=e.stateCode;if(i!==s)throw l.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:i??"",returnedStateCode:s??""}}),W(!1),new a.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,a.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await l.getAccessToken())try{({user:t,oAuthTokens:n}=await l.link()),pe.current=e.provider;let r=Ye(t);t&&r&&o.emitPrivyEvent(de,"linkAccount","onSuccess",{user:t,linkMethod:pe.current,linkedAccount:r})}catch(t){throw W(!1),o.emitPrivyEvent(de,"linkAccount","onError",t.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:n}=await l.authenticate()),pe.current=e.provider;let i=Ye(t);t&&i&&void 0!==r&&o.emitPrivyEvent(de,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:pe.current,loginAccount:i})}catch(e){throw W(!1),H({status:"error",error:e}),o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return v(t),k(r||!1),w(!0),W(!1),H({status:"done"}),n&&t&&o.emitPrivyEvent(de,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{let i=new ke({email:e,captchaToken:t,disableSignup:r});l.startAuthFlow(i);try{pe.current="email",M({status:"sending-code"}),await i.sendCodeEmail({withPrivyUi:n}),M({status:"awaiting-code-input"})}catch(e){throw M({status:"error",error:e}),"login"===ye.current?o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ye.current&&o.emitPrivyEvent(de,"linkAccount","onError",e.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,r)=>{let n=new _e(e,t,r);l.startAuthFlow(n);try{await n.sendCodeEmail({withPrivyUi:!0})}catch(e){o.emitPrivyEvent(de,"update","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:pe.current})}},initUpdatePhone:async(e,t,r)=>{let n=new Me(e,t,r);l.startAuthFlow(n);try{await n.sendSmsCode({withPrivyUi:!0})}catch(e){o.emitPrivyEvent(de,"update","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:pe.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{L({status:"sending-code"});let i=new Ne({phoneNumber:e,captchaToken:t,disableSignup:r});l.startAuthFlow(i);try{pe.current="sms",await i.sendSmsCode({withPrivyUi:n}),L({status:"awaiting-code-input"})}catch(e){throw L({status:"error",error:e}),"login"===ye.current?o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ye.current&&o.emitPrivyEvent(de,"linkAccount","onError",e.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(l.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(l.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function n(e){l.authFlow instanceof ke?M(e):l.authFlow instanceof Ne&&L(e)}if(n({status:"submitting-code"}),!p){let e=new a.PrivyNotReadyError;throw n({status:"error",error:e}),e}if(l.authFlow instanceof ke)l.authFlow.meta.emailCode=e.trim();else{if(!(l.authFlow instanceof Ne)){let e=new a.PrivyClientError("Must initialize a passwordless code flow first");throw n({status:"error",error:e}),e}l.authFlow.meta.smsCode=e.trim()}let i=await Kn();if("link"===ye.current)try{({user:t}=await l.link())}catch(e){throw n({status:"error",error:e}),o.emitPrivyEvent(de,"linkAccount","onError",e.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:pe.current}),e}else if("update"===ye.current)try{({user:t}=await l.link())}catch(e){throw n({status:"error",error:e}),o.emitPrivyEvent(de,"update","onError",e.privyErrorCode||a.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:pe.current}),e}else try{({user:t,isNewUser:r}=await l.authenticate())}catch(e){throw n({status:"error",error:e}),o.emitPrivyEvent(de,"login","onError",e.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let s=t||g;v(s||null),k(r||!1),w(!0),n({status:"done"});let c=null;return l.authFlow instanceof ke?c=s?.linkedAccounts.find((({type:e})=>"email"===e))||null:l.authFlow instanceof Ne&&(c=s?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:s,isNewUser:r||!1,wasAlreadyAuthenticated:!!i,linkedAccount:c}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{ye.current="link",pe.current="siwe",B({status:"generating-message"});let n=await l.generateSiweNonce({address:e,captchaToken:r});return B({status:"awaiting-signature"}),o.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:n})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await l.generateSiweNonce({address:e});return o.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r})=>{let n;n=await l.linkSmartWallet({message:e,signature:t,smartWalletType:r}),v((n=await Ze.refreshSessionAndUser()??n)||g||null)},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})=>{let s;je("siwe");let c=null;try{B({status:"submitting-signature"}),s=await l.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}),s=await Ze.refreshSessionAndUser()??s,B({status:"done"}),(c=Ye(s)||null)&&o.emitPrivyEvent(de,"linkAccount","onSuccess",{user:s,linkMethod:"siwe",linkedAccount:c})}catch(e){throw o.emitPrivyEvent(de,"linkAccount","onError",e.privyErrorCode||a.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),ye.current=null,pe.current=null,B({status:"error",error:e}),e}let d=s||g;return v(d||null),ye.current=null,pe.current=null,{user:d,linkedAccount:c}},refreshSessionAndUser:async()=>{let e=await l.getAuthenticatedUser();return w(!!e),v(e),e},walletProxy:K,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>l.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await l.acceptTerms();return v(e),e},getUsdTokenPrice:e=>l.getUsdTokenPrice(e),getUsdPriceForSol:()=>l.getUsdPriceForSol(),getSplTokenMetadata:e=>l.getSplTokenMetadata(e),recoverPrimaryWallet:async e=>new Promise((async(t,r)=>{let n=o.getPrivyPrimaryWallet(e?.user??g)||o.getImportedPrivyEthereumWallet(e?.user??g)||o.getImportedPrivySolanaWallet(e?.user??g);n||t(!0);let i=await Kn();if(!i||!K||!n)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));let{entropyId:a,entropyIdVerifier:s}=o.getEntropyDetailsFromAccount(n);try{await K.connect({accessToken:i,entropyId:a,entropyIdVerifier:s}),t(!0)}catch(e){o.errorIndicatesRecoveryIsNeeded(e)&&"privy"===n.recoveryMethod?(l.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:n.address}}),(await K.recover({entropyId:a,entropyIdVerifier:s,accessToken:i})).entropyId||r(Error("Unable to recover wallet")),l.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:n.address}}),t(!0)):o.errorIndicatesRecoveryIsNeeded(e)&&"privy"!==n.recoveryMethod?(J({recoverWallet:{entropyId:a,entropyIdVerifier:s,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:n.recoveryMethod,action:"recover"}}),ge(o.embeddedWalletRecoveryScreen(n.recoveryMethod))):r(e)}})),embeddedSolanaWallets:A,createEmbeddedSolanaWallet:async e=>{e&&"target"in e&&(e=void 0);let t=await Ze.refreshSessionAndUser();if(!t)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return(async(e,t,r)=>{let n=o.getPrivyEthereumWallet(e),i=o.getPrivySolanaWallet(e),s=r&&"createAdditional"in r&&r.createAdditional,l=r&&"walletIndex"in r?r.walletIndex:void 0,c=(o.getLatestPrivySolanaWallet(e)?.walletIndex??-1)+1;if(i&&!s&&"number"!=typeof l)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");if("number"==typeof l&&l<0)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${l}) is invalid.`);let[d,u]=await Promise.all([Ze.initializeWalletProxy(t),Kn()]);if(!d||!u)throw o.emitPrivyEvent(de,"createWallet","onError",a.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return await He({user:e,wp:d,accessToken:u,walletIndex:l??c,ethereumWallet:n})})(t,15e3,e)},exportSolanaWallet:e=>new Promise((async(t,r)=>{if(!m||!g)return void r(Error("User must be authenticated before exporting their Privy wallet"));let n=e?.address??o.getPrivySolanaWallet(g)?.address;if(!n)return void r(Error("User does not have an HD Solana wallet."));let{signingWallet:i,rootWallet:a}=o.getSolanaSigningAndRootWallet(g,n);if(!i||!a)return void r(Error("Must have a Privy wallet before exporting"));if(!await Kn()||!K)return void r(Error("Must have valid access token to enroll in MFA"));if(!K)return void r(Error("Must have a Privy wallet before exporting"));let{entropyId:c,entropyIdVerifier:d}=o.getEntropyDetailsFromAccount(a),u={appId:s.appId,appClientId:s.clientId,origin:l.apiUrl,walletToExport:i,primaryWallet:a,onSuccess:t,onFailure:r};J({connectWallet:{entropyId:c,entropyIdVerifier:d,onCompleteNavigateTo:b.EmbeddedWalletKeyExportScreen,onFailure:r,shouldForceMFA:!0},keyExport:u}),ge(b.EmbeddedWalletConnectingScreen)})),setReadyToTrue:e=>{y(!0),Q?.(e)},updateWallets:()=>Le(),fundWallet:async(e,t)=>{J({funding:u.prepareFundingModalData({address:e,appConfig:Y,fundWalletConfig:t,methodScreen:o.FundingMethodSelectionScreen})}),ge(o.FundingMethodSelectionScreen)},openModal:ge,requestFarcasterSignerStatus:async e=>{let t=await Kn(),r=g?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!K||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!g?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let n=await l.requestFarcasterSignerStatus(e);return"approved"===n.status&&v(await l.getAuthenticatedUser()||g||null),n},connectCoinbaseSmartWallet:async()=>{Y.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=l.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||l.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Pe(e);await Ce("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,telegramWebAppData:a,farcasterEmbeddedAddress:o,oAuthUserInfo:s})=>{let c=await l.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,telegramWebAppData:a,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return v(c),c}};Hn=Ze.recoverPrimaryWallet,zn=Ze.recoverPrimaryWallet,Vn=Ze.solanaSignMessage;let et=r.useMemo((()=>({wallets:f,ready:re&&ue})),[f,re,ue]),tt=l.authFlow instanceof o.TelegramAuthFlow,rt=!Y.headless&&Y.captchaEnabled&&!m&&(p||tt);/*#__PURE__*/return e.jsx(o.PrivyContext.Provider,{value:Qe,children:/*#__PURE__*/e.jsx(o.PrivyEventsContext.Provider,{value:de,children:/*#__PURE__*/e.jsx(o.UseWalletsContext.Provider,{value:et,children:/*#__PURE__*/e.jsx(o.CaptchaProvider,{...Y,children:/*#__PURE__*/e.jsxs(a.InternalPrivyContext.Provider,{value:Ze,children:[/*#__PURE__*/e.jsx(o.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(o.ModalProvider,{data:X,setModalData:J,setInitialScreen:S,initialScreen:_,authenticated:m,open:d,children:[s.children,rt&&/*#__PURE__*/e.jsx(Et,{delayedExecution:!1}),/*#__PURE__*/e.jsx(Nt,{theme:{...Y.appearance.palette||{}}}),!Y.render.standalone&&/*#__PURE__*/e.jsx(Kt,{open:d})]})}),/*#__PURE__*/e.jsx(ir,{appId:s.appId,appClientId:s.clientId,clientAnalyticsId:l.clientAnalyticsId,origin:l.apiUrl,mfaMethods:g?.mfaMethods,mfaPromise:le,mfaSubmitPromise:ce,onLoad:$,onLoadFailed:()=>null}),Y.loginConfig.telegramAuthConfiguration&&
|
|
4
|
-
/*#__PURE__*/e.jsx(o.Hide,{$if:!0,children:/*#__PURE__*/e.jsx(Gt,{scriptHost:s.apiUrl||o.DEFAULT_PRIVY_API_URL,botUsername:Y.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};const ti=()=>{let{getAccessToken:e,user:t}=o.usePrivyContext(),{refreshSessionAndUser:n,initializeWalletProxy:i}=a.usePrivyInternal(),s=o.useEmitPrivyEvent();return{importWallet:r.useCallback((({privateKey:r})=>K.importWallet({getAccessToken:e,user:t,initializeWalletProxy:i,refreshSessionAndUser:n,emitPrivyEvent:s},{privateKey:r,chainType:"ethereum"})),[t,e,n,i,s])}};let ri=async(e,t,r,n,i)=>{if(!e)throw n("linkAccount","onError",a.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:i}),new a.PrivyClientError("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(i))))throw new a.PrivyClientError(`OAuth account of type ${i} not linked to the account.`);await r(i)};exports.EthereumWalletConnector=o.EthereumWalletConnector,exports.SUPPORTED_CHAINS=o.DEFAULT_SUPPORTED_CHAINS,exports.VERSION=o.VERSION,exports.WalletConnector=o.WalletConnector,exports.addPrivyRpcToChain=o.addPrivyRpcToChain,exports.addRpcUrlOverrideToChain=o.addRpcUrlOverrideToChain,exports.errorIndicatesMaxMfaRetries=o.errorIndicatesMaxMfaRetries,exports.errorIndicatesMfaTimeout=o.errorIndicatesMfaTimeout,exports.errorIndicatesMfaVerificationFailed=o.errorIndicatesMfaVerificationFailed,exports.useSolanaWallets=o.useSolanaWallets,exports.useWallets=o.useWallets,exports.useActiveWallet=g.useActiveWallet,exports.useConnectWallet=g.useConnectWallet,exports.useFundWallet=g.useFundWallet,exports.useLogin=g.useLogin,exports.useLogout=g.useLogout,exports.getEmbeddedConnectedWallet=b.getEmbeddedConnectedWallet,exports.Captcha=Et,exports.ConnectorManager=it,exports.LoginModal=Kt,exports.PrivyClient=vt,exports.PrivyProvider=({config:t,...r})=>{var n;if("undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol)throw new a.PrivyClientError("Embedded wallet is only available over HTTPS");if("string"!=typeof(n=r.appId)||25!==n.length)throw new a.PrivyClientError("Cannot initialize the Privy provider with an invalid Privy app ID");Fn||(Fn=new vt({appId:r.appId,appClientId:r.clientId,apiUrl:r.apiUrl}));let i=Object.assign({},t);/*#__PURE__*/
|
|
5
|
-
return e.jsx(o.PrivyAppConfigProvider,{client:Fn,clientConfig:i,children:/*#__PURE__*/e.jsx(o.PrivyPluginProvider,{children:/*#__PURE__*/e.jsx(ei,{...r,client:Fn})})})},exports.getAccessToken=function(){return Fn?Fn.getCustomerAccessToken():Promise.resolve(o.s.get(o.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.useConnectCoinbaseSmartWallet=()=>{let{connectCoinbaseSmartWallet:e}=a.usePrivyInternal();return{connectCoinbaseSmartWallet:e}},exports.useCreateWallet=function(e){let{createWallet:t}=r.useContext(o.PrivyContext);return o.usePrivyEventSubscription("createWallet",e),{createWallet:t}},exports.useCrossAppAccounts=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:n,sendTransactionWithCrossAppWallet:i}=o.usePrivyContext();return{loginWithCrossAppAccount:({appId:t})=>e({appId:t,action:"login"}),linkCrossAppAccount:({appId:t})=>e({appId:t,action:"link"}),unlinkCrossAppAccount:t,signMessage:r,signTypedData:n,sendTransaction:i}},exports.useCustomAuth=e=>{let{customAuthStatus:t}=a.usePrivyInternal();return o.usePrivyEventSubscription("customAuth",e),{status:t}},exports.useDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=a.usePrivyInternal();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},exports.useFarcasterSigner=function(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=o.usePrivyContext();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}},exports.useGuestAccounts=function(){let{createGuestAccount:e}=r.useContext(o.PrivyContext);return{createGuestAccount:e}},exports.useHeadlessDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=a.usePrivyInternal();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}},exports.useIdentityToken=function(){let{identityToken:e}=ut();return{identityToken:e}},exports.useImportWallet=ti,exports.useLinkAccount=function(e){let{linkEmail:t,linkPhone:n,linkWallet:i,linkGoogle:a,linkApple:s,linkTwitter:l,linkDiscord:c,linkGithub:d,linkLinkedIn:u,linkTiktok:h,linkSpotify:p,linkInstagram:y,linkTelegram:m,linkFarcaster:w}=r.useContext(o.PrivyContext);return o.usePrivyEventSubscription("linkAccount",e),{linkEmail:t,linkPhone:n,linkWallet:i,linkGoogle:a,linkApple:s,linkTwitter:l,linkDiscord:c,linkGithub:d,linkLinkedIn:u,linkTiktok:h,linkSpotify:p,linkInstagram:y,linkFarcaster:w,linkTelegram:m}},exports.useLinkWithPasskey=e=>{let{initLinkWithPasskey:t,linkWithPasskey:n,passkeyAuthState:i,setPasskeyAuthState:o}=a.usePrivyInternal();return{linkWithPasskey:r.useCallback((async()=>{try{await t();let r=await n();if(!r)throw Error("Error, user not found");let i=r.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:r,linkMethod:"passkey",linkedAccount:i})}catch(t){throw o({status:"error",error:t}),e?.onError?.(t.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[n]),state:i}},exports.useLinkWithSiwe=e=>{let t=o.useCaptcha(),{siweState:n,setSiweState:i,linkWithSiwe:s,generateSiweMessage:l}=a.usePrivyInternal();return{generateSiweMessage:r.useCallback((async({address:t,chainId:r})=>{try{if(!t||!r)throw Error("wallet address and chainId required to generate nonce");return await l({address:t,chainId:r}).then((e=>e))}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[l]),linkWithSiwe:r.useCallback((async({signature:r,message:n,chainId:l,walletClientType:c,connectorType:d})=>{try{if(t.enabled&&"success"!==t.status)throw new o.CaptchaError(t.error,null,a.PrivyErrorCode.CAPTCHA_FAILURE);let{user:i,linkedAccount:u}=await s({message:n,signature:r,chainId:l,walletClientType:c,connectorType:d});u&&e?.onSuccess?.({user:i,linkMethod:"siwe",linkedAccount:u})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[s,t.status]),state:n}},exports.useLoginWithEmail=e=>{let t=o.useCaptcha(),{emailOtpState:n,setEmailOtpState:i,initLoginWithEmail:s,loginWithCode:l}=a.usePrivyInternal();return{sendCode:r.useCallback((async({email:r,disableSignup:n})=>{try{let e;if(!r)throw Error("Email required to send OTP code");if(t.enabled&&"error"===t.status)throw new o.CaptchaError(t.error,null,a.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await s({email:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[s]),loginWithCode:r.useCallback((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new o.CaptchaError(t.error,null,a.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:s,linkedAccount:c}=await l(r);e?.onComplete?.({user:n,isNewUser:i,wasAlreadyAuthenticated:s,loginMethod:"email",loginAccount:c})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t.status]),state:n}},exports.useLoginWithOAuth=e=>{o.usePrivyEventSubscription("login",e);let t=o.useCaptcha(),n=o.useIsServerConfigLoaded(),{ready:i,user:s}=o.usePrivyContext(),{initLoginWithHeadlessOAuth:l,loginWithHeadlessOAuth:c,oAuthState:d,setOAuthState:u,isHeadlessOAuthLoading:h}=a.usePrivyInternal(),p=r.useCallback((async e=>{try{if(t.enabled&&"success"!==t.status)throw new o.CaptchaError(t.error,null,a.PrivyErrorCode.CAPTCHA_FAILURE);return await l(e.provider,t.token,e.disableSignup)}catch(e){throw u({status:"error",error:e}),e}}),[l,t]),y=r.useCallback((async()=>{let e=Re();try{if(s)return console.warn("Cannot login with OAuth when already logged in"),s;if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");if(e.popupFlow)return}catch(e){throw u({status:"error",error:e}),e}try{return await c(e)}catch(e){throw u({status:"error",error:e}),e}finally{o.stripUrlOAuthParamsAndRemoveStateCode()}}),[c]);return r.useEffect((()=>{let e=Re();i&&n&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&y().catch((()=>{}))}),[i,n]),{initOAuth:p,loading:h,state:d}},exports.useLoginWithPasskey=e=>{let t=o.useCaptcha(),{initLoginWithPasskey:n,loginWithPasskey:i,passkeyAuthState:s,setPasskeyAuthState:l}=a.usePrivyInternal();return{loginWithPasskey:r.useCallback((async r=>{try{let s;if(t.enabled&&"error"===t.status)throw new o.CaptchaError(t.error,null,a.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),s=await t.waitForResult()),await n({captchaToken:s,withPrivyUi:!1});let{user:l,isNewUser:c,wasAlreadyAuthenticated:d,loginAccount:u}=await i(r);e?.onComplete?.({user:l,isNewUser:c,wasAlreadyAuthenticated:d,loginMethod:"passkey",loginAccount:u})}catch(r){throw l({status:"error",error:r}),e?.onError?.(r.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[i,t.status]),state:s}},exports.useLoginWithSms=e=>{let t=o.useCaptcha(),{smsOtpState:n,setSmsOtpState:i,initLoginWithSms:s,loginWithCode:l}=a.usePrivyInternal();return{sendCode:r.useCallback((async({phoneNumber:r,disableSignup:n})=>{try{let e;if(!r)throw Error("SMS required to send OTP code");if(t.enabled&&"error"===t.status)throw new o.CaptchaError(t.error,null,a.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await s({phoneNumber:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[s]),loginWithCode:r.useCallback((async({code:r})=>{try{if(t.enabled&&"success"!==t.status)throw new o.CaptchaError(t.error,null,a.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:s,linkedAccount:c}=await l(r);e?.onComplete?.({user:n,isNewUser:i,wasAlreadyAuthenticated:s,loginMethod:"sms",loginAccount:c})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t.status]),state:n}},exports.useLoginWithTelegram=e=>{let t=o.useCaptcha(),{initLoginWithTelegram:n,loginWithTelegram:i,telegramAuthState:s,setTelegramAuthState:l}=a.usePrivyInternal();return{login:r.useCallback((async r=>{try{if(t.enabled&&"success"!==t.status)throw new o.CaptchaError(t.error,null,a.PrivyErrorCode.CAPTCHA_FAILURE);await n(t.token,r?.disableSignup);let{user:s,isNewUser:l,loginAccount:c,wasAlreadyAuthenticated:d}=await i({intent:"login"});e?.onComplete?.({user:s,isNewUser:l,wasAlreadyAuthenticated:d,loginMethod:"telegram",loginAccount:c})}catch(r){throw l({status:"error",error:r}),e?.onError?.(r.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[n,i,t]),state:s}},exports.useMfa=jt,exports.useMfaEnrollment=rn,exports.useModalStatus=()=>{let{isModalOpen:e}=r.useContext(o.PrivyContext);return{isOpen:e}},exports.useOAuthTokens=function(e){let{authenticated:t,user:r}=o.usePrivyContext(),{initLoginWithOAuth:n}=a.usePrivyInternal(),i=o.useEmitPrivyEvent();return o.usePrivyEventSubscription("oAuthAuthorization",e),{reauthorize:e=>ri(t,r,n,i,e.provider)}},exports.usePrivy=()=>{let{importWallet:e}=ti();return{...r.useContext(o.PrivyContext),importWallet:e}},exports.useRegisterMfaListener=Ct,exports.useSendTransaction=function(e){let{sendTransaction:t}=r.useContext(o.PrivyContext);return o.usePrivyEventSubscription("sendTransaction",e),{sendTransaction:t}},exports.useSetWalletPassword=function(e){let{setWalletPassword:t}=r.useContext(o.PrivyContext);return o.usePrivyEventSubscription("setWalletPassword",e),{setWalletPassword:t}},exports.useSetWalletRecovery=function(e){let{setWalletRecovery:t}=r.useContext(o.PrivyContext);return o.usePrivyEventSubscription("setWalletRecovery",e),{setWalletRecovery:t}},exports.useSignAuthorization=()=>{let{ready:e,wallets:t}=o.useWallets(),{user:n}=o.usePrivyContext(),{rpcConfig:i,chains:s,appId:l}=a.usePrivyInternal();return{signAuthorization:r.useCallback((async(r,a)=>{if(!n)throw Error("User must be authenticated before signing with a Privy wallet");if(!e)throw Error("Wallets are not ready");let c=a?.address??o.getPrivyEthereumWallet(n)?.address??P.zeroAddress,d=t.find((e=>P.getAddress(e.address)===P.getAddress(c)));if(!d)throw Error("Signing wallet not found.");let u=r.chainId??Number(d.chainId.split(":")[1]),h=s.find((e=>e.id===u));if(!h)throw Error("Error, chain not configured in PrivyProvider config");let p=P.createWalletClient({account:c,chain:h,transport:P.http(o.getJsonRpcEndpointFromChain(h,i,l))}).extend($.eip7702Actions()),y=await p.prepareAuthorization({...r,sponsor:r.sponsor||void 0}),m=await d.getEthereumProvider(),w=await m.request({method:"secp256k1_sign",params:[$.hashAuthorization(y)]});return{...y,...P.parseSignature(w)}}),[e,t,n,s])}},exports.useSignMessage=function(e){let{signMessage:t}=r.useContext(o.PrivyContext);return o.usePrivyEventSubscription("signMessage",e),{signMessage:t}},exports.useSignTransaction=function(){let{signTransaction:e}=r.useContext(o.PrivyContext);return{signTransaction:e}},exports.useSignTypedData=function(e){let{signTypedData:t}=r.useContext(o.PrivyContext);return o.usePrivyEventSubscription("signTypedData",e),{signTypedData:t}},exports.useSignupWithPasskey=e=>{let t=o.useCaptcha(),{initSignupWithPasskey:n,signupWithPasskey:i,passkeyAuthState:s,setPasskeyAuthState:l}=a.usePrivyInternal();return{signupWithPasskey:r.useCallback((async()=>{try{let r;if(t.enabled&&"error"===t.status)throw new o.CaptchaError(t.error,null,a.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),r=await t.waitForResult()),await n({captchaToken:r,withPrivyUi:!1});let{user:s,isNewUser:l,wasAlreadyAuthenticated:c,loginAccount:d}=await i();e?.onComplete?.({user:s,isNewUser:l,wasAlreadyAuthenticated:c,loginMethod:"passkey",loginAccount:d})}catch(t){throw l({status:"error",error:t}),e?.onError?.(t.privyErrorCode||a.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[i,t.status]),state:s}},exports.useToken=function(e){let{getAccessToken:t}=r.useContext(o.PrivyContext);return o.usePrivyEventSubscription("accessToken",e),{getAccessToken:t}},exports.useUpdateAccount=function(e){let{updateEmail:t,updatePhone:n}=r.useContext(o.PrivyContext);return o.usePrivyEventSubscription("update",e),{updateEmail:t,updatePhone:n}},exports.useUser=()=>{let{setUser:e,client:t}=r.useContext(a.InternalPrivyContext),{user:n}=r.useContext(o.PrivyContext);return{user:n,refreshUser:r.useCallback((async()=>{let r=await(t?.updateUserAndIdToken());return e(r??null),r}),[t,e])}};
|
|
1
|
+
"use strict";var e=require("./privy-provider-CWADob3g.js"),r=require("./useActiveWallet-D5FyaqZJ.js"),t=require("react"),o=require("./internal-context-HesndSYh.js"),i=require("viem"),n=require("viem/experimental"),s=require("./getEmbeddedConnectedWallet-DTU4T9TJ.js");require("react/jsx-runtime"),require("mipd"),require("react-device-detect"),require("viem/utils"),require("uuid"),require("jose"),require("eventemitter3"),require("@coinbase/wallet-sdk"),require("@privy-io/js-sdk-core"),require("@marsidev/react-turnstile"),require("styled-components"),require("tinycolor2"),require("@heroicons/react/24/outline/ArrowLeftIcon"),require("@heroicons/react/24/outline/ArrowRightIcon"),require("@heroicons/react/24/outline/QuestionMarkCircleIcon"),require("@heroicons/react/24/outline/XMarkIcon"),require("@heroicons/react/24/outline/CheckIcon"),require("@heroicons/react/24/outline/Square2StackIcon"),require("@heroicons/react/24/outline/WalletIcon"),require("zustand"),require("@walletconnect/ethereum-provider"),require("@heroicons/react/24/outline/UserCircleIcon"),require("@heroicons/react/24/outline/EnvelopeIcon"),require("@heroicons/react/20/solid/CheckIcon"),require("@heroicons/react/24/outline/PhoneIcon"),require("@heroicons/react/24/outline/ExclamationTriangleIcon"),require("@heroicons/react/24/outline/ExclamationCircleIcon"),require("@heroicons/react/24/outline/ArrowTopRightOnSquareIcon"),require("@heroicons/react/24/solid/DocumentCheckIcon"),require("@heroicons/react/24/solid/XCircleIcon"),require("fast-password-entropy"),require("secure-password-utilities"),require("secure-password-utilities/wordlists"),require("@heroicons/react/24/outline/LockClosedIcon"),require("@heroicons/react/24/outline/PencilSquareIcon"),require("@heroicons/react/24/solid/CheckCircleIcon"),require("@heroicons/react/24/outline/ArrowPathIcon"),require("@heroicons/react/24/outline/EyeIcon"),require("@heroicons/react/24/outline/EyeSlashIcon"),require("@heroicons/react/24/outline/KeyIcon"),require("@heroicons/react/24/outline/ArrowDownTrayIcon"),require("@heroicons/react/24/outline/ClipboardDocumentCheckIcon"),require("@heroicons/react/24/outline/DocumentDuplicateIcon"),require("@heroicons/react/24/solid/LockClosedIcon"),require("@heroicons/react/24/outline/ShieldCheckIcon"),require("qrcode"),require("@heroicons/react/24/outline/FingerPrintIcon"),require("@heroicons/react/24/outline/ChevronRightIcon"),require("@heroicons/react/24/outline/DevicePhoneMobileIcon"),require("@heroicons/react/24/outline/ChevronDownIcon"),require("@heroicons/react/24/outline/CalendarIcon"),require("@headlessui/react"),require("@heroicons/react/24/outline/CheckCircleIcon"),require("@heroicons/react/24/outline/InformationCircleIcon"),require("@heroicons/react/24/outline/CreditCardIcon"),require("@heroicons/react/24/outline/QrCodeIcon"),require("@heroicons/react/24/solid/ArrowsRightLeftIcon"),require("@heroicons/react/24/outline/GlobeAltIcon"),require("ofetch"),require("@heroicons/react/24/outline"),require("@heroicons/react/24/outline/ClipboardDocumentIcon"),require("@heroicons/react/24/outline/CloudArrowUpIcon"),require("@heroicons/react/24/outline/NoSymbolIcon"),require("@heroicons/react/24/outline/ClockIcon"),require("@heroicons/react/24/outline/TrashIcon"),require("@heroicons/react/24/solid/CheckBadgeIcon"),require("@heroicons/react/24/solid/IdentificationIcon"),require("@heroicons/react/24/outline/MinusCircleIcon"),require("@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon"),require("@heroicons/react/24/solid/ShieldCheckIcon"),require("js-cookie");let a=async(e,r,t,i,n)=>{if(!e)throw i("linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:n}),new o.PrivyClientError("User must be authenticated before linking an account.");if(!r?.linkedAccounts.some((e=>e.type.includes(n))))throw new o.PrivyClientError(`OAuth account of type ${n} not linked to the account.`);await t(n)};exports.Captcha=e.Captcha,exports.ConnectorManager=e.ConnectorManager,exports.EthereumWalletConnector=e.EthereumWalletConnector,exports.LoginModal=e.LoginModal,exports.PrivyClient=e.PrivyClient,exports.PrivyProvider=e.PrivyProvider,exports.SUPPORTED_CHAINS=e.DEFAULT_SUPPORTED_CHAINS,exports.VERSION=e.VERSION,exports.WalletConnector=e.WalletConnector,exports.addPrivyRpcToChain=e.addPrivyRpcToChain,exports.addRpcUrlOverrideToChain=e.addRpcUrlOverrideToChain,exports.errorIndicatesMaxMfaRetries=e.errorIndicatesMaxMfaRetries,exports.errorIndicatesMfaTimeout=e.errorIndicatesMfaTimeout,exports.errorIndicatesMfaVerificationFailed=e.errorIndicatesMfaVerificationFailed,exports.getAccessToken=e.getCustomerAccessToken,exports.useIdentityToken=e.useIdentityToken,exports.useImportWallet=e.useImportWallet,exports.useLogout=e.useLogout,exports.useMfa=e.useMfa,exports.useMfaEnrollment=e.useMfaEnrollment,exports.usePrivy=e.usePrivy,exports.useRegisterMfaListener=e.useRegisterMfaListener,exports.useSolanaWallets=e.useSolanaWallets,exports.useWallets=e.useWallets,exports.useActiveWallet=r.useActiveWallet,exports.useConnectWallet=r.useConnectWallet,exports.useFundWallet=r.useFundWallet,exports.useLogin=r.useLogin,exports.getEmbeddedConnectedWallet=s.getEmbeddedConnectedWallet,exports.useConnectCoinbaseSmartWallet=()=>{let{connectCoinbaseSmartWallet:e}=o.usePrivyInternal();return{connectCoinbaseSmartWallet:e}},exports.useConnectOrCreateWallet=r=>{let{connectOrCreateWallet:t}=e.usePrivyContext();return e.usePrivyEventSubscription("connectOrCreateWallet",r),{connectOrCreateWallet:t}},exports.useCreateWallet=function(r){let{createWallet:o}=t.useContext(e.PrivyContext);return e.usePrivyEventSubscription("createWallet",r),{createWallet:o}},exports.useCrossAppAccounts=()=>{let{startCrossAppAuthFlow:r,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:o,signTypedDataWithCrossAppWallet:i,sendTransactionWithCrossAppWallet:n}=e.usePrivyContext();return{loginWithCrossAppAccount:({appId:e})=>r({appId:e,action:"login"}),linkCrossAppAccount:({appId:e})=>r({appId:e,action:"link"}),unlinkCrossAppAccount:t,signMessage:o,signTypedData:i,sendTransaction:n}},exports.useCustomAuth=r=>{let{customAuthStatus:t}=o.usePrivyInternal();return e.usePrivyEventSubscription("customAuth",r),{status:t}},exports.useDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:r}=o.usePrivyInternal();return{delegateWallet:async({address:e,chainType:t})=>await r({address:e,chainType:t,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},exports.useFarcasterSigner=function(){let{getFarcasterSignerPublicKey:r,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:o}=e.usePrivyContext();return{getFarcasterSignerPublicKey:r,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:o}},exports.useGuestAccounts=function(){let r=e.useAppConfig(),{getAccessToken:t,createWallet:i}=e.usePrivy(),n=e.useEmitPrivyEvent(),{client:s,setUser:a,setAuthenticated:u,setIsNewUser:l,initializeWalletProxy:c,refreshSessionAndUser:d}=o.usePrivyInternal();return{createGuestAccount:async()=>{if(!r.id||!s)throw Error("SDK not yet ready");s.startAuthFlow(new e.GuestFlow(r.id));try{let{user:h,isNewUser:p}=await s.authenticate();if(p=p||!1,!h)throw new o.PrivyClientError("Unable to authenticate guest account");let y=await t(),C=await c(e.WALLET_PROXY_TIMEOUT);if(y&&C)try{let t=e.shouldCreateEmbeddedEthWallet(h,r.embeddedWallets.ethereum.createOnLogin),o=e.shouldCreateEmbeddedSolWallet(h,r.embeddedWallets.solana.createOnLogin);if(t&&o){let e=await i();await C.createSolana({accessToken:y,ethereumAddress:e?.address}),h=await d()}else o?(await C.createSolana({accessToken:y,ethereumAddress:e.getPrivyEthereumWallet(h)?.address}),h=await d()):t?(await i(),h=await d()):a(h)}catch(e){a(h),console.warn("Unable to create embedded wallet for guest account")}return l(p),u(!0),n("login","onComplete",{user:h,isNewUser:p,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),h}catch(e){throw n("login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}}}},exports.useHeadlessDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:r}=o.usePrivyInternal();return{delegateWallet:async({address:e,chainType:t})=>await r({address:e,chainType:t,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}},exports.useLinkAccount=function(r){let{linkEmail:o,linkPhone:i,linkWallet:n,linkGoogle:s,linkApple:a,linkTwitter:u,linkDiscord:l,linkGithub:c,linkLinkedIn:d,linkTiktok:h,linkSpotify:p,linkInstagram:y,linkTelegram:C,linkFarcaster:g}=t.useContext(e.PrivyContext);return e.usePrivyEventSubscription("linkAccount",r),{linkEmail:o,linkPhone:i,linkWallet:n,linkGoogle:s,linkApple:a,linkTwitter:u,linkDiscord:l,linkGithub:c,linkLinkedIn:d,linkTiktok:h,linkSpotify:p,linkInstagram:y,linkFarcaster:g,linkTelegram:C}},exports.useLinkWithPasskey=e=>{let{initLinkWithPasskey:r,linkWithPasskey:i,passkeyAuthState:n,setPasskeyAuthState:s}=o.usePrivyInternal();return{linkWithPasskey:t.useCallback((async()=>{try{await r();let t=await i();if(!t)throw Error("Error, user not found");let o=t.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,r)=>r.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:t,linkMethod:"passkey",linkedAccount:o})}catch(r){throw s({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),r}}),[i]),state:n}},exports.useLinkWithSiwe=r=>{let i=e.useCaptcha(),{siweState:n,setSiweState:s,linkWithSiwe:a,generateSiweMessage:u}=o.usePrivyInternal();return{generateSiweMessage:t.useCallback((async({address:e,chainId:t})=>{try{if(!e||!t)throw Error("wallet address and chainId required to generate nonce");return await u({address:e,chainId:t}).then((e=>e))}catch(e){throw s({status:"error",error:e}),r?.onError?.(e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),e}}),[u]),linkWithSiwe:t.useCallback((async({signature:t,message:n,chainId:u,walletClientType:l,connectorType:c})=>{try{if(i.enabled&&"success"!==i.status)throw new e.CaptchaError(i.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:s,linkedAccount:d}=await a({message:n,signature:t,chainId:u,walletClientType:l,connectorType:c});d&&r?.onSuccess?.({user:s,linkMethod:"siwe",linkedAccount:d})}catch(t){throw s({status:"error",error:t}),r?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[a,i.status]),state:n}},exports.useLoginWithEmail=r=>{let i=e.useCaptcha(),{emailOtpState:n,setEmailOtpState:s,initLoginWithEmail:a,loginWithCode:u}=o.usePrivyInternal();return{sendCode:t.useCallback((async({email:t,disableSignup:n})=>{try{let r;if(!t)throw Error("Email required to send OTP code");if(i.enabled&&"error"===i.status)throw new e.CaptchaError(i.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return i.enabled&&"success"!==i.status&&(i.execute(),r=await i.waitForResult()),await a({email:t,captchaToken:r,disableSignup:n,withPrivyUi:!1})}catch(t){throw s({status:"error",error:t}),r?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[a]),loginWithCode:t.useCallback((async({code:t})=>{try{if(i.enabled&&"error"===i.status)throw new e.CaptchaError(i.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:s,wasAlreadyAuthenticated:a,linkedAccount:l}=await u(t);r?.onComplete?.({user:n,isNewUser:s,wasAlreadyAuthenticated:a,loginMethod:"email",loginAccount:l})}catch(t){throw s({status:"error",error:t}),r?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[u,i.status]),state:n}},exports.useLoginWithOAuth=r=>{e.usePrivyEventSubscription("login",r);let i=e.useCaptcha(),n=e.useIsServerConfigLoaded(),{ready:s,user:a}=e.usePrivyContext(),{initLoginWithHeadlessOAuth:u,loginWithHeadlessOAuth:l,oAuthState:c,setOAuthState:d,isHeadlessOAuthLoading:h}=o.usePrivyInternal(),p=t.useCallback((async r=>{try{if(i.enabled&&"success"!==i.status)throw new e.CaptchaError(i.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return await u(r.provider,i.token,r.disableSignup)}catch(r){throw d({status:"error",error:r}),r}}),[u,i]),y=t.useCallback((async()=>{let r=e.detectCompletingOAuthFlow();try{if(a)return console.warn("Cannot login with OAuth when already logged in"),a;if(!r.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");if(r.popupFlow)return}catch(r){throw d({status:"error",error:r}),r}try{return await l(r)}catch(r){throw d({status:"error",error:r}),r}finally{e.stripUrlOAuthParamsAndRemoveStateCode()}}),[l]);return t.useEffect((()=>{let r=e.detectCompletingOAuthFlow();s&&n&&r.inProgress&&!r.withPrivyUi&&!r.popupFlow&&y().catch((()=>{}))}),[s,n]),{initOAuth:p,loading:h,state:c}},exports.useLoginWithPasskey=r=>{let i=e.useCaptcha(),{initLoginWithPasskey:n,loginWithPasskey:s,passkeyAuthState:a,setPasskeyAuthState:u}=o.usePrivyInternal();return{loginWithPasskey:t.useCallback((async t=>{try{let a;if(i.enabled&&"error"===i.status)throw new e.CaptchaError(i.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);i.enabled&&"success"!==i.status&&(i.execute(),a=await i.waitForResult()),await n({captchaToken:a,withPrivyUi:!1});let{user:u,isNewUser:l,wasAlreadyAuthenticated:c,loginAccount:d}=await s(t);r?.onComplete?.({user:u,isNewUser:l,wasAlreadyAuthenticated:c,loginMethod:"passkey",loginAccount:d})}catch(t){throw u({status:"error",error:t}),r?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[s,i.status]),state:a}},exports.useLoginWithSms=r=>{let i=e.useCaptcha(),{smsOtpState:n,setSmsOtpState:s,initLoginWithSms:a,loginWithCode:u}=o.usePrivyInternal();return{sendCode:t.useCallback((async({phoneNumber:t,disableSignup:n})=>{try{let r;if(!t)throw Error("SMS required to send OTP code");if(i.enabled&&"error"===i.status)throw new e.CaptchaError(i.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return i.enabled&&"success"!==i.status&&(i.execute(),r=await i.waitForResult()),await a({phoneNumber:t,captchaToken:r,disableSignup:n,withPrivyUi:!1})}catch(t){throw s({status:"error",error:t}),r?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[a]),loginWithCode:t.useCallback((async({code:t})=>{try{if(i.enabled&&"success"!==i.status)throw new e.CaptchaError(i.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:s,wasAlreadyAuthenticated:a,linkedAccount:l}=await u(t);r?.onComplete?.({user:n,isNewUser:s,wasAlreadyAuthenticated:a,loginMethod:"sms",loginAccount:l})}catch(t){throw s({status:"error",error:t}),r?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[u,i.status]),state:n}},exports.useLoginWithTelegram=r=>{let i=e.useCaptcha(),{initLoginWithTelegram:n,loginWithTelegram:s,telegramAuthState:a,setTelegramAuthState:u}=o.usePrivyInternal();return{login:t.useCallback((async t=>{try{if(i.enabled&&"success"!==i.status)throw new e.CaptchaError(i.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);await n(i.token,t?.disableSignup);let{user:a,isNewUser:u,loginAccount:l,wasAlreadyAuthenticated:c}=await s({intent:"login"});r?.onComplete?.({user:a,isNewUser:u,wasAlreadyAuthenticated:c,loginMethod:"telegram",loginAccount:l})}catch(t){throw u({status:"error",error:t}),r?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[n,s,i]),state:a}},exports.useModalStatus=()=>{let{isModalOpen:r}=t.useContext(e.PrivyContext);return{isOpen:r}},exports.useOAuthTokens=function(r){let{authenticated:t,user:i}=e.usePrivyContext(),{initLoginWithOAuth:n}=o.usePrivyInternal(),s=e.useEmitPrivyEvent();return e.usePrivyEventSubscription("oAuthAuthorization",r),{reauthorize:e=>a(t,i,n,s,e.provider)}},exports.useSendTransaction=function(r){let{sendTransaction:o}=t.useContext(e.PrivyContext);return e.usePrivyEventSubscription("sendTransaction",r),{sendTransaction:o}},exports.useSetWalletPassword=function(r){let{setWalletPassword:o}=t.useContext(e.PrivyContext);return e.usePrivyEventSubscription("setWalletPassword",r),{setWalletPassword:o}},exports.useSetWalletRecovery=function(r){let{setWalletRecovery:o}=t.useContext(e.PrivyContext);return e.usePrivyEventSubscription("setWalletRecovery",r),{setWalletRecovery:o}},exports.useSignAuthorization=()=>{let{ready:r,wallets:s}=e.useWallets(),{user:a}=e.usePrivyContext(),{rpcConfig:u,chains:l,appId:c}=o.usePrivyInternal();return{signAuthorization:t.useCallback((async(t,o)=>{if(!a)throw Error("User must be authenticated before signing with a Privy wallet");if(!r)throw Error("Wallets are not ready");let d=o?.address??e.getPrivyEthereumWallet(a)?.address??i.zeroAddress,h=s.find((e=>i.getAddress(e.address)===i.getAddress(d)));if(!h)throw Error("Signing wallet not found.");let p=t.chainId??Number(h.chainId.split(":")[1]),y=l.find((e=>e.id===p));if(!y)throw Error("Error, chain not configured in PrivyProvider config");let C=i.createWalletClient({account:d,chain:y,transport:i.http(e.getJsonRpcEndpointFromChain(y,u,c))}).extend(n.eip7702Actions()),g=await C.prepareAuthorization({...t,sponsor:t.sponsor||void 0}),w=await h.getEthereumProvider(),A=await w.request({method:"secp256k1_sign",params:[n.hashAuthorization(g)]});return{...g,...i.parseSignature(A)}}),[r,s,a,l])}},exports.useSignMessage=function(r){let{signMessage:o}=t.useContext(e.PrivyContext);return e.usePrivyEventSubscription("signMessage",r),{signMessage:o}},exports.useSignTransaction=function(){let{signTransaction:r}=t.useContext(e.PrivyContext);return{signTransaction:r}},exports.useSignTypedData=function(r){let{signTypedData:o}=t.useContext(e.PrivyContext);return e.usePrivyEventSubscription("signTypedData",r),{signTypedData:o}},exports.useSignupWithPasskey=r=>{let i=e.useCaptcha(),{initSignupWithPasskey:n,signupWithPasskey:s,passkeyAuthState:a,setPasskeyAuthState:u}=o.usePrivyInternal();return{signupWithPasskey:t.useCallback((async()=>{try{let t;if(i.enabled&&"error"===i.status)throw new e.CaptchaError(i.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);i.enabled&&"success"!==i.status&&(i.execute(),t=await i.waitForResult()),await n({captchaToken:t,withPrivyUi:!1});let{user:a,isNewUser:u,wasAlreadyAuthenticated:l,loginAccount:c}=await s();r?.onComplete?.({user:a,isNewUser:u,wasAlreadyAuthenticated:l,loginMethod:"passkey",loginAccount:c})}catch(e){throw u({status:"error",error:e}),r?.onError?.(e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}}),[s,i.status]),state:a}},exports.useToken=function(r){let{getAccessToken:o}=t.useContext(e.PrivyContext);return e.usePrivyEventSubscription("accessToken",r),{getAccessToken:o}},exports.useUpdateAccount=function(r){let{updateEmail:o,updatePhone:i}=t.useContext(e.PrivyContext);return e.usePrivyEventSubscription("update",r),{updateEmail:o,updatePhone:i}},exports.useUser=()=>{let{setUser:r,client:i}=t.useContext(o.InternalPrivyContext),{user:n}=t.useContext(e.PrivyContext);return{user:n,refreshUser:t.useCallback((async()=>{let e=await(i?.updateUserAndIdToken());return r(e??null),e}),[i,r])}};
|