@privy-io/react-auth 3.3.0 → 3.4.0

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.
Files changed (42) hide show
  1. package/dist/cjs/{SignRequestScreen-CvBcoZRA.js → SignRequestScreen-BtiA_kjR.js} +19 -19
  2. package/dist/cjs/abstract-smart-wallets.js +1 -1
  3. package/dist/cjs/index.js +7 -7
  4. package/dist/cjs/{smart-wallets-Cgmp6lBz.js → smart-wallets-CT6HYICU.js} +1 -1
  5. package/dist/cjs/smart-wallets.js +1 -1
  6. package/dist/cjs/solana.js +1 -1
  7. package/dist/cjs/ui.js +1 -1
  8. package/dist/cjs/use-export-wallet-C_4yZPUM.js +2 -0
  9. package/dist/cjs/{useActiveWallet-DAK4USsc.js → useActiveWallet-DygS7fQB.js} +1 -1
  10. package/dist/cjs/{usePrivy-BQiDRA6a.js → usePrivy-8s4mCLcX.js} +1 -1
  11. package/dist/dts/extended-chains.d.mts +1 -1
  12. package/dist/dts/extended-chains.d.ts +1 -1
  13. package/dist/dts/farcaster.d.mts +1 -1
  14. package/dist/dts/farcaster.d.ts +1 -1
  15. package/dist/dts/index.d.mts +6 -4
  16. package/dist/dts/index.d.ts +6 -4
  17. package/dist/dts/smart-wallets.d.mts +2 -2
  18. package/dist/dts/smart-wallets.d.ts +2 -2
  19. package/dist/dts/solana.d.mts +4 -5
  20. package/dist/dts/solana.d.ts +4 -5
  21. package/dist/dts/{types-C97UOzaM.d.mts → types-tFJ_e9u8.d.mts} +5 -5
  22. package/dist/dts/{types-C97UOzaM.d.ts → types-tFJ_e9u8.d.ts} +5 -5
  23. package/dist/dts/ui.d.mts +1 -1
  24. package/dist/dts/ui.d.ts +1 -1
  25. package/dist/esm/{SignRequestScreen-Dnn_x6kV.mjs → SignRequestScreen-Dkx-HBRI.mjs} +17 -17
  26. package/dist/esm/abstract-smart-wallets.mjs +1 -1
  27. package/dist/esm/extended-chains.mjs +1 -1
  28. package/dist/esm/farcaster.mjs +1 -1
  29. package/dist/esm/index.mjs +4 -4
  30. package/dist/esm/{internal-context-LlMdpfkb.mjs → internal-context-CfE_S5P-.mjs} +1 -1
  31. package/dist/esm/{privy-context-C7K3ZBW-.mjs → privy-context-DDSW3jEM.mjs} +1 -1
  32. package/dist/esm/{smart-wallets-D86YXRN5.mjs → smart-wallets-BElFh8An.mjs} +1 -1
  33. package/dist/esm/smart-wallets.mjs +1 -1
  34. package/dist/esm/solana.mjs +1 -1
  35. package/dist/esm/ui.mjs +2 -2
  36. package/dist/esm/use-export-wallet-OoiI5as_.mjs +1 -0
  37. package/dist/esm/{use-sign-with-user-signer-DwqsbciW.mjs → use-sign-with-user-signer-DVcbjNtZ.mjs} +1 -1
  38. package/dist/esm/{useActiveWallet-YrSgEFNG.mjs → useActiveWallet-BjD-txC9.mjs} +1 -1
  39. package/dist/esm/{usePrivy-CYAVrCyA.mjs → usePrivy-BJYprMT0.mjs} +1 -1
  40. package/package.json +6 -6
  41. package/dist/cjs/use-export-wallet-Crjmwv6E.js +0 -2
  42. package/dist/esm/use-export-wallet-DVZxxj2x.mjs +0 -1
package/dist/cjs/index.js CHANGED
@@ -1,7 +1,7 @@
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("@privy-io/js-sdk-core"),o=require("./paths-B00ZrFQm.js"),s=require("./SignRequestScreen-CvBcoZRA.js"),l=require("uuid"),c=require("jose"),d=require("./privy-context-NMR-GjnL.js"),u=require("eventemitter3"),h=require("@coinbase/wallet-sdk"),p=require("@privy-io/ethereum"),y=require("ofetch"),m=require("js-cookie"),w=require("zustand"),g=require("@marsidev/react-turnstile"),v=require("styled-components"),f=require("./internal-context-DNWjSiYq.js"),C=require("./useActiveWallet-DAK4USsc.js"),E=require("@heroicons/react/24/outline/DevicePhoneMobileIcon"),A=require("@heroicons/react/24/outline/FingerPrintIcon"),P=require("@heroicons/react/24/outline/PhoneIcon"),k=require("@heroicons/react/24/outline/ShieldCheckIcon"),b=require("@heroicons/react/24/outline/CalendarIcon"),x=require("@heroicons/react/24/outline/ExclamationTriangleIcon"),T=require("viem"),S=require("@headlessui/react"),_=require("@privy-io/urls"),I=require("./usePrivy-BQiDRA6a.js"),U=require("lucide-react"),W=require("@heroicons/react/24/outline/EnvelopeIcon"),R=require("@heroicons/react/24/outline/QuestionMarkCircleIcon"),O=require("@heroicons/react/24/solid/CheckBadgeIcon"),M=require("@heroicons/react/24/solid/IdentificationIcon"),N=require("@heroicons/react/24/outline/ChevronRightIcon"),j=require("@heroicons/react/24/outline/MinusCircleIcon"),F=require("@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon"),L=require("@heroicons/react/24/outline/ClockIcon"),D=require("@heroicons/react/24/outline/CheckCircleIcon"),q=require("@heroicons/react/24/solid/ShieldCheckIcon"),H=require("@heroicons/react/24/outline/GlobeAltIcon"),B=require("./frame-8JZCzmCf.js"),z=require("@privy-io/public-api"),K=require("./use-sign-with-user-signer-Q0_LRVtz.js"),V=require("./getEmbeddedConnectedWallet-6TsVZJkD.js"),$=require("viem/accounts");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("@scure/base"),require("tinycolor2"),require("@heroicons/react/24/outline/UserCircleIcon"),require("@heroicons/react/24/outline/ArrowLeftIcon"),require("@heroicons/react/24/outline/ArrowRightIcon"),require("@heroicons/react/24/outline/XMarkIcon"),require("@heroicons/react/20/solid/CheckIcon"),require("@heroicons/react/24/outline/WalletIcon"),require("@heroicons/react/24/outline/ExclamationCircleIcon"),require("@heroicons/react/24/outline/Square2StackIcon"),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/outline/ArrowPathIcon"),require("@heroicons/react/24/outline/EyeIcon"),require("@heroicons/react/24/outline/EyeSlashIcon"),require("@heroicons/react/24/outline/KeyIcon"),require("@heroicons/react/24/solid/CheckCircleIcon"),require("@heroicons/react/24/outline/ArrowDownTrayIcon"),require("@heroicons/react/24/outline/ClipboardDocumentCheckIcon"),require("@heroicons/react/24/outline/DocumentDuplicateIcon"),require("@heroicons/react/24/solid/XCircleIcon"),require("@heroicons/react/24/outline"),require("@tanstack/react-virtual"),require("@heroicons/react/24/outline/CheckIcon"),require("qrcode"),require("@walletconnect/ethereum-provider"),require("@heroicons/react/24/outline/CreditCardIcon"),require("@heroicons/react/24/outline/QrCodeIcon"),require("@heroicons/react/24/solid/ArrowsRightLeftIcon"),require("@heroicons/react/24/outline/InformationCircleIcon"),require("@heroicons/react/24/outline/ClipboardDocumentIcon"),require("@heroicons/react/24/outline/ChevronDownIcon");var Z=/*#__PURE__*/Y(r),J=/*#__PURE__*/Y(a),X=/*#__PURE__*/G(c),Q=/*#__PURE__*/Y(u),ee=/*#__PURE__*/Y(m),te=/*#__PURE__*/Y(E),re=/*#__PURE__*/Y(A),ne=/*#__PURE__*/Y(P),ie=/*#__PURE__*/Y(k),ae=/*#__PURE__*/Y(b),oe=/*#__PURE__*/Y(x),se=/*#__PURE__*/Y(W),le=/*#__PURE__*/Y(R),ce=/*#__PURE__*/Y(O),de=/*#__PURE__*/Y(M),ue=/*#__PURE__*/Y(N),he=/*#__PURE__*/Y(j),pe=/*#__PURE__*/Y(F),ye=/*#__PURE__*/Y(L),me=/*#__PURE__*/Y(D),we=/*#__PURE__*/Y(q),ge=/*#__PURE__*/Y(H);function ve(e){return e?{"privy-ui":"t"}:void 0}class fe{async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new o.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessAuthenticatePath,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw o.formatApiError(e)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new o.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessLinkPath,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw o.formatApiError(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new o.PrivyClientError("Email must be set when initialzing authentication.");let n=ve(r);try{return await this.api.post(o.passwordlessInitPath,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw o.formatApiError(e)}}constructor({email:e,captchaToken:t,disableSignup:r}){this.meta={email:e,captchaToken:t,disableSignup:r??!1}}}class Ce extends fe{async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new o.PrivyClientError("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(o.updateEmailPath,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw o.formatApiError(e)}}constructor(e,t,r){super({email:t,captchaToken:r}),this.meta={email:t,captchaToken:r,oldAddress:e,disableSignup:!1}}}class Ee{get meta(){return this._meta}async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new o.PrivyClientError("Auth flow must be initialized first");try{let e=await this.api.post(o.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 o.PrivyClientError("No response from authentication");return e}catch(e){throw o.formatApiError(e)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.farcasterLinkPath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(e){throw o.formatApiError(e)}}async _startChannelOnce(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");let e=await this.api.post(o.farcasterInitPath,{token:this.captchaToken});n.isMobile&&!n.isIOS&&e.connect_uri&&s.openHref(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new o.PrivyClientError("Auth flow must be initialized first");let e=await this.api.get(o.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 s.RunEffectOnce(this._startChannelOnce.bind(this)),this.pollForReady=new s.RunEffectOnce(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function Ae(){return"undefined"!=typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function Pe(){if(!Ae())return;let e=window.chrome;return e?.runtime?.id}function ke(){if(!Ae())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function be(e){return new Promise(((t,r)=>{ke()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},(async e=>{try{let r=function(){if(!Ae())return;let e=window.chrome;return e?.runtime?.lastError?.message}();if(r||!e){let e=`WebAuthFlow failed: ${r||"Response URI missing"}`;throw Error(e)}let n=new URL(e),i=Pe();if(!i)throw Error("Invalid extension context");if("chrome-extension:"===n.protocol){if(n.hostname!==i)throw Error("Invalid responseUri origin")}else{if("https:"!==n.protocol)throw Error("Invalid responseUri protocol");{let e=n.hostname.split(".");if(3!==e.length||"chromiumapp"!==e[1]||"org"!==e[2]||e[0]!==i)throw Error("Invalid responseUri origin")}}let a=n.searchParams.get("privy_oauth_state"),o=n.searchParams.get("privy_oauth_code");if(!a||!o)throw Error("Invalid responseUri - missing required parameters");t({privyOAuthState:a,privyOAuthCode:o})}catch(e){r(e)}})):r(Error("Chrome identity API not available"))}))}class xe{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new o.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new o.PrivyClientError("User denied confirmation during OAuth flow");let e=s.getCodeVerifier();try{let t=await this.api.post(o.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 s.s.del(s.CODE_VERIFIER_KEY),s.s.del(s.HEADLESS_OAUTH_KEY),s.s.del(s.OAUTH_DISABLE_SIGNUP_KEY),t}catch(e){let t=o.formatApiError(e);if(t.privyErrorCode)throw new o.PrivyClientError(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new o.PrivyClientError("Invalid code during oauth flow.",void 0,o.PrivyErrorCode.OAUTH_USER_DENIED);throw new o.PrivyClientError("Invalid code during OAuth flow.",void 0,o.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new o.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new o.PrivyClientError("User denied confirmation during OAuth flow");let e=s.s.get(s.CODE_VERIFIER_KEY);if(!e)throw new o.PrivyClientError("Authentication error.");try{let t=await this.api.post(o.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return s.s.del(s.CODE_VERIFIER_KEY),t}catch(e){throw o.formatApiError(e)}}async getAuthorizationUrl(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.provider)throw new o.PrivyClientError("Provider must be set when initializing OAuth authentication.");let e=s.createCodeVerifier();s.s.put(s.CODE_VERIFIER_KEY,e);let t=s.createStateCode();s.s.put(s.STATE_CODE_KEY,t);let r=await s.deriveCodeChallengeFromCodeVerifier(e);this.meta.withPrivyUi||s.s.put(s.HEADLESS_OAUTH_KEY,!0),this.meta.disableSignup?s.s.put(s.OAUTH_DISABLE_SIGNUP_KEY,!0):s.s.del(s.OAUTH_DISABLE_SIGNUP_KEY);let n=ve(this.meta.withPrivyUi),i=window.location.href,a=function(){let e=Pe();if(e)return`https://${e}.chromiumapp.org`}();a&&(i=a);try{return await this.api.post(o.oAuthInitPath,{provider:this.meta.provider,redirect_to:this.meta.customOAuthRedirectUrl||i,token:this.meta.captchaToken,code_challenge:r,state_code:t},{headers:{...n}})}catch(e){throw o.formatApiError(e)}}constructor(e){this.meta=e}}const Te=({style:t})=>/*#__PURE__*/e.jsx(ge.default,{style:{color:"var(--privy-color-error)",...t}});let Se={google:{name:"Google",component:s.Google},discord:{name:"Discord",component:s.Discord},github:{name:"Github",component:s.Github},linkedin:{name:"LinkedIn",component:s.LinkedIn},twitter:{name:"Twitter",component:s.Twitter},spotify:{name:"Spotify",component:s.Spotify},instagram:{name:"Instagram",component:s.Instagram},tiktok:{name:"Tiktok",component:s.Tiktok},line:{name:"LINE",component:s.Line},twitch:{name:"Twitch",component:s.Twitch},apple:{name:"Apple",component:s.Apple}},_e=({iconUrl:e,...t})=>Z.default.createElement("svg",{width:"33",height:"32",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...t},Z.default.createElement("foreignObject",{x:"2",y:"2",width:"29",height:"28"},Z.default.createElement("img",{src:e,width:"29",height:"28",style:{display:"block",objectFit:"contain",borderRadius:"4px"},alt:"Provider icon"})));const Ie=(e,t)=>{if(e in Se)return Se[e];if(d.isCustomOAuthProvider(e)&&t){let r=t.find((t=>t.provider===e));if(r)return{name:r.provider_display_name,component:e=>Z.default.createElement(_e,{...e,iconUrl:r.provider_icon_url})}}return{name:"Unknown",component:Te}};function Ue(){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:!s.s.get(s.HEADLESS_OAUTH_KEY),popupFlow:null!==window.opener&&i,disableSignup:!!s.s.get(s.OAUTH_DISABLE_SIGNUP_KEY)}}class We{async initRegisterFlow(e){if(!this.api)throw new o.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 o.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 o.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 o.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new o.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(o.passkeyRegisterPath,{relying_party:this.meta.initRegisterResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new o.PrivyClientError("Passkey request timed out or rejected by user.",void 0,o.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw o.formatApiError(e)}}async authenticate(){if(this.authenticateForRegistration)return this.register();let e=await import("@simplewebauthn/browser");if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new o.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(o.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 o.PrivyClientError("Passkey request timed out or rejected by user.",void 0,o.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw o.formatApiError(e)}}async link(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new o.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(o.passkeyLinkPath,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new o.PrivyClientError("Passkey request timed out or rejected by user.",void 0,o.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw o.formatApiError(e)}}async _initRegisterOnce(e){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");let t=ve(e);return await this.api.post(o.passkeyInitRegisterPath,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");let t=ve(e);return await this.api.post(o.passkeyInitAuthenticatePath,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");return await this.api.post(o.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 s.RunEffectOnce(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new s.RunEffectOnce(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new s.RunEffectOnce(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t}}}class Re{async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new o.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessSmsAuthenticatePath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw o.formatApiError(e)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new o.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessSmsLinkPath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw o.formatApiError(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new o.PrivyClientError("phone nNumber must be set when initialzing authentication.");let n=ve(r);try{return await this.api.post(o.passwordlessSmsInitPath,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw o.formatApiError(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:r}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:r??!1}}}class Oe extends Re{async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new o.PrivyClientError("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(o.updatePhonePath,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw o.formatApiError(e)}}constructor(e,t,r){super({phoneNumber:t,captchaToken:r}),this.meta={phoneNumber:t,captchaToken:r,oldPhoneNumber:e,disableSignup:!1}}}class Me{static parse(e){try{return new Me(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return X.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=X.decodeJwt(e)}}class Ne extends Me{static parse(e){try{return new Ne(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}let je,Fe;class Le extends s.EthereumWalletConnector{async initialize(){await this.importPromise,await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:s.BASE_ACCOUNT_DATA_URI,id:"com.coinbase.wallet"}}async promptConnection(){try{await this.importPromise;let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new o.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw s.formatConnectorError(e)}}constructor(e,t,r,n,i){super("base_account",e,t,r),this.connectorType="base_account",this.walletClientType="base_account",this.displayName="Base",this.setBaseAccountSdk=i,this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.baseAccountConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},je?(this.proxyProvider.setWalletProvider(je.getProvider()),this.setBaseAccountSdk(je),console.log("Base Account SDK Initialized")):this.importPromise=import("@base-org/account").then((({createBaseAccountSDK:e})=>{je=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider(je.getProvider()),this.setBaseAccountSdk(je),console.log("Base Account SDK Initialized")})).catch(console.error)}}let De=[1,11155111,137,10,8453,84532,42161,7777777,43114,56];class qe extends s.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:s.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 o.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw s.formatConnectorError(e)}}updateConnectionPreference(e){this.coinbaseWalletConfig={...this.coinbaseWalletConfig,preference:{...this.coinbaseWalletConfig.preference,options:e}},this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",Fe=h.createCoinbaseWalletSDK({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(Fe.getProvider())}constructor(e,t,r,n){if(super("coinbase_wallet",e,t,r),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.coinbaseWalletConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},this.walletClientType="smartWalletOnly"===this.coinbaseWalletConfig.preference?.options?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!Fe){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter((e=>!De.includes(e))):[];e.length>0&&!e.every((e=>a.DEFAULT_SUPPORTED_CHAIN_IDS.has(e)))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${e.join(", ")}`),Fe=h.createCoinbaseWalletSDK(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(Fe.getProvider())}}class He extends s.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:[s.toHex(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:s.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 Be=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];class ze extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class Ke extends Q.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new ze(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await ui()||!this.address)throw new ze("Disconnected",4900);let{hash:r}=await mi(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new ze(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await ui()||!this.address)throw new ze("Disconnected",4900);let{signature:r}=await yi(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new ze(`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 ze(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=s.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 hi({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 pi(s.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:s.toHex(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...p.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 s.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=>Be.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await ui();if(await wi({address:this.address}),!t||!this.address)throw new ze("Disconnected",4900);try{let r={method:e.method,params:e.params},n=this.walletAccount;return n&&d.getIsUnifiedWallet(n)?this.handleWalletApiRequest(r,n,t):(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:r})).response.data}catch(e){throw console.error(e),new ze("Disconnected",4900)}}}async handleWalletApiRequest(e,t,r){let n=this.privyClient;if(!n)throw new ze("Disconnected",4900);if("secp256k1_sign"===e.method){let i=await a.rpc(n,(async({message:e})=>this.walletProxy.signWithUserSigner({accessToken:r,message:e})),{chain_type:"ethereum",method:"secp256k1_sign",wallet_id:t.id,params:{hash:e.params[0]}});if("secp256k1_sign"!==i.method)throw new ze(`Invalid params for ${e.method}`,4200);return i.data.signature}throw new ze(`Method not supported: ${e.method}`,4200)}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:n,rpcConfig:i,chains:a,appId:o,chainId:l=1,walletIndex:c,privyClient:d,walletAccount:u}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=n,this.chainId=l,this.rpcConfig=i,this.chains=a,this.publicClient=s.getPublicClient(l,this.chains,i,{appId:o}),this.rpcTimeoutDuration=s.getRpcTimeout(i,"privy"),this.appId=o,this.walletIndex=c,this.privyClient=d,this.walletAccount=u}}function Ve(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var $e=0;class Ye extends s.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 o.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw s.formatConnectorError(e)}}constructor(e,t,r,n,i){super(i||"unknown",e,t,r),this.connectorType="injected",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=n;let a=n.provider;this.proxyProvider.setWalletProvider(a)}}var Ge="__private_"+$e+++"__walletBranding";class Ze extends s.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 Ve(this,Ge)[Ge]??{name:"Browser Extension",icon:s.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 o.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw s.formatConnectorError(e)}}constructor(e,t,r,n,i){super(i??"unknown",e,t,r),Object.defineProperty(this,Ge,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(n),"metamask"===i?Ve(this,Ge)[Ge]={name:"MetaMask",icon:s.Metamask,id:"io.metamask"}:"phantom"===i&&(Ve(this,Ge)[Ge]={name:"Phantom",icon:s.Phantom,id:"phantom"})}}class Je extends Ye{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 o.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw s.formatConnectorError(e)}}}class Xe extends Q.default{get wallets(){let e=new Set;return 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)}))}async initialize(e){if(this.initialized&&!e||(e&&this.removeAllConnectors(),this.externalWalletConfig.disableAllExternalWallets))return;let t=s.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"}),this.walletList.includes("base_account")&&this.createEthereumWalletConnector({connectorType:"base_account",walletClientType:"base_account"}),Object.values(s.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 s.SolanaNullConnector({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,r){return"wallet_connect_v2"===e?this.walletConnectors.filter(s.isEthereumWalletConnector).find((t=>t.connectorType===e&&(!r||t.wallets.some((e=>e.address===r)))))??null:this.walletConnectors.filter(s.isEthereumWalletConnector).find((n=>n.connectorType===e&&n.walletClientType===t&&(!r||n.wallets.some((e=>e.address===r)))))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(s.isSolanaWalletConnector).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}findImportedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded_imported"===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.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&this.emit("walletsUpdated")}addEmbeddedWalletConnectors({walletProxy:e,user:t,embeddedWallets:r,defaultChain:n,appId:i,privyClient:a}){let{entropyId:o,entropyIdVerifier:l}=s.getEntropyDetailsForUser(t);for(let t of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===t.walletIndex));if(r&&s.isEthereumWalletConnector(r))r.proxyProvider.walletProxy=e;else{let r=new He({provider:new Ke({walletProxy:e,address:t.address,entropyId:o,entropyIdVerifier:l,rpcConfig:this.rpcConfig,chains:this.chains,appId:i,chainId:n.id,walletIndex:t.walletIndex,privyClient:a,walletAccount:t}),chains:this.chains,defaultChain:n,rpcConfig:this.rpcConfig,imported:!1,walletIndex:t.walletIndex});this.addWalletConnector(r)}}}addImportedWalletConnector(e,t,r,n){let i=this.findWalletConnector("embedded_imported","privy",t);if(i&&s.isEthereumWalletConnector(i))i.proxyProvider.walletProxy=e;else{let i=new He({provider:new Ke({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.storedConnections=s.loadConnectionHistory(),this.emit("walletsUpdated")}removeImportedWalletConnectors(){let e=this.findImportedWalletConnectors();e.length&&(e.forEach((e=>{let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1)})),this.storedConnections=s.loadConnectionHistory(),this.emit("walletsUpdated"))}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:n}){let i=this.findWalletConnector(e,t);if(i&&s.isEthereumWalletConnector(i))return i instanceof s.WalletConnectV2WalletConnector&&i.resetConnection(t),i;let a=(()=>"injected"!==e?"coinbase_wallet"===e?new qe(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new Le(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new s.WalletConnectV2WalletConnector({walletConnectCloudProjectId:this.walletConnectCloudProjectId,rpcConfig:this.rpcConfig,chains:this.chains,defaultChain:this.defaultChain,shouldEnforceDefaultChainOnConnect:this.shouldEnforceDefaultChainOnConnect,privyAppId:this.privyAppId,privyAppName:this.privyAppName,walletClientType:t}):n?new s.EthereumNullConnector({id:n.client,name:n.name,defaultChain:this.defaultChain,walletClientType:n.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new Je(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Ze(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Ze(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Ze(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new Ye(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)}))}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,o,l,c,d,u,h){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.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=n,this.defaultChain=i,this.walletConnectors=[],this.initialized=!1,this.store=a,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=l,this.externalWalletConfig=c,this.privyAppName=d,this.walletChainType=h||"ethereum-only",this.setBaseAccountSdk=u,this.storedConnections=s.loadConnectionHistory()}}let Qe=[o.sessionsRefreshPath,o.sessionsLogoutPath,o.analyticsEventsPath];class et{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw o.formatApiError(e)}}async post(e,t,r){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...r})}catch(e){throw o.formatApiError(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw o.formatApiError(e)}}constructor({appId:e,appClientId:t,client:r,defaults:n}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=r.clientAnalyticsId,this.sdkVersion=s.VERSION,this.client=r,this.defaults=n,this.fallbackApiUrl=r.fallbackApiUrl,this.baseFetch=y.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=Qe.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 o.PrivyTimeoutError}})}}let tt=/paymaster\.biconomy\.io\/api/i,rt={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const nt=(e,t)=>e&&tt.test(e)?rt:t&&t.policy_id?{policyId:t.policy_id}:void 0,it=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});class at{async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.customJwtAccountAuthenticatePath,{token:this.meta.token})}catch(e){throw o.formatApiError(e)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.customJwtAccountLinkPath,{token:this.meta.token})}catch(e){throw o.formatApiError(e)}}constructor(e){this.meta={token:e}}}class ot{getOrCreateGuestCredential(e){let t=s.getGuestCredentialStorageKey(e);if(s.e$1()){if(s.s.get(t))return s.s.get(t);{let e=c.base64url.encode(s.randomBytes(32));return s.s.put(t,e),e}}return c.base64url.encode(s.randomBytes(32))}async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.guestAccountAuthenticatePath,{guest_credential:this.meta.guestCredential})}catch(e){throw o.formatApiError(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}function st(){return!(n.isSafari&&window.location.origin.startsWith("http://localhost"))}const lt=w.create((()=>({identityToken:null})));var ct,dt=((ct={}).PRIVY="privy_access_token",ct.CUSTOMER="customer_access_token",ct);class ut{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)}get privyAccessToken(){return this._getToken(s.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}_getToken(e){try{let t=s.s.get(e);return"string"==typeof t?Me.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=s.s.get(s.REFRESH_TOKEN_STORAGE_KEY);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=s.s.get(s.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return null;{let r=new Me(t);return r.isExpired()?(s.s.del(s.getProviderAccessTokenStorageKey(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=ee.default.get(s.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!==s.DEPRECATED_REFRESH_TOKEN;return this.mightHaveServerCookies||t&&r}hasActiveAccessToken(e){let t=Me.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?s.s.put(s.getProviderAccessTokenStorageKey(e),t):s.s.del(s.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:d.convertUserResponseToUser(r),isNewUser:n,oAuthTokens:a}}catch(e){throw console.warn("Error authenticating session"),o.formatPrivyError(e)}}_trackAuthenticateEvents(e,t){let r=function(e){return e instanceof fe?"email":e instanceof Re?"sms":e instanceof s.SiweFlow?"siwe":e instanceof ot?"guest":e instanceof at?"custom_auth":e instanceof xe?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:d.convertUserResponseToUser(t),oAuthTokens:n}}catch(e){throw console.warn("Error linking account"),o.formatPrivyError(e)}}async _refresh(){if(!this.api)throw new o.PrivyClientError("Session has no API instance");if(!this.client)throw new o.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(o.sessionsRefreshPath,t?{refresh_token:t}:{},{headers:n})}return this.handleTokenResponse(r),d.convertUserResponseToUser(r.user)}catch(e){if(e instanceof o.PrivyApiError&&e.privyErrorCode===o.PrivyErrorCode.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw o.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(o.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=s.s.get(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY);if(s.s.put(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY,e),!this.client?.useServerCookies){let t=Me.parse(e)?.expiration;ee.default.set(s.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:st(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else s.s.del(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY),ee.default.remove(s.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(s.s.put(s.REFRESH_TOKEN_STORAGE_KEY,e),this.client?.useServerCookies||ee.default.set(s.SESSION_COOKIE_KEY,"t",{sameSite:"Strict",secure:st(),expires:30})):(s.s.del(s.REFRESH_TOKEN_STORAGE_KEY),ee.default.remove(s.REFRESH_TOKEN_COOKIE_KEY),ee.default.remove(s.SESSION_COOKIE_KEY))}storePrivyAccessToken(e){"string"==typeof e?s.s.put(s.PRIVY_ACCESS_TOKEN_STORAGE_KEY,e):s.s.del(s.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}storeIdentityToken(e){if(lt.setState({identityToken:e}),this.client?.useServerCookies)return;s.s.put(s.IDENTITY_TOKEN_STORAGE_KEY,e);let t=Me.parse(e)?.expiration;ee.default.set(s.IDENTITY_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:st(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){s.s.del(s.IDENTITY_TOKEN_STORAGE_KEY),lt.setState({identityToken:null}),ee.default.remove(s.IDENTITY_TOKEN_COOKIE_KEY)}constructor(){this.authenticateOnce=new s.RunEffectOnce((async e=>this._authenticate(e))),this.linkOnce=new s.RunEffectOnce((async e=>this._link(e))),this.refreshOnce=new s.RunEffectOnce(this._refresh.bind(this)),this.destroyOnce=new s.RunEffectOnce(this._destroy.bind(this))}}let ht;var pt=0,yt="__private_"+pt+++"__getOrGenerateClientAnalyticsId";class mt{getAppId(){return this.appId}initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:n,store:i,walletList:a,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c,setBaseAccountSdk:d}){this.connectors||(this.connectors=new Xe(this.appId,e,t,r,n,i,a,o,s,l,d,c))}generateApi(){let e=new et({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 o.PrivyClientError("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new o.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(o.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw o.formatApiError(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(o.mfaPasskeyInitPath,{});return it(e.options)}catch(e){throw o.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(o.acceptTermsPath,{});return d.convertUserResponseToUser(e)}catch(e){throw o.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(o.unlinkEmailPath,{address:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async unlinkPhone(e){try{let t=await this.api.post(o.unlinkPhonePath,{phoneNumber:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(o.unlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(o.siwsUnlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(o.unlinkOAuthPath,{provider:e,subject:t});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(r)}catch(e){throw o.formatPrivyError(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(o.unlinkFarcasterPath,{fid:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async unlinkTelegram(e){try{let t=await this.api.post(o.telegramAccountUnlinkPath,{telegram_user_id:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async revokeDelegatedWallet(){try{await this.api.post(o.delegatedActionsRevokePath,{})}catch(e){throw o.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(o.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(o.moonpayPluginOnRampPath,e)}catch(e){throw o.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(o.coinbaseOnRampInitPath,e)}catch(e){throw o.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${o.coinbaseOnRampStatusPath}?partnerUserId=${e}`)}catch(e){throw o.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(dt.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(dt.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?Ne.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,smartWalletVersion:r.smart_wallet_version,smartWalletType:r.smart_wallet_type,configuredNetworks:r.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:nt(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw o.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(o.siweInitPath,{address:e,token:t})).nonce}catch(e){throw o.formatPrivyError(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i,mode:a}){return await this.api.post(o.siweAuthenticatePath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:i,mode:a})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}){return await this.api.post(o.siweLinkPath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})}async linkSmartWallet({message:e,signature:t,smartWalletType:r,smartWalletVersion:n}){try{let i=await this.api.post(o.smartWalletLinkPath,{message:e,signature:t,smart_wallet_type:r,smart_wallet_version:n});return d.convertUserResponseToUser(i)}catch(e){throw o.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 d.convertUserResponseToUser(a)}catch(e){throw o.formatPrivyError(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(o.siwsInitPath,{address:e,token:t})).nonce}catch(e){throw o.formatPrivyError(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:i,messageType:a="plain"}){return await this.api.post(o.siwsAuthenticatePath,{message:e,signature:t,walletClientType:r,connectorType:n,mode:i,message_type:a})}async authenticateWithSiws({message:e,signature:t,walletClientType:r,connectorType:n,mode:i,messageType:a="plain"}){let o=await this.authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:i,messageType:a});this.session.handleTokenResponse(o);let s=d.convertUserResponseToUser(o.user);if(!s)throw Error("Authentication failed - no user returned");return{user:s,isNewUser:o.is_new_user||!1}}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,telegramWebAppData:a,farcasterEmbeddedAddress:s,oAuthUserInfo:l}){try{let c,u;switch(r){case"email":c=o.transferEmailPath,u={nonce:e,email:t};break;case"sms":c=o.transferPhonePath,u={nonce:e,phoneNumber:t};break;case"siwe":if(c=o.transferWalletPath,!n)throw Error("Wallet parameters must be defined");u={nonce:e,address:t,...n};break;case"farcaster":c=o.transferFarcasterPath,u={nonce:e,farcaster_id:t,farcaster_embedded_address:s};break;case"telegram":c=o.telegramAccountTransferPath,u={nonce:e,telegram_auth_result:i,telegram_web_app_data:a};break;case"siws":c=o.siwsTransferPath,u={nonce:e,address:t,...n};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:c=o.transferOAuthPath,u={nonce:e,userInfo:l}}let h=await this.api.post(c,u);return await this.getAuthenticatedUser()??d.convertUserResponseToUser(h)}catch(e){throw o.formatPrivyError(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,messageType:i="plain"}){return await this.api.post(o.siwsLinkPath,{message:e,signature:t,walletClientType:r,connectorType:n,message_type:i})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:n,messageType:i="plain"}){try{let a=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,messageType:i});return d.convertUserResponseToUser(a)}catch(e){throw o.formatPrivyError(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(o.usersMePath);return this.session.updateIdentityToken(e.identity_token),d.convertUserResponseToUser(e.user)}catch(e){throw o.formatPrivyError(e)}}async scanTransaction(e){try{return await this.api.post(o.transactionScanningPath,e)}catch(e){throw o.formatPrivyError(e)}}constructor({apiUrl:e=s.DEFAULT_PRIVY_API_URL,appId:t,appClientId:r,timeout:n=s.DEFAULT_API_TIMEOUT_MS}){Object.defineProperty(this,yt,{value:wt}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==s.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,yt)[yt](),ht||(ht=new ut),this.session=ht,this.api=this.generateApi(),this.session.client=this}}function wt(){if("undefined"==typeof window)return null;try{let e=s.s.get(s.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=l.v4();try{return s.s.put(s.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}const gt=({delayedExecution:t,...n})=>{let{enabled:i,siteKey:a,appId:o,setError:l,setToken:c,setExecuting:d,ref:u}=s.useCaptcha(),[,h]=r.useMemo((()=>a?.split("t:")||[]),[a]);if(r.useEffect((()=>u.current?.remove),[]),!i)return null;if(!h)throw Error("Unsupported captcha site key");/*#__PURE__*/return e.jsx("div",{className:"hidden h-0 w-0",children:/*#__PURE__*/e.jsx(g.Turnstile,{...n,ref:u,siteKey:h,options:{action:o,size:"invisible",...t?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{n.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:()=>{n.onError?.(),l("Captcha failed"),d(!1)},onSuccess:e=>{n.onSuccess?.(e),c(e),d(!1)},onExpire:()=>{n.onExpire?.();try{u.current?.reset(),l(void 0),c(void 0)}catch(e){l("expired_and_failed_reset")}}})})};function vt(e){s.usePrivyEventSubscription("configureMfa",e)}const ft=/*#__PURE__*/v.styled.div.withConfig({displayName:"AppLogoContainer",componentId:"sc-ba98f772-0"})(["display:flex;flex-direction:column;align-items:center;padding:0px 0px 30px;@media (max-width:440px){padding:10px 10px 20px;}"]),Ct=/*#__PURE__*/v.styled.div.withConfig({displayName:"Title",componentId:"sc-ba98f772-1"})(["font-size:18px;line-height:30px;text-align:center;font-weight:600;margin-bottom:10px;"]),Et=/*#__PURE__*/v.styled.div.withConfig({displayName:"SubTitle",componentId:"sc-ba98f772-2"})(["font-size:0.875rem;text-align:center;"]),At=/*#__PURE__*/v.styled.div.withConfig({displayName:"Container",componentId:"sc-ba98f772-3"})(["display:flex;flex-direction:column;align-items:center;gap:10px;flex-grow:1;padding:20px 0;@media (max-width:440px){padding:10px 10px 20px;}"]),Pt=/*#__PURE__*/v.styled.div.withConfig({displayName:"List",componentId:"sc-ba98f772-4"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.75rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),kt=/*#__PURE__*/v.styled.div.withConfig({displayName:"ListItemIcon",componentId:"sc-ba98f772-5"})(["width:25px;display:flex;align-items:center;justify-content:flex-start;> svg{z-index:2;height:25px !important;width:25px !important;color:var(--privy-color-accent);}"]),bt=/*#__PURE__*/v.styled.div.withConfig({displayName:"ListItem",componentId:"sc-ba98f772-6"})(["display:flex;align-items:center;gap:10px;font-size:0.875rem;line-height:1rem;text-align:left;"]),xt=/*#__PURE__*/v.styled.div.withConfig({displayName:"BottomSection",componentId:"sc-ba98f772-7"})(["display:flex;flex-direction:column;gap:10px;padding-top:20px;"]),Tt=/*#__PURE__*/v.styled.div.withConfig({displayName:"MethodList",componentId:"sc-ba98f772-8"})(["display:flex;flex-direction:column;align-items:stretch;gap:1rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),St=/*#__PURE__*/v.styled.div.withConfig({displayName:"MethodListItem",componentId:"sc-ba98f772-9"})(["display:flex;gap:5px;width:100%;position:relative;"]),_t=/*#__PURE__*/v.styled.button.withConfig({displayName:"RemoveMethodButton",componentId:"sc-ba98f772-10"})(["&&{background-color:transparent;color:var(--privy-color-foreground-3);padding:0 0.75rem;display:flex;align-items:center;height:100%;> svg{z-index:2;height:20px !important;width:20px !important;}}&&:hover{color:var(--privy-color-error);}"]),It=/*#__PURE__*/v.styled.div.withConfig({displayName:"MethodText",componentId:"sc-ba98f772-11"})(["display:flex;align-items:center;gap:0.5rem;> svg{z-index:2;height:20px !important;width:20px !important;}"]),Ut=/*#__PURE__*/v.styled.div.withConfig({displayName:"ExtraText",componentId:"sc-ba98f772-12"})(["display:flex;align-items:center;gap:6px;font-weight:400 !important;color:",";> svg{z-index:2;height:18px !important;width:18px !important;display:flex !important;align-items:flex-end;}"],(e=>e.$isAccent?"var(--privy-color-accent)":"var(--privy-color-foreground-3)")),Wt=/*#__PURE__*/v.styled.div.withConfig({displayName:"SmsInsecureText",componentId:"sc-ba98f772-13"})(["width:100%;display:flex;justify-content:space-between;"]),Rt=/*#__PURE__*/v.styled.p.withConfig({displayName:"TermsText",componentId:"sc-ba98f772-14"})(["text-align:left;width:100%;color:var(--privy-color-foreground-3) !important;"]),Ot=/*#__PURE__*/v.styled.button.withConfig({displayName:"PrimaryTextButton",componentId:"sc-ba98f772-15"})(["display:flex;flex-direction:row;align-items:center;justify-content:center;user-select:none;&{width:100%;cursor:pointer;border-radius:var(--privy-border-radius-md);font-size:0.875rem;line-height:1rem;font-style:normal;font-weight:500;line-height:22px;letter-spacing:-0.016px;}&&{color:",";background-color:transparent;padding:0.5rem 0px;}&:hover{text-decoration:underline;}"],(e=>"dark"===e.theme?"var(--privy-color-foreground-2)":"var(--privy-color-accent)")),Mt=/*#__PURE__*/v.styled.div.withConfig({displayName:"IconWrapper",componentId:"sc-ba98f772-16"})(["display:flex;align-items:center;justify-content:center;color:var(--privy-color-accent);width:100%;> svg{z-index:2;width:3rem;height:3rem;}"]),Nt=/*#__PURE__*/v.styled.div.withConfig({displayName:"ErrorMessage",componentId:"sc-ba98f772-17"})(["color:var(--privy-color-error);"]),jt=({handleClose:t,user:r,onSelect:n})=>/*#__PURE__*/e.jsxs(s.ScreenLayout,{title:"Verify your identity",subtitle:"Choose a verification method",icon:ie.default,iconVariant:"subtle",onClose:t,showClose:!0,watermark:!0,children:[/*#__PURE__*/e.jsxs(Tt,{children:[r.mfaMethods.includes("totp")&&/*#__PURE__*/e.jsxs(s.LoginMethodButton,{onClick:()=>n("totp"),children:[/*#__PURE__*/e.jsx(s.LoginMethodIconWrapper,{children:/*#__PURE__*/e.jsx(te.default,{})}),"Authenticator app"]},"totp"),r.mfaMethods.includes("sms")&&/*#__PURE__*/e.jsxs(s.LoginMethodButton,{onClick:()=>n("sms"),children:[/*#__PURE__*/e.jsx(s.LoginMethodIconWrapper,{children:/*#__PURE__*/e.jsx(ne.default,{})}),"SMS"]},"sms"),r.mfaMethods.includes("passkey")&&/*#__PURE__*/e.jsxs(s.LoginMethodButton,{onClick:()=>n("passkey"),children:[/*#__PURE__*/e.jsx(s.LoginMethodIconWrapper,{children:/*#__PURE__*/e.jsx(re.default,{})}),"Passkey"]},"passkey")]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}),Ft=({pendingTransaction:t})=>{let{wallets:n}=s.useWallets(),{walletProxy:i,rpcConfig:a,chains:o,appId:l,nativeTokenSymbolForChainId:c}=f.usePrivyInternal(),[d,u]=r.useState(null),[h,p]=r.useState(t),{tokenPrice:y}=s.useGetTokenPrice(h.chainId),m=c(t.chainId)||"ETH",w=r.useMemo((()=>n.find((e=>"privy"===e.walletClientType))),[n]);return r.useEffect((()=>{(async function(){if(!i||!w)return h;let e=s.getPublicClient(h.chainId,o,a,{appId:l}),t=await s.prepareTransactionRequest(h,e,w.address);return u(T.toHex(BigInt(t.gas??0))),t})().then(p).catch(console.error)}),[i]),w?/*#__PURE__*/e.jsx(Lt,{children:/*#__PURE__*/e.jsx(s.TransactionDetails,{from:w.address,to:h.to,txn:h,gas:d??void 0,tokenPrice:y,tokenSymbol:m})}):null};let Lt=/*#__PURE__*/v.styled.div.withConfig({displayName:"TransactionInfoWrapper",componentId:"sc-8d9a2f57-0"})(["width:100%;padding:1rem 0;"]);const Dt=({style:t,...r})=>/*#__PURE__*/e.jsx("svg",{x:0,y:0,width:"65",height:"64",viewBox:"0 0 65 64",style:{height:"64px",width:"65px",...t},fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M3.71369 17.5625V10.375C3.71369 6.44625 6.85845 3.25 10.7238 3.25H17.7953C18.6783 3.25 19.3941 2.52244 19.3941 1.625C19.3941 0.727562 18.6783 0 17.7953 0H10.7238C5.09529 0 0.516113 4.65419 0.516113 10.375V17.5625C0.516113 18.4599 1.23194 19.1875 2.1149 19.1875C2.99787 19.1875 3.71369 18.4599 3.71369 17.5625ZM17.7953 60.7501C18.6783 60.7501 19.3941 61.4777 19.3941 62.3751C19.3941 63.2726 18.6783 64.0001 17.7953 64.0001H10.7238C5.09529 64.0001 0.516113 59.3459 0.516113 53.6251V46.4376C0.516113 45.5402 1.23194 44.8126 2.1149 44.8126C2.99787 44.8126 3.71369 45.5402 3.71369 46.4376V53.6251C3.71369 57.5538 6.85845 60.7501 10.7238 60.7501H17.7953ZM63.4839 46.4376V53.6251C63.4839 59.3459 58.9048 64.0001 53.2763 64.0001H46.2047C45.3217 64.0001 44.6059 63.2726 44.6059 62.3751C44.6059 61.4777 45.3217 60.7501 46.2047 60.7501H53.2763C57.1416 60.7501 60.2864 57.5538 60.2864 53.6251V46.4376C60.2864 45.5402 61.0022 44.8126 61.8851 44.8126C62.7681 44.8126 63.4839 45.5402 63.4839 46.4376ZM63.4839 10.375V17.5625C63.4839 18.4599 62.7681 19.1875 61.8851 19.1875C61.0022 19.1875 60.2864 18.4599 60.2864 17.5625V10.375C60.2864 6.44625 57.1416 3.25 53.2763 3.25H46.2047C45.3217 3.25 44.6059 2.52244 44.6059 1.625C44.6059 0.727562 45.3217 0 46.2047 0H53.2763C58.9048 0 63.4839 4.65419 63.4839 10.375ZM43.0331 47.3022C43.7067 46.6698 43.7483 45.6022 43.1262 44.9176C42.5039 44.233 41.4536 44.1906 40.78 44.823C38.3832 47.0732 35.265 48.3125 31.9997 48.3125C28.7344 48.3125 25.6162 47.0732 23.2194 44.823C22.5457 44.1906 21.4955 44.233 20.8732 44.9176C20.251 45.6022 20.2927 46.6698 20.9663 47.3022C23.9784 50.1301 27.8968 51.6875 31.9997 51.6875C36.1026 51.6875 40.021 50.1301 43.0331 47.3022ZM35.3207 24.1249V36.1249C35.3207 38.5029 33.4173 40.4374 31.0777 40.4374H29.7249C28.8079 40.4374 28.0646 39.6819 28.0646 38.7499C28.0646 37.8179 28.8079 37.0624 29.7249 37.0624H31.0777C31.5863 37.0624 32.0001 36.6419 32.0001 36.1249V24.1249C32.0001 23.1929 32.7434 22.4374 33.6604 22.4374C34.5774 22.4374 35.3207 23.1929 35.3207 24.1249ZM46.7581 28.8437V24.0312C46.7581 23.151 46.056 22.4374 45.19 22.4374C44.324 22.4374 43.622 23.151 43.622 24.0312V28.8437C43.622 29.7239 44.324 30.4374 45.19 30.4374C46.056 30.4374 46.7581 29.7239 46.7581 28.8437ZM17.6109 28.8437C17.6109 29.7239 18.313 30.4374 19.1789 30.4374C20.0449 30.4374 20.747 29.7239 20.747 28.8437V24.0312C20.747 23.151 20.0449 22.4374 19.1789 22.4374C18.313 22.4374 17.6109 23.151 17.6109 24.0312V28.8437Z"})}),qt=({hasBlockingError:t,error:r,onClose:n,onBack:i,handleSubmit:a,account:o,submitSuccess:l})=>{let{pendingTransaction:c}=f.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:n},"header"),/*#__PURE__*/e.jsx(s.e$2,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:l,fail:!!r}),r?/*#__PURE__*/e.jsx(oe.default,{style:{width:"38px",height:"38px"}}):/*#__PURE__*/e.jsx(Dt,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsx(Ct,{style:{marginTop:"1rem"},children:"Verifying with passkey"}),/*#__PURE__*/e.jsxs(Pt,{children:[/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(ie.default,{})}),"Approve this action using your touch, face, PIN, or hardware key."]}),/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(ae.default,{})}),"You last added a passkey on"," ",o?.firstVerifiedAt?.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),"."]})]}),c&&/*#__PURE__*/e.jsx(At,{children:/*#__PURE__*/e.jsx(Ft,{pendingTransaction:c})}),r&&/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Nt,{style:{marginTop:"1.25rem"},children:r.message}),/*#__PURE__*/e.jsx(s.PrimaryButton,{disabled:t,onClick:a,style:{margin:"1.25rem auto 0"},children:"Try again"})]}),i&&/*#__PURE__*/e.jsx(Ot,{style:{marginTop:"1rem"},onClick:i,children:"Choose another method"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})};let Ht=Array(6).fill("");var Bt,zt=((Bt=zt||{})[Bt.RESET_AFTER_DELAY=0]="RESET_AFTER_DELAY",Bt[Bt.CLEAR_ON_NEXT_VALID_INPUT=1]="CLEAR_ON_NEXT_VALID_INPUT",Bt);function Kt(e){return/^[0-9]{1}$/.test(e)}function Vt(e){return 6===e.length&&e.every(Kt)}const $t=({onChange:t,disabled:i,errorReasonOverride:a,success:o})=>{let[s,l]=r.useState(Ht),[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(Kt(t))),0),i=r.split(""),a=!i.every(Kt),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(),Vt(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(Yt,{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()}Vt(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(Gt,{$fail:!!a||!!c,children:a||c})})]})})};let Yt=/*#__PURE__*/v.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);}}"]),Gt=/*#__PURE__*/v.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 Zt=({selectedMethod:t,submitSuccess:r,hasBlockingError:n,onClose:i,onBack:a,handleSubmitCode:o})=>{let l=s.useAppConfig(),{pendingTransaction:c}=f.usePrivyInternal();switch(t){case"sms":/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:i},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ne.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Enter verification code"}),/*#__PURE__*/e.jsxs(At,{children:[/*#__PURE__*/e.jsx($t,{success:r,disabled:n,onChange:o}),/*#__PURE__*/e.jsxs(Et,{children:["To continue, please enter the 6-digit code sent to your ",/*#__PURE__*/e.jsx("strong",{children:"mobile device"})]}),c&&/*#__PURE__*/e.jsx(Ft,{pendingTransaction:c})]}),a&&/*#__PURE__*/e.jsx(Ot,{theme:l?.appearance.palette.colorScheme,onClick:a,children:"Choose another method"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:i,children:"Cancel"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});case"totp":/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:i},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(te.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Enter verification code"}),/*#__PURE__*/e.jsxs(At,{children:[/*#__PURE__*/e.jsx($t,{success:r,disabled:n,onChange:o}),/*#__PURE__*/e.jsxs(Et,{children:["To continue, please enter the 6-digit code generated from your"," ",/*#__PURE__*/e.jsx("strong",{children:"authenticator app"})]}),c&&/*#__PURE__*/e.jsx(Ft,{pendingTransaction:c})]}),a&&/*#__PURE__*/e.jsx(Ot,{theme:l?.appearance.palette.colorScheme,onClick:a,children:"Choose another method"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:i,children:"Cancel"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});default:return null}},Jt=e=>s.errorIndicatesMaxMfaRetries(e)?{isBlocking:!0,error:Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.")}:s.errorIndicatesMfaVerificationFailed(e)?{isBlocking:!1,error:Error("The code you entered is not valid")}:s.errorIndicatesMfaTimeout(e)?{isBlocking:!0,error:Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.")}:(console.error(e),{isBlocking:!1,error:Error("Something went wrong.")}),Xt={component:()=>{let{user:t}=d.usePrivyContext(),{data:n}=s.usePrivyModal(),[i,a]=r.useState(t?.mfaMethods[0]),[o,l]=r.useState(!1),[c,u]=r.useState(),[h,p]=r.useState();if(r.useEffect((()=>{a(t?.mfaMethods[0])}),[t?.mfaMethods]),!n?.mfaVerify)throw Error("Missing modal data for MFA verification screen.");let{onFailure:y,onSuccess:m,generateOptions:w,verifyTotpCode:g,verifyPasskey:v,verifySmsCode:f,sendSmsCode:C}=n.mfaVerify,E=async e=>{if("passkey"!==e)try{a(e),"sms"===e&&(a(e),await C()),"totp"===e&&a(e)}catch(e){console.error(e)}else try{a(e);let t=await w();if(!t)throw Error("something went wrong");u(t),await v(t),l(!0),p(void 0),m()}catch(e){p(Jt(e))}},A=async e=>{p(void 0);try{if(!e||!i)return;if("passkey"===i){if(!c)throw Error("Missing passkey challenge");await v(c)}else"sms"===i?await f(e):"totp"===i&&await g(e);p(void 0),l(!0),m()}catch(e){throw Jt(e).error}},P=()=>{h||!o?y(h?.error??Error("Canceled MFA verification.")):m()},k=r.useRef(!1);return r.useEffect((()=>{!k.current&&i&&(k.current=!0,E(i).finally((()=>{k.current=!1})))}),[open]),t?"passkey"===i?/*#__PURE__*/e.jsx(qt,{account:t.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],submitSuccess:o,hasBlockingError:h?.isBlocking??!1,error:h?.error,onClose:P,onBack:()=>{a(void 0),p(void 0)},handleSubmit:()=>A(c).catch(p)}):"sms"===i||"totp"===i?/*#__PURE__*/e.jsx(Zt,{selectedMethod:i,submitSuccess:o,hasBlockingError:h?.isBlocking??!1,handleSubmitCode:A,onClose:P,onBack:t.mfaMethods.length>1?()=>a(void 0):void 0}):/*#__PURE__*/e.jsx(jt,{user:t,onSelect:E,handleClose:P}):null}};function Qt(){let{promptMfa:e,init:t,submit:n,cancel:i,mfaMethods:a}=r.useContext(d.PrivyContext);return{promptMfa:e,init:t,submit:n,cancel:i,mfaMethods:a}}const er=({onClose:t})=>{let{user:n}=d.usePrivyContext(),[i,a]=r.useState(n?.mfaMethods[0]??null),{init:o,cancel:s,submit:l}=Qt(),[c,u]=r.useState(!1),[h,p]=r.useState(null),[y,m]=r.useState();r.useEffect((()=>{a(n?.mfaMethods[0]??null)}),[n?.mfaMethods]);let w=r.useRef(!1);async function g(e){m(void 0);try{if(!e||!i)return;await l(i,e),u(!0),m(void 0),t()}catch(e){throw Jt(e).error}}async function v(e){if("passkey"!==e)try{a(e),await o(e)}catch(e){console.error(e)}else try{a(e);let r=await o(e);if(!r)throw Error("something went wrong");p(r),await l(e,r),u(!0),m(void 0),t()}catch(e){m(Jt(e))}}r.useEffect((()=>{!w.current&&i&&(w.current=!0,v(i).finally((()=>{w.current=!1})))}),[]);let f=()=>{a(null),m(void 0),s(),t()};return n?"passkey"===i?/*#__PURE__*/e.jsx(qt,{account:n.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],submitSuccess:c,hasBlockingError:y?.isBlocking??!1,error:y?.error,onClose:f,onBack:()=>{a(null),m(void 0)},handleSubmit:()=>g(h).catch(m)}):i?/*#__PURE__*/e.jsx(Zt,{submitSuccess:c,hasBlockingError:y?.isBlocking??!1,handleSubmitCode:g,selectedMethod:i,onClose:f,onBack:n.mfaMethods.length>1?()=>a(null):void 0}):/*#__PURE__*/e.jsx(jt,{user:n,onSelect:v,handleClose:f}):null},tr=w.create((()=>({inProgressMfaFlow:void 0})));const rr=/*#__PURE__*/v.createGlobalStyle([":root{","};"],(e=>nr(e.palette)));const nr=e=>
2
- /*#__PURE__*/v.css(["",""],Object.entries(function(e){return{"--privy-color-background":e.background,"--privy-color-background-2":e.background2,"--privy-color-background-3":e.background3,"--privy-color-foreground":e.foreground,"--privy-color-foreground-2":e.foreground2,"--privy-color-foreground-3":e.foreground3,"--privy-color-foreground-4":e.foreground4,"--privy-color-foreground-accent":e.foregroundAccent,"--privy-color-accent":e.accent,"--privy-color-accent-light":e.accentLight,"--privy-color-accent-hover":e.accentHover,"--privy-color-accent-dark":e.accentDark,"--privy-color-accent-darkest":e.accentDarkest,"--privy-color-success":e.success,"--privy-color-success-dark":e.successDark,"--privy-color-success-light":e.successLight,"--privy-color-success-bg":e.successBg,"--privy-color-error":e.error,"--privy-color-error-light":e.errorLight,"--privy-color-error-bg":e.errorBg,"--privy-color-error-bg-hover":e.errorBgHover,"--privy-color-warn":e.warn,"--privy-color-warn-light":e.warnLight,"--privy-color-warn-bg":e.warnBg,"--privy-color-warning-dark":e.warningDark,"--privy-color-error-dark":e.errorDark,"--privy-color-info-bg":e.infoBg,"--privy-color-info-bg-hover":e.infoBgHover,"--privy-color-border-default":e.borderDefault,"--privy-color-border-hover":e.borderHover,"--privy-color-border-focus":e.borderFocus,"--privy-color-border-error":e.borderError,"--privy-color-border-success":e.borderSuccess,"--privy-color-border-warning":e.borderWarning,"--privy-color-border-info":e.borderInfo,"--privy-color-border-interactive":e.borderInteractive,"--privy-color-border-interactive-hover":e.borderInteractiveHover,"--privy-color-background-hover":e.backgroundHover,"--privy-color-background-clicked":e.backgroundClicked,"--privy-color-background-disabled":e.backgroundDisabled,"--privy-color-background-interactive":e.backgroundInteractive,"--privy-color-background-interactive-hover":e.backgroundInteractiveHover,"--privy-color-background-interactive-clicked":e.backgroundInteractiveClicked,"--privy-color-background-interactive-disabled":e.backgroundInteractiveDisabled,"--privy-color-foreground-hover":e.foregroundHover,"--privy-color-foreground-clicked":e.foregroundClicked,"--privy-color-foreground-disabled":e.foregroundDisabled,"--privy-color-foreground-interactive":e.foregroundInteractive,"--privy-color-foreground-interactive-hover":e.foregroundInteractiveHover,"--privy-link-navigation-color":e.linkNavigationColor,"--privy-link-navigation-decoration":e.linkNavigationDecoration,"--privy-accent-has-good-contrast":e.accentHasGoodContrast,"--privy-color-icon-default":e.iconDefault,"--privy-color-icon-muted":e.iconMuted,"--privy-color-icon-subtle":e.iconSubtle,"--privy-color-icon-inverse":e.iconInverse,"--privy-color-icon-success":e.iconSuccess,"--privy-color-icon-warning":e.iconWarning,"--privy-color-icon-error":e.iconError,"--privy-color-icon-interactive":e.iconInteractive,"--privy-color-icon-default-hover":e.iconDefaultHover,"--privy-color-icon-muted-hover":e.iconMutedHover,"--privy-color-icon-subtle-hover":e.iconSubtleHover,"--privy-color-icon-default-clicked":e.iconDefaultClicked,"--privy-color-icon-muted-clicked":e.iconMutedClicked,"--privy-color-icon-subtle-clicked":e.iconSubtleClicked,"--privy-color-icon-default-disabled":e.iconDefaultDisabled,"--privy-color-icon-muted-disabled":e.iconMutedDisabled,"--privy-color-icon-subtle-disabled":e.iconSubtleDisabled,"--privy-color-icon-error-hover":e.iconErrorHover,"--privy-color-icon-interactive-hover":e.iconInteractiveHover,"--privy-color-icon-error-clicked":e.iconErrorClicked,"--privy-color-icon-interactive-clicked":e.iconInteractiveClicked,"--privy-color-icon-muted-disabled-alt":e.iconMutedDisabledAlt,"--privy-color-icon-subtle-disabled-alt":e.iconSubtleDisabledAlt,"--privy-border-radius-xs":"6px","--privy-border-radius-sm":"8px","--privy-border-radius-md":"12px","--privy-border-radius-mdlg":"16px","--privy-border-radius-lg":"24px","--privy-border-radius-full":"9999px","--privy-height-modal-full":"620px","--privy-height-modal-compact":"480px"}}(e)).map((([e,t])=>`${e}: ${t};`)).join("\n")),ir=/*#__PURE__*/v.styled.div.withConfig({displayName:"StylesWrapper",componentId:"sc-188229e4-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 3px var(--privy-color-border-focus);}.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"),ar=({children:t,open:r,onClick:n,...i})=>/*#__PURE__*/e.jsx(S.Transition,{show:r,as:Z.default.Fragment,children:/*#__PURE__*/e.jsxs(S.Dialog,{onClose:n,...i,as:sr,children:[/*#__PURE__*/e.jsx(S.TransitionChild,{as:Z.default.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/e.jsx(or,{id:"privy-dialog-backdrop","aria-hidden":"true"})}),/*#__PURE__*/e.jsx(lr,{children:/*#__PURE__*/e.jsx(S.TransitionChild,{as:Z.default.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/e.jsx(S.DialogPanel,{as:cr,children:t})})})]})});let or=/*#__PURE__*/v.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;}"]),sr=/*#__PURE__*/v.styled.div.withConfig({displayName:"DialogWrapper",componentId:"sc-3cfde0b5-1"})(["position:relative;z-index:999999;"]),lr=/*#__PURE__*/v.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 cr=/*#__PURE__*/v.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);}"]),dr=/*#__PURE__*/v.styled.div.withConfig({displayName:"CenterItem",componentId:"sc-3cfde0b5-4"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;"]);let ur=()=>{let{ready:t,isModalOpen:n}=d.usePrivyContext(),{headless:i}=s.useAppConfig(),{currentScreen:a}=s.usePrivyModal(),{status:o,execute:l,reset:c,enabled:u}=s.useCaptcha(),h=tr((e=>e.inProgressMfaFlow)),p=()=>tr.setState({inProgressMfaFlow:void 0}),y=n&&a&&a.isCaptchaRequired&&!i&&"ready"===o;return r.useEffect((()=>{y&&l()}),[y]),r.useEffect((()=>{!n&&u&&c()}),[n,u]),a&&!t&&a.isShownBeforeReady?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(dr,{children:/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):a||"txn"!==h?a?
3
- /*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.Hide,{$if:!!h,children:/*#__PURE__*/e.jsx(a.component,{})}),"txn"===h&&/*#__PURE__*/e.jsx(er,{onClose:p}),"auth"===h&&/*#__PURE__*/e.jsx(Xt.component,{})]}):null:/*#__PURE__*/e.jsx(er,{onClose:p})},hr=()=>{let t=r.useRef(null);/*#__PURE__*/return e.jsx(mr,{style:{height:C.useElementHeight(t)},id:"privy-modal-content",children:/*#__PURE__*/e.jsx("div",{ref:t,children:/*#__PURE__*/e.jsx(ur,{})})})};const pr=({open:t})=>{let n=s.useAppConfig(),{gracefulClosePrivyModal:i}=(()=>{let{closePrivyModal:e}=f.usePrivyInternal(),{onUserCloseViaDialogOrKeybindRef:t}=s.usePrivyModal();return{gracefulClosePrivyModal:r.useCallback((()=>{if(!t?.current)return e({shouldCallAuthOnSuccess:!1});t.current()}),[e])}})(),a=tr((e=>e.inProgressMfaFlow));return vt({onMfaRequired:()=>{n.mfa.noPromptOnMfaRequired||tr.setState({inProgressMfaFlow:"txn"})}}),n.render.standalone?/*#__PURE__*/e.jsx(ir,{children:/*#__PURE__*/e.jsx(yr,{id:"privy-modal-content",children:/*#__PURE__*/e.jsx(ur,{})})}):/*#__PURE__*/e.jsx(ar,{open:!(!t&&!a),id:"privy-dialog","aria-label":"log in or sign up","aria-labelledby":"privy-dialog-title",onClick:()=>i(),children:/*#__PURE__*/e.jsx(ir,{children:/*#__PURE__*/e.jsx(hr,{})})})};let yr=/*#__PURE__*/v.styled.div.withConfig({displayName:"ContentWrapper",componentId:"sc-b220e1ee-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;"]),mr=/*#__PURE__*/v.styled(yr).withConfig({displayName:"BaseModal",componentId:"sc-b220e1ee-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 wr(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})}const gr=()=>{let{ready:e}=s.useWallets(),{client:t}=f.usePrivyInternal();return r.useEffect((()=>{let r=()=>{if(!t.connectors||!e)return;let r=t.connectors.wallets.map((e=>({address:e.address,connectorType:e.connectorType,walletClientType:e.walletClientType,connectedAt:e.connectedAt,id:e.meta.id})));s.s.put(s.CONNECTIONS_HISTORY_KEY,r)};return t.connectors?.on("walletsUpdated",r),()=>{t.connectors?.off("walletsUpdated",r)}}),[e,t.connectors]),null};async function vr(e,t,r,n,i,a=!1){let o=a,l=async l=>{if(o&&t&&t.length>0){l===(a?0:1)?i("configureMfa","onMfaRequired",{mfaMethods:t}):n.current?.reject(new s.PrivyIframeError("missing_or_invalid_mfa","MFA verification failed, retry."));let o=await new Promise(((e,t)=>{r.current={resolve:e,reject:t},setTimeout((()=>{let e=new s.PrivyIframeError("mfa_timeout","Timed out waiting for MFA code");n.current?.reject(e),t(e)}),3e5)}));return await e(o)}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;o=!0}if(null===c){let e=new s.PrivyIframeError("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw n.current?.reject(e),e}return c}var fr;let Cr=(fr=0,()=>"id-"+fr++);function Er(e){return void 0!==e.error}let Ar=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:user-signer:sign":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={}}},Pr=new Map,kr=(e,t)=>"bigint"==typeof t?t.toString():t;function br(e,t,r,n){let i=r.contentWindow;if(!i)throw Error("iframe not initialized");let a=((e,t)=>`${e}${JSON.stringify(t,kr)}`)(e,t);if("privy:wallet:create"===e){let e=Pr.get(a);if(e)return e}let o=new Promise(((r,a)=>{let o=Cr();Ar.enqueue(o,{resolve:r,reject:a}),i.postMessage({id:o,event:e,data:t},n)})).finally((()=>{Pr.delete(a)}));return Pr.set(a,o),o}function xr(t){let n=s.useIsServerConfigLoaded(),i=r.useRef(null),a=r.useRef(t.mfaMethods),o=s.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=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data);case"privy:user-signer:sign":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:add":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:set-recovery":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:connect":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:recover":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:rpc":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallet:create":let r=Ar.dequeue(e.event,e.id);return Er(e)?r.reject(new s.PrivyIframeError(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallets:import":let n=Ar.dequeue(e.event,e.id);return Er(e)?n.reject(new s.PrivyIframeError(e.error.type,e.error.message)):n.resolve(e.data);case"privy:mfa:verify":let i=Ar.dequeue(e.event,e.id);return Er(e)?i.reject(new s.PrivyIframeError(e.error.type,e.error.message)):i.resolve(e.data);case"privy:mfa:init-enrollment":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:submit-enrollment":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:unenroll":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:clear":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:auth:unlink-passkey":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:solana-wallet:create":let a=Ar.dequeue(e.event,e.id);return Er(e)?a.reject(new s.PrivyIframeError(e.error.type,e.error.message)):a.resolve(e.data);case"privy:farcaster:init-signer":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:sign":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:delegated-actions:consent":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}(e.data)}let n={signWithUserSigner:r=>vr((n=>br("privy:user-signer:sign",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),addWallet:r=>vr((n=>br("privy:wallets:add",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),setRecovery:r=>vr((n=>br("privy:wallets:set-recovery",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),connect:r=>vr((n=>br("privy:wallets:connect",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),recover:r=>vr((n=>br("privy:wallets:recover",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o,!r.recoveryAccessToken&&!r.recoveryPassword&&!r.recoverySecretOverride),rpc:r=>vr((n=>br("privy:wallets:rpc",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),create:r=>br("privy:wallet:create",r,e,t.origin),importWallet:r=>br("privy:wallets:import",r,e,t.origin),createSolana:r=>vr((n=>br("privy:solana-wallet:create",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),createDelegatedAction:r=>br("privy:delegated-actions:consent",r,e,t.origin),verifyMfa:r=>vr((n=>br("privy:mfa:verify",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o,!0),initEnrollMfa:r=>vr((n=>br("privy:mfa:init-enrollment",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),submitEnrollMfa:r=>vr((n=>br("privy:mfa:submit-enrollment",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),unenrollMfa:r=>vr((n=>br("privy:mfa:unenroll",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),clearMfa:r=>br("privy:mfa:clear",r,e,t.origin),unlinkPasskeyAccount:r=>vr((n=>br("privy:auth:unlink-passkey",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),initFarcasterSigner:r=>br("privy:farcaster:init-signer",r,e,t.origin),signFarcasterMessage:r=>br("privy:farcaster:sign",r,e,t.origin)};window.addEventListener("message",r);let c=new AbortController;return s.invokeUntilSettled((()=>br("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?
4
- /*#__PURE__*/e.jsx("iframe",{ref:i,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>c(!0),src:_.constructURL({origin:t.origin,path:`/apps/${t.appId}/embedded-wallets`,query:{caid:t.clientAnalyticsId,client_id:t.appClientId}})}):null}const Tr=({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new o.PrivyClientError("Address to delegate is not associated with current user.");if(!I.isFirstClassChainWallet(r))throw new o.PrivyClientError(`useDelegatedActions is not supported for ${r.chainType} wallets. Use the useSessionSigners hook to provision server side access on behalf of your users.`);return{address:r.address,chainType:r.chainType,walletIndex:r.walletIndex??0}},Sr=({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new o.PrivyClientError("Address to delegate is not associated with current user.");let n=r.imported?r:d.getPrivyPrimaryWallet(t);if(!n)throw new o.PrivyClientError("Unable to determine root address for delegated address.");if(!I.isFirstClassChainWallet(n))throw new o.PrivyClientError(`useDelegatedActions is not supported for ${n.chainType} wallets. Use the useSessionSigners hook to provision server side access on behalf of your users.`);return{address:n.address,chainType:n.chainType,imported:n.imported}},_r=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&e.delegated));const Ir=()=>{let e=s.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=>s.setExternalWalletState({listings:e}))).catch(console.error)}),[e.walletConnectCloudProjectId])},Ur="popup-privy-oauth",Wr="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";class Rr{async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw o.formatApiError(e)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw o.formatApiError(e)}}constructor({authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}){this.meta={authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}}}async function Or({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 o.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,customAuthAuthorizeUrl:n.provider_app_custom_auth_authorize_url,customAuthTransactUrl:n.provider_app_custom_auth_transact_url}}const Mr=async({user:e,address:t,client:r,request:n,requesterAppId:i,reconnect:a})=>{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 o.PrivyClientError("Cannot request a signature with this wallet address");let c=r.getProviderAccessToken(l.providerApp.id),d=await Or({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 o.PrivyClientError("Cannot transact against a read-only provider app");await a({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 o.PrivyClientError("Transactions require a valid token");let u=s.triggerPopup();if(!u)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Missing token",address:t}}),new o.PrivyClientError("Failed to initialize signature request");let h=new URL(d.customAuthTransactUrl||`${d.apiUrl}/oauth/transact`);return h.searchParams.set("token",c||""),h.searchParams.set("request",Nr(n)),u.location=h.href,new Promise(((e,i)=>{let a=setTimeout((()=>{d(),i(new o.PrivyClientError("Request timeout")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Request timeout",address:t}})}),12e4),s=setInterval((()=>{u.closed&&(d(),i(new o.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(a),window.removeEventListener("message",c)}}))};let Nr=e=>JSON.stringify({content:{request:{request:jr(e,T.toHex)}},timestamp:Date.now(),callbackUrl:window.origin});const jr=(e,t)=>"bigint"==typeof e?t(e):Array.isArray(e)?e.map((e=>jr(e,t))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,r])=>[e,jr(r,t)]))):e,Fr=({passkeys:t,isLoading:r,errorReason:n,success:i,expanded:a,onLinkPasskey:o,onUnlinkPasskey:l,onExpand:c,onBack:d,onClose:u})=>i?/*#__PURE__*/e.jsx(s.ScreenLayout,{title:"Passkeys updated",icon:U.CheckCircle,iconVariant:"success",primaryCta:{label:"Done",onClick:u},onClose:u,watermark:!0}):a?/*#__PURE__*/e.jsx(s.ScreenLayout,{icon:U.FingerprintIcon,title:"Your passkeys",onBack:d,onClose:u,watermark:!0,children:/*#__PURE__*/e.jsx(Dr,{passkeys:t,expanded:a,onUnlink:l,onExpand:c})}):/*#__PURE__*/e.jsx(s.ScreenLayout,{icon:U.FingerprintIcon,title:"Set up passkey verification",subtitle:"Verify with passkey",primaryCta:{label:"Add new passkey",onClick:o,loading:r},onClose:u,watermark:!0,helpText:n||void 0,children:0===t.length?/*#__PURE__*/e.jsx(qr,{}):/*#__PURE__*/e.jsx(Lr,{children:/*#__PURE__*/e.jsx(Dr,{passkeys:t,expanded:a,onUnlink:l,onExpand:c})})});let Lr=/*#__PURE__*/v.styled.div.withConfig({displayName:"ContentContainer",componentId:"sc-d4c46a0c-0"})(["margin-bottom:12px;"]),Dr=({passkeys:t,expanded:n,onUnlink:i,onExpand:a})=>{let[o,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($r,{children:"Your passkeys"}),/*#__PURE__*/e.jsxs(Vr,{children:[t.slice(0,c).map((t=>/*#__PURE__*/e.jsxs(Zr,{children:[/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(Yr,{children:d(t)}),/*#__PURE__*/e.jsxs(Gr,{children:["Last used:"," ",(t.latestVerifiedAt??t.firstVerifiedAt)?.toLocaleString()??"N/A"]})]}),/*#__PURE__*/e.jsx(Xr,{disabled:o.includes(t.credentialId),onClick:()=>(async e=>{l((t=>t.concat([e]))),await i(e),l((t=>t.filter((t=>t!==e))))})(t.credentialId),children:o.includes(t.credentialId)?/*#__PURE__*/e.jsx(s.ButtonLoader,{}):/*#__PURE__*/e.jsx(U.Trash2,{size:16})})]},t.credentialId))),t.length>2&&!n&&/*#__PURE__*/e.jsx(Kr,{onClick:a,children:"View all"})]})]})},qr=()=>/*#__PURE__*/e.jsxs(s.TodoList,{style:{color:"var(--privy-color-foreground)"},children:[/*#__PURE__*/e.jsx(s.TodoItem,{children:"Verify with Touch ID, Face ID, PIN, or hardware key"}),/*#__PURE__*/e.jsx(s.TodoItem,{children:"Takes seconds to set up and use"}),/*#__PURE__*/e.jsx(s.TodoItem,{children:"Use your passkey to verify transactions and login to your account"})]});const Hr={component:()=>{let{user:t,unlinkPasskey:n}=d.usePrivyContext(),{linkWithPasskey:i,closePrivyModal:a}=f.usePrivyInternal(),s=t?.linkedAccounts.filter((e=>"passkey"===e.type)),[l,c]=r.useState(!1),[u,h]=r.useState(""),[p,y]=r.useState(!1),[m,w]=r.useState(!1);return r.useEffect((()=>{0===s.length&&w(!1)}),[s.length]),/*#__PURE__*/e.jsx(Fr,{passkeys:s,isLoading:l,errorReason:u,success:p,expanded:m,onLinkPasskey:()=>{c(!0),i().then((()=>y(!0))).catch((e=>{if(e instanceof o.PrivyError){if(e.privyErrorCode===o.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE)return void h("Cannot link more passkeys to account.");if(e.privyErrorCode===o.PrivyErrorCode.PASSKEY_NOT_ALLOWED)return void h("Passkey request timed out or rejected by user.")}h("Unknown error occurred.")})).finally((()=>{c(!1)}))},onUnlinkPasskey:async e=>(c(!0),await n(e).then((()=>y(!0))).catch((e=>{e instanceof o.PrivyError&&e.privyErrorCode===o.PrivyErrorCode.MISSING_MFA_CREDENTIALS?h("Cannot unlink a passkey enrolled in MFA"):h("Unknown error occurred.")})).finally((()=>{c(!1)}))),onExpand:()=>w(!0),onBack:()=>w(!1),onClose:()=>a()})}},Br=/*#__PURE__*/v.styled.div.withConfig({displayName:"DoubleIconWrapper",componentId:"sc-d4c46a0c-1"})(["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 zr=/*#__PURE__*/v.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 Kr=/*#__PURE__*/v.styled.button.withConfig({displayName:"LinkButton",componentId:"sc-d4c46a0c-2"})(["",""],zr);let Vr=/*#__PURE__*/v.styled.div.withConfig({displayName:"List",componentId:"sc-d4c46a0c-3"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.8rem;padding:0.5rem 0rem 0rem;flex-grow:1;width:100%;"]),$r=/*#__PURE__*/v.styled.div.withConfig({displayName:"PasskeyListTitle",componentId:"sc-d4c46a0c-4"})(["line-height:20px;height:20px;font-size:1em;font-weight:450;display:flex;justify-content:flex-beginning;width:100%;"]),Yr=/*#__PURE__*/v.styled.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-d4c46a0c-5"})(["font-size:1em;line-height:1.3em;font-weight:500;color:var(--privy-color-foreground-2);padding:0.2em 0;"]),Gr=/*#__PURE__*/v.styled.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-d4c46a0c-6"})(["font-size:0.875rem;line-height:1rem;color:#64668b;padding:0.2em 0;"]),Zr=/*#__PURE__*/v.styled.div.withConfig({displayName:"PasskeyListItem",componentId:"sc-d4c46a0c-7"})(["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__*/v.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);}"]),Xr=/*#__PURE__*/v.styled.button.withConfig({displayName:"PasskeyItemUnlinkButton",componentId:"sc-d4c46a0c-8"})(["",""],Jr);const Qr=new Map([[s.FundingMethodSelectionScreen,null],[s.TransferFromWalletScreen,"external"],[s.AwaitingExternalTransferScreen,"external"],[s.AwaitingEvmToSolBridgingScreen,"external"],[s.AwaitingSolToEvmBridgingScreen,"external"],[s.ManualTransferScreen,"manual"],[s.MoonpayStatusScreen,"moonpay"]]),en=()=>{let e=s.useAppConfig(),{user:t}=d.usePrivyContext(),{client:n,refreshSessionAndUser:i,walletProxy:a}=f.usePrivyInternal();return{migrate:r.useCallback((async()=>{if("legacy-embedded-wallets-only"===e.embeddedWallets.mode)return{success:!0};if(!t)throw new o.PrivyClientError("User must be authenticated before migrating wallets",o.PrivyErrorCode.MUST_BE_AUTHENTICATED);let r=d.getPrivyPrimaryWallet(t);if(!r||d.getIsUnifiedWallet(r)||!I.isFirstClassChainWallet(r))return{success:!0};if(!a)throw new o.PrivyClientError("Cannot connect to wallet proxy");let l=await n.getAccessToken();if(!l)throw new o.PrivyClientError("User must be authenticated before migrating wallets",o.PrivyErrorCode.MUST_BE_AUTHENTICATED);let c=r.imported?[r]:t.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&!e.imported)).filter(I.isFirstClassChainWallet),{entropyId:u,entropyIdVerifier:h}=s.getEntropyDetailsForUser(t,r);try{await a.connect({accessToken:l,entropyId:u,entropyIdVerifier:h})}catch(e){if(!s.errorIndicatesRecoveryIsNeeded(e)||"privy"!==r.recoveryMethod)throw e;await a.recover({accessToken:l,entropyId:u,entropyIdVerifier:h})}return await a.createDelegatedAction({accessToken:l,rootWallet:{address:r.address,chainType:r.chainType,imported:r.imported},delegatedWallets:c}),await i(),{success:!0}}),[e.embeddedWallets.mode,t,a,n,i])}},tn=({disabled:e})=>{let{migrate:t}=en(),{user:n}=d.usePrivyContext(),{walletProxy:i}=f.usePrivyInternal();return r.useEffect((()=>{!e&&n&&i&&t().catch((e=>{console.debug("Unable to migrate wallets: ",e)}))}),[n,i,e,t]),null},rn=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}),nn=({providerApp:t,success:n,error:i,onClose:a})=>{let{title:o,subtitle:l}=r.useMemo((()=>n?{title:`Successfully connected with ${t.name}`,subtitle:"You're good to go!"}:i?{title:"Authentication failed",subtitle:i.message}:{title:`Connecting to ${t.name}`,subtitle:`Please check the pop-up from ${t.name} to continue`}),[n,i,t.name]);/*#__PURE__*/return e.jsx(s.ScreenLayout,{title:o,subtitle:l,icon:t.logoUrl,iconVariant:"loading",iconLoadingStatus:{success:n,fail:!!i},onBack:a,watermark:!0})},an={component:()=>{let t=s.useAppConfig(),{data:n,navigate:i,setModalData:a,onUserCloseViaDialogOrKeybindRef:l}=s.usePrivyModal(),{crossAppAuthFlow:c,updateWallets:d,closePrivyModal:u,createAnalyticsEvent:h}=f.usePrivyInternal(),{logout:p}=C.useLogout(),[y,m]=r.useState({}),w=n?.crossAppAuth,g={id:w.appId,name:w.name,logoUrl:w.logoUrl},v=new o.PrivyClientError(`There was an issue connecting your ${g.name} account. Please try again.`),E=new s.RunEffectOnce((async e=>{if(w.popup)try{let t=await c({appId:e,popup:w.popup,action:w.action});m({data:t})}catch(e){if(e instanceof o.PrivyClientError)m({error:e});else if(e instanceof o.PrivyApiError){if(e.privyErrorCode===o.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return a({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:`privy:${g.id}`,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void i(s.LinkConflictScreen);w.popup&&w.popup.close(),m({error:v})}else m({error:v})}else m({error:v})})),A=()=>{y.data&&(d(),w.onSuccess(y.data),u({shouldCallAuthOnSuccess:!0,isSuccess:!0})),w.onError(y.error??new o.PrivyClientError("User canceled flow")),u({shouldCallAuthOnSuccess:!1,isSuccess:!1})};return l.current=A,r.useEffect((()=>{g.id.length&&E.execute(g.id)}),[g.id]),r.useEffect((()=>{if(!y.data)return;let e=y.data;if(t.legal.requireUsersAcceptTerms&&!e.hasAcceptedTerms){let e=setTimeout((()=>{i(s.AffirmativeConsentScreen)}),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(s.shouldProceedtoEmbeddedWalletCreationFlow(e,t.embeddedWallets)){let e=setTimeout((()=>{a({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),h({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:`privy:${g.id}`,screen:"CrossAppAuthScreen"}}),p()},callAuthOnSuccessOnClose:!0}}),i(s.EmbeddedWalletOnAccountCreateScreen)}),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}let r=setTimeout(A,s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(r)}),[y.data]),/*#__PURE__*/e.jsx(nn,{providerApp:g,success:!!y.data,error:y.error,onClose:A})}},on=({appName:t,address:r,success:n,error:i,onAccept:a,onDecline:o,onClose:l})=>n||i?/*#__PURE__*/e.jsx(s.ScreenLayout,{title:i?"Something went wrong":"Success!",subtitle:i?"Please try again.":`You've successfully granted delegated action permissions to ${t}.`,icon:i?U.AlertCircle:U.CheckCircle,iconVariant:i?"error":"success",onBack:l,watermark:!0}):/*#__PURE__*/e.jsx(s.ScreenLayout,{title:"Enable offline access",subtitle:`By confirming, ${t} will be able to use your wallet for you even when you're not around. You can revoke this later.`,icon:U.CloudUpload,primaryCta:{label:"Accept",onClick:a},secondaryCta:{label:"Not now",onClick:o},onBack:l,watermark:!0,children:/*#__PURE__*/e.jsx(s.WalletInfoCard,{address:r,title:"Wallet"})}),sn={component:()=>{let{data:t}=s.usePrivyModal(),n=s.useAppConfig(),{closePrivyModal:i}=f.usePrivyInternal(),[a,l]=r.useState(!1),[c,d]=r.useState(),{address:u,onDelegate:h,onSuccess:p,onError:y}=t.delegatedActions.consent,m=async()=>{a?p():y(c??new o.PrivyClientError("User declined delegating actions.")),i({shouldCallAuthOnSuccess:!1})};return r.useEffect((()=>{if(!a&&!c)return;let e=setTimeout(m,s.DEFAULT_SUCCESS_SCREEN_LONG_DURATION_MS);return()=>clearTimeout(e)}),[a,c]),/*#__PURE__*/e.jsx(on,{appName:n.name,address:u,success:a,error:c,onAccept:async()=>{try{await h(),l(!0)}catch(e){d(e)}},onDecline:()=>{m()},onClose:m})}},ln=({appName:t,success:r,error:n,onRevoke:i,onDeny:a,onClose:o})=>r||n?/*#__PURE__*/e.jsx(s.ScreenLayout,{title:n?"Something went wrong":"Success!",subtitle:n?"Please try again.":"You've successfully revoked permissions.",icon:n?U.AlertCircle:U.CheckCircle,iconVariant:n?"error":"success",onBack:o,watermark:!0}):/*#__PURE__*/e.jsx(s.ScreenLayout,{title:"Revoke offline access to wallet",subtitle:`By confirming, ${t} will no longer be able to use this wallet on your behalf when you are not online.`,icon:U.Ban,primaryCta:{label:"Confirm",onClick:i},secondaryCta:{label:"Deny",onClick:a},onBack:o,watermark:!0}),cn={component:()=>{let{data:t}=s.usePrivyModal(),n=s.useAppConfig(),{closePrivyModal:i}=f.usePrivyInternal(),[a,l]=r.useState(!1),[c,d]=r.useState(),{onRevoke:u,onSuccess:h,onError:p}=t.delegatedActions.revoke,y=async()=>{a?h():p(c??new o.PrivyClientError("User declined revoking access to their delegated wallet.")),i({shouldCallAuthOnSuccess:!1})};return r.useEffect((()=>{if(!a&&!c)return;let e=setTimeout(y,s.DEFAULT_SUCCESS_SCREEN_LONG_DURATION_MS);return()=>clearTimeout(e)}),[a,c]),/*#__PURE__*/e.jsx(ln,{appName:n.name,success:a,error:c,onRevoke:async()=>{try{await u(),l(!0)}catch(e){d(e)}},onDeny:()=>{y()},onClose:y})}};let dn="#8a63d2";const un=({appName:t,loading:r,success:i,errorMessage:a,connectUri:o,onBack:l,onClose:c,onOpenFarcaster:d})=>n.isMobile||r?n.isIOS?/*#__PURE__*/e.jsx(s.ScreenLayout,{title:a?a.message:"Add a signer to Farcaster",subtitle:a?a.detail:`This will allow ${t} to add casts, likes, follows, and more on your behalf.`,icon:s.Farcaster,iconVariant:"loading",iconLoadingStatus:{success:i,fail:!!a},primaryCta:o&&d?{label:"Open Farcaster app",onClick:d}:void 0,onBack:l,onClose:c,watermark:!0}):/*#__PURE__*/e.jsx(s.ScreenLayout,{title:a?a.message:"Requesting signer from Farcaster",subtitle:a?a.detail:"This should only take a moment",icon:s.Farcaster,iconVariant:"loading",iconLoadingStatus:{success:i,fail:!!a},onBack:l,onClose:c,watermark:!0,children:o&&n.isMobile&&/*#__PURE__*/e.jsx(hn,{children:/*#__PURE__*/e.jsx(s.OpenLinkButton,{text:"Take me to Farcaster",url:o,color:dn})})}):
5
- /*#__PURE__*/e.jsx(s.ScreenLayout,{title:"Add a signer to Farcaster",subtitle:`This will allow ${t} to add casts, likes, follows, and more on your behalf.`,onBack:l,onClose:c,watermark:!0,children:/*#__PURE__*/e.jsxs(pn,{children:[/*#__PURE__*/e.jsx(yn,{children:o?/*#__PURE__*/e.jsx(s.QrCode,{url:o,size:275,squareLogoElement:s.Farcaster}):/*#__PURE__*/e.jsx(gn,{children:/*#__PURE__*/e.jsx(s.Loader,{})})}),/*#__PURE__*/e.jsxs(mn,{children:[/*#__PURE__*/e.jsx(wn,{children:"Or copy this link and paste it into a phone browser to open the Farcaster app."}),o&&/*#__PURE__*/e.jsx(s.CopytoClipboardButton,{text:o,itemName:"link",color:dn})]})]})});let hn=/*#__PURE__*/v.styled.div.withConfig({displayName:"MobileLinkContainer",componentId:"sc-75c99bb6-0"})(["margin-top:24px;"]),pn=/*#__PURE__*/v.styled.div.withConfig({displayName:"ContentContainer",componentId:"sc-75c99bb6-1"})(["display:flex;flex-direction:column;align-items:center;gap:24px;"]),yn=/*#__PURE__*/v.styled.div.withConfig({displayName:"QrContainer",componentId:"sc-75c99bb6-2"})(["padding:24px;position:relative;display:flex;align-items:center;justify-content:center;min-height:275px;"]),mn=/*#__PURE__*/v.styled.div.withConfig({displayName:"InstructionsContainer",componentId:"sc-75c99bb6-3"})(["display:flex;flex-direction:column;align-items:center;gap:16px;"]),wn=/*#__PURE__*/v.styled.div.withConfig({displayName:"InstructionText",componentId:"sc-75c99bb6-4"})(["font-size:0.875rem;text-align:center;color:var(--privy-color-foreground-2);"]),gn=/*#__PURE__*/v.styled.div.withConfig({displayName:"LoaderWrapper",componentId:"sc-75c99bb6-5"})(["position:relative;width:82px;height:82px;"]);const vn={component:()=>{let{lastScreen:t,navigateBack:n,data:i}=s.usePrivyModal(),a=s.useAppConfig(),{requestFarcasterSignerStatus:o,closePrivyModal:l}=f.usePrivyInternal(),[c,d]=r.useState(void 0),[u,h]=r.useState(!1),[p,y]=r.useState(!1),m=r.useRef([]),w=i?.farcasterSigner;r.useEffect((()=>{let e=Date.now(),t=setInterval((async()=>{if(!w?.public_key)return clearInterval(t),void d({retryable:!0,message:"Connect failed",detail:"Something went wrong. Please try again."});"approved"===w.status&&(clearInterval(t),h(!1),y(!0),m.current.push(setTimeout((()=>l({shouldCallAuthOnSuccess:!1,isSuccess:!0})),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS)));let r=await o(w?.public_key),n=Date.now()-e;"approved"===r.status?(clearInterval(t),h(!1),y(!0),m.current.push(setTimeout((()=>l({shouldCallAuthOnSuccess:!1,isSuccess:!0})),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS))):n>3e5?(clearInterval(t),d({retryable:!0,message:"Connect failed",detail:"The request timed out. Try again."})):"revoked"===r.status&&(clearInterval(t),d({retryable:!0,message:"Request rejected",detail:"The request was rejected. Please try again."}))}),2e3);return()=>{clearInterval(t),m.current.forEach((e=>clearTimeout(e)))}}),[]);let g="pending_approval"===w?.status?w.signer_approval_url:void 0;/*#__PURE__*/return e.jsx(un,{appName:a.name,loading:u,success:p,errorMessage:c,connectUri:g,onBack:t?n:void 0,onClose:l,onOpenFarcaster:()=>{g&&(window.location.href=g)}})}},fn=({onClose:t})=>/*#__PURE__*/e.jsx(s.ScreenLayout,{title:"Could not log in with provider",subtitle:"It looks like you're using an in-app browser. To log in, please try again using an external browser.",icon:U.ExternalLink,primaryCta:{label:"Close",onClick:t},watermark:!0}),Cn={component:()=>{let{closePrivyModal:t}=f.usePrivyInternal();/*#__PURE__*/return e.jsx(fn,{onClose:()=>t()})}},En=({title:t="Connect your email",subtitle:r="Add your email to your account"})=>/*#__PURE__*/e.jsx(s.ScreenLayout,{title:t,subtitle:r,icon:se.default,watermark:!0,children:/*#__PURE__*/e.jsx(s.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(s.ConnectEmailForm,{stacked:!0})})}),An={component:()=>{let t=s.useAppConfig();/*#__PURE__*/return e.jsx(En,{subtitle:`Add your email to your ${t?.name} account`})}},Pn=({title:t="Connect your phone",subtitle:n="Add your number to your account",onSubmit:i,isSubmitting:a=!1})=>{let[o,l]=r.useState(null),c=async()=>{o?.qualifiedPhoneNumber&&await i(o)};/*#__PURE__*/return e.jsx(s.ScreenLayout,{title:t,subtitle:n,icon:ne.default,primaryCta:{label:a?"Submitting":"Submit",onClick:c,disabled:!o?.isValid||a},watermark:!0,children:/*#__PURE__*/e.jsx(s.ConnectPhoneNumberForm,{onChange:e=>{l(e)},onSubmit:c,noIncludeSubmitButton:!0,hideRecent:!0})})},kn={component:()=>{let{currentScreen:t,data:n,navigate:i,setModalData:a}=s.usePrivyModal(),o=s.useAppConfig(),{initLoginWithSms:l}=f.usePrivyInternal(),[c,d]=r.useState(!1);/*#__PURE__*/return e.jsx(Pn,{subtitle:`Add your number to your ${o?.name} account`,onSubmit:async e=>{d(!0);try{await l({phoneNumber:e.qualifiedPhoneNumber,withPrivyUi:!0}),i(s.AwaitingPasswordlessCodeScreen)}catch(e){a({errorModalData:{error:e,previousScreen:n?.errorModalData?.previousScreen||t||kn}}),i(s.ErrorScreen)}finally{d(!1)}},isSubmitting:c})}},bn=({title:t="Could not connect with wallet",subtitle:r="Please check that Phantom multichain is enabled and try again.",primaryCtaText:n="Try again",secondaryCtaText:i="Cancel",onTryAgain:a,onCancel:o})=>/*#__PURE__*/e.jsx(s.ScreenLayout,{title:t,subtitle:r,icon:U.XCircle,iconVariant:"error",primaryCta:{label:n,onClick:a},secondaryCta:{label:i,onClick:o},watermark:!0}),xn={component:()=>{let{closePrivyModal:t}=f.usePrivyInternal(),{navigate:r}=s.usePrivyModal();/*#__PURE__*/return e.jsx(bn,{onTryAgain:()=>{r(s.LandingScreen)},onCancel:async()=>{await t()}})}};function Tn(){let{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:n,submitEnrollmentWithSms:i,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:o,unenroll:s,enrollInMfa:l}=r.useContext(d.PrivyContext);return{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:n,submitEnrollmentWithSms:i,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:o,unenrollWithSms:()=>s("sms"),unenrollWithTotp:()=>s("totp"),unenrollWithPasskey:e=>s("passkey",e),showMfaEnrollmentModal:()=>l(!0),closeMfaEnrollmentModal:()=>l(!1)}}const Sn=t=>/*#__PURE__*/e.jsxs(_n,{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 _n=/*#__PURE__*/v.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 In=({showIntro:t,userMfaMethods:r,appMfaMethods:n,userHasAuthSms:i,isTotpLoading:a,isPasskeyLoading:o,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(s.ModalHeader,{backFn:t?d:void 0,onClose:c},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ie.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Choose a verification method"}),r.length>0?/*#__PURE__*/e.jsx(Et,{children:"To add or delete verification methods, verification is required."}):/*#__PURE__*/e.jsx(Et,{children:"How would you like to verify your identity?"}),l&&/*#__PURE__*/e.jsx(Nt,{style:{marginTop:"1.25rem"},children:l.message}),/*#__PURE__*/e.jsxs(Tt,{children:[(y.passkey||p.passkey)&&/*#__PURE__*/e.jsxs(St,{children:[/*#__PURE__*/e.jsx(s.LoginMethodButton,{style:{justifyContent:"center"},onClick:()=>u("passkey"),disabled:p.passkey||o,children:o?/*#__PURE__*/e.jsx(s.Loader,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/e.jsxs(Wt,{children:[/*#__PURE__*/e.jsxs(It,{children:[/*#__PURE__*/e.jsx(re.default,{}),"Passkey"]}),p.passkey?/*#__PURE__*/e.jsx(Un,{color:"green",children:"Enabled"}):/*#__PURE__*/e.jsx(Ut,{$isAccent:!0,children:/*#__PURE__*/e.jsx(ue.default,{})})]})}),p.passkey&&/*#__PURE__*/e.jsx(_t,{style:{position:"absolute",right:0},onClick:()=>h("passkey"),children:/*#__PURE__*/e.jsx(he.default,{})})]},"passkey"),(y.totp||p.totp)&&/*#__PURE__*/e.jsxs(St,{children:[/*#__PURE__*/e.jsx(s.LoginMethodButton,{style:{justifyContent:"center"},disabled:p.totp||a,onClick:()=>u("totp"),children:a?/*#__PURE__*/e.jsx(s.Loader,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/e.jsxs(Wt,{children:[/*#__PURE__*/e.jsxs(It,{children:[/*#__PURE__*/e.jsx(te.default,{}),"Authenticator app"]}),p.totp&&/*#__PURE__*/e.jsx(Un,{color:"green",children:"Enabled"})]})}),p.totp&&/*#__PURE__*/e.jsx(_t,{style:{position:"absolute",right:0},onClick:()=>h("totp"),children:/*#__PURE__*/e.jsx(he.default,{})})]},"totp"),(y.sms||p.sms)&&/*#__PURE__*/e.jsxs(St,{children:[/*#__PURE__*/e.jsx(s.LoginMethodButton,{disabled:p.sms||i,onClick:()=>u("sms"),children:/*#__PURE__*/e.jsxs(Wt,{children:[/*#__PURE__*/e.jsxs(It,{children:[/*#__PURE__*/e.jsx(ne.default,{}),"SMS"]}),p.sms&&/*#__PURE__*/e.jsx(Un,{color:"green",children:"Enabled"}),i&&/*#__PURE__*/e.jsx(Ut,{children:"Disabled"})]})}),p.sms&&/*#__PURE__*/e.jsx(_t,{style:{position:"absolute",right:0},onClick:()=>h("sms"),children:/*#__PURE__*/e.jsx(he.default,{})})]},"sms")]}),/*#__PURE__*/e.jsx(Wn,{children:"You can always change your selection later"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})};let Un=/*#__PURE__*/v.styled(s.Chip).withConfig({displayName:"StyledChip",componentId:"sc-24f8b314-0"})(["margin-right:1.5rem;"]),Wn=/*#__PURE__*/v.styled(Rt).withConfig({displayName:"StyledTerms",componentId:"sc-24f8b314-1"})(["&&{margin-top:1rem;}text-align:center;"]);const Rn=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{x:0,y:0,width:"65",height:"64",viewBox:"0 0 65 64",style:{height:"64px",width:"65px",...t},xmlns:"http://www.w3.org/2000/svg",...r,children:[/*#__PURE__*/e.jsxs("g",{clipPath:"url(#clip0_113_33841)",children:[/*#__PURE__*/e.jsx("path",{d:"M39.1193 0.943398C34.636 -0.174912 29.9185 -0.334713 25.328 0.656273C24.9732 0.732859 24.7477 1.08253 24.8243 1.43729C24.9009 1.79205 25.2506 2.01756 25.6053 1.94097C30.0015 0.991934 34.53 1.14842 38.8375 2.22802C49.1385 4.80983 57.7129 12.5548 60.9786 22.6718C62.2416 26.5843 62.7781 30.7505 62.8855 35.1167C62.8945 35.4795 63.1958 35.7664 63.5586 35.7575C63.9215 35.7485 64.2083 35.4472 64.1994 35.0843C64.0905 30.6582 63.5477 26.3849 62.2536 22.3432C58.8621 11.7515 49.9005 3.63265 39.1193 0.943398Z"}),/*#__PURE__*/e.jsx("path",{d:"M21.9931 2.93163C22.343 2.83511 22.5484 2.47325 22.4518 2.12339C22.3553 1.77352 21.9935 1.56815 21.6436 1.66466C16.8429 2.98903 10.0898 7.56519 5.91628 13.6786C5.91465 13.681 5.91304 13.6834 5.91145 13.6858C2.24684 19.2083 -0.0503572 26.1484 0.591012 32.8828C0.591623 32.8892 0.592328 32.8956 0.593127 32.902C0.746837 34.1317 1.00488 35.3591 1.26323 36.5879C1.80735 39.1761 2.35282 41.7706 1.92765 44.4064C1.86986 44.7647 2.11347 45.102 2.47177 45.1598C2.83007 45.2176 3.16738 44.974 3.22518 44.6157C3.66961 41.8605 3.11776 39.173 2.56581 36.4851C2.31054 35.2419 2.05525 33.9987 1.89847 32.7486C1.29525 26.3851 3.46802 19.7466 7.00418 14.416C11.0189 8.5373 17.5201 4.16562 21.9931 2.93163Z"}),/*#__PURE__*/e.jsx("path",{d:"M30.6166 4.39985C38.8671 3.89603 47.1159 7.26314 52.6556 13.7139C52.8921 13.9893 52.8605 14.4042 52.5852 14.6406C52.3099 14.8771 51.895 14.8455 51.6585 14.5702C46.3904 8.43576 38.541 5.23144 30.6927 5.71195C30.6899 5.71212 30.6871 5.71227 30.6843 5.71241C20.7592 6.19265 11.4643 12.9257 8.04547 22.3603C7.92183 22.7016 7.54498 22.8779 7.20375 22.7543C6.86253 22.6306 6.68616 22.2538 6.80981 21.9126C10.4114 11.9735 20.1717 4.90702 30.6166 4.39985Z"}),/*#__PURE__*/e.jsx("path",{d:"M54.6576 16.5848C54.4553 16.2836 54.047 16.2033 53.7457 16.4057C53.4444 16.608 53.3642 17.0163 53.5665 17.3176C56.6376 21.8904 57.9074 26.8665 58.4094 32.7717C58.4401 33.1333 58.7582 33.4016 59.1199 33.3708C59.4815 33.3401 59.7497 33.022 59.719 32.6604C59.206 26.6261 57.8965 21.4076 54.6576 16.5848Z"}),/*#__PURE__*/e.jsx("path",{d:"M59.2796 35.4504C59.6419 35.4277 59.9539 35.703 59.9765 36.0653C60.2242 40.0279 60.2265 44.5112 59.7881 47.8243C59.7405 48.1841 59.4102 48.4372 59.0504 48.3896C58.6906 48.342 58.4376 48.0117 58.4852 47.6519C58.9077 44.4586 58.91 40.0704 58.6648 36.1473C58.6421 35.785 58.9174 35.473 59.2796 35.4504Z"}),/*#__PURE__*/e.jsx("path",{d:"M7.05311 25.5432C7.13829 25.1904 6.92135 24.8354 6.56855 24.7502C6.21576 24.665 5.86071 24.882 5.77553 25.2348C5.2932 27.2325 5.0428 29.2847 5.03288 31.3388C5.02266 33.4559 5.41742 35.5225 5.81234 37.5899C6.1354 39.2811 6.45855 40.9728 6.5602 42.6932C6.69373 44.9531 6.21839 47.2163 5.39698 49.3703C5.26766 49.7094 5.43774 50.0891 5.77685 50.2184C6.11596 50.3477 6.4957 50.1777 6.62502 49.8386C7.49325 47.5617 8.01954 45.1092 7.87221 42.6157C7.77126 40.9071 7.44813 39.2252 7.12512 37.5439C6.73099 35.4925 6.33704 33.442 6.34716 31.3451C6.35659 29.3933 6.59455 27.4425 7.05311 25.5432Z"}),/*#__PURE__*/e.jsx("path",{d:"M24.2964 10.94C24.4317 11.2768 24.2683 11.6595 23.9315 11.7947C17.1187 14.5307 12.0027 20.7047 10.959 27.9852C10.523 31.0269 10.9941 34.0398 11.465 37.052C11.7303 38.7483 11.9954 40.4443 12.0985 42.1451C12.3221 45.833 11.902 49.8839 9.50192 53.5696C9.30387 53.8737 8.89677 53.9597 8.59264 53.7617C8.28851 53.5636 8.20251 53.1565 8.40056 52.8524C10.5873 49.4944 11.0012 45.7644 10.7867 42.2246C10.6821 40.499 10.4185 38.7833 10.1552 37.0686C9.68265 33.9923 9.21067 30.9195 9.65804 27.7987C10.7724 20.025 16.221 13.4748 23.4417 10.5751C23.7785 10.4399 24.1612 10.6032 24.2964 10.94Z"}),/*#__PURE__*/e.jsx("path",{d:"M47.3662 14.6814C41.9915 9.64741 34.2017 7.89046 27.122 9.4433C26.7675 9.52105 26.5432 9.87147 26.6209 10.226C26.6987 10.5805 27.0491 10.8048 27.4036 10.7271C34.1075 9.25665 41.4426 10.934 46.4677 15.6406C50.7033 19.6077 53.1628 25.38 53.8066 31.6779C53.8435 32.0389 54.1661 32.3017 54.5272 32.2648C54.8883 32.2279 55.151 31.9053 55.1141 31.5442C54.4456 25.0047 51.8822 18.9111 47.3662 14.6814Z"}),/*#__PURE__*/e.jsx("path",{d:"M54.9766 34.6738C55.3376 34.6368 55.6604 34.8994 55.6975 35.2604C56.3216 41.337 56.0526 47.9003 55.1104 54.2496C55.0571 54.6086 54.7229 54.8565 54.3639 54.8032C54.0049 54.7499 53.7571 54.4157 53.8103 54.0567C54.7394 47.7957 55.001 41.3439 54.39 35.3947C54.353 35.0336 54.6156 34.7109 54.9766 34.6738Z"}),/*#__PURE__*/e.jsx("path",{d:"M32.0659 13.3553C21.9959 13.3553 13.814 21.3892 13.814 31.3219C13.814 32.3829 13.9081 33.4225 14.0876 34.4334C14.1511 34.7907 14.4922 35.029 14.8495 34.9655C15.2069 34.9021 15.4451 34.561 15.3817 34.2036C15.2155 33.2677 15.1283 32.305 15.1283 31.3219C15.1283 22.1352 22.7014 14.6696 32.0659 14.6696C36.2978 14.6696 40.1642 16.1949 43.1319 18.7152C43.4086 18.9501 43.8233 18.9163 44.0582 18.6396C44.2931 18.363 44.2593 17.9483 43.9827 17.7134C40.7847 14.9975 36.6188 13.3553 32.0659 13.3553Z"}),/*#__PURE__*/e.jsx("path",{d:"M45.455 20.1635C45.717 19.9123 46.133 19.921 46.3842 20.183C49.2843 23.2072 50.2126 27.9605 50.8269 31.9494C51.5188 36.4426 51.6244 40.826 51.6244 42.8585C51.6244 43.2214 51.3302 43.5156 50.9673 43.5156C50.6044 43.5156 50.3101 43.2214 50.3101 42.8585C50.3101 40.8589 50.2055 36.5497 49.5279 32.1494C48.9577 28.4462 48.1356 23.9082 45.4356 21.0927C45.1844 20.8307 45.1931 20.4147 45.455 20.1635Z"}),/*#__PURE__*/e.jsx("path",{d:"M51.4576 46.6219C51.4864 46.2601 51.2165 45.9435 50.8547 45.9146C50.493 45.8858 50.1763 46.1557 50.1474 46.5175C49.8247 50.5654 49.403 54.6088 48.5474 58.3439C48.4663 58.6977 48.6874 59.0502 49.0412 59.1312C49.3949 59.2123 49.7474 58.9912 49.8285 58.6374C50.7067 54.8039 51.134 50.6806 51.4576 46.6219Z"}),/*#__PURE__*/e.jsx("path",{d:"M15.1454 36.852C15.5015 36.7819 15.847 37.0137 15.9171 37.3698C17.3066 44.4257 16.3467 50.8355 12.6672 56.4502C12.4682 56.7537 12.0609 56.8385 11.7573 56.6396C11.4538 56.4407 11.369 56.0333 11.5679 55.7298C15.0299 50.4469 15.9617 44.3985 14.6276 37.6238C14.5575 37.2677 14.7893 36.9221 15.1454 36.852Z"}),/*#__PURE__*/e.jsx("path",{d:"M32.0659 17.631C25.5291 17.631 19.1165 22.691 18.462 29.0504C18.1754 31.8345 18.578 34.5769 18.9807 37.3204C19.3323 39.7159 19.684 42.1124 19.5772 44.5381C19.3328 50.0898 17.7039 54.6726 14.905 58.4471C14.6888 58.7386 14.7499 59.1502 15.0414 59.3663C15.333 59.5825 15.7445 59.5214 15.9607 59.2299C18.9293 55.2266 20.6354 50.386 20.8903 44.5959C20.9966 42.1811 20.6438 39.7923 20.2912 37.4051C19.888 34.6752 19.4851 31.9473 19.7694 29.1849C20.3444 23.5983 26.0946 18.9453 32.0659 18.9453C34.851 18.9453 42.057 20.4534 44.3492 27.9205C45.7856 32.5998 46.1774 38.9326 45.8295 45.0849C45.4816 51.2364 44.3994 57.12 42.9442 60.8928C42.8136 61.2314 42.9822 61.6118 43.3208 61.7424C43.6594 61.873 44.0398 61.7044 44.1704 61.3658C45.6929 57.4186 46.7895 51.386 47.1417 45.1591C47.4938 38.9329 47.1068 32.4249 45.6056 27.5348C43.0612 19.2461 35.0851 17.631 32.0659 17.631Z"}),/*#__PURE__*/e.jsx("path",{d:"M21.9529 56.4512C22.2569 56.6494 22.3426 57.0566 22.1444 57.3606C21.7369 57.9854 21.3784 58.6391 21.0199 59.2928C20.6614 59.9465 20.3028 60.6004 19.8953 61.2253C19.697 61.5293 19.2898 61.615 18.9858 61.4167C18.6819 61.2184 18.5962 60.8113 18.7944 60.5073C19.2019 59.8825 19.5604 59.2288 19.9189 58.5751C20.2774 57.9213 20.636 57.2675 21.0435 56.6426C21.2418 56.3386 21.649 56.2529 21.9529 56.4512Z"}),/*#__PURE__*/e.jsx("path",{d:"M27.5799 24.4525C27.8816 24.2508 27.9625 23.8426 27.7608 23.541C27.559 23.2393 27.1509 23.1583 26.8492 23.3601C24.247 25.1006 22.6505 27.494 22.6505 31.0002C22.6505 33.088 23.0203 34.7946 23.3997 36.5449C23.9674 39.1641 24.3524 41.7777 24.2832 44.468C24.1992 47.7349 23.56 50.7201 22.3313 53.564C22.1873 53.8971 22.3407 54.2839 22.6739 54.4278C23.0071 54.5718 23.3938 54.4184 23.5378 54.0852C24.8369 51.0784 25.509 47.9266 25.5971 44.5018C25.6689 41.7062 25.2732 38.9892 24.6845 36.267C24.3042 34.509 23.9648 32.9394 23.9648 31.0002C23.9648 27.9961 25.2863 25.9866 27.5799 24.4525Z"}),/*#__PURE__*/e.jsx("path",{d:"M30.1447 22.1436C32.8717 21.5877 35.8061 22.2746 37.966 24.0228C41.8241 27.1455 42.3372 32.8403 42.753 37.4549L42.7742 37.69C43.3115 43.6385 42.6964 49.4163 41.4575 55.2186C41.3817 55.5736 41.0326 55.7999 40.6776 55.7241C40.3227 55.6483 40.0964 55.2991 40.1722 54.9442C41.3926 49.2288 41.9873 43.5885 41.4652 37.8082C41.4479 37.6169 41.4307 37.4228 41.4133 37.2264L41.4131 37.2235C41.0438 33.0534 40.5812 27.8304 37.1392 25.0444C35.2926 23.5498 32.7599 22.9518 30.4073 23.4314C30.0517 23.5039 29.7046 23.2744 29.6321 22.9188C29.5596 22.5632 29.7891 22.2161 30.1447 22.1436Z"}),/*#__PURE__*/e.jsx("path",{d:"M40.5287 58.4885C40.6183 58.1368 40.4057 57.7791 40.054 57.6896C39.7023 57.6 39.3446 57.8126 39.2551 58.1643C38.8578 59.7247 38.2456 61.1333 37.4695 62.4301C37.2831 62.7415 37.3844 63.145 37.6958 63.3314C38.0072 63.5178 38.4108 63.4165 38.5972 63.1051C39.4336 61.7075 40.0977 60.1816 40.5287 58.4885Z"}),/*#__PURE__*/e.jsx("path",{d:"M37.3152 48.9521C37.6756 48.9948 37.9332 49.3215 37.8906 49.682C37.2699 54.9267 35.8688 59.6042 33.6205 63.6613C33.4446 63.9787 33.0446 64.0934 32.7272 63.9175C32.4097 63.7416 32.295 63.3417 32.4709 63.0242C34.6226 59.1416 35.9811 54.6339 36.5854 49.5275C36.6281 49.1671 36.9548 48.9095 37.3152 48.9521Z"}),/*#__PURE__*/e.jsx("path",{d:"M37.1798 30.6556C36.7242 28.2212 34.6349 26.3591 32.0985 26.3591C28.6638 26.3591 26.254 29.8212 27.1032 33.0422C28.54 38.7279 28.7759 44.2077 27.8032 49.4855L27.8025 49.4893C26.9584 54.228 25.3374 58.4908 23.1263 62.1031C22.9368 62.4127 23.0342 62.8172 23.3437 63.0067C23.6533 63.1962 24.0578 63.0988 24.2473 62.7893C26.5488 59.0292 28.2249 54.6109 29.0961 49.7218C30.106 44.2403 29.8558 38.5684 28.3765 32.7168L28.3748 32.7099C27.7378 30.3005 29.5133 27.6734 32.0985 27.6734C33.9641 27.6734 35.5393 29.0459 35.8871 30.8929C36.8436 36.4411 37.3418 41.5862 36.9871 46.016C36.9581 46.3778 37.2279 46.6945 37.5897 46.7235C37.9515 46.7525 38.2682 46.4827 38.2972 46.1209C38.6649 41.5294 38.1459 36.2576 37.1815 30.6648C37.1809 30.6617 37.1804 30.6586 37.1798 30.6556Z"}),/*#__PURE__*/e.jsx("path",{d:"M30.1376 59.1171C30.4604 59.283 30.5876 59.6792 30.4217 60.002L28.6804 63.3906C28.5145 63.7134 28.1184 63.8406 27.7956 63.6747C27.4728 63.5088 27.3456 63.1127 27.5114 62.7899L29.2527 59.4013C29.4186 59.0785 29.8147 58.9513 30.1376 59.1171Z"}),/*#__PURE__*/e.jsx("path",{d:"M32.5872 31.2892C32.5042 30.9359 32.1505 30.7168 31.7972 30.7998C31.4439 30.8828 31.2247 31.2365 31.3077 31.5898C33.5238 41.0232 33.2194 49.3066 30.5201 56.363C30.3905 56.702 30.5602 57.0819 30.8991 57.2115C31.2381 57.3412 31.618 57.1715 31.7477 56.8326C34.5622 49.475 34.8483 40.9141 32.5872 31.2892Z"})]}),/*#__PURE__*/e.jsx("defs",{children:/*#__PURE__*/e.jsx("clipPath",{id:"clip0_113_33841",children:/*#__PURE__*/e.jsx("rect",{width:"64",height:"64",fill:"white",transform:"translate(0.483887)"})})})]}),On=({onClose:t,onReset:n,submitEnrollmentWithPasskey:i})=>{let{user:a}=d.usePrivyContext(),{initLinkWithPasskey:o,linkWithPasskey:l}=f.usePrivyInternal(),c=s.useAppConfig(),[u,h]=r.useState(!1),[p,y]=r.useState(!1),[m,w]=r.useState(null),g=r.useMemo((()=>a?.linkedAccounts.filter((e=>"passkey"===e.type))??[]),[a]),v=async e=>{h(!0);try{await i(e)}catch(e){w(e)}finally{h(!1)}},C=async()=>{y(!0),w(null);try{await o();let e=await l(),t=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];await v(t)}catch(e){w(e)}finally{y(!1)}};return 0===g.length||p?/*#__PURE__*/e.jsx(Mn,{onReset:n,onClose:t,onClick:C,isCreating:p}):m?/*#__PURE__*/e.jsx(s.ErrorScreenView,{allowlistConfig:c.allowlistConfig,error:m,onBack:()=>w(null),onRetry:()=>w(null)}):/*#__PURE__*/e.jsx(Nn,{passkeys:g,isSubmitting:u,isCreating:p,onReset:n,onClose:t,onSubmitEnrollment:()=>v(g.map((e=>e.credentialId))),onAddPasskey:C})};let Mn=({onReset:t,onClose:r,onClick:n,isCreating:i})=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:t,onClose:r},"header"),/*#__PURE__*/e.jsx(ft,{children:/*#__PURE__*/e.jsxs(Br,{children:[/*#__PURE__*/e.jsx(Dt,{}),/*#__PURE__*/e.jsx(Rn,{})]})}),/*#__PURE__*/e.jsx(Ct,{children:"Set up passkey verification"}),/*#__PURE__*/e.jsxs(Pt,{children:[/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(ie.default,{})}),"Verify with Touch ID, Face ID, PIN, or hardware key"]}),/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(ye.default,{})}),"Takes seconds to set up and use"]}),/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(pe.default,{})}),"Use your passkey to verify transactions and login to your account"]})]}),/*#__PURE__*/e.jsx(s.PrimaryButton,{style:{marginTop:"2.25rem"},onClick:n,loading:i,children:"Add a new passkey"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}),Nn=({onReset:t,onClose:n,onAddPasskey:i,onSubmitEnrollment:a,passkeys:o,isSubmitting:l,isCreating:c})=>{let[d,u]=r.useState(!1),h=d?o.length:o.length>3?2:3;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:d?()=>u(!1):t,onClose:n},"header"),!d&&/*#__PURE__*/e.jsx(ft,{children:/*#__PURE__*/e.jsxs(Br,{children:[/*#__PURE__*/e.jsx(Dt,{}),/*#__PURE__*/e.jsx(Rn,{})]})}),/*#__PURE__*/e.jsx(Ct,{children:"Enable your passkeys for verification"}),/*#__PURE__*/e.jsxs(Pt,{children:[o.slice(0,h).map((t=>/*#__PURE__*/e.jsxs(jn,{children:[/*#__PURE__*/e.jsx(Fn,{children:Dn(t)}),/*#__PURE__*/e.jsxs(Ln,{children:["Last used: ",t.latestVerifiedAt?.toLocaleString()]})]},t.credentialId))),!d&&o.length>3&&/*#__PURE__*/e.jsx(qn,{onClick:()=>u(!0),children:"View All"})]}),/*#__PURE__*/e.jsx(s.PrimaryButton,{style:{marginTop:"1.5rem"},onClick:a,loading:l,children:"Enable passkeys"}),o.length<5&&/*#__PURE__*/e.jsx(qn,{style:{marginTop:"0.5rem"},onClick:i,disabled:c,children:c?/*#__PURE__*/e.jsx(s.Loader,{style:{height:"1rem",width:"1rem",borderWidth:2}}):"Add new passkey"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},jn=/*#__PURE__*/v.styled.div.withConfig({displayName:"PasskeyItem",componentId:"sc-23451ce2-0"})(["&&{padding:0.75rem 1rem;text-align:left;border-radius:0.5rem;border:1px solid var(--privy-color-foreground-4);width:100%;}"]),Fn=/*#__PURE__*/v.styled.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-23451ce2-1"})(["font-size:0.875rem;line-height:1.375rem;font-weight:500;color:var(--privy-color-foreground-1);"]),Ln=/*#__PURE__*/v.styled.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-23451ce2-2"})(["font-size:0.75rem;font-weight:400;line-height:1.125rem;color:var(--privy-color-foreground-2);"]),Dn=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 qn=/*#__PURE__*/v.styled.button.withConfig({displayName:"StyledLink",componentId:"sc-23451ce2-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;}}"]),Hn=({appName:t,onComplete:n,onReset:i,onClose:o})=>{let[l,c]=r.useState(""),[d,u]=r.useState(!1),[h,p]=r.useState(null),[y,m]=r.useState("enroll"),{initEnrollmentWithSms:w,submitEnrollmentWithSms:g}=Tn(),{data:v}=s.usePrivyModal(),f=s.useAppConfig();function C(){v?.mfaEnrollmentFlow?.onSuccess(),n()}return h?/*#__PURE__*/e.jsx(s.ErrorScreenView,{allowlistConfig:f.allowlistConfig,error:h,onBack:()=>p(null),onRetry:()=>p(null)}):"enroll"===y?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:i,onClose:o},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ne.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Set up SMS verification"}),/*#__PURE__*/e.jsxs(Et,{children:["We'll text a verification code to this mobile device whenever you use your ",t," ","wallet."]}),/*#__PURE__*/e.jsxs(At,{children:[/*#__PURE__*/e.jsx(s.ConnectPhoneNumberForm,{onSubmit:async function({qualifiedPhoneNumber:e}){try{await w({phoneNumber:e}),c(e),m("verify")}catch(e){p(e)}},hideRecent:!0}),/*#__PURE__*/e.jsxs(Rt,{children:["By providing your mobile number, you agree to receive text messages from ",f?.name,". Some carrier charges may apply"]})]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):d?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:C},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(me.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"SMS verification added"}),/*#__PURE__*/e.jsxs(Et,{children:["From now on, you'll enter the verification code sent to your mobile device whenever you use your ",t," wallet."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:C,children:"Done"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:function(){"verify"===y?m("enroll"):i()},onClose:o},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ne.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Enter enrollment code"}),/*#__PURE__*/e.jsxs(At,{children:[/*#__PURE__*/e.jsx($t,{onChange:async function(e){try{if(!e)return;await g({phoneNumber:l,mfaCode:e}),u(!0)}catch(e){if(s.errorIndicatesMfaRateLimit(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(s.errorIndicatesMfaVerificationFailed(e))throw Error("The code you entered is not valid");if(s.errorIndicatesMfaTimeout(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw s.errorIndicatesMfaCanceled(e)?Error("Verification canceled"):Error("Unknown error")}}}),/*#__PURE__*/e.jsxs(Et,{children:["To continue, enter the 6-digit code sent to ",/*#__PURE__*/e.jsx("strong",{children:a.lastFourDigits(l)})]})]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},Bn=({size:t,authUrl:r})=>/*#__PURE__*/e.jsx(s.QrCode,{url:r,squareLogoElement:we.default,size:t,fgColor:"#1F1F1F"}),zn=({onClose:t,onReset:n,totpInfo:i,submitEnrollmentWithTotp:a,error:o})=>{let[l,c]=r.useState("enroll");return"enroll"===l?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:n,onClose:t},"header"),/*#__PURE__*/e.jsx(s.Title,{children:"Scan QR code"}),/*#__PURE__*/e.jsx(s.Subtitle,{children:"Open your authenticator app and scan this code to continue"}),/*#__PURE__*/e.jsx(s.CenteredItemWithPadding,{children:/*#__PURE__*/e.jsx(Bn,{authUrl:i.authUrl,size:240})}),/*#__PURE__*/e.jsx(s.LabelXs,{style:{textAlign:"left"},children:"Setup key"}),/*#__PURE__*/e.jsxs(s.Box,{style:{marginTop:"0.25rem"},children:[/*#__PURE__*/e.jsx(C.Column,{children:"•".repeat(16)}),/*#__PURE__*/e.jsx(s.CopytoClipboardButton,{itemName:" ",text:i.secret})]}),/*#__PURE__*/e.jsx(s.PrimaryButton,{style:{marginTop:"1rem"},onClick:function(){c("verify")},children:"Continue"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:function(){"verify"===l?c("enroll"):n()},onClose:t},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(te.default,{})}),/*#__PURE__*/e.jsx(s.Title,{children:"Enter enrollment code"}),/*#__PURE__*/e.jsx(s.Subtitle,{children:"To continue, enter the 6-digit code generated from your authenticator app"}),/*#__PURE__*/e.jsx(At,{children:/*#__PURE__*/e.jsx($t,{onChange:async function(e){try{if(!e)return;await a({mfaCode:e})}catch(e){if(s.errorIndicatesMfaRateLimit(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(s.errorIndicatesMfaVerificationFailed(e))throw Error("The code you entered is not valid");if(s.errorIndicatesMfaTimeout(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw s.errorIndicatesMfaCanceled(e)?Error("Verification canceled"):Error("Unknown error")}},errorReasonOverride:o?.message})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},Kn={component:()=>{let{user:t,enrollInMfa:n,ready:i}=d.usePrivyContext(),[a,o]=r.useState(null),{unenrollWithSms:l,unenrollWithTotp:c,unenrollWithPasskey:u,submitEnrollmentWithTotp:h,initEnrollmentWithPasskey:p,submitEnrollmentWithPasskey:y,initEnrollmentWithTotp:m}=Tn(),{data:w,onUserCloseViaDialogOrKeybindRef:g}=s.usePrivyModal(),v=s.useAppConfig(),{closePrivyModal:C}=f.usePrivyInternal(),{promptMfa:E}=Qt(),[A,P]=r.useState(!1),[k,b]=r.useState(null),[x,T]=r.useState(null),S=()=>{C({shouldCallAuthOnSuccess:!0}),n(!1),setTimeout((()=>{o(null),b(null)}),500)},[_,I]=r.useState(!1),[U,W]=r.useState();g.current=S;let R=t?.mfaMethods.includes("sms"),O=!!t?.phone,M=t?.mfaMethods.includes("totp"),N=t?.mfaMethods.includes("passkey"),j=R||M||N,F=t?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function L(){o(null),b(null)}async function D(e=F){I(!0);try{return await p(),await y({credentialIds:e},{removeForLogin:w?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa}),w?.mfaEnrollmentFlow?.onSuccess(),S()}catch(e){W(e)}finally{I(!1)}}if(r.useEffect((()=>{j&&P(!0)}),[j]),!i||!t||!v/*#__PURE__*/)return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:S},"header"),/*#__PURE__*/e.jsx(ft,{children:/*#__PURE__*/e.jsx(Sn,{})}),/*#__PURE__*/e.jsx(At,{children:/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("sms"===a)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:L,onClose:S},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(le.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Remove SMS verification?"}),/*#__PURE__*/e.jsxs(Et,{children:["MFA adds an extra layer of security to your ",v?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{$warn:!0,onClick:async function(){o(null);try{await l()}catch(e){o(null)}},children:"Remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("totp"===a)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:L,onClose:S},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(le.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Remove authenticator app verification?"}),/*#__PURE__*/e.jsxs(Et,{children:["MFA adds an extra layer of security to your ",v?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{$warn:!0,onClick:async function(){o(null);try{await c()}catch(e){o(null)}},children:"Remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("passkey"===a){let t=w?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:L,onClose:S},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(le.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/e.jsx(Et,{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(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{$warn:!0,onClick:async function(){o(null);try{await u({removeForLogin:w?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa})}catch(e){o(null)}},children:"Remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})}if(0===w.mfaEnrollmentFlow.mfaMethods.length&&!j)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:S},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ie.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Add more security"}),/*#__PURE__*/e.jsxs(Et,{children:[v?.name," does not have any verification methods enabled."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:S,children:"Close"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});let q=!j&&!A;return q?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:S},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ie.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Transaction Protection"}),/*#__PURE__*/e.jsx(Et,{children:"Set up transaction protection to add an extra layer of security to your account"}),/*#__PURE__*/e.jsxs(Pt,{children:[/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(ce.default,{})}),"Enable 2-Step verification for your ",v?.name," wallet."]}),/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(de.default,{})}),"You'll be prompted to authenticate to complete transactions."]})]}),/*#__PURE__*/e.jsxs(xt,{children:[/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>P(!0),children:"Continue"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:S,children:"Not now"})]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):"sms"===k?/*#__PURE__*/e.jsx(Hn,{appName:v?.name||"Privy",onComplete:S,onReset:L,onClose:S}):"totp"===k&&x?/*#__PURE__*/e.jsx(zn,{onClose:S,onReset:L,submitEnrollmentWithTotp:({mfaCode:e})=>async function(e){try{return W(void 0),await h({mfaCode:e}),w?.mfaEnrollmentFlow?.onSuccess(),S()}catch(e){W(e)}finally{o(null)}}(e),totpInfo:{...x,appName:v?.name||"Privy"}}):"passkey"===k?/*#__PURE__*/e.jsx(On,{onReset:L,onClose:S,submitEnrollmentWithPasskey:D}):/*#__PURE__*/e.jsx(In,{showIntro:q,userMfaMethods:t.mfaMethods,appMfaMethods:v.mfa.methods,userHasAuthSms:O,onBackToIntro:function(){P(!1)},handleSelectMethod:async function(e){try{await E()}catch(e){return void W(e)}return"totp"===e?(b(e),T(null),void m().then((e=>{T(e)})).catch((()=>{T(null),L()}))):"passkey"===e&&1===F.length?await D():void b(e)},isTotpLoading:"totp"===k&&!x,isPasskeyLoading:_,error:U,onClose:S,setRemovingMfaMethod:async e=>{try{await E()}catch(e){return void W(e)}o(e)}})}},Vn=({providerName:t,ProviderLogo:r,success:n,errorMessage:i,onRetry:a})=>{let o=n?`Successfully connected with ${t}`:i?i.message:`Verifying connection to ${t}`;/*#__PURE__*/return e.jsx(s.ScreenLayout,{title:o,subtitle:n?"You're good to go!":i?i.detail:"Just a few moments more",icon:r,iconVariant:"loading",iconLoadingStatus:{success:n,fail:!!i},secondaryCta:i?.retryable&&a?{label:"Retry",onClick:a}:void 0,watermark:!0})},$n={component:()=>{let{authenticated:t,logout:n,ready:i,user:a}=d.usePrivyContext(),{setModalData:l,navigate:c,resetNavigation:u}=s.usePrivyModal(),h=s.useAppConfig(),{getAuthMeta:p,initLoginWithOAuth:y,loginWithOAuth:m,updateWallets:w,setReadyToTrue:g,closePrivyModal:v,createAnalyticsEvent:C}=f.usePrivyInternal(),[E,A]=r.useState(!1),[P,k]=r.useState(void 0),b=p()?.provider||"google",{name:x,component:T}=Ie(b,h.customOAuthProviders);return r.useEffect((()=>{m(b).then((()=>{A(!0),g(!0)})).catch((e=>{if(g(!1),e?.privyErrorCode===o.PrivyErrorCode.ALLOWLIST_REJECTED)return k(void 0),u(),void c(s.AllowlistRejectionScreen);if(e?.privyErrorCode===o.PrivyErrorCode.USER_LIMIT_REACHED)return console.error(new o.PrivyUserLimitReachedError(e).toString()),k(void 0),u(),void c(s.UserLimitReachedScreen);if(e?.privyErrorCode===o.PrivyErrorCode.USER_DOES_NOT_EXIST)return k(void 0),u(),void c(s.AccountNotFoundScreen);if(e?.privyErrorCode===o.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return k(void 0),u(),l({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:p()?.provider,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void c(s.LinkConflictScreen);let{retryable:t,detail:r}=function(e,t,r){let n={detail:"",retryable:!1},i=s.e(t);if(e?.privyErrorCode===o.PrivyErrorCode.LINKED_TO_ANOTHER_USER&&(n.detail="This account has already been linked to another user."),e?.privyErrorCode===o.PrivyErrorCode.INVALID_CREDENTIALS&&(n.retryable=!0,n.detail="Something went wrong. Try again."),e.privyErrorCode===o.PrivyErrorCode.OAUTH_USER_DENIED&&(n.detail=`Retry and check ${i} to finish connecting your account.`,n.retryable=!0),e?.privyErrorCode===o.PrivyErrorCode.TOO_MANY_REQUESTS&&(n.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===o.PrivyErrorCode.TOO_MANY_REQUESTS&&e.message.includes("provider rate limit")){let e=Ie(t,r).name;n.detail=`Request limit reached for ${e}. Please wait a moment and try again.`}if(e?.privyErrorCode===o.PrivyErrorCode.OAUTH_ACCOUNT_SUSPENDED){let e=Ie(t,r).name;n.detail=`Your ${e} account is suspended. Please try another login method.`}return e?.privyErrorCode===o.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE&&(n.detail="You cannot authorize more than one account for this user."),e?.privyErrorCode===o.PrivyErrorCode.OAUTH_UNEXPECTED&&t.startsWith("privy:")&&(n.detail="Something went wrong. Please try again."),n}(e,b,h.customOAuthProviders);k({retryable:t,detail:r,message:"Authentication failed"})})).finally((()=>{s.stripUrlOAuthParamsAndRemoveStateCode()}))}),[x,b]),r.useEffect((()=>{if(i&&t&&E&&a){if(h?.legal.requireUsersAcceptTerms&&!a.hasAcceptedTerms){let e=setTimeout((()=>{c(s.AffirmativeConsentScreen)}),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(s.shouldProceedtoEmbeddedWalletCreationFlow(a,h.embeddedWallets)){let e=setTimeout((()=>{l({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),C({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:b,screen:"OAuthStatusScreen"}}),n()},callAuthOnSuccessOnClose:!0}}),c(s.EmbeddedWalletOnAccountCreateScreen)}),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}{let e=setTimeout((()=>v({shouldCallAuthOnSuccess:!0,isSuccess:!0})),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return w(),()=>clearTimeout(e)}}}),[i,t,E,a]),/*#__PURE__*/e.jsx(Vn,{providerName:x,ProviderLogo:T,success:E,errorMessage:P,onRetry:P?.retryable?()=>{s.stripUrlOAuthParamsAndRemoveStateCode(),y(b),k(void 0)}:void 0})}},Yn=/*#__PURE__*/r.forwardRef(((t,n)=>{let[i,a]=r.useState(""),[o,l]=r.useState(""),[c,u]=r.useState(!1),{authenticated:h,user:p}=d.usePrivyContext(),{initUpdateEmail:y}=f.usePrivyInternal(),{navigate:m,setModalData:w,currentScreen:g}=s.usePrivyModal(),{enabled:v,token:C}=s.useCaptcha(),E=s.useAppConfig(),A=s.validateEmail(i)&&(E.disablePlusEmails&&i.includes("+")?(o||l("Please enter a valid email address without a '+'."),!1):(o&&l(""),!0)),P=c||!A,k=()=>{!v||C||h?(async e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");u(!0);try{await y({oldAddress:p.email.address,newAddress:i,captchaToken:e}),m(s.AwaitingPasswordlessCodeScreen)}catch(e){w({errorModalData:{error:e,previousScreen:g||s.LandingScreen}})}u(!1)})(C):(w({captchaModalData:{callback:e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");return y({oldAddress:p.email.address,newAddress:i,captchaToken:e})},userIntentRequired:!1,onSuccessNavigateTo:s.AwaitingPasswordlessCodeScreen,onErrorNavigateTo:s.ErrorScreen}}),m(s.CaptchaScreen))};/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsxs(Gn,{children:[o&&/*#__PURE__*/e.jsx(s.ErrorMessage,{style:{marginTop:"0.25rem",textAlign:"left"},children:o}),/*#__PURE__*/e.jsxs(Zn,{$error:!!o,children:[/*#__PURE__*/e.jsx(s.LoginMethodIconWrapper,{children:/*#__PURE__*/e.jsx(U.Mail,{})}),/*#__PURE__*/e.jsx("input",{ref:n,id:"email-input",type:"email",placeholder:"your@email.com",onChange:e=>a(e.target.value),onKeyUp:e=>{"Enter"===e.key&&k()},value:i,autoComplete:"email"}),t.stacked?null:/*#__PURE__*/e.jsx(s.EmbeddedButton,{isSubmitting:c,onClick:k,disabled:P,children:"Submit"})]})]}),t.stacked?/*#__PURE__*/e.jsx(s.PrimaryButton,{loadingText:null,loading:c,disabled:P,onClick:k,style:{width:"100%"},children:"Submit"}):null]})}));let Gn=s.InputContainerForm,Zn=s.EmailUpdateForm;const Jn=({title:t="Update your email",subtitle:r="Add the email address you'd like to use going forward. We'll send you a confirmation code"})=>/*#__PURE__*/e.jsx(s.ScreenLayout,{title:t,subtitle:r,icon:se.default,watermark:!0,children:/*#__PURE__*/e.jsx(s.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(Yn,{stacked:!0})})}),Xn={component:()=>/*#__PURE__*/e.jsx(Jn,{})},Qn=({title:t="Update your phone number",subtitle:n="Add the phone number you'd like to use going forward. We'll send you a confirmation code",onSubmit:i,isSubmitting:a=!1})=>{let[o,l]=r.useState(null);/*#__PURE__*/return e.jsx(s.ScreenLayout,{title:t,subtitle:n,icon:ne.default,primaryCta:{label:a?"Submitting":"Update",onClick:async()=>{o?.qualifiedPhoneNumber&&await i(o)},disabled:!o?.isValid||a},watermark:!0,children:/*#__PURE__*/e.jsx(s.ConnectPhoneNumberForm,{onChange:e=>{l(e)},onSubmit:async()=>{},noIncludeSubmitButton:!0,hideRecent:!0})})},ei={component:()=>{let{currentScreen:t,data:n,navigate:i,setModalData:a}=s.usePrivyModal(),{user:o}=d.usePrivyContext(),{initUpdatePhone:l}=f.usePrivyInternal(),[c,u]=r.useState(!1);/*#__PURE__*/return e.jsx(Qn,{onSubmit:async e=>{u(!0);try{if(!o?.phone?.number)throw Error("User is required to have an phone number to update it.");await l(o?.phone?.number,e.qualifiedPhoneNumber),i(s.AwaitingPasswordlessCodeScreen)}catch(e){a({errorModalData:{error:e,previousScreen:n?.errorModalData?.previousScreen||t||kn}}),i(s.ErrorScreen)}finally{u(!1)}},isSubmitting:c})}};function ti({subscribe:e,getExternalJwt:t,enabled:n=!0,onAuthenticated:i,onUnauthenticated:a,onError:s}){let{client:l,onCustomAuthAuthenticated:c}=f.usePrivyInternal(),{logout:d,authenticated:u,ready:h}=I.usePrivy();if(!l)throw new o.PrivyClientError("`useSyncJwtBasedAuthState` must be used within a `PrivyProvider`");let[p,y]=r.useState({status:"initial"}),m=r.useRef(),w=r.useRef(!1),g=r.useRef(t);r.useEffect((()=>{g.current=t}),[t]);let v=r.useRef(i);r.useEffect((()=>{v.current=i}),[i]);let C=r.useRef(a);r.useEffect((()=>{C.current=a}),[a]);let E=r.useRef(s);return r.useEffect((()=>{E.current=s}),[s]),r.useEffect((()=>{if(!n||!h)return;let t=async()=>{if(!w.current){w.current=!0;try{y({status:"loading"});let e=await g.current();if(void 0!==m.current&&m.current===e)return void y({status:"done"});if(!e)return u&&(await d(),C.current?.()),m.current=e,void y({status:"done"});l.startAuthFlow(new at(e));let{user:t,isNewUser:r=!1}=await l.authenticate();if(!t)throw new o.PrivyClientError("Failed to sync with custom auth provider");v.current?.({user:t,isNewUser:r}),c(t,r),m.current=e,y({status:"done"})}catch(e){if(console.warn(e),await d().catch((()=>{})),C.current?.(),e instanceof o.PrivyApiError&&e.privyErrorCode===o.PrivyErrorCode.LINKED_TO_ANOTHER_USER)return y({status:"initial"}),void setTimeout((()=>{t()}),0);E.current?.(e),y({status:"error",error:e})}finally{w.current=!1}}};return t(),e(t)}),[e,l,c,u,d,n,h]),n?{state:p}:{state:{status:"not-enabled"}}}let ri=w.create((()=>({jwtAuthFlowState:{status:"not-enabled"}})));function ni({customAuth:e}){let{jwtAuthFlowState:t}=function({customAuth:e}){let t=s.useEmitPrivyEvent(),n=r.useRef(),i=r.useCallback((e=>(n.current=e,()=>{n.current=void 0})),[]),a=e?.getCustomAccessToken??(()=>Promise.resolve(void 0)),{state:l}=ti({enabled:!0===e?.enabled,subscribe:i,getExternalJwt:a,onAuthenticated:({user:e,isNewUser:r})=>{t("login","onComplete",{user:e,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),t("customAuth","onAuthenticated",{user:e})},onUnauthenticated:()=>{t("customAuth","onUnauthenticated")},onError:e=>{t("login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}});return r.useEffect((()=>{(async()=>{e&&!e.isLoading&&n.current?.()})()}),[e?.enabled,e?.getCustomAccessToken,e?.isLoading]),{jwtAuthFlowState:l}}({customAuth:e});return r.useEffect((()=>{ri.setState({jwtAuthFlowState:t})}),[t]),null}const ii=/*#__PURE__*/r.createContext(!1);let ai,oi,si,li,ci,di;async function ui(){return ai?ai.getAccessToken():Promise.resolve(s.s.get(s.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||s.s.get(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const hi=(e,t)=>oi(e,t),pi=(e,t)=>si(e,t),yi=(e,t)=>li(e,t),mi=(e,t)=>ci(e,t),wi=e=>di(e);let gi=l=>{let c=l.client,u=l.privy,h=s.usePlugins();Ir();let[p,y]=r.useState(!1),m=tr((e=>e.inProgressMfaFlow)),[w,g]=r.useState(!1),[v,C]=r.useState(!1),[E,A]=r.useState(null),[P,k]=r.useState([]),[b,x]=r.useState(void 0),[T,S]=r.useState(!1),[_,U]=r.useState(null),[W,R]=r.useState(!1),[O,M]=r.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:f.notImplemented}),[N,j]=r.useState({status:"initial"}),[F,L]=r.useState({status:"initial"}),[D,q]=r.useState({status:"initial"}),[H,B]=r.useState({status:"initial"}),[z,K]=r.useState({status:"initial"}),[V,$]=r.useState({status:"initial"}),[Y,G]=r.useState(null),Z=s.useAppConfig(),J=s.useIsServerConfigLoaded(),[X,Q]=r.useState({}),[ee,te]=r.useState(null),re=r.useRef(null),[ne,ie]=r.useState(!1),[ae,oe]=r.useState(!1),se=r.useRef(null),le=r.useRef(null),ce=r.useRef(s.privyEventsDefault),[de,ue]=r.useState(!1);c.onStoreCustomerAccessToken=e=>{e&&s.emitPrivyEvent(ce,"accessToken","onAccessTokenGranted",{accessToken:e})},c.onDeleteCustomerAccessToken=()=>{A(null),C(!1),s.emitPrivyEvent(ce,"accessToken","onAccessTokenRemoved")};let he=r.useRef(null),pe=r.useRef(null),ye=r.useRef(!1),me=({showWalletUIs:e})=>ye.current?ye.current:void 0!==e?!e:!Z.embeddedWallets.showWalletUIs,we=e=>{U(e),setTimeout((()=>{y(!0)}),15)};r.useEffect((()=>{if(!E)return void c.connectors?.removeEmbeddedWalletConnectors();let e=d.getPrivyEthereumWallet(E),t=d.getPrivyEthereumHDWallets(E),r=d.getImportedPrivyEthereumWallets(E);e&&t.length||c.connectors?.removeEmbeddedWalletConnectors(),r.length||c.connectors?.removeImportedWalletConnectors(),c.connectors?Y?(e&&c.connectors.addEmbeddedWalletConnectors({walletProxy:Y,user:E,embeddedWallets:t,defaultChain:Z.defaultChain,appId:l.appId,privyClient:u}),r.forEach((e=>c.connectors?.addImportedWalletConnector(Y,e.address,Z.defaultChain,l.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")}),[Y,E]),r.useEffect((()=>{Y&&re.current?.(Y)}),[Y]);let ge=r.useCallback(((e,t)=>{A(e),S(t),C(!0),oe(!0)}),[]);r.useEffect((()=>{ae&&Y&&E&&(async()=>{let e=s.shouldCreateEmbeddedEthWallet(E,Z.embeddedWallets.ethereum.createOnLogin),t=s.shouldCreateEmbeddedSolWallet(E,Z.embeddedWallets.solana.createOnLogin),r=await ui();if(r){if(e&&t){let e=await Y.create({accessToken:r});return await Y.createSolana({accessToken:r,ethereumAddress:e?.address}),void oe(!1)}if(t)return await Y.createSolana({accessToken:r,ethereumAddress:d.getPrivyEthereumWallet(E)?.address}),await Ke.refreshSessionAndUser(),void oe(!1);if(e)return await Y.create({accessToken:r}),void oe(!1)}})().catch(console.error)}),[ae&&Y&&E]),r.useEffect((()=>{if(Z.externalWallets.solana.connectors)return Z.externalWallets.solana.connectors.onMount(),()=>Z.externalWallets.solana.connectors?.onUnmount()}),[Z.externalWallets.solana.connectors]),r.useEffect((()=>{!w&&J&&async function(){let e,r=ve(),n=Ae(),i=t.createStore();c.initializeConnectorManager({walletConnectCloudProjectId:Z.walletConnectCloudProjectId,rpcConfig:Z.rpcConfig,chains:Z.chains,defaultChain:Z.defaultChain,store:i,walletList:Z.appearance.walletList,shouldEnforceDefaultChainOnConnect:Z.shouldEnforceDefaultChainOnConnect,externalWalletConfig:Z.externalWallets,appName:Z.name??"Privy",walletChainType:Z.appearance.walletChainType,setBaseAccountSdk:x}),c.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=c.connectors.walletConnectors.length,r=c.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?ue(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),ue(!0)}),1500)})),c.connectors?.initialize().then((()=>{Ie()}));let a=await c.getAuthenticatedUser(),o=!!a;Z.legal.requireUsersAcceptTerms&&a&&!a.hasAcceptedTerms?(await c.logout(),Ke.setReadyToTrue(!0),s.emitPrivyEvent(ce,"logout","onSuccess")):(Z.customAuth?.enabled||(C(!!a),a&&s.emitPrivyEvent(ce,"login","onComplete",{user:a,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),A(a)),r?pe.current=o?"link":"login":n&&!o?(pe.current="login",Q({telegramAuthModalData:{seamlessAuth:!0}}),we(s.TelegramAuthScreen)):Ke.setReadyToTrue(!!a))}()}),[c,ee,w,J]),r.useEffect((()=>{if(w){if(!E||!E.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void ie(!!Y);if([...P].some((e=>"privy"===e.walletClientType)))return void ie(!0);ie(!!Y)}}),[w,E,P,Y]),r.useEffect((()=>{c.connectors?.setWalletList(Z.appearance.walletList)}),[Z.appearance.walletList.join()]);let ve=()=>{let e=Ue();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(Ur).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(c.startAuthFlow(new xe({...e,customOAuthRedirectUrl:Z.customOAuthRedirectUrl})),we($n),!0))},Ae=()=>{let e=s.detectCompletingTelegramFlow();if(!e||!Z.loginMethods.telegram||!Z.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new s.TelegramAuthFlow;return c.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},Pe=async(e,t,r,n)=>{if("solana_adapter"!==e)Te(await(c.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,n);else{let e=c.connectors?.findSolanaWalletConnector(t);if(!e)return;Te(e,t,r,n)}};async function Te(e,t,r,n){if(!e)return M({status:"disconnected",connectedWallet:null,connectError:new o.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:f.notImplemented}),n?.(null,r);M({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:f.notImplemented}),e instanceof s.WalletConnectV2WalletConnector&&t&&await e.resetConnection(t),M({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Te(e,t,r,n)});try{let t=await e.connect({showPrompt:!0});if((!t||s.isBaseConnectedEthereumWallet(t))&&Z.shouldEnforceDefaultChainOnConnect&&!Z.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){M((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:f.notImplemented})));try{await(t?.switchChain(Z.defaultChain.id)),t&&(t.chainId=s.formatChainIdToCAIP2(i.toHex(Z.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${Z.defaultChain.id}`)}}return M((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:f.notImplemented}))),t&&s.emitPrivyEvent(ce,"connectWallet","onSuccess",{wallet:t}),n?.(t,r)}catch(e){return e instanceof o.PrivyError?(console.warn(e.cause?e.cause:e.message),s.emitPrivyEvent(ce,"connectWallet","onError",e.privyErrorCode||o.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),s.emitPrivyEvent(ce,"connectWallet","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),M((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Se=async(e,t,r)=>{if(null===e||!s.isBaseConnectedEthereumWallet(e))return;let n=new s.SiweFlow(c,e,t,r);c.startAuthFlow(n)},_e=async(e,t,r,n="plain")=>{let i=h(s.SOLANA_LEDGER_PLUGIN_ID);if("transaction"===n&&!i)throw new o.PrivyClientError("useSolanaLedger plugin hook must be mounted");if(null===e||!s.isBaseConnectedSolanaWallet(e))return;let a=new s.SiwsFlow(e,c,t,r,n,i);c.startAuthFlow(a)},Ie=()=>{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=s.getWalletConfigForConnector({connectorType:t,walletClientType:r});if(!i||!i.isInstalled)return we(xn);if(!c.connectors)throw new o.PrivyClientError("Connector not initialized");we(n?s.ConnectOnlyStatusScreen:s.ConnectionStatusScreen);let a=new URL(window.location.href);a.searchParams.delete("privy_connector"),a.searchParams.delete("privy_wallet_client"),a.searchParams.delete("privy_connect_only"),window.history.pushState({},"",a),Pe(t,r,void 0,n?void 0:"solana_adapter"===t?_e:Se)};r.useEffect((()=>{w&&v&&null===E&&c.getAuthenticatedUser().then(A)}),[w,v,E,c]);let Me=e=>{if(!v)throw s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new o.PrivyClientError("User must be authenticated before linking an account.")},Ne=e=>{if(!v||!E)return!1;if("privy"===e.walletClientType)return!0;for(let t of E.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},je=()=>{k((e=>{let t=c.connectors?.wallets.filter(s.isBaseConnectedEthereumWallet).map((e=>({...e,linked:Ne(e),loginOrLink:async()=>{if(!await e.isConnected())throw new o.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot link or login with embedded wallet");(async e=>{let t;if(!c.connectors)throw new o.PrivyClientError("Connector not initialized");t="ethereum"===e.type?c.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:c.connectors.findSolanaWalletConnector(e.walletClientType)||null,M((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:f.notImplemented}))),Z.captchaEnabled&&!v?(Q({captchaModalData:{callback:t=>s.isBaseConnectedEthereumWallet(e)?Se(e,t):_e(e,t),userIntentRequired:!1,onSuccessNavigateTo:s.ConnectionStatusScreen,onErrorNavigateTo:s.ErrorScreen}}),we(s.CaptchaScreen)):(s.isBaseConnectedEthereumWallet(e)?await Se(e):await _e(e),we(s.ConnectionStatusScreen))})(e)},fund:async t=>{await Ke.fundWallet(e.address,t)},unlink:async()=>{if(!v)throw new o.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot unlink an embedded wallet");A(await c.unlinkEthereumWallet(e.address))}})))||[];return s.areWalletArraysEqual(e,t)?e:t}))};r.useEffect((()=>{je()}),[E?.linkedAccounts,v,w]),r.useEffect((()=>{if(w){if(!c.connectors)throw new o.PrivyClientError("Connector not initialized");je(),c.connectors.on("walletsUpdated",je)}}),[w]),r.useEffect((()=>{[...Z.loginMethodsAndOrder?.primary??[],...Z.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>c.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!c]);let Fe=({transaction:e,sponsor:t,uiOptions:r,fundWalletConfig:n,address:h,signOnly:p})=>new Promise((async(y,m)=>{let{requesterAppId:w}=r||{},g=p?"signTransaction":"sendTransaction",f=h?d.getPrivyWalletWithAddress(E,h):d.getPrivyEthereumWallet(E);if(!f&&h){let r=d.getConnectedWalletWithAddress(P,h);if(r){if(t)throw new o.PrivyClientError("Cannot sponsor transactions for externally connected wallet.");try{let t=await r.getEthereumProvider(),n={...e,from:h,chainId:e.chainId||Number(r.chainId.replace("eip155:","")),value:void 0!==e.value?i.toHex(e.value):void 0},a=await t.request({method:"sendTransaction"===g?"eth_sendTransaction":"eth_signTransaction",params:[n]});return s.emitPrivyEvent(ce,g,"onSuccess",{hash:a}),void y({hash:a})}catch(e){return s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.TRANSACTION_FAILURE),void m(e??new s.PrivyProviderRpcError("Unable to "+g+e))}}}if(!f)return s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void m(new o.PrivyClientError("No embedded or connected wallet found for address."));if(!v||!E)return s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void m(Error("User must be authenticated before signing with a Privy wallet"));let C=f.address,A=f.walletIndex??0,{entropyId:k,entropyIdVerifier:b}=s.getEntropyDetailsForUser(E,f),x=Ve.wallets.find((e=>"privy"===e.walletClientType&&i.getAddress(e.address)===i.getAddress(C)));if(!x)return s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void m(Error("Must have a Privy wallet before signing"));let T=await x.getEthereumProvider(),S=await T.request({method:"eth_chainId"}),_=e.chainId?Number(e.chainId):I.extractChainIdFromCAIP2(S);(e=>{if(!Z.chains.map((e=>e.id)).includes(e))throw new o.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,o.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(_);let U={...e,from:e.from??C,chainId:_},W=await ui();if(!W||!Y)return s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void m(Error("Must have valid access token and Privy wallet to send transaction"));let R=s.getPublicClient(U.chainId,Z.chains,Z.rpcConfig,{appId:l.appId}),O=d.getIsUnifiedWallet(f),M=async({transactionRequest:e})=>{try{let r;if(!await Ke.recoverEmbeddedWallet({address:C}))throw s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),m(Error("Unable to connect to wallet")),Error("Unable to connect to wallet");if(t){let t=await(async({transactionRequest:e})=>{if(!O)throw new o.PrivyClientError("Sponsoring is only supported for wallets on the TEE stack");if(p)throw new o.PrivyClientError("Cannot sponsor a sign transaction request");let t=e=>null==e?void 0:i.toHex(e),r=await a.rpc(u,(async({message:e})=>await Y.signWithUserSigner({accessToken:W,requesterAppId:w,message:e})),{chain_type:"ethereum",method:"eth_sendTransaction",caip2:s.formatChainIdToCAIP2(i.toHex(e.chainId)),sponsor:!0,params:{transaction:{from:e.from,to:e.to,chain_id:t(e.chainId),data:i.isHex(e.data)?e.data?e.data:i.toHex(Uint8Array.from(e.data)):void 0,value:t(e.value)}},wallet_id:f.id});if(r.data&&"hash"in r.data)return r.data.hash;throw new s.PrivyProviderRpcError("Unable to sign transaction")})({transactionRequest:e});return s.emitPrivyEvent(ce,"sendTransaction","onSuccess",{hash:t}),t}if(O){let t=e=>null==e?void 0:i.toHex(e),n=await a.rpc(u,(async({message:e})=>await Y.signWithUserSigner({accessToken:W,requesterAppId:w,message:e})),{chain_type:"ethereum",method:"eth_signTransaction",params:{transaction:{from:e.from,to:e.to,nonce:t(e.nonce),chain_id:t(e.chainId),data:i.isHex(e.data)?e.data?e.data:i.toHex(Uint8Array.from(e.data)):void 0,value:t(e.value),type:e.type,gas_limit:t(e.gasLimit??e.gas),gas_price:t(e.gasPrice??e.gas),max_fee_per_gas:t(e.maxFeePerGas),max_priority_fee_per_gas:t(e.maxPriorityFeePerGas)}},wallet_id:f.id});if(!n.data||!("signed_transaction"in n.data))throw new s.PrivyProviderRpcError("Unable to sign transaction");r=n.data.signed_transaction}else r=await async function({accessToken:e,entropyId:t,entropyIdVerifier:r,transactingWalletIndex:n,walletProxy:i,transactionRequest:a,requesterAppId:o}){return(await i.rpc({entropyId:t,entropyIdVerifier:r,hdWalletIndex:n??0,chainType:"ethereum",accessToken:e,requesterAppId:o,request:{method:"eth_signTransaction",params:[a]}})).response.data}({accessToken:W,entropyId:k,entropyIdVerifier:b,transactingWalletIndex:A,walletProxy:Y,transactionRequest:e,requesterAppId:w});if(p)return s.emitPrivyEvent(ce,"signTransaction","onSuccess",{signature:r}),r;{let e=await R.sendRawTransaction({serializedTransaction:r});return s.emitPrivyEvent(ce,"sendTransaction","onSuccess",{hash:e}),e}}catch(e){throw s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.TRANSACTION_FAILURE),e}};if(me({showWalletUIs:r?.showWalletUIs})){let e=p||t?U:await s.prepareTransactionRequest(U,R,U.from);try{let t=await M({transactionRequest:e});p?s.emitPrivyEvent(ce,"signTransaction","onSuccess",{signature:t}):s.emitPrivyEvent(ce,"sendTransaction","onSuccess",{hash:t}),y({hash:t})}catch(e){s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.TRANSACTION_FAILURE),m(e)}}else{let e={connectingWalletAddress:C,recoveryMethod:f.recoveryMethod,entropyId:k,entropyIdVerifier:b,onCompleteNavigateTo:s.SendTransactionScreen,isUnifiedWallet:O,onFailure:e=>{s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),m(e)}},i=(e=>!!e.fundingConfig&&I.filterSupportedOptions(e.fundingConfig.options).length>=1)(Z)?I.prepareFundingModalData({address:C,appConfig:Z,fundWalletConfig:n,methodScreen:s.FundingMethodSelectionScreen,chainIdOverride:U.chainId,comingFromSendTransactionScreen:!0}):void 0;Q({connectWallet:e,sendTransaction:{transactionRequest:U,transactingWalletIndex:A,transactingWalletAddress:C,entropyId:k,entropyIdVerifier:b,signOnly:p,scanTransaction:async()=>{let e=await s.prepareTransactionRequest(U,R,U.from);return await c.scanTransaction({metadata:{domain:Z.embeddedWallets.transactionScanning.domain},chain_id:e.chainId.toString(),request:{method:"eth_sendTransaction",params:[{from:e.from,to:e.to,value:e.value?.toString(),gas:e.gas?.toString(),gasPrice:e.gasPrice?.toString(),nonce:e.nonce?.toString(),data:e.data}]}})},getIsSponsored:async()=>!!t,onConfirm:({transactionRequest:e})=>M({transactionRequest:e}),onSuccess:e=>{p?s.emitPrivyEvent(ce,"signTransaction","onSuccess",{signature:e.hash}):s.emitPrivyEvent(ce,"sendTransaction","onSuccess",{hash:e.hash}),y(e)},onFailure:e=>{s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.TRANSACTION_FAILURE),m(e)},uiOptions:r||{},fundWalletConfig:n,requesterAppId:w},funding:i}),we(s.EmbeddedWalletConnectingScreen)}}));function Le(){return new Promise((async(e,t)=>{let r=await ui();if(!r||!Y)throw Error("Must have valid access token to enroll in MFA");try{await Y.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let De=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],qe=e=>{let t=E?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=s.toDisplayFromAccountType(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:n}),new o.PrivyClientError(`User already has an account of type ${r} linked.`)};async function He({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){U(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!v||!E)throw s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=d.getPrivyPrimaryWallet(E);if(!n||!Y)throw s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");let i=d.getIsUnifiedWallet(n);if(i)throw s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.UNSUPPORTED_WALLET_TYPE),new o.PrivyClientError("User owned wallet recovery is only supported for on-device execution and this app uses TEE execution. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");try{await Le()}catch(e){throw s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((a,l)=>{let c="user-passcode"===n.recoveryMethod,d=s.toEmbeddedWalletSetRecoveryScreen({walletAction:"update",availableRecoveryMethods:Z.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:c,showAutomaticRecovery:e}),{entropyId:u,entropyIdVerifier:h}=s.getEntropyDetailsForUser(E),p={recoveryMethod:n.recoveryMethod,connectingWalletAddress:n.address,onCompleteNavigateTo:d,shouldForceMFA:!1,entropyId:u,isUnifiedWallet:i,entropyIdVerifier:h,onFailure:e=>{s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),l(e)}};Q({setWalletPassword:{onSuccess:e=>{s.emitPrivyEvent(ce,r,"onSuccess",{method:"user-passcode",wallet:e}),a(e)},onFailure:e=>{s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),l(e)},callAuthOnSuccessOnClose:!1},recoverWallet:{entropyId:u,entropyIdVerifier:h,onFailure:l},connectWallet:p,recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:c,shouldCreateEth:!1,shouldCreateSol:!1}}),we(s.EmbeddedWalletConnectingScreen)}))}async function Be({appId:e,action:t}){let r=await ui();if("link"===t&&!r)throw s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new o.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw s.emitPrivyEvent(ce,"login","onError",o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new o.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");he.current=`privy:${e}`,pe.current=t;let n=s.triggerPopup();return c.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,i)=>{let{name:a,logoUrl:o}=await Or({api:c.api,providerAppId:e,requesterAppId:Z.id});Q({crossAppAuth:{appId:e,name:a,logoUrl:o,action:t,popup:n,onSuccess:r,onError:i}}),we(an)}))}let ze={ready:w,authenticated:v,user:E,walletConnectors:c.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),Q({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,walletChainType:e?.walletChainType,description:e?.description}}),we(s.ConnectOnlyLandingScreen)},linkWallet:e=>{e&&"target"in e&&e&&(e=void 0),Me("siwe"),he.current="siwe",pe.current="link",Q({...X,externalConnectWallet:{...X.externalConnectWallet,walletList:e?.walletList,walletChainType:e?.walletChainType,description:e?.description||`Link a wallet to your ${Z?.name} account`}}),we(s.AuthenticateWithWalletScreen)},startCrossAppAuthFlow:Be,linkEmail:()=>{Me("email"),qe("email"),he.current="email",pe.current="link",we(An)},linkPhone:()=>{Me("sms"),qe("phone"),he.current="sms",pe.current="link",we(kn)},linkGoogle:async()=>{Me("google"),qe("google_oauth"),pe.current="link",await Ke.initLoginWithOAuth("google")},linkTwitter:async()=>{Me("twitter"),qe("twitter_oauth"),pe.current="link",await Ke.initLoginWithOAuth("twitter")},linkTwitch:async()=>{Me("twitch"),qe("twitch_oauth"),pe.current="link",await Ke.initLoginWithOAuth("twitch")},linkDiscord:async()=>{Me("discord"),qe("discord_oauth"),pe.current="link",await Ke.initLoginWithOAuth("discord")},linkGithub:async()=>{Me("github"),qe("github_oauth"),pe.current="link",await Ke.initLoginWithOAuth("github")},linkSpotify:async()=>{Me("spotify"),qe("spotify_oauth"),pe.current="link",await Ke.initLoginWithOAuth("spotify")},linkInstagram:async()=>{Me("instagram"),qe("instagram_oauth"),pe.current="link",await Ke.initLoginWithOAuth("instagram")},linkTiktok:async()=>{Me("tiktok"),qe("tiktok_oauth"),pe.current="link",await Ke.initLoginWithOAuth("tiktok")},linkLine:async()=>{Me("line"),qe("line_oauth"),pe.current="link",await Ke.initLoginWithOAuth("line")},linkLinkedIn:async()=>{Me("linkedin"),qe("linkedin_oauth"),pe.current="link",await Ke.initLoginWithOAuth("linkedin")},linkApple:async()=>{Me("apple"),qe("apple_oauth"),pe.current="link",await Ke.initLoginWithOAuth("apple")},linkPasskey:async()=>{Me("passkey"),qe("passkey"),await Ke.initLinkWithPasskey(),we(Hr)},linkTelegram:async e=>{if(Me("telegram"),qe("telegram"),pe.current="link",he.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new s.TelegramAuthFlow;c.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=s.convertInitDataRawToTelegramWebAppData(e.launchParams.initDataRaw),Q({telegramAuthModalData:{seamlessAuth:!0}}),we(s.TelegramAuthScreen)}else s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await Ke.initLoginWithTelegram();we(s.TelegramAuthScreen)},linkFarcaster:async()=>{Me("farcaster"),qe("farcaster"),await Ke.initLoginWithFarcaster(),pe.current="link",he.current="farcaster",we(s.FarcasterConnectStatusScreen)},updateEmail:()=>{if(Me("email"),!E?.email)throw new o.PrivyClientError("User does not have an email linked to their account.");pe.current="update",he.current="email",we(Xn)},updatePhone:()=>{if(Me("sms"),!E?.phone)throw new o.PrivyClientError("User does not have a phone number linked to their account.");pe.current="update",he.current="sms",we(ei)},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(!w){let e=await new Promise((e=>{te((t=>e.bind(t)))}));if(te(null),e)return void console.warn(t)}!E||E.isGuest?(pe.current="login",Q({login:e}),we(s.LandingScreen)):console.warn(t)},connectOrCreateWallet:async()=>{w||(await new Promise((e=>{te((()=>e))})),te(null)),v?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(pe.current="connect-or-create",we(s.ConnectOrCreateScreen))},logout:async()=>{if(pe.current=null,he.current=null,E&&c.clearProviderAcccessTokens(E),U(null),await c.logout(),E&&Y)try{await Y.clearMfa({userId:E.id})}catch(e){}A(null),C(!1),s.emitPrivyEvent(ce,"logout","onSuccess"),y(!1),s.s.del(s.CLIENT_ANALYTICS_ID_KEY),s.s.del(s.getGuestCredentialStorageKey(Z.id))},getAccessToken:r.useCallback((()=>c.getCustomerAccessToken()),[c]),unlinkWallet:async e=>{let t;return A(t=e.startsWith("0x")?await c.unlinkEthereumWallet(e):await c.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await c.unlinkEmail(e);return A(t),t},unlinkPhone:async e=>{let t=await c.unlinkPhone(e);return A(t),t},unlinkGoogle:async e=>{let t=await c.unlinkOAuth("google",e);return A(t),t},unlinkTwitter:async e=>{let t=await c.unlinkOAuth("twitter",e);return A(t),t},unlinkTwitch:async e=>{let t=await c.unlinkOAuth("twitch",e);return A(t),t},unlinkDiscord:async e=>{let t=await c.unlinkOAuth("discord",e);return A(t),t},unlinkGithub:async e=>{let t=await c.unlinkOAuth("github",e);return A(t),t},unlinkSpotify:async e=>{let t=await c.unlinkOAuth("spotify",e);return A(t),t},unlinkInstagram:async e=>{let t=await c.unlinkOAuth("instagram",e);return A(t),t},unlinkTiktok:async e=>{let t=await c.unlinkOAuth("tiktok",e);return A(t),t},unlinkLine:async e=>{let t=await c.unlinkOAuth("line",e);return A(t),t},unlinkLinkedIn:async e=>{let t=await c.unlinkOAuth("linkedin",e);return A(t),t},unlinkApple:async e=>{let t=await c.unlinkOAuth("apple",e);return A(t),t},unlinkFarcaster:async e=>{let t=await c.unlinkFarcaster(e);return A(t),t},unlinkTelegram:async e=>{let t=await c.unlinkTelegram(e);return A(t),t},unlinkPasskey:async e=>{let t=await ui();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!Y)throw Error("Wallet proxy not initialized.");let r=Z.passkeys.shouldUnenrollMfaOnUnlink;await Y.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let n=await c.getAuthenticatedUser();return A(n),n},unlinkCrossAppAccount:async({subject:e})=>{let t=E?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new o.PrivyClientError("Invalid subject");c.storeProviderAccessToken(t.id,null);let r=await c.unlinkOAuth(`privy:${t.id}`,e);return A(r),r},setWalletRecovery:async e=>He({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>He({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(r,n)=>{let{requesterAppId:l}=t?.uiOptions||{},h=e.message,p=t?.address?d.getPrivyWalletWithAddress(E,t.address):d.getPrivyEthereumWallet(E);if(!p&&void 0!==t?.address){let e=d.getConnectedWalletWithAddress(P,t.address);if(e)try{let t=await e.getEthereumProvider(),n=await t.request({method:"personal_sign",params:[h,e.address]});return s.emitPrivyEvent(ce,"signMessage","onSuccess",{signature:n}),void r({signature:n})}catch(e){return s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),void n(e??new s.PrivyProviderRpcError("Unable to sign message"))}}if(!p)throw new o.PrivyClientError("No embedded or connected wallet found for address.");if(!v||!E)return s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let y=p.address,m=p.walletIndex??0,{entropyId:w,entropyIdVerifier:g}=s.getEntropyDetailsForUser(E,p),f=d.getIsUnifiedWallet(p);if("string"!=typeof h||h.length<1)return s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.INVALID_MESSAGE),void n(Error("Message must be a non-empty string"));let C=async()=>{let t;if(!v)throw Error("User must be authenticated before signing with a Privy wallet");let r=await ui();if(!Y||!r||!await Ke.recoverEmbeddedWallet({address:y}))throw Error("Unable to connect to wallet");if(c.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:y,requesterAppId:l}}),f){let n=i.isHex(e.message,{strict:!0}),o=await a.rpc(u,(async({message:e})=>await Y.signWithUserSigner({accessToken:r,requesterAppId:l,message:e})),{chain_type:"ethereum",method:"personal_sign",params:n?{message:h.slice(2),encoding:"hex"}:{message:h,encoding:"utf-8"},wallet_id:p.id});if(!o.data||!("signature"in o.data))throw new s.PrivyProviderRpcError("Unable to sign message");t=o.data.signature}else{let{response:e}=await Y.rpc({accessToken:r,entropyId:w,entropyIdVerifier:g,chainType:"ethereum",hdWalletIndex:m,requesterAppId:l,request:{method:"personal_sign",params:[h,y]}});t=e.data}return c.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:y,requesterAppId:l}}),t};if(me({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await C();s.emitPrivyEvent(ce,"signMessage","onSuccess",{signature:e}),r({signature:e})}catch(e){s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new s.PrivyProviderRpcError("Unable to sign message"))}else Q({signMessage:{method:"personal_sign",data:h,confirmAndSign:C,onSuccess:e=>{s.emitPrivyEvent(ce,"signMessage","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:p.recoveryMethod,connectingWalletAddress:y,entropyId:w,entropyIdVerifier:g,onCompleteNavigateTo:s.SignRequestScreen,isUnifiedWallet:f,onFailure:e=>{s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),we(s.EmbeddedWalletConnectingScreen)})),signTypedData:(e,t)=>new Promise((async(r,n)=>{let{requesterAppId:i}=t?.uiOptions||{},l=t?.address?d.getPrivyWalletWithAddress(E,t.address):d.getPrivyEthereumWallet(E);if(!l&&t?.address){let i=d.getConnectedWalletWithAddress(P,t.address);if(i)try{let t=await i.getEthereumProvider(),n=s.generateTypedDataWithDomainType(e),a=await t.request({method:"eth_signTypedData_v4",params:[i.address,n]});return s.emitPrivyEvent(ce,"signTypedData","onSuccess",{signature:a}),void r({signature:a})}catch(e){return s.emitPrivyEvent(ce,"signTypedData","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),void n(e??new s.PrivyProviderRpcError("Unable to sign typed data "+e))}}if(!l)throw new o.PrivyClientError("No embedded or connected wallet found for address.");if(!v||!E)return s.emitPrivyEvent(ce,"signTypedData","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let h=l.address,p=l.walletIndex??0,{entropyId:y,entropyIdVerifier:m}=s.getEntropyDetailsForUser(E,l),w=d.getIsUnifiedWallet(l),g=s.generateTypedDataWithDomainType(e),f=async()=>{let e;if(!v)throw Error("User must be authenticated before signing with a Privy wallet");let t=await ui();if(!Y||!t||!await Ke.recoverEmbeddedWallet({address:h}))throw Error("Unable to connect to wallet");if(c.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:h,requesterAppId:i}}),w){let{domain:r,types:n,primaryType:o,message:c}=g,d=await a.rpc(u,(async({message:e})=>await Y.signWithUserSigner({accessToken:t,requesterAppId:i,message:e})),{chain_type:"ethereum",method:"eth_signTypedData_v4",params:{typed_data:{domain:r,types:n,primary_type:o,message:c}},wallet_id:l.id});if(!d.data||!("signature"in d.data))throw new s.PrivyProviderRpcError("Unable to sign message");e=d.data.signature}else{let{response:r}=await Y.rpc({accessToken:t,entropyId:y,entropyIdVerifier:m,chainType:"ethereum",hdWalletIndex:p,requesterAppId:i,request:{method:"eth_signTypedData_v4",params:[h,g]}});e=r.data}return c.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:h,requesterAppId:i}}),e};if(me({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await f();s.emitPrivyEvent(ce,"signTypedData","onSuccess",{signature:e}),r({signature:e})}catch(e){s.emitPrivyEvent(ce,"signTypedData","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new s.PrivyProviderRpcError("Unable to sign message"))}else Q({signMessage:{method:"eth_signTypedData_v4",data:g,confirmAndSign:f,onSuccess:e=>{s.emitPrivyEvent(ce,"signTypedData","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{s.emitPrivyEvent(ce,"signTypedData","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:l.recoveryMethod,connectingWalletAddress:l.address,entropyId:y,isUnifiedWallet:w,entropyIdVerifier:m,onCompleteNavigateTo:s.SignRequestScreen,onFailure:e=>{s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),we(s.EmbeddedWalletConnectingScreen)})),sendTransaction:async(e,t)=>await Fe({transaction:e,sponsor:t?.sponsor,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await Fe({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:e=>new Promise((async(t,r)=>{if(!v||!E)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?d.getPrivyWalletWithAddress(E,e.address):d.getPrivyEthereumWallet(E);if(!n)return void r(new o.PrivyClientError("User must have an embedded wallet."));let a=n.address,{entropyId:u,entropyIdVerifier:h}=s.getEntropyDetailsForUser(E,n),p=d.getIsUnifiedWallet(n);if(!a)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(a))return void r(Error("Must provide a valid Ethereum address."));let y={recoveryMethod:n.recoveryMethod,connectingWalletAddress:n.address,isUnifiedWallet:p,entropyId:u,entropyIdVerifier:h,onCompleteNavigateTo:s.EmbeddedWalletKeyExportScreen,onFailure:r,shouldForceMFA:!0};Q(X),await ui()&&Y?Y?I.isFirstClassChainWallet(n)?(Q({keyExport:{appId:l.appId,appClientId:l.clientId,origin:c.apiUrl,address:n.address,entropyId:u,entropyIdVerifier:h,hdWalletIndex:n.walletIndex,chainType:n.chainType,walletId:n.id,isUnifiedWallet:p,imported:n.imported,onSuccess:t,onFailure:r},connectWallet:y}),we(s.EmbeddedWalletConnectingScreen)):r(Error(`Export is not supported for ${n.chainType} wallets`)):r(Error("Must have a Privy wallet before exporting")):r(Error("Must have valid access token to enroll in MFA"))})),promptMfa:Le,async init(e){switch(e){case"sms":return void await c.initMfaSmsVerification();case"passkey":return await c.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 o.PrivyClientError("Invalid MFA code");se.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{le.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new o.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),n=rn(await r.startAuthentication(t));se.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{le.current={resolve:e,reject:t}}));break;default:throw se.current?.reject(new o.PrivyClientError("Unsupported MFA method")),new o.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){se.current?.reject(new o.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await ui();if(!t||!Y)throw Error("Must have valid access token to enroll in MFA");await Y.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return Ke.closePrivyModal(),void t();Z.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."),Q({mfaEnrollmentFlow:{mfaMethods:Z.mfa.methods,shouldUnlinkOnUnenrollMfa:Z.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),we(Kn)})),async initEnrollmentWithTotp(){let e=await ui();if(!e||!Y)throw Error("Must have valid access token to enroll in MFA");let t=await Y.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await ui();if(!t||!Y)throw Error("Must have valid access token to enroll in MFA");await Y.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),A(await c.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await ui();if(!t||!Y)throw Error("Must have valid access token to enroll in MFA");await Y.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),A(await c.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await ui();if(!r||!Y)throw Error("Must have valid access token to enroll in MFA");await Y.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),A(await c.getAuthenticatedUser())},async unenroll(e,t={}){let r=await ui();if(!r||!Y)throw Error("Must have valid access token to remove MFA");"passkey"===e?await Y.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await Y.unenrollMfa({method:e,accessToken:r}),A(await c.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await ui(),t=E?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!Y||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(d.getIsUnifiedWallet(t))throw new o.PrivyClientError("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!E?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverEmbeddedWallet({address:t.address}))throw Error("Unable to connect to wallet");let r=await Y.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&A(await c.getAuthenticatedUser()||E||null),Q({farcasterSigner:r}),we(vn)},getFarcasterSignerPublicKey:async()=>{let e,t=await ui(),r=E?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Y||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(d.getIsUnifiedWallet(r))throw new o.PrivyClientError("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!E?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!E.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=E.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await ui(),r=E?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Y||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(d.getIsUnifiedWallet(r))throw new o.PrivyClientError("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!E?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!E.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let n=await import("@simplewebauthn/browser"),i=await Y.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:n.bufferToBase64URLString(e)},fid:BigInt(E.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(i.signature))},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let n=E?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Mr({user:E,client:c,address:t,requesterAppId:Z.id,request:{method:n?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:Be})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let n=E?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),i=s.generateTypedDataWithDomainType(e);return Mr({user:E,client:c,address:t,requesterAppId:Z.id,request:{method:n?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,i],chainId:r},reconnect:Be})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=E?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Mr({user:E,client:c,address:t,requesterAppId:Z.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:Be})},signTransactionWithCrossAppWallet(e,{address:t}){let r=E?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Mr({user:E,client:c,address:t,requesterAppId:Z.id,request:{method:r?"privy_signSmartWalletTx":"eth_signTransaction",params:[e],chainId:e.chainId},reconnect:Be})},isModalOpen:p||!!m,mfaMethods:Z.mfa.methods};oi=ze.signMessage,si=ze.signTypedData,ci=async(e,t)=>await Fe({transaction:e,...t,signOnly:!1}),li=async(e,t)=>({signature:(await Fe({transaction:e,...t,signOnly:!0})).hash});let Ke={privy:u,setAuthenticated:C,setUser:A,setIsNewUser:S,isNewUserThisSession:T,pendingTransaction:null,walletConnectionStatus:O,setWalletConnectionStatus:M,connectors:c.connectors?.walletConnectors??[],rpcConfig:Z.rpcConfig,chains:Z.chains,appId:l.appId,showFiatPrices:"native-token"!==Z.embeddedWallets.priceDisplay.primary,clientAnalyticsId:c.clientAnalyticsId,onCustomAuthAuthenticated:ge,hideWalletUIs:ye,isHeadlessSigning:r.useCallback(me,[Z.embeddedWallets.showWalletUIs]),emailOtpState:F,setEmailOtpState:L,smsOtpState:D,setSmsOtpState:q,oAuthState:z,setOAuthState:K,telegramAuthState:V,setTelegramAuthState:$,siweState:H,setSiweState:B,isHeadlessOAuthLoading:W,baseAccountSdk:b,setBaseAccountSdk:x,nativeTokenSymbolForChainId:e=>Z.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(Y)return Y;let t=new Promise((e=>{re.current=e})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return re.current=null,n},getAuthFlow:()=>c.authFlow,getAuthMeta:()=>c.authFlow?.meta,client:c,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=w&&v&&E;r&&he.current&&(t=De(E)),"login"===pe.current?e.shouldCallAuthOnSuccess&&r&&he.current?s.emitPrivyEvent(ce,"login","onComplete",{user:E,isNewUser:T,wasAlreadyAuthenticated:!1,loginMethod:he.current,loginAccount:t??null}):s.emitPrivyEvent(ce,"login","onError",o.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===pe.current&&t?e.isSuccess&&r&&he.current?s.emitPrivyEvent(ce,"linkAccount","onSuccess",{user:E,linkMethod:he.current,linkedAccount:t}):he.current&&s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:he.current}):"update"===pe.current&&t?e.isSuccess&&r&&he.current?s.emitPrivyEvent(ce,"update","onSuccess",{user:E,updateMethod:he.current,updatedAccount:t}):he.current&&s.emitPrivyEvent(ce,"update","onError",o.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:he.current}):"connect-or-create"===pe.current&&(P[0]?s.emitPrivyEvent(ce,"connectOrCreateWallet","onSuccess",{wallet:P[0]}):s.emitPrivyEvent(ce,"connectOrCreateWallet","onError",o.PrivyErrorCode.USER_EXITED_AUTH_FLOW));let n=_&&Qr.has(_),i=_===s.ErrorScreen&&X.errorModalData&&Qr.has(X.errorModalData.previousScreen);if((n||i)&&X.funding){let e,t=Qr.get(_)??null;if("solana"===X.funding.chainType){let r=Z.solanaRpcs[X.funding.chain];if(!r)return void console.warn("Unable to load solana rpc, skipping balance");if(h(s.SOLANA_FUNDING_PLUGIN_ID))try{e=await s.fetchWalletBalance({rpc:r.rpc,address:X.funding.address})}catch{console.error("Unable to pull wallet balance")}else console.warn("Unable to load solana plugin, skipping balance");s.emitPrivyEvent(ce,"fundSolanaWallet","onUserExited",{address:X.funding.address,fundingMethod:t,chain:X.funding.chain,balance:e})}else{let r=s.getPublicClient(X.funding.chain.id,Z.chains,Z.rpcConfig,{appId:l.appId});try{e=await r.getBalance({address:X.funding.address})}catch{console.error("Unable to pull wallet balance")}s.emitPrivyEvent(ce,"fundWallet","onUserExited",{address:X.funding.address,chain:X.funding.chain,fundingMethod:t,balance:e})}}Q((e=>({...e,externalConnectWallet:{}}))),pe.current=null,he.current=null,S(!1),y(!1),setTimeout((()=>{c.authFlow=void 0}),200)},openPrivyModal:we,connectWallet:Te,initLoginWithWallet:async(e,t,r,n)=>{s.isBaseConnectedEthereumWallet(e)?(he.current="siwe",Se(e,t,r)):(he.current="siws",_e(e,t,r,n))},loginWithWallet:async()=>{let e,t,r;if(!w)throw new o.PrivyNotReadyError;if(c.authFlow instanceof s.SiweFlow?e="siwe":c.authFlow instanceof s.SiwsFlow&&(e="siws"),!e)throw new o.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await c.getAccessToken())try{({user:t}=await c.link()),he.current=e}catch(t){throw s.emitPrivyEvent(ce,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await c.authenticate()),he.current=e}catch(e){throw s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}A(t||E||null),S(r||!1),C(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(n,i)=>{let a=await ui();if(!v||!E||!a)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new o.PrivyClientError("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let s=Ke.walletProxy??await Ke.initializeWalletProxy(15e3);if(!s)throw new o.PrivyClientError("Wallet proxy not initialized.");if((({address:e,user:t})=>!!_r(t).find((t=>t.address===e)))({address:e,user:E}))return n();let l=d.getPrivyWalletWithAddress(E,e);if(!l)throw new o.PrivyClientError("Address to delegate is not associated with current user.");if(d.getIsUnifiedWallet(l))throw new o.PrivyClientError("useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");let c=Tr({address:e,user:E}),u=Sr({address:e,user:E}),h=async()=>{await s.createDelegatedAction({accessToken:a,rootWallet:u,delegatedWallets:[c]}),await Ke.refreshSessionAndUser()};if(await Ke.recoverEmbeddedWallet({address:e}),r)Q({delegatedActions:{consent:{address:e,onDelegate:h,onSuccess:async()=>{n()},onError:async e=>{i(e)}}}}),we(sn);else try{await h(),n()}catch(e){i(e)}})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!v||!E)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");let n=_r(E);if(0===n.length)throw new o.PrivyClientError("User has no delegated wallets to revoke.");if(n.some(d.getIsUnifiedWallet))throw new o.PrivyClientError("useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");let i=async()=>{await c.revokeDelegatedWallet(),await Ke.refreshSessionAndUser()};if(e)Q({delegatedActions:{revoke:{onRevoke:i,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),we(cn);else try{await i(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new Ee(e,t);c.startAuthFlow(r);try{he.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===pe.current?s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===pe.current&&s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!w)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof Ee))throw new o.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await c.getAccessToken())try{({user:e}=await c.link()),he.current="farcaster"}catch(e){throw s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await c.authenticate()),he.current="farcaster"}catch(e){throw s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}A(e||null),S(t||!1),C(!0)},async crossAppAuthFlow({appId:e,popup:t,action:r}){let n=`privy:${e}`;he.current=n;let{url:i,stateCode:a,codeVerifier:l}=await async function({api:e,appId:t}){let r=s.createCodeVerifier(),n=s.createStateCode(),i=await s.deriveCodeChallengeFromCodeVerifier(r);try{let{url:a}=await e.post(o.oAuthInitPath,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:i,state_code:n});return{url:a,stateCode:n,codeVerifier:r}}catch(e){throw o.formatApiError(e)}}({api:c.api,appId:e});if(!i)throw c.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new o.PrivyClientError("No authorization URL returned for cross-app auth.");try{let s=await async function({url:e,popup:t}){return t.location=e,new Promise(((e,r)=>{let n,i=setTimeout((()=>{r(new o.PrivyClientError("Authorization request timed out after 2 minutes.")),a()}),12e4);function a(){t?.close(),window.removeEventListener("message",l)}let s=setInterval((()=>{t?.closed&&!n&&(a(),clearInterval(s),clearTimeout(i),r(new o.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),a()),"PRIVY_OAUTH_ERROR"===t.data.type&&(clearTimeout(i),r(new o.PrivyClientError(t.data.error)),a()),t.data.type===Wr&&((n=new BroadcastChannel(Ur)).onmessage=l))}window.addEventListener("message",l)}))}({url:i,popup:t,provider:n}),d=s.stateCode,u=s.authorizationCode;if(d!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:n,storedStateCode:a??"",returnedStateCode:d??""}}),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);let h=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:i,client:a}){if(!n||!t)throw new o.PrivyClientError("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===n)throw new o.PrivyClientError("User denied confirmation during cross-app auth flow");try{let o=new Rr({authorizationCode:n,stateCode:t,codeVerifier:r,provider:`privy:${e}`});a.startAuthFlow(o);let s="link"===i?await a.link():await a.authenticate(),l=s.oAuthTokens?.accessToken;return console.debug(),l}catch(e){let t=o.formatApiError(e);if(t.privyErrorCode===o.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED)throw t;if(t.privyErrorCode)throw new o.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 o.PrivyClientError("Invalid code during cross-app auth flow.",void 0,o.PrivyErrorCode.OAUTH_USER_DENIED);throw new o.PrivyClientError("Invalid code during cross-app auth flow.",void 0,o.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:l,stateCode:d,authorizationCode:u,action:r,client:c});h&&c.storeProviderAccessToken(e,h);let p=await Ke.refreshSessionAndUser();if(!p)throw new o.PrivyClientError("Unable to update user");return c.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),p}catch(e){throw c.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:n}}),e}},async initLoginWithOAuth(e,t,r){if(he.current=e,!s.e$1())return void we(Cn);if("google"===e&&s.e$3(window.navigator.userAgent))return void we(Cn);"twitter"===e&&window.opener&&window.opener.postMessage({type:Wr},"*"),s.s.del(s.HEADLESS_OAUTH_KEY),s.s.del(s.OAUTH_DISABLE_SIGNUP_KEY);let i=new xe({provider:e,disableSignup:!!r,withPrivyUi:!0,customOAuthRedirectUrl:Z.customOAuthRedirectUrl});t&&i.addCaptchaToken(t),c.startAuthFlow(i);let a=await c.authFlow.getAuthorizationUrl();if(a&&a.url)if("twitter"===e&&n.isAndroid&&(a.url=a.url.replace("x.com","twitter.com")),"chrome-extension:"===window.location.protocol&&ke())try{let{privyOAuthCode:e,privyOAuthState:t}=await be(a.url);we($n),i.meta.stateCode=t,i.meta.authorizationCode=e}catch(e){throw console.error("OAuth in chrome extension flow failed:",e),e}else window.location.assign(a.url)},async initLoginWithTelegram(e,t){if(!w)throw new o.PrivyNotReadyError;he.current="telegram";let r=new s.TelegramAuthFlow(e,t);c.startAuthFlow(r),$({status:"loading"}),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>Z.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:Z.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):("link"===pe.current?s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}):"login"===pe.current?s.emitPrivyEvent(ce,"login","onError",o.PrivyErrorCode.INVALID_CREDENTIALS):"update"===pe.current&&s.emitPrivyEvent(ce,"login","onError",o.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT),t(new o.PrivyClientError("Telegram auth failed or was canceled by the client"))))):t(new o.PrivyClientError("Telegram was not initialized")):t(new o.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(c.authFlow instanceof s.TelegramAuthFlow))throw new o.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");c.authFlow.meta.captchaToken||=e?.captchaToken;let n=await ui(),i=e?.intent||pe.current;if("login"===i)try{let e=await c.authenticate();t=e.user,r=e.isNewUser,he.current="telegram"}catch(e){throw s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==i)throw new o.PrivyClientError("Unknown auth intent");try{t=(await c.link()).user,he.current="telegram"}catch(e){throw s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}A(t),S(r||!1),C(!0),$({status:"done"});let a=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,loginAccount:a}},async loginWithOAuth(e){let t,r,n;if(!(c.authFlow instanceof xe))throw new o.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let i=s.s.get(s.STATE_CODE_KEY),a=c.authFlow.meta.stateCode;if(i!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:i??"",returnedStateCode:a??""}}),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await c.getAccessToken())try{let r=await c.link();t=r.user,n=r.oAuthTokens,he.current=e}catch(t){throw s.emitPrivyEvent(ce,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let i=await c.authenticate();t=i.user,r=i.isNewUser,n=i.oAuthTokens,he.current=e}catch(t){throw"login"===pe.current?s.emitPrivyEvent(ce,"login","onError",t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===pe.current&&s.emitPrivyEvent(ce,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return A(t),S(r||!1),C(!0),n&&t&&s.emitPrivyEvent(ce,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),n},passkeyAuthState:N,setPasskeyAuthState:j,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new We({captchaToken:e,setPasskeyAuthState:j});c.startAuthFlow(r),pe.current="login";try{he.current="passkey",j({status:"generating-challenge"}),await r.initRegisterFlow(t),j({status:"awaiting-passkey"})}catch(e){throw j({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!w)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof We))throw new o.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==he.current){let e=new o.PrivyClientError("Must init login with Passkey flow first.");throw j({status:"error",error:e}),e}let r=await ui();try{he.current="passkey",j({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await c.authenticate())}catch(e){throw j({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}A(e),S(t||!1),C(!0),j({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 We({captchaToken:e,setPasskeyAuthState:j});c.startAuthFlow(r),pe.current="login";try{he.current="passkey",j({status:"generating-challenge"}),await r.initAuthenticationFlow(t),j({status:"awaiting-passkey"})}catch(e){throw j({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,r;if(!w)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof We))throw new o.PrivyClientError("Must initialize Passkey flow first.");if(e?.credentialIds&&(c.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==he.current){let e=new o.PrivyClientError("Must init login with Passkey flow first.");throw j({status:"error",error:e}),e}let n=await ui();try{he.current="passkey",j({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await c.authenticate())}catch(e){throw j({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}A(t),S(r||!1),C(!0),j({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 We({captchaToken:e});c.startAuthFlow(t),pe.current="link",he.current="passkey",j({status:"generating-challenge"});try{await t.initLinkFlow(),j({status:"awaiting-passkey"})}catch(e){throw s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),j({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!w)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof We))throw new o.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==he.current)throw new o.PrivyClientError("Must init login with Passkey flow first.");try{he.current="passkey",({user:e}=await c.link())}catch(e){throw s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return A(e||E||null),j({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!s.e$1())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&&s.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 xe({provider:e,withPrivyUi:!1,disableSignup:r??!1,customOAuthRedirectUrl:Z.customOAuthRedirectUrl});t&&n.addCaptchaToken(t),K({status:"loading"});let i=await c.startAuthFlow(n).getAuthorizationUrl();if(i?.url)if("chrome-extension:"===window.location.protocol&&ke())try{let{privyOAuthCode:e,privyOAuthState:t}=await be(i.url);n.meta.stateCode=t,n.meta.authorizationCode=e,await this.loginWithHeadlessOAuth(n.meta)}catch(e){throw K({status:"error",error:e}),e}else window.location.assign(i.url)},async loginWithHeadlessOAuth(e){let t,r,n;R(!0),K({status:"loading"}),c.startAuthFlow(new xe({...e,customOAuthRedirectUrl:Z.customOAuthRedirectUrl}));let i=s.s.get(s.STATE_CODE_KEY),a=e.stateCode;if(i!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:i??"",returnedStateCode:a??""}}),R(!1),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await c.getAccessToken())try{({user:t,oAuthTokens:n}=await c.link()),he.current=e.provider;let r=De(t);t&&r&&s.emitPrivyEvent(ce,"linkAccount","onSuccess",{user:t,linkMethod:he.current,linkedAccount:r})}catch(t){throw R(!1),s.emitPrivyEvent(ce,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:n}=await c.authenticate()),he.current=e.provider;let i=De(t);t&&i&&void 0!==r&&s.emitPrivyEvent(ce,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:he.current,loginAccount:i})}catch(e){throw R(!1),K({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return A(t),S(r||!1),C(!0),R(!1),K({status:"done"}),n&&t&&s.emitPrivyEvent(ce,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{let i=new fe({email:e,captchaToken:t,disableSignup:r});c.startAuthFlow(i);try{he.current="email",L({status:"sending-code"}),await i.sendCodeEmail({withPrivyUi:n}),L({status:"awaiting-code-input"})}catch(e){throw L({status:"error",error:e}),"login"===pe.current?s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===pe.current&&s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async({oldAddress:e,newAddress:t,captchaToken:r})=>{let n=new Ce(e,t,r);c.startAuthFlow(n);try{await n.sendCodeEmail({withPrivyUi:!0})}catch(e){s.emitPrivyEvent(ce,"update","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:he.current})}},initUpdatePhone:async(e,t,r)=>{let n=new Oe(e,t,r);c.startAuthFlow(n);try{await n.sendSmsCode({withPrivyUi:!0})}catch(e){s.emitPrivyEvent(ce,"update","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:he.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{q({status:"sending-code"});let i=new Re({phoneNumber:e,captchaToken:t,disableSignup:r});c.startAuthFlow(i);try{he.current="sms",await i.sendSmsCode({withPrivyUi:n}),q({status:"awaiting-code-input"})}catch(e){throw q({status:"error",error:e}),"login"===pe.current?s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===pe.current&&s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(c.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(c.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function n(e){c.authFlow instanceof fe?L(e):c.authFlow instanceof Re&&q(e)}if(n({status:"submitting-code"}),!w){let e=new o.PrivyNotReadyError;throw n({status:"error",error:e}),e}if(c.authFlow instanceof fe)c.authFlow.meta.emailCode=e.trim();else{if(!(c.authFlow instanceof Re)){let e=new o.PrivyClientError("Must initialize a passwordless code flow first");throw n({status:"error",error:e}),e}c.authFlow.meta.smsCode=e.trim()}let i=await ui();if("link"===pe.current)try{({user:t}=await c.link())}catch(e){throw n({status:"error",error:e}),s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:he.current}),e}else if("update"===pe.current)try{({user:t}=await c.link())}catch(e){throw n({status:"error",error:e}),s.emitPrivyEvent(ce,"update","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:he.current}),e}else try{({user:t,isNewUser:r}=await c.authenticate())}catch(e){throw n({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let a=t||E;A(a||null),S(r||!1),C(!0),n({status:"done"});let l=null;return c.authFlow instanceof fe?l=a?.linkedAccounts.find((({type:e})=>"email"===e))||null:c.authFlow instanceof Re&&(l=a?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:a,isNewUser:r||!1,wasAlreadyAuthenticated:!!i,linkedAccount:l}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{pe.current=v?"link":"login",he.current="siwe",B({status:"generating-message"});let n=await c.generateSiweNonce({address:e,captchaToken:r});return B({status:"awaiting-signature"}),s.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:n})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await c.generateSiweNonce({address:e});return s.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r,smartWalletVersion:n})=>{let i;i=await c.linkSmartWallet({message:e,signature:t,smartWalletType:r,smartWalletVersion:n}),A((i=await Ke.refreshSessionAndUser()??i)||E||null)},loginWithSiwe:async({message:e,signature:t,captchaToken:r,disableSignup:n})=>{let i,a=null;try{if(E)throw Error("User already authenticated");let o=new s.SiweFlow(c,void 0,r,n,{message:e,signature:t});c.startAuthFlow(o),he.current="siwe",pe.current="login",B({status:"submitting-signature"});let l=await c.authenticate();if(({user:a,isNewUser:i}=l),!a)throw Error("Authentication failed - no user returned")}catch(e){throw s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),B({status:"error",error:e}),e}return A(a),S(i||!1),C(!0),B({status:"done"}),pe.current=null,he.current=null,{user:a,isNewUser:i||!1}},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})=>{let a;Me("siwe");let l=null;try{B({status:"submitting-signature"}),a=await c.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}),a=await Ke.refreshSessionAndUser()??a,B({status:"done"}),(l=De(a)||null)&&s.emitPrivyEvent(ce,"linkAccount","onSuccess",{user:a,linkMethod:"siwe",linkedAccount:l})}catch(e){throw s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),pe.current=null,he.current=null,B({status:"error",error:e}),e}let d=a||E;return A(d||null),pe.current=null,he.current=null,{user:d,linkedAccount:l}},refreshSessionAndUser:async()=>{let e=await c.getAuthenticatedUser();return C(!!e),A(e),e},walletProxy:Y,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>c.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await c.acceptTerms();return A(e),e},getUsdTokenPrice:e=>c.getUsdTokenPrice(e),getUsdPriceForSol:()=>c.getUsdPriceForSol(),getSplTokenMetadata:e=>c.getSplTokenMetadata(e),recoverEmbeddedWallet:async e=>new Promise((async(t,r)=>{if(!E)return void t(!0);let n=e?.address?d.getPrivyWalletWithAddress(E,e.address):d.getPrivyPrimaryWallet(E)||d.getImportedPrivyEthereumWallets(E).at(0)||d.getImportedPrivySolanaWallets(E).at(0);if(!n||d.getIsUnifiedWallet(n))return void t(!0);let i=await ui();if(!i||!Y||!n)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));let{entropyId:a,entropyIdVerifier:o}=s.getEntropyDetailsForUser(E,n);try{await Y.connect({accessToken:i,entropyId:a,entropyIdVerifier:o}),t(!0)}catch(e){if(s.errorIndicatesRecoveryIsNeeded(e)&&"privy"===n.recoveryMethod){let e;c.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:n.address}});try{e=await Y.recover({entropyId:a,entropyIdVerifier:o,accessToken:i})}catch(e){return void r(e)}e.entropyId||r(Error("Unable to recover wallet")),c.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:n.address}}),t(!0)}else s.errorIndicatesRecoveryIsNeeded(e)&&"privy"!==n.recoveryMethod&&"privy-v2"!==n.recoveryMethod?(Q({recoverWallet:{entropyId:a,entropyIdVerifier:o,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:n.recoveryMethod,action:"recover",shouldCreateEth:!1,shouldCreateSol:!1}}),we(s.embeddedWalletRecoveryScreen(n.recoveryMethod))):r(e)}})),setReadyToTrue:e=>{g(!0),ee?.(e)},updateWallets:()=>je(),fundWallet:async(e,t)=>{Q({funding:I.prepareFundingModalData({address:e,appConfig:Z,fundWalletConfig:t,methodScreen:s.FundingMethodSelectionScreen})}),we(s.FundingMethodSelectionScreen)},openModal:we,requestFarcasterSignerStatus:async e=>{let t=await ui(),r=E?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Y||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!E?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let n=await c.requestFarcasterSignerStatus(e);return"approved"===n.status&&A(await c.getAuthenticatedUser()||E||null),n},connectCoinbaseSmartWallet:async()=>{Z.externalWallets.coinbaseWallet.config.preference={...Z.externalWallets.coinbaseWallet.config.preference,options:"smartWalletOnly"};let e=c.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||c.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Te(e);await Pe("coinbase_wallet","coinbase_smart_wallet")},connectBaseAccount:async()=>{let e=c.connectors?.findWalletConnector("base_account","base_account");if(e)return Te(e);await Pe("base_account","base_account")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,telegramWebAppData:a,farcasterEmbeddedAddress:o,oAuthUserInfo:s})=>{let l=await c.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,telegramWebAppData:a,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return A(l),l},inProgressAuthFlowRef:pe,inProgressLoginOrLinkMethodRef:he};di=Ke.recoverEmbeddedWallet,Ke.recoverEmbeddedWallet;let Ve=r.useMemo((()=>({wallets:P,ready:ne&&de})),[P,ne,de]),$e=c.authFlow instanceof s.TelegramAuthFlow,Ye=!Z.headless&&Z.captchaEnabled&&!v&&(w||$e);/*#__PURE__*/return e.jsx(ii.Provider,{value:!0,children:/*#__PURE__*/e.jsx(d.PrivyContext.Provider,{value:ze,children:/*#__PURE__*/e.jsx(s.PrivyEventsContext.Provider,{value:ce,children:/*#__PURE__*/e.jsx(s.UseWalletsContext.Provider,{value:Ve,children:/*#__PURE__*/e.jsx(s.CaptchaProvider,{...Z,children:/*#__PURE__*/e.jsxs(f.InternalPrivyContext.Provider,{value:Ke,children:[/*#__PURE__*/e.jsx(s.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(s.ModalProvider,{data:X,setModalData:Q,setInitialScreen:U,initialScreen:_,authenticated:v,open:p,children:[l.children,/*#__PURE__*/e.jsx(ni,{customAuth:Z.customAuth}),Ye&&/*#__PURE__*/e.jsx(gt,{delayedExecution:!1}),/*#__PURE__*/e.jsx(gr,{}),/*#__PURE__*/e.jsx(tn,{disabled:Z.embeddedWallets.disableAutomaticMigration}),/*#__PURE__*/e.jsx(rr,{palette:Z.appearance.palette||{}}),!Z.render.standalone&&/*#__PURE__*/e.jsx(pr,{open:p})]})}),/*#__PURE__*/e.jsx(xr,{appId:l.appId,appClientId:l.clientId,clientAnalyticsId:c.clientAnalyticsId,origin:c.apiUrl,mfaMethods:E?.mfaMethods,mfaPromise:se,mfaSubmitPromise:le,onLoad:G,onLoadFailed:()=>null}),Z.loginConfig.telegramAuthConfiguration&&
6
- /*#__PURE__*/e.jsx(s.Hide,{$if:!0,children:/*#__PURE__*/e.jsx(wr,{scriptHost:l.apiUrl||s.DEFAULT_PRIVY_API_URL,botUsername:Z.loginConfig.telegramAuthConfiguration.botName})})]})})})})})})};const vi=()=>{let{setModalData:e}=s.usePrivyModal(),{openModal:t,privy:n,closePrivyModal:i}=f.usePrivyInternal(),{user:a}=d.usePrivyContext();return r.useMemo((()=>({verify:async({standalone:r=!0}={standalone:!0})=>new Promise(((o,s)=>a?0===a.mfaMethods.length?o():(e((e=>({...e,mfaVerify:{onSuccess:async()=>{r?await i({shouldCallAuthOnSuccess:!1,isSuccess:!0}):tr.setState({inProgressMfaFlow:void 0}),o()},onFailure:async e=>{r?await i({shouldCallAuthOnSuccess:!1,isSuccess:!1}):tr.setState({inProgressMfaFlow:void 0}),s(e)},sendSmsCode:async()=>{throw Error("Not enabled")},verifySmsCode:async()=>{throw Error("Not enabled")},verifyTotpCode:async e=>{await n.fetchPrivyRoute(z.MfaAuthTotpVerify,{body:{code:e}})},generateOptions:async()=>it((await n.fetchPrivyRoute(z.MfaAuthPasskeyInit,{body:{}})).options),verifyPasskey:async e=>{let t=await import("@simplewebauthn/browser"),r=await t.startAuthentication(e);await n.fetchPrivyRoute(z.MfaAuthPasskeyVerify,{body:{authenticator_response:rn(r)}})}}}))),void(r?t(Xt):tr.setState({inProgressMfaFlow:"auth"}))):s(Error("Must be logged in to verify MFA"))))})),[n,e,t,i])},fi={component:()=>{let{user:t,ready:n}=d.usePrivyContext(),{data:i,onUserCloseViaDialogOrKeybindRef:a}=s.usePrivyModal(),o=s.useAppConfig(),[l,c]=r.useState(null),[u,h]=r.useState(null),[p,y]=r.useState(null),[m,w]=r.useState(!1),[g,v]=r.useState(!1),[f,C]=r.useState(),E=async()=>{f?A(f):t?await P({user:t}):A(Error("Must be logged in to manage MFA")),setTimeout((()=>{c(null),h(null)}),500)};if(a.current=E,!i?.mfaEnroll)throw Error("Missing modal data for MFA enrollment screen.");let{onFailure:A,onSuccess:P,mfaMethods:k,verify:b,generateTotpSecret:x,enrollTotp:T,unenrollTotp:S,enrollPasskey:_}=i.mfaEnroll,I=t?.mfaMethods.includes("sms"),U=t?.mfaMethods.includes("totp"),W=t?.mfaMethods.includes("passkey"),R=!!t?.phone,O=t?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function M(){c(null),h(null),C(void 0)}async function N(e=O){try{C(void 0),v(!0);let t=await _(e);return await P({user:t})}catch(e){C(e)}finally{v(!1),w(!1)}}if(!n||!t||!o)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:E},"header"),/*#__PURE__*/e.jsx(ft,{children:/*#__PURE__*/e.jsx(Sn,{})}),/*#__PURE__*/e.jsx(At,{children:/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("sms"===l)return null;if("totp"===l)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:M,onClose:E},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(le.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Remove authenticator app verification?"}),/*#__PURE__*/e.jsxs(Et,{children:["MFA adds an extra layer of security to your ",o?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{$warn:!0,onClick:async function(){try{C(void 0),v(!0);let e=await S();return await P({user:e})}catch(e){C(e)}finally{v(!1),c(null)}},loading:g,children:"Remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("passkey"===l){let t=i.mfaEnroll.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:M,onClose:E},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(le.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/e.jsx(Et,{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(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{$warn:!0,onClick:async function(){try{C(void 0),v(!0);let e=await _([]);return await P({user:e})}catch(e){C(e)}finally{v(!1),c(null)}},loading:g,children:"Remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})}return 0!==k.length||I||U||W?"sms"===u?null:"totp"===u&&p?/*#__PURE__*/e.jsx(zn,{onClose:E,onReset:M,submitEnrollmentWithTotp:e=>async function(e){try{C(void 0),v(!0);let t=await T(e);return await P({user:t})}catch(e){C(e)}finally{v(!1),c(null)}}(e.mfaCode),error:f,totpInfo:{...p,appName:o?.name||"Privy"}}):"passkey"===u?/*#__PURE__*/e.jsx(On,{onReset:M,onClose:E,submitEnrollmentWithPasskey:N}):/*#__PURE__*/e.jsx(In,{showIntro:!1,userMfaMethods:t.mfaMethods,appMfaMethods:o.mfa.methods,userHasAuthSms:R,onBackToIntro:()=>{},handleSelectMethod:async function(e){C(void 0);try{await b()}catch(e){return void C(e)}return"totp"===e?(h(e),y(null),void x().then((({totpSecret:e,totpAuthUrl:t})=>{y({authUrl:t,secret:e})})).catch((()=>{y(null),M()}))):"passkey"===e&&1===O.length?await N():void h(e)},isTotpLoading:"totp"===u&&!p,isPasskeyLoading:m,error:f,onClose:E,setRemovingMfaMethod:async function(e){C(void 0);try{await b()}catch(e){return void C(e)}c(e)}}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:E},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ie.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Add more security"}),/*#__PURE__*/e.jsxs(Et,{children:[o?.name," does not have any verification methods enabled."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:E,children:"Close"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})}};let Ci=async(e,t,r,n,i)=>{if(!e)throw n("linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:i}),new o.PrivyClientError("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(i))))throw new o.PrivyClientError(`OAuth account of type ${i} not linked to the account.`);await r(i)};Object.defineProperty(exports,"SUPPORTED_CHAINS",{enumerable:!0,get:function(){return a.DEFAULT_SUPPORTED_CHAINS}}),Object.defineProperty(exports,"addPrivyRpcToChain",{enumerable:!0,get:function(){return a.addPrivyRpcToChain}}),Object.defineProperty(exports,"addRpcUrlOverrideToChain",{enumerable:!0,get:function(){return a.addRpcUrlOverrideToChain}}),exports.EthereumWalletConnector=s.EthereumWalletConnector,exports.VERSION=s.VERSION,exports.WalletConnector=s.WalletConnector,exports.errorIndicatesMaxMfaRetries=s.errorIndicatesMaxMfaRetries,exports.errorIndicatesMfaTimeout=s.errorIndicatesMfaTimeout,exports.errorIndicatesMfaVerificationFailed=s.errorIndicatesMfaVerificationFailed,exports.useWallets=s.useWallets,exports.useActiveWallet=C.useActiveWallet,exports.useConnectWallet=C.useConnectWallet,exports.useFundWallet=C.useFundWallet,exports.useLogin=C.useLogin,exports.useLogout=C.useLogout,exports.useCreateWallet=I.useCreateWallet,exports.useImportWallet=I.useImportWallet,exports.usePrivy=I.usePrivy,exports.getEmbeddedConnectedWallet=V.getEmbeddedConnectedWallet,exports.Captcha=gt,exports.ConnectorManager=Xe,exports.LoginModal=pr,exports.PrivyClient=mt,exports.PrivyProvider=({config:t,...n})=>{var i;if((()=>{if(r.useContext(ii))throw new o.PrivyClientError("Multiple PrivyProvider instances found","Found multiple instances of PrivyProvider, ensure there is only one mounted in your application tree.")})(),"undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol&&"chrome-extension:"!==window.location.protocol)throw new o.PrivyClientError("Embedded wallet is only available over HTTPS");if("string"!=typeof(i=n.appId)||25!==i.length)throw new o.PrivyClientError("Cannot initialize the Privy provider with an invalid Privy app ID");ai||(ai=new mt({appId:n.appId,appClientId:n.clientId,apiUrl:n.apiUrl}));let a=Object.assign({},t),l=r.useMemo((()=>new J.default({appId:n.appId,clientId:n.clientId,storage:s.s,baseUrl:n.apiUrl,sdkVersion:"react-auth:3.3.0"})),[]);/*#__PURE__*/
7
- return e.jsx(s.PrivyAppConfigProvider,{client:l,legacyClient:ai,appClientId:n.clientId,clientConfig:a,children:/*#__PURE__*/e.jsx(s.PrivyPluginProvider,{children:/*#__PURE__*/e.jsx(gi,{...n,client:ai,privy:l})})})},exports.getAccessToken=function(){return ai?ai.getCustomerAccessToken():Promise.resolve(s.s.get(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.toViemAccount=async({wallet:e})=>{let t=await e.getEthereumProvider();return $.toAccount({address:e.address,sign:async({hash:r})=>{if("privy"!==e.walletClientType)throw new a.PrivyClientError({error:"Unprefixed signing is not supported by external wallets.",code:"unsupported_wallet_type"});return await t.request({method:"secp256k1_sign",params:[r]})},signMessage:async({message:r})=>await t.request({method:"personal_sign",params:[r,e.address]}),signTypedData:async r=>await t.request({method:"eth_signTypedData_v4",params:[e.address,r]}),signTransaction:async e=>await t.request({method:"eth_signTransaction",params:[e]})})},exports.useAuthMfa=vi,exports.useAuthMfaEnrollment=()=>{let e=s.useAppConfig(),{setModalData:t}=s.usePrivyModal(),{verify:n}=vi(),{openModal:i,privy:a,closePrivyModal:o,refreshSessionAndUser:l,setUser:c}=f.usePrivyInternal();return r.useMemo((()=>({enroll:async()=>new Promise(((r,s)=>{t({mfaEnroll:{onSuccess:async e=>{await o({shouldCallAuthOnSuccess:!1,isSuccess:!0}),r(e)},onFailure:async e=>{await o({shouldCallAuthOnSuccess:!1,isSuccess:!1}),s(e)},verify:()=>n({standalone:!1}),shouldUnlinkOnUnenrollMfa:!0,mfaMethods:e.mfa.methods,sendSmsCode:async()=>{throw Error("Not enabled")},enrollSms:async()=>{throw Error("Not enabled")},unenrollSms:async()=>{throw Error("Not enabled")},generateTotpSecret:async()=>await a.fetchPrivyRoute(z.MfaAuthTotpInit,{body:{}}),enrollTotp:async e=>{await a.fetchPrivyRoute(z.MfaAuthTotpEnroll,{body:{code:e}});let t=await l();return c(t),t},unenrollTotp:async()=>{await a.fetchPrivyRoute(z.MfaAuthTotpUnenroll,{body:{}});let e=await l();return c(e),e},enrollPasskey:async e=>{await a.fetchPrivyRoute(z.MfaAuthPasskeyEnrollment,{body:{credential_ids:e,remove_for_login:!0}});let t=await l();return c(t),t}}}),i(fi)}))})),[a,t,i,o])},exports.useAuthorizationSignature=()=>{let{signWithUserSigner:e}=K.useSignWithUserSigner();return r.useMemo((()=>({async generateAuthorizationSignature(t){let{signature:r}=await a.generateAuthorizationSignature(e,t);return{signature:r}}})),[e])},exports.useBaseAccountSdk=()=>{let{baseAccountSdk:e}=f.usePrivyInternal();return{baseAccountSdk:e}},exports.useConnectBaseAccount=()=>{let{connectBaseAccount:e}=f.usePrivyInternal();return{connectBaseAccount:e}},exports.useConnectCoinbaseSmartWallet=()=>{let{connectCoinbaseSmartWallet:e}=f.usePrivyInternal();return{connectCoinbaseSmartWallet:e}},exports.useConnectOrCreateWallet=e=>{let{connectOrCreateWallet:t}=d.usePrivyContext();return s.usePrivyEventSubscription("connectOrCreateWallet",e),{connectOrCreateWallet:t}},exports.useCrossAppAccounts=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:n,sendTransactionWithCrossAppWallet:i,signTransactionWithCrossAppWallet:a}=d.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,signTransaction:a}},exports.useCustomAuth=e=>{let t=ri((e=>e.jwtAuthFlowState));return s.usePrivyEventSubscription("customAuth",e),{status:t}},exports.useDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=f.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}=d.usePrivyContext();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}},exports.useGetAccessTokenForProvider=()=>r.useMemo((()=>({getAccessTokenForProvider:({appId:e})=>{try{let t=s.s.get(s.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return{token:null};{let r=new Me(t);return r.isExpired()?(s.s.del(s.getProviderAccessTokenStorageKey(e)),{token:null}):{token:r.value}}}catch(e){return console.error(e),{token:null}}}})),[]),exports.useGuestAccounts=function(){let e=s.useAppConfig(),t=s.useEmitPrivyEvent(),{client:r,setUser:n,setAuthenticated:i,setIsNewUser:a,initializeWalletProxy:l}=f.usePrivyInternal(),{create:c}=I.useCreateWalletInternal();return{createGuestAccount:async()=>{if(!e.id||!r)throw Error("SDK not yet ready");r.startAuthFlow(new ot(e.id));try{let d=await r.authenticate(),u=d.user,h=d.isNewUser??!1;if(!u)throw new o.PrivyClientError("Unable to authenticate guest account");let p=await r.getAccessToken(),y=await l(s.WALLET_PROXY_TIMEOUT);if(p&&y)try{let t=s.shouldCreateEmbeddedEthWallet(u,e.embeddedWallets.ethereum.createOnLogin),r=s.shouldCreateEmbeddedSolWallet(u,e.embeddedWallets.solana.createOnLogin);t&&r?(u=(await c({chainType:"ethereum",latestUser:u})).user,u=(await c({chainType:"solana",latestUser:u})).user):r?u=(await c({chainType:"solana",latestUser:u})).user:t?u=(await c({chainType:"ethereum",latestUser:u})).user:n(u)}catch(e){n(u),console.warn("Unable to create embedded wallet for guest account")}return a(h),i(!0),t("login","onComplete",{user:u,isNewUser:h,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),u}catch(e){throw t("login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}}}},exports.useHeadlessDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=f.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}=lt();return{identityToken:e}},exports.useLinkAccount=function(e){let{linkEmail:t,linkPhone:n,linkWallet:i,linkGoogle:a,linkApple:o,linkTwitter:l,linkTwitch:c,linkDiscord:u,linkGithub:h,linkLinkedIn:p,linkTiktok:y,linkLine:m,linkSpotify:w,linkInstagram:g,linkTelegram:v,linkFarcaster:f,linkPasskey:C}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("linkAccount",e),{linkEmail:t,linkPhone:n,linkWallet:i,linkGoogle:a,linkApple:o,linkTwitter:l,linkTwitch:c,linkDiscord:u,linkGithub:h,linkLinkedIn:p,linkTiktok:y,linkLine:m,linkSpotify:w,linkInstagram:g,linkFarcaster:f,linkTelegram:v,linkPasskey:C}},exports.useLinkJwtAccount=function(e){let{client:t}=f.usePrivyInternal(),[n,i]=r.useState({status:"initial"});return{linkWithCustomJwt:r.useCallback((async r=>{try{i({status:"initial"}),t.startAuthFlow(new at(r)),i({status:"loading"});let{user:n}=await t.link();if(!n)throw Error("Error, user not found");let a=n.linkedAccounts.filter((e=>"custom_auth"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime())).at(0);return i({status:"done"}),e?.onSuccess?.({user:n,linkMethod:"custom",linkedAccount:a}),{user:n}}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"custom"}),r}}),[t.startAuthFlow,t.link]),state:n}},exports.useLinkWithPasskey=e=>{let{initLinkWithPasskey:t,linkWithPasskey:n,passkeyAuthState:i,setPasskeyAuthState:a}=f.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 a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[n]),state:i}},exports.useLinkWithSiwe=e=>{let t=s.useCaptcha(),{siweState:n,setSiweState:i,linkWithSiwe:a,generateSiweMessage:l}=f.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||o.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 s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:i,linkedAccount:u}=await a({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||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[a,t.status]),state:n}},exports.useLinkWithSiws=()=>{let e=s.useCaptcha(),{client:t,setUser:n,refreshSessionAndUser:i}=f.usePrivyInternal(),{authenticated:a}=I.usePrivy();return{generateSiwsMessage:r.useCallback((async({address:r})=>{let n;if(e.enabled&&"error"===e.status)throw new s.CaptchaError(e.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),n=await e.waitForResult());let i=await t.generateSiwsNonce({address:r,captchaToken:n});return s.prepareSiwsMessageWithNonce({address:r,nonce:i})}),[e,t]),linkWithSiws:r.useCallback((async({signature:r,message:l,walletClientType:c,connectorType:d})=>{if(!a)throw Error("User must be authenticated before linking");if(e.enabled&&"error"===e.status)throw new s.CaptchaError(e.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let u=await t.linkWithSiws({message:l,signature:r,walletClientType:c,connectorType:d,messageType:"plain"}),h=(e=>{if(!e)return;let t=e.linkedAccounts;return t&&0!==t.length?t[t.length-1]:void 0})(u=await i()??u)||null;return n(u||null),{user:u,linkedAccount:h}}),[a,e,t,i,n])}},exports.useLoginWithEmail=e=>{let t=s.useCaptcha(),{emailOtpState:n,setEmailOtpState:i,initLoginWithEmail:a,loginWithCode:l}=f.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 s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a({email:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:r.useCallback((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:c}=await l(r);e?.onComplete?.({user:n,isNewUser:i,wasAlreadyAuthenticated:a,loginMethod:"email",loginAccount:c})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t.status]),state:n}},exports.useLoginWithFarcasterV2=()=>{let{client:e,setAuthenticated:t,setUser:n}=f.usePrivyInternal();return r.useMemo((()=>({init:async()=>{if(!e)throw new o.PrivyClientError("Must initialize Privy client first.");let t=new B.FarcasterFramesFlow;return e.startAuthFlow(t),await t.init()},login:async({fid:r,message:i,signature:a})=>{if(!e)throw new o.PrivyClientError("Must initialize Privy client first.");if(!(e.authFlow instanceof B.FarcasterFramesFlow))throw new o.PrivyClientError("Must initialize Farcaster Mini App flow first.");e.authFlow.setAuthData({message:i,signature:a,fid:r});let{user:s}=await e.authenticate();if(!s)throw new o.PrivyClientError("Failed to login with Farcaster V2");return n(s),t(!0),{user:s}}})),[e,n,t])},exports.useLoginWithOAuth=e=>{s.usePrivyEventSubscription("login",e);let t=s.useCaptcha(),n=s.useIsServerConfigLoaded(),{ready:i,user:a}=d.usePrivyContext(),{initLoginWithHeadlessOAuth:l,loginWithHeadlessOAuth:c,oAuthState:u,setOAuthState:h,isHeadlessOAuthLoading:p}=f.usePrivyInternal(),y=r.useCallback((async e=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return await l(e.provider,t.token,e.disableSignup)}catch(e){throw h({status:"error",error:e}),e}}),[l,t]),m=r.useCallback((async()=>{let e=Ue();try{if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");let t=e.provider;if(d.isCustomOAuthProvider(t)){if(a&&a.linkedAccounts.some((e=>e.type===t)))return console.warn("User is already logged in with this OAuth provider"),a}else if(a&&t in a&&a[t])return console.warn("User is already logged in with this OAuth provider"),a;if(e.popupFlow)return}catch(e){throw h({status:"error",error:e}),e}try{return await c(e)}catch(e){throw h({status:"error",error:e}),e}finally{s.stripUrlOAuthParamsAndRemoveStateCode()}}),[c]);return r.useEffect((()=>{let e=Ue();i&&n&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&m().catch((()=>{}))}),[i,n]),{initOAuth:y,loading:p,state:u}},exports.useLoginWithPasskey=e=>{let t=s.useCaptcha(),{initLoginWithPasskey:n,loginWithPasskey:i,passkeyAuthState:a,setPasskeyAuthState:l}=f.usePrivyInternal();return{loginWithPasskey:r.useCallback((async r=>{try{let a;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),a=await t.waitForResult()),await n({captchaToken:a,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||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[i,t.status]),state:a}},exports.useLoginWithSiwe=e=>{let t=s.useCaptcha(),{siweState:n,setSiweState:i,client:a,generateSiweMessage:l,loginWithSiwe:c}=f.usePrivyInternal();return{generateSiweNonce:r.useCallback((async r=>{try{let e;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),i({status:"generating-message"});let n=await a.generateSiweNonce({address:r?.address,captchaToken:e});return i({status:"awaiting-signature"}),n}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a,t]),generateSiweMessage:r.useCallback((async({address:r,chainId:n})=>{try{let e;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await l({address:r,chainId:n,captchaToken:e})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t]),loginWithSiwe:r.useCallback((async({message:r,signature:n,disableSignup:a})=>{try{let i;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),i=await t.waitForResult());let{user:l,isNewUser:d}=await c({message:r,signature:n,captchaToken:i,disableSignup:a});return e?.onComplete?.({user:l,isNewUser:d,wasAlreadyAuthenticated:!1,loginMethod:"siwe",loginAccount:null}),l}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[c,t.status]),state:n}},exports.useLoginWithSiws=()=>{let e=s.useCaptcha(),{client:t,setAuthenticated:n,setUser:i,setIsNewUser:a}=f.usePrivyInternal(),{authenticated:l}=I.usePrivy();return{generateSiwsMessage:r.useCallback((async({address:r})=>{let n;if(e.enabled&&"error"===e.status)throw new s.CaptchaError(e.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),n=await e.waitForResult());let i=await t.generateSiwsNonce({address:r,captchaToken:n});return s.prepareSiwsMessageWithNonce({address:r,nonce:i})}),[e,t]),loginWithSiws:r.useCallback((async({message:r,signature:c,disableSignup:d})=>{if(l)throw Error("User already authenticated");if(e.enabled&&"error"===e.status)throw new s.CaptchaError(e.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),await e.waitForResult());let{user:u,isNewUser:h}=await t.authenticateWithSiws({message:r,signature:c,mode:d?"no-signup":"login-or-sign-up",messageType:"plain"});if(!u)throw Error("Authentication failed - no user returned");return i(u),a(h||!1),n(!0),u}),[l,e,t,n,i,a])}},exports.useLoginWithSms=e=>{let t=s.useCaptcha(),{smsOtpState:n,setSmsOtpState:i,initLoginWithSms:a,loginWithCode:l}=f.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 s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a({phoneNumber:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:r.useCallback((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:c}=await l(r);e?.onComplete?.({user:n,isNewUser:i,wasAlreadyAuthenticated:a,loginMethod:"sms",loginAccount:c})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t.status]),state:n}},exports.useLoginWithTelegram=e=>{let t=s.useCaptcha(),{initLoginWithTelegram:n,loginWithTelegram:i,telegramAuthState:a,setTelegramAuthState:l}=f.usePrivyInternal();return{login:r.useCallback((async r=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);await n(t.token,r?.disableSignup);let{user:a,isNewUser:l,loginAccount:c,wasAlreadyAuthenticated:d}=await i({intent:"login"});e?.onComplete?.({user:a,isNewUser:l,wasAlreadyAuthenticated:d,loginMethod:"telegram",loginAccount:c})}catch(r){throw l({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[n,i,t]),state:a}},exports.useMfa=Qt,exports.useMfaEnrollment=Tn,exports.useMigrateWallets=en,exports.useModalStatus=()=>{let{isModalOpen:e}=r.useContext(d.PrivyContext);return{isOpen:e}},exports.useOAuthTokens=function(e){let{authenticated:t,user:r}=d.usePrivyContext(),{initLoginWithOAuth:n}=f.usePrivyInternal(),i=s.useEmitPrivyEvent();return s.usePrivyEventSubscription("oAuthAuthorization",e),{reauthorize:e=>Ci(t,r,n,i,e.provider)}},exports.useRecoverEmbeddedWallet=()=>{let{user:e}=d.usePrivyContext(),{walletProxy:t}=f.usePrivyInternal();return{recover:r.useCallback((async r=>{if(!t)throw Error("Wallet proxy is not ready");let n=await ui();if(!e||!n)throw new o.PrivyClientError("User must be logged in before attempting to modify the recovery method.");let{entropyId:i,entropyIdVerifier:a}=s.getEntropyDetailsForUser(e);try{await t.recover({entropyId:i,entropyIdVerifier:a,accessToken:n,...r})}catch{throw new o.PrivyClientError("Unable to recover wallets")}}),[t,e])}},exports.useRegisterMfaListener=vt,exports.useSendTransaction=function(e){let{sendTransaction:t}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("sendTransaction",e),{sendTransaction:t}},exports.useSessionSigners=()=>{let{addSessionSignersInternal:e,removeSessionSignersInternal:t}=(()=>{let{user:e}=d.usePrivyContext(),t=f.usePrivyInternal(),{signWithUserSigner:r}=K.useSignWithUserSigner(),n=async({wallet:n,additional_signers:i})=>{let s=await t.client.getAccessToken();if(!e||!s)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if(!n.id)throw new o.PrivyClientError("Wallet to add signers to must have ID on server");if(!t.walletProxy)throw new o.PrivyClientError("Wallet proxy not initialized.");await a.updateWallet(t.privy,{wallet_id:n.id},r,{additional_signers:i})};return{addSessionSignersInternal:async({address:r,signers:i})=>{let l=await t.client.getAccessToken();if(!e||!l)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to add a session signer.");let c=t.walletProxy??await t.initializeWalletProxy(15e3);if(!c)throw new o.PrivyClientError("Wallet proxy not initialized.");let u=d.getPrivyWalletWithAddress(e,r);if(!u)throw new o.PrivyClientError("Address to add signers too is not associated with current user.");if(d.getIsUnifiedWallet(u)){if(0===i.length)throw new o.PrivyClientError("Must specify at least one signer to add.");let e=[...(await a.getWallet(t.privy,{wallet_id:u.id})).additional_signers,...s.parseAdditionalSigners(i)];await n({wallet:u,additional_signers:e})}else{if(u.delegated)return{user:e};if(i.length>0)throw new o.PrivyClientError("Specifying signers in addSessionSigners is only supported for TEE execution and this app uses On-device execution. Pass an empty array for signers instead. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let n=Tr({address:r,user:e}),a=Sr({address:r,user:e});await t.recoverEmbeddedWallet({address:r}),await c.createDelegatedAction({accessToken:l,rootWallet:a,delegatedWallets:[n]})}let h=await t.refreshSessionAndUser();if(!h)throw Error("Could not refresh user");return{user:h}},removeSessionSignersInternal:async({address:r})=>{let i=await t.client.getAccessToken();if(!e||!i)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if(!(t.walletProxy??await t.initializeWalletProxy(15e3)))throw new o.PrivyClientError("Wallet proxy not initialized.");let a=d.getPrivyWalletWithAddress(e,r);if(!a)throw new o.PrivyClientError("Address to remove signers from is not associated with current user.");d.getIsUnifiedWallet(a)?await n({wallet:a,additional_signers:[]}):await t.client.revokeDelegatedWallet();let s=await t.refreshSessionAndUser();if(!s)throw Error("Could not refresh user");return{user:s}}}})();return{addSessionSigners:async({address:t,signers:r})=>e({address:t,signers:r}),removeSessionSigners:async({address:e})=>t({address:e})}},exports.useSetWalletRecovery=function(e){let{setWalletRecovery:t}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("setWalletRecovery",e),{setWalletRecovery:t}},exports.useSign7702Authorization=()=>{let{ready:e,wallets:t}=s.useWallets(),{user:n}=d.usePrivyContext(),{rpcConfig:a,chains:o,appId:l}=f.usePrivyInternal();return{signAuthorization:r.useCallback((async(r,c)=>{let u;if(!n)throw Error("User must be authenticated before signing with a Privy wallet");if(!e)throw Error("Wallets are not ready");let h=c?.address??d.getPrivyEthereumWallet(n)?.address??T.zeroAddress,p=t.find((e=>T.getAddress(e.address)===T.getAddress(h)));if(!p)throw Error("Signing wallet not found.");let y=r.chainId??Number(p.chainId.split(":")[1]);if(0===y)u={chainId:0,address:r.contractAddress,nonce:r.nonce??0};else{let e=o.find((e=>e.id===y));if(!e)throw Error("Error, chain not configured in PrivyProvider config");let t=T.createWalletClient({account:h,chain:e,transport:T.http(s.getJsonRpcEndpointFromChain(e,a,l))});u=await t.prepareAuthorization({...r})}let m=await p.getEthereumProvider(),w=await m.request({method:"secp256k1_sign",params:[i.hashAuthorization(u)]});return{...u,...T.parseSignature(w)}}),[e,t,n,o])}},exports.useSignMessage=function(e){let{signMessage:t}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("signMessage",e),{signMessage:t}},exports.useSignTransaction=function(){let{signTransaction:e}=r.useContext(d.PrivyContext);return{signTransaction:e}},exports.useSignTypedData=function(e){let{signTypedData:t}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("signTypedData",e),{signTypedData:t}},exports.useSignupWithPasskey=e=>{let t=s.useCaptcha(),{initSignupWithPasskey:n,signupWithPasskey:i,passkeyAuthState:a,setPasskeyAuthState:l}=f.usePrivyInternal();return{signupWithPasskey:r.useCallback((async()=>{try{let r;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),r=await t.waitForResult()),await n({captchaToken:r,withPrivyUi:!1});let{user:a,isNewUser:l,wasAlreadyAuthenticated:c,loginAccount:d}=await i();e?.onComplete?.({user:a,isNewUser:l,wasAlreadyAuthenticated:c,loginMethod:"passkey",loginAccount:d})}catch(t){throw l({status:"error",error:t}),e?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[i,t.status]),state:a}},exports.useSubscribeToJwtAuthWithFlag=function({isAuthenticated:e,isLoading:t,...n}){let i=r.useRef();r.useEffect((()=>{t||i.current?.()}),[e,t]);let a=r.useCallback((e=>(i.current=e,()=>{i.current=void 0})),[]);return ti({...n,subscribe:a})},exports.useSyncJwtBasedAuthState=ti,exports.useToken=function(e){let{getAccessToken:t}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("accessToken",e),{getAccessToken:t}},exports.useUpdateAccount=function(e){let{updateEmail:t,updatePhone:n}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("update",e),{updateEmail:t,updatePhone:n}},exports.useUpdateEmail=e=>{let{user:t}=d.usePrivyContext(),{loginWithCode:n,emailOtpState:i,setEmailOtpState:a,client:s,inProgressAuthFlowRef:l,inProgressLoginOrLinkMethodRef:c}=f.usePrivyInternal();return{state:i,sendCode:r.useCallback((async({newEmailAddress:r})=>{try{if(!t?.email)throw Error("User is required to have an email address to update it.");let e=new Ce(t.email.address,r);s.startAuthFlow(e),await e.sendCodeEmail({withPrivyUi:!1})}catch(r){a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[t?.email]),verifyCode:r.useCallback((async({code:r})=>{try{if(!t?.email)throw Error("User is required to have an email address to update it.");l.current="update",c.current="email";let{user:i,linkedAccount:a}=await n(r);return e?.onSuccess?.({user:i,updateMethod:"email",updatedAccount:a}),{user:i}}catch(r){a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[t?.email])}},exports.useUser=()=>{let{setUser:e,client:t}=r.useContext(f.InternalPrivyContext),{user:n}=r.useContext(d.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("react/jsx-runtime"),t=require("mipd"),r=require("react"),n=require("react-device-detect"),i=require("viem/utils"),a=require("@privy-io/js-sdk-core"),o=require("./paths-B00ZrFQm.js"),s=require("./SignRequestScreen-BtiA_kjR.js"),l=require("uuid"),c=require("jose"),d=require("./privy-context-NMR-GjnL.js"),u=require("eventemitter3"),h=require("@coinbase/wallet-sdk"),p=require("@privy-io/ethereum"),y=require("ofetch"),m=require("js-cookie"),w=require("zustand"),g=require("@marsidev/react-turnstile"),f=require("styled-components"),v=require("./internal-context-DNWjSiYq.js"),C=require("./useActiveWallet-DygS7fQB.js"),E=require("@heroicons/react/24/outline/DevicePhoneMobileIcon"),A=require("@heroicons/react/24/outline/FingerPrintIcon"),P=require("@heroicons/react/24/outline/PhoneIcon"),k=require("@heroicons/react/24/outline/ShieldCheckIcon"),b=require("@heroicons/react/24/outline/CalendarIcon"),x=require("@heroicons/react/24/outline/ExclamationTriangleIcon"),T=require("viem"),S=require("@headlessui/react"),_=require("@privy-io/urls"),I=require("./usePrivy-8s4mCLcX.js"),U=require("lucide-react"),W=require("@heroicons/react/24/outline/EnvelopeIcon"),R=require("@heroicons/react/24/outline/QuestionMarkCircleIcon"),O=require("@heroicons/react/24/solid/CheckBadgeIcon"),M=require("@heroicons/react/24/solid/IdentificationIcon"),N=require("@heroicons/react/24/outline/ChevronRightIcon"),j=require("@heroicons/react/24/outline/MinusCircleIcon"),F=require("@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon"),L=require("@heroicons/react/24/outline/ClockIcon"),D=require("@heroicons/react/24/outline/CheckCircleIcon"),q=require("@heroicons/react/24/solid/ShieldCheckIcon"),H=require("@heroicons/react/24/outline/GlobeAltIcon"),B=require("./frame-8JZCzmCf.js"),z=require("@privy-io/public-api"),K=require("./use-sign-with-user-signer-Q0_LRVtz.js"),V=require("./getEmbeddedConnectedWallet-6TsVZJkD.js"),$=require("viem/accounts");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("@scure/base"),require("tinycolor2"),require("@heroicons/react/24/outline/UserCircleIcon"),require("@heroicons/react/24/outline/ArrowLeftIcon"),require("@heroicons/react/24/outline/ArrowRightIcon"),require("@heroicons/react/24/outline/XMarkIcon"),require("@heroicons/react/20/solid/CheckIcon"),require("@heroicons/react/24/outline/WalletIcon"),require("@heroicons/react/24/outline/ExclamationCircleIcon"),require("@heroicons/react/24/outline/Square2StackIcon"),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/outline/ArrowPathIcon"),require("@heroicons/react/24/outline/EyeIcon"),require("@heroicons/react/24/outline/EyeSlashIcon"),require("@heroicons/react/24/outline/KeyIcon"),require("@heroicons/react/24/solid/CheckCircleIcon"),require("@heroicons/react/24/outline/ArrowDownTrayIcon"),require("@heroicons/react/24/outline/ClipboardDocumentCheckIcon"),require("@heroicons/react/24/outline/DocumentDuplicateIcon"),require("@heroicons/react/24/solid/XCircleIcon"),require("@heroicons/react/24/outline"),require("@tanstack/react-virtual"),require("@heroicons/react/24/outline/CheckIcon"),require("qrcode"),require("@walletconnect/ethereum-provider"),require("@heroicons/react/24/outline/CreditCardIcon"),require("@heroicons/react/24/outline/QrCodeIcon"),require("@heroicons/react/24/solid/ArrowsRightLeftIcon"),require("@heroicons/react/24/outline/InformationCircleIcon"),require("@heroicons/react/24/outline/ClipboardDocumentIcon"),require("@heroicons/react/24/outline/ChevronDownIcon");var Z=/*#__PURE__*/Y(r),J=/*#__PURE__*/Y(a),X=/*#__PURE__*/G(c),Q=/*#__PURE__*/Y(u),ee=/*#__PURE__*/Y(m),te=/*#__PURE__*/Y(E),re=/*#__PURE__*/Y(A),ne=/*#__PURE__*/Y(P),ie=/*#__PURE__*/Y(k),ae=/*#__PURE__*/Y(b),oe=/*#__PURE__*/Y(x),se=/*#__PURE__*/Y(W),le=/*#__PURE__*/Y(R),ce=/*#__PURE__*/Y(O),de=/*#__PURE__*/Y(M),ue=/*#__PURE__*/Y(N),he=/*#__PURE__*/Y(j),pe=/*#__PURE__*/Y(F),ye=/*#__PURE__*/Y(L),me=/*#__PURE__*/Y(D),we=/*#__PURE__*/Y(q),ge=/*#__PURE__*/Y(H);function fe(e){return e?{"privy-ui":"t"}:void 0}class ve{async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new o.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessAuthenticatePath,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw o.formatApiError(e)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new o.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessLinkPath,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw o.formatApiError(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new o.PrivyClientError("Email must be set when initialzing authentication.");let n=fe(r);try{return await this.api.post(o.passwordlessInitPath,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw o.formatApiError(e)}}constructor({email:e,captchaToken:t,disableSignup:r}){this.meta={email:e,captchaToken:t,disableSignup:r??!1}}}class Ce extends ve{async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new o.PrivyClientError("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(o.updateEmailPath,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw o.formatApiError(e)}}constructor(e,t,r){super({email:t,captchaToken:r}),this.meta={email:t,captchaToken:r,oldAddress:e,disableSignup:!1}}}class Ee{get meta(){return this._meta}async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new o.PrivyClientError("Auth flow must be initialized first");try{let e=await this.api.post(o.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 o.PrivyClientError("No response from authentication");return e}catch(e){throw o.formatApiError(e)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.farcasterLinkPath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(e){throw o.formatApiError(e)}}async _startChannelOnce(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");let e=await this.api.post(o.farcasterInitPath,{token:this.captchaToken});n.isMobile&&!n.isIOS&&e.connect_uri&&s.openHref(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new o.PrivyClientError("Auth flow must be initialized first");let e=await this.api.get(o.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 s.RunEffectOnce(this._startChannelOnce.bind(this)),this.pollForReady=new s.RunEffectOnce(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function Ae(){return"undefined"!=typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function Pe(){if(!Ae())return;let e=window.chrome;return e?.runtime?.id}function ke(){if(!Ae())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function be(e){return new Promise(((t,r)=>{ke()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},(async e=>{try{let r=function(){if(!Ae())return;let e=window.chrome;return e?.runtime?.lastError?.message}();if(r||!e){let e=`WebAuthFlow failed: ${r||"Response URI missing"}`;throw Error(e)}let n=new URL(e),i=Pe();if(!i)throw Error("Invalid extension context");if("chrome-extension:"===n.protocol){if(n.hostname!==i)throw Error("Invalid responseUri origin")}else{if("https:"!==n.protocol)throw Error("Invalid responseUri protocol");{let e=n.hostname.split(".");if(3!==e.length||"chromiumapp"!==e[1]||"org"!==e[2]||e[0]!==i)throw Error("Invalid responseUri origin")}}let a=n.searchParams.get("privy_oauth_state"),o=n.searchParams.get("privy_oauth_code");if(!a||!o)throw Error("Invalid responseUri - missing required parameters");t({privyOAuthState:a,privyOAuthCode:o})}catch(e){r(e)}})):r(Error("Chrome identity API not available"))}))}class xe{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new o.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new o.PrivyClientError("User denied confirmation during OAuth flow");let e=s.getCodeVerifier();try{let t=await this.api.post(o.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 s.f.del(s.CODE_VERIFIER_KEY),s.f.del(s.HEADLESS_OAUTH_KEY),s.f.del(s.OAUTH_DISABLE_SIGNUP_KEY),t}catch(e){let t=o.formatApiError(e);if(t.privyErrorCode)throw new o.PrivyClientError(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new o.PrivyClientError("Invalid code during oauth flow.",void 0,o.PrivyErrorCode.OAUTH_USER_DENIED);throw new o.PrivyClientError("Invalid code during OAuth flow.",void 0,o.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new o.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new o.PrivyClientError("User denied confirmation during OAuth flow");let e=s.f.get(s.CODE_VERIFIER_KEY);if(!e)throw new o.PrivyClientError("Authentication error.");try{let t=await this.api.post(o.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return s.f.del(s.CODE_VERIFIER_KEY),t}catch(e){throw o.formatApiError(e)}}async getAuthorizationUrl(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.provider)throw new o.PrivyClientError("Provider must be set when initializing OAuth authentication.");let e=s.createCodeVerifier();s.f.put(s.CODE_VERIFIER_KEY,e);let t=s.createStateCode();s.f.put(s.STATE_CODE_KEY,t);let r=await s.deriveCodeChallengeFromCodeVerifier(e);this.meta.withPrivyUi||s.f.put(s.HEADLESS_OAUTH_KEY,!0),this.meta.disableSignup?s.f.put(s.OAUTH_DISABLE_SIGNUP_KEY,!0):s.f.del(s.OAUTH_DISABLE_SIGNUP_KEY);let n=fe(this.meta.withPrivyUi),i=window.location.href,a=function(){let e=Pe();if(e)return`https://${e}.chromiumapp.org`}();a&&(i=a);try{return await this.api.post(o.oAuthInitPath,{provider:this.meta.provider,redirect_to:this.meta.customOAuthRedirectUrl||i,token:this.meta.captchaToken,code_challenge:r,state_code:t},{headers:{...n}})}catch(e){throw o.formatApiError(e)}}constructor(e){this.meta=e}}const Te=({style:t})=>/*#__PURE__*/e.jsx(ge.default,{style:{color:"var(--privy-color-error)",...t}});let Se={google:{name:"Google",component:s.Google},discord:{name:"Discord",component:s.Discord},github:{name:"Github",component:s.Github},linkedin:{name:"LinkedIn",component:s.LinkedIn},twitter:{name:"Twitter",component:s.Twitter},spotify:{name:"Spotify",component:s.Spotify},instagram:{name:"Instagram",component:s.Instagram},tiktok:{name:"Tiktok",component:s.Tiktok},line:{name:"LINE",component:s.Line},twitch:{name:"Twitch",component:s.Twitch},apple:{name:"Apple",component:s.Apple}},_e=({iconUrl:e,...t})=>Z.default.createElement("svg",{width:"33",height:"32",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...t},Z.default.createElement("foreignObject",{x:"2",y:"2",width:"29",height:"28"},Z.default.createElement("img",{src:e,width:"29",height:"28",style:{display:"block",objectFit:"contain",borderRadius:"4px"},alt:"Provider icon"})));const Ie=(e,t)=>{if(e in Se)return Se[e];if(d.isCustomOAuthProvider(e)&&t){let r=t.find((t=>t.provider===e));if(r)return{name:r.provider_display_name,component:e=>Z.default.createElement(_e,{...e,iconUrl:r.provider_icon_url})}}return{name:"Unknown",component:Te}};function Ue(){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:!s.f.get(s.HEADLESS_OAUTH_KEY),popupFlow:null!==window.opener&&i,disableSignup:!!s.f.get(s.OAUTH_DISABLE_SIGNUP_KEY)}}class We{async initRegisterFlow(e){if(!this.api)throw new o.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 o.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 o.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 o.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new o.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(o.passkeyRegisterPath,{relying_party:this.meta.initRegisterResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new o.PrivyClientError("Passkey request timed out or rejected by user.",void 0,o.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw o.formatApiError(e)}}async authenticate(){if(this.authenticateForRegistration)return this.register();let e=await import("@simplewebauthn/browser");if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new o.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(o.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 o.PrivyClientError("Passkey request timed out or rejected by user.",void 0,o.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw o.formatApiError(e)}}async link(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new o.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(o.passkeyLinkPath,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new o.PrivyClientError("Passkey request timed out or rejected by user.",void 0,o.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw o.formatApiError(e)}}async _initRegisterOnce(e){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");let t=fe(e);return await this.api.post(o.passkeyInitRegisterPath,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");let t=fe(e);return await this.api.post(o.passkeyInitAuthenticatePath,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");return await this.api.post(o.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 s.RunEffectOnce(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new s.RunEffectOnce(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new s.RunEffectOnce(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t}}}class Re{async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new o.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessSmsAuthenticatePath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw o.formatApiError(e)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new o.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(o.passwordlessSmsLinkPath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw o.formatApiError(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new o.PrivyClientError("phone nNumber must be set when initialzing authentication.");let n=fe(r);try{return await this.api.post(o.passwordlessSmsInitPath,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw o.formatApiError(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:r}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:r??!1}}}class Oe extends Re{async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new o.PrivyClientError("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(o.updatePhonePath,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw o.formatApiError(e)}}constructor(e,t,r){super({phoneNumber:t,captchaToken:r}),this.meta={phoneNumber:t,captchaToken:r,oldPhoneNumber:e,disableSignup:!1}}}class Me{static parse(e){try{return new Me(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return X.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=X.decodeJwt(e)}}class Ne extends Me{static parse(e){try{return new Ne(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}let je,Fe;class Le extends s.EthereumWalletConnector{async initialize(){await this.importPromise,await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:s.BASE_ACCOUNT_DATA_URI,id:"com.coinbase.wallet"}}async promptConnection(){try{await this.importPromise;let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new o.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw s.formatConnectorError(e)}}constructor(e,t,r,n,i){super("base_account",e,t,r),this.connectorType="base_account",this.walletClientType="base_account",this.displayName="Base",this.setBaseAccountSdk=i,this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.baseAccountConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},je?(this.proxyProvider.setWalletProvider(je.getProvider()),this.setBaseAccountSdk(je),console.log("Base Account SDK Initialized")):this.importPromise=import("@base-org/account").then((({createBaseAccountSDK:e})=>{je=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider(je.getProvider()),this.setBaseAccountSdk(je),console.log("Base Account SDK Initialized")})).catch(console.error)}}let De=[1,11155111,137,10,8453,84532,42161,7777777,43114,56];class qe extends s.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:s.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 o.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw s.formatConnectorError(e)}}updateConnectionPreference(e){this.coinbaseWalletConfig={...this.coinbaseWalletConfig,preference:{...this.coinbaseWalletConfig.preference,options:e}},this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",Fe=h.createCoinbaseWalletSDK({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(Fe.getProvider())}constructor(e,t,r,n){if(super("coinbase_wallet",e,t,r),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.coinbaseWalletConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},this.walletClientType="smartWalletOnly"===this.coinbaseWalletConfig.preference?.options?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!Fe){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter((e=>!De.includes(e))):[];e.length>0&&!e.every((e=>a.DEFAULT_SUPPORTED_CHAIN_IDS.has(e)))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${e.join(", ")}`),Fe=h.createCoinbaseWalletSDK(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(Fe.getProvider())}}class He extends s.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:[s.toHex(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:s.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 Be=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];class ze extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class Ke extends Q.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new ze(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await ui()||!this.address)throw new ze("Disconnected",4900);let{hash:r}=await mi(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new ze(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await ui()||!this.address)throw new ze("Disconnected",4900);let{signature:r}=await yi(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new ze(`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 ze(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=s.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 hi({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 pi(s.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:s.toHex(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...p.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 s.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=>Be.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await ui();if(await wi({address:this.address}),!t||!this.address)throw new ze("Disconnected",4900);try{let r={method:e.method,params:e.params},n=this.walletAccount;return n&&d.getIsUnifiedWallet(n)?this.handleWalletApiRequest(r,n,t):(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:r})).response.data}catch(e){throw console.error(e),new ze("Disconnected",4900)}}}async handleWalletApiRequest(e,t,r){let n=this.privyClient;if(!n)throw new ze("Disconnected",4900);if("secp256k1_sign"===e.method){let i=await a.rpc(n,(async({message:e})=>this.walletProxy.signWithUserSigner({accessToken:r,message:e})),{chain_type:"ethereum",method:"secp256k1_sign",wallet_id:t.id,params:{hash:e.params[0]}});if("secp256k1_sign"!==i.method)throw new ze(`Invalid params for ${e.method}`,4200);return i.data.signature}throw new ze(`Method not supported: ${e.method}`,4200)}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:n,rpcConfig:i,chains:a,appId:o,chainId:l=1,walletIndex:c,privyClient:d,walletAccount:u}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=n,this.chainId=l,this.rpcConfig=i,this.chains=a,this.publicClient=s.getPublicClient(l,this.chains,i,{appId:o}),this.rpcTimeoutDuration=s.getRpcTimeout(i,"privy"),this.appId=o,this.walletIndex=c,this.privyClient=d,this.walletAccount=u}}function Ve(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var $e=0;class Ye extends s.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 o.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw s.formatConnectorError(e)}}constructor(e,t,r,n,i){super(i||"unknown",e,t,r),this.connectorType="injected",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=n;let a=n.provider;this.proxyProvider.setWalletProvider(a)}}var Ge="__private_"+$e+++"__walletBranding";class Ze extends s.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 Ve(this,Ge)[Ge]??{name:"Browser Extension",icon:s.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 o.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw s.formatConnectorError(e)}}constructor(e,t,r,n,i){super(i??"unknown",e,t,r),Object.defineProperty(this,Ge,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new s.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(n),"metamask"===i?Ve(this,Ge)[Ge]={name:"MetaMask",icon:s.Metamask,id:"io.metamask"}:"phantom"===i&&(Ve(this,Ge)[Ge]={name:"Phantom",icon:s.Phantom,id:"phantom"})}}class Je extends Ye{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 o.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw s.formatConnectorError(e)}}}class Xe extends Q.default{get wallets(){let e=new Set;return 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)}))}async initialize(e){if(this.initialized&&!e||(e&&this.removeAllConnectors(),this.externalWalletConfig.disableAllExternalWallets))return;let t=s.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"}),this.walletList.includes("base_account")&&this.createEthereumWalletConnector({connectorType:"base_account",walletClientType:"base_account"}),Object.values(s.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 s.SolanaNullConnector({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,r){return"wallet_connect_v2"===e?this.walletConnectors.filter(s.isEthereumWalletConnector).find((t=>t.connectorType===e&&(!r||t.wallets.some((e=>e.address===r)))))??null:this.walletConnectors.filter(s.isEthereumWalletConnector).find((n=>n.connectorType===e&&n.walletClientType===t&&(!r||n.wallets.some((e=>e.address===r)))))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(s.isSolanaWalletConnector).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}findImportedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded_imported"===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.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&this.emit("walletsUpdated")}addEmbeddedWalletConnectors({walletProxy:e,user:t,embeddedWallets:r,defaultChain:n,appId:i,privyClient:a}){let{entropyId:o,entropyIdVerifier:l}=s.getEntropyDetailsForUser(t);for(let t of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===t.walletIndex));if(r&&s.isEthereumWalletConnector(r))r.proxyProvider.walletProxy=e;else{let r=new He({provider:new Ke({walletProxy:e,address:t.address,entropyId:o,entropyIdVerifier:l,rpcConfig:this.rpcConfig,chains:this.chains,appId:i,chainId:n.id,walletIndex:t.walletIndex,privyClient:a,walletAccount:t}),chains:this.chains,defaultChain:n,rpcConfig:this.rpcConfig,imported:!1,walletIndex:t.walletIndex});this.addWalletConnector(r)}}}addImportedWalletConnector(e,t,r,n){let i=this.findWalletConnector("embedded_imported","privy",t);if(i&&s.isEthereumWalletConnector(i))i.proxyProvider.walletProxy=e;else{let i=new He({provider:new Ke({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.storedConnections=s.loadConnectionHistory(),this.emit("walletsUpdated")}removeImportedWalletConnectors(){let e=this.findImportedWalletConnectors();e.length&&(e.forEach((e=>{let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1)})),this.storedConnections=s.loadConnectionHistory(),this.emit("walletsUpdated"))}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:n}){let i=this.findWalletConnector(e,t);if(i&&s.isEthereumWalletConnector(i))return i instanceof s.WalletConnectV2WalletConnector&&i.resetConnection(t),i;let a=(()=>"injected"!==e?"coinbase_wallet"===e?new qe(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new Le(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new s.WalletConnectV2WalletConnector({walletConnectCloudProjectId:this.walletConnectCloudProjectId,rpcConfig:this.rpcConfig,chains:this.chains,defaultChain:this.defaultChain,shouldEnforceDefaultChainOnConnect:this.shouldEnforceDefaultChainOnConnect,privyAppId:this.privyAppId,privyAppName:this.privyAppName,walletClientType:t}):n?new s.EthereumNullConnector({id:n.client,name:n.name,defaultChain:this.defaultChain,walletClientType:n.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new Je(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Ze(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Ze(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Ze(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new Ye(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)}))}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,o,l,c,d,u,h){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.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=n,this.defaultChain=i,this.walletConnectors=[],this.initialized=!1,this.store=a,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=l,this.externalWalletConfig=c,this.privyAppName=d,this.walletChainType=h||"ethereum-only",this.setBaseAccountSdk=u,this.storedConnections=s.loadConnectionHistory()}}let Qe=[o.sessionsRefreshPath,o.sessionsLogoutPath,o.analyticsEventsPath];class et{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw o.formatApiError(e)}}async post(e,t,r){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...r})}catch(e){throw o.formatApiError(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw o.formatApiError(e)}}constructor({appId:e,appClientId:t,client:r,defaults:n}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=r.clientAnalyticsId,this.sdkVersion=s.VERSION,this.client=r,this.defaults=n,this.fallbackApiUrl=r.fallbackApiUrl,this.baseFetch=y.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=Qe.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 o.PrivyTimeoutError}})}}let tt=/paymaster\.biconomy\.io\/api/i,rt={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const nt=(e,t)=>e&&tt.test(e)?rt:t&&t.policy_id?{policyId:t.policy_id}:void 0,it=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});class at{async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.customJwtAccountAuthenticatePath,{token:this.meta.token})}catch(e){throw o.formatApiError(e)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.customJwtAccountLinkPath,{token:this.meta.token})}catch(e){throw o.formatApiError(e)}}constructor(e){this.meta={token:e}}}class ot{getOrCreateGuestCredential(e){let t=s.getGuestCredentialStorageKey(e);if(s.e$1()){if(s.f.get(t))return s.f.get(t);{let e=c.base64url.encode(s.randomBytes(32));return s.f.put(t,e),e}}return c.base64url.encode(s.randomBytes(32))}async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.guestAccountAuthenticatePath,{guest_credential:this.meta.guestCredential})}catch(e){throw o.formatApiError(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}function st(){return!(n.isSafari&&window.location.origin.startsWith("http://localhost"))}const lt=w.create((()=>({identityToken:null})));var ct,dt=((ct={}).PRIVY="privy_access_token",ct.CUSTOMER="customer_access_token",ct);class ut{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)}get privyAccessToken(){return this._getToken(s.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}_getToken(e){try{let t=s.f.get(e);return"string"==typeof t?Me.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=s.f.get(s.REFRESH_TOKEN_STORAGE_KEY);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=s.f.get(s.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return null;{let r=new Me(t);return r.isExpired()?(s.f.del(s.getProviderAccessTokenStorageKey(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=ee.default.get(s.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!==s.DEPRECATED_REFRESH_TOKEN;return this.mightHaveServerCookies||t&&r}hasActiveAccessToken(e){let t=Me.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?s.f.put(s.getProviderAccessTokenStorageKey(e),t):s.f.del(s.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:d.convertUserResponseToUser(r),isNewUser:n,oAuthTokens:a}}catch(e){throw console.warn("Error authenticating session"),o.formatPrivyError(e)}}_trackAuthenticateEvents(e,t){let r=function(e){return e instanceof ve?"email":e instanceof Re?"sms":e instanceof s.SiweFlow?"siwe":e instanceof ot?"guest":e instanceof at?"custom_auth":e instanceof xe?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:d.convertUserResponseToUser(t),oAuthTokens:n}}catch(e){throw console.warn("Error linking account"),o.formatPrivyError(e)}}async _refresh(){if(!this.api)throw new o.PrivyClientError("Session has no API instance");if(!this.client)throw new o.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(o.sessionsRefreshPath,t?{refresh_token:t}:{},{headers:n})}return this.handleTokenResponse(r),d.convertUserResponseToUser(r.user)}catch(e){if(e instanceof o.PrivyApiError&&e.privyErrorCode===o.PrivyErrorCode.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw o.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(o.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=s.f.get(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY);if(s.f.put(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY,e),!this.client?.useServerCookies){let t=Me.parse(e)?.expiration;ee.default.set(s.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:st(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else s.f.del(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY),ee.default.remove(s.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(s.f.put(s.REFRESH_TOKEN_STORAGE_KEY,e),this.client?.useServerCookies||ee.default.set(s.SESSION_COOKIE_KEY,"t",{sameSite:"Strict",secure:st(),expires:30})):(s.f.del(s.REFRESH_TOKEN_STORAGE_KEY),ee.default.remove(s.REFRESH_TOKEN_COOKIE_KEY),ee.default.remove(s.SESSION_COOKIE_KEY))}storePrivyAccessToken(e){"string"==typeof e?s.f.put(s.PRIVY_ACCESS_TOKEN_STORAGE_KEY,e):s.f.del(s.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}storeIdentityToken(e){if(lt.setState({identityToken:e}),this.client?.useServerCookies)return;s.f.put(s.IDENTITY_TOKEN_STORAGE_KEY,e);let t=Me.parse(e)?.expiration;ee.default.set(s.IDENTITY_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:st(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){s.f.del(s.IDENTITY_TOKEN_STORAGE_KEY),lt.setState({identityToken:null}),ee.default.remove(s.IDENTITY_TOKEN_COOKIE_KEY)}constructor(){this.authenticateOnce=new s.RunEffectOnce((async e=>this._authenticate(e))),this.linkOnce=new s.RunEffectOnce((async e=>this._link(e))),this.refreshOnce=new s.RunEffectOnce(this._refresh.bind(this)),this.destroyOnce=new s.RunEffectOnce(this._destroy.bind(this))}}let ht;var pt=0,yt="__private_"+pt+++"__getOrGenerateClientAnalyticsId";class mt{getAppId(){return this.appId}initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:n,store:i,walletList:a,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c,setBaseAccountSdk:d}){this.connectors||(this.connectors=new Xe(this.appId,e,t,r,n,i,a,o,s,l,d,c))}generateApi(){let e=new et({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 o.PrivyClientError("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new o.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(o.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw o.formatApiError(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(o.mfaPasskeyInitPath,{});return it(e.options)}catch(e){throw o.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(o.acceptTermsPath,{});return d.convertUserResponseToUser(e)}catch(e){throw o.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(o.unlinkEmailPath,{address:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async unlinkPhone(e){try{let t=await this.api.post(o.unlinkPhonePath,{phoneNumber:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(o.unlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(o.siwsUnlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(o.unlinkOAuthPath,{provider:e,subject:t});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(r)}catch(e){throw o.formatPrivyError(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(o.unlinkFarcasterPath,{fid:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async unlinkTelegram(e){try{let t=await this.api.post(o.telegramAccountUnlinkPath,{telegram_user_id:e});return await this.getAuthenticatedUser()??d.convertUserResponseToUser(t)}catch(e){throw o.formatPrivyError(e)}}async revokeDelegatedWallet(){try{await this.api.post(o.delegatedActionsRevokePath,{})}catch(e){throw o.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(o.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(o.moonpayPluginOnRampPath,e)}catch(e){throw o.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(o.coinbaseOnRampInitPath,e)}catch(e){throw o.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${o.coinbaseOnRampStatusPath}?partnerUserId=${e}`)}catch(e){throw o.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(dt.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(dt.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?Ne.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,smartWalletVersion:r.smart_wallet_version,smartWalletType:r.smart_wallet_type,configuredNetworks:r.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:nt(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw o.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(o.siweInitPath,{address:e,token:t})).nonce}catch(e){throw o.formatPrivyError(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i,mode:a}){return await this.api.post(o.siweAuthenticatePath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:i,mode:a})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}){return await this.api.post(o.siweLinkPath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})}async linkSmartWallet({message:e,signature:t,smartWalletType:r,smartWalletVersion:n}){try{let i=await this.api.post(o.smartWalletLinkPath,{message:e,signature:t,smart_wallet_type:r,smart_wallet_version:n});return d.convertUserResponseToUser(i)}catch(e){throw o.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 d.convertUserResponseToUser(a)}catch(e){throw o.formatPrivyError(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(o.siwsInitPath,{address:e,token:t})).nonce}catch(e){throw o.formatPrivyError(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:i,messageType:a="plain"}){return await this.api.post(o.siwsAuthenticatePath,{message:e,signature:t,walletClientType:r,connectorType:n,mode:i,message_type:a})}async authenticateWithSiws({message:e,signature:t,walletClientType:r,connectorType:n,mode:i,messageType:a="plain"}){let o=await this.authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:i,messageType:a});this.session.handleTokenResponse(o);let s=d.convertUserResponseToUser(o.user);if(!s)throw Error("Authentication failed - no user returned");return{user:s,isNewUser:o.is_new_user||!1}}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,telegramWebAppData:a,farcasterEmbeddedAddress:s,oAuthUserInfo:l}){try{let c,u;switch(r){case"email":c=o.transferEmailPath,u={nonce:e,email:t};break;case"sms":c=o.transferPhonePath,u={nonce:e,phoneNumber:t};break;case"siwe":if(c=o.transferWalletPath,!n)throw Error("Wallet parameters must be defined");u={nonce:e,address:t,...n};break;case"farcaster":c=o.transferFarcasterPath,u={nonce:e,farcaster_id:t,farcaster_embedded_address:s};break;case"telegram":c=o.telegramAccountTransferPath,u={nonce:e,telegram_auth_result:i,telegram_web_app_data:a};break;case"siws":c=o.siwsTransferPath,u={nonce:e,address:t,...n};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:c=o.transferOAuthPath,u={nonce:e,userInfo:l}}let h=await this.api.post(c,u);return await this.getAuthenticatedUser()??d.convertUserResponseToUser(h)}catch(e){throw o.formatPrivyError(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,messageType:i="plain"}){return await this.api.post(o.siwsLinkPath,{message:e,signature:t,walletClientType:r,connectorType:n,message_type:i})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:n,messageType:i="plain"}){try{let a=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,messageType:i});return d.convertUserResponseToUser(a)}catch(e){throw o.formatPrivyError(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(o.usersMePath);return this.session.updateIdentityToken(e.identity_token),d.convertUserResponseToUser(e.user)}catch(e){throw o.formatPrivyError(e)}}async scanTransaction(e){try{return await this.api.post(o.transactionScanningPath,e)}catch(e){throw o.formatPrivyError(e)}}constructor({apiUrl:e=s.DEFAULT_PRIVY_API_URL,appId:t,appClientId:r,timeout:n=s.DEFAULT_API_TIMEOUT_MS}){Object.defineProperty(this,yt,{value:wt}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==s.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,yt)[yt](),ht||(ht=new ut),this.session=ht,this.api=this.generateApi(),this.session.client=this}}function wt(){if("undefined"==typeof window)return null;try{let e=s.f.get(s.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=l.v4();try{return s.f.put(s.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}const gt=({delayedExecution:t,...n})=>{let{enabled:i,siteKey:a,appId:o,setError:l,setToken:c,setExecuting:d,ref:u}=s.useCaptcha(),[,h]=r.useMemo((()=>a?.split("t:")||[]),[a]);if(r.useEffect((()=>u.current?.remove),[]),!i)return null;if(!h)throw Error("Unsupported captcha site key");/*#__PURE__*/return e.jsx("div",{className:"hidden h-0 w-0",children:/*#__PURE__*/e.jsx(g.Turnstile,{...n,ref:u,siteKey:h,options:{action:o,size:"invisible",...t?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{n.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:()=>{n.onError?.(),l("Captcha failed"),d(!1)},onSuccess:e=>{n.onSuccess?.(e),c(e),d(!1)},onExpire:()=>{n.onExpire?.();try{u.current?.reset(),l(void 0),c(void 0)}catch(e){l("expired_and_failed_reset")}}})})};function ft(e){s.usePrivyEventSubscription("configureMfa",e)}const vt=/*#__PURE__*/f.styled.div.withConfig({displayName:"AppLogoContainer",componentId:"sc-ba98f772-0"})(["display:flex;flex-direction:column;align-items:center;padding:0px 0px 30px;@media (max-width:440px){padding:10px 10px 20px;}"]),Ct=/*#__PURE__*/f.styled.div.withConfig({displayName:"Title",componentId:"sc-ba98f772-1"})(["font-size:18px;line-height:30px;text-align:center;font-weight:600;margin-bottom:10px;"]),Et=/*#__PURE__*/f.styled.div.withConfig({displayName:"SubTitle",componentId:"sc-ba98f772-2"})(["font-size:0.875rem;text-align:center;"]),At=/*#__PURE__*/f.styled.div.withConfig({displayName:"Container",componentId:"sc-ba98f772-3"})(["display:flex;flex-direction:column;align-items:center;gap:10px;flex-grow:1;padding:20px 0;@media (max-width:440px){padding:10px 10px 20px;}"]),Pt=/*#__PURE__*/f.styled.div.withConfig({displayName:"List",componentId:"sc-ba98f772-4"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.75rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),kt=/*#__PURE__*/f.styled.div.withConfig({displayName:"ListItemIcon",componentId:"sc-ba98f772-5"})(["width:25px;display:flex;align-items:center;justify-content:flex-start;> svg{z-index:2;height:25px !important;width:25px !important;color:var(--privy-color-accent);}"]),bt=/*#__PURE__*/f.styled.div.withConfig({displayName:"ListItem",componentId:"sc-ba98f772-6"})(["display:flex;align-items:center;gap:10px;font-size:0.875rem;line-height:1rem;text-align:left;"]),xt=/*#__PURE__*/f.styled.div.withConfig({displayName:"BottomSection",componentId:"sc-ba98f772-7"})(["display:flex;flex-direction:column;gap:10px;padding-top:20px;"]),Tt=/*#__PURE__*/f.styled.div.withConfig({displayName:"MethodList",componentId:"sc-ba98f772-8"})(["display:flex;flex-direction:column;align-items:stretch;gap:1rem;padding:1rem 0rem 0rem;flex-grow:1;width:100%;"]),St=/*#__PURE__*/f.styled.div.withConfig({displayName:"MethodListItem",componentId:"sc-ba98f772-9"})(["display:flex;gap:5px;width:100%;position:relative;"]),_t=/*#__PURE__*/f.styled.button.withConfig({displayName:"RemoveMethodButton",componentId:"sc-ba98f772-10"})(["&&{background-color:transparent;color:var(--privy-color-foreground-3);padding:0 0.75rem;display:flex;align-items:center;height:100%;> svg{z-index:2;height:20px !important;width:20px !important;}}&&:hover{color:var(--privy-color-error);}"]),It=/*#__PURE__*/f.styled.div.withConfig({displayName:"MethodText",componentId:"sc-ba98f772-11"})(["display:flex;align-items:center;gap:0.5rem;> svg{z-index:2;height:20px !important;width:20px !important;}"]),Ut=/*#__PURE__*/f.styled.div.withConfig({displayName:"ExtraText",componentId:"sc-ba98f772-12"})(["display:flex;align-items:center;gap:6px;font-weight:400 !important;color:",";> svg{z-index:2;height:18px !important;width:18px !important;display:flex !important;align-items:flex-end;}"],(e=>e.$isAccent?"var(--privy-color-accent)":"var(--privy-color-foreground-3)")),Wt=/*#__PURE__*/f.styled.div.withConfig({displayName:"SmsInsecureText",componentId:"sc-ba98f772-13"})(["width:100%;display:flex;justify-content:space-between;"]),Rt=/*#__PURE__*/f.styled.p.withConfig({displayName:"TermsText",componentId:"sc-ba98f772-14"})(["text-align:left;width:100%;color:var(--privy-color-foreground-3) !important;"]),Ot=/*#__PURE__*/f.styled.button.withConfig({displayName:"PrimaryTextButton",componentId:"sc-ba98f772-15"})(["display:flex;flex-direction:row;align-items:center;justify-content:center;user-select:none;&{width:100%;cursor:pointer;border-radius:var(--privy-border-radius-md);font-size:0.875rem;line-height:1rem;font-style:normal;font-weight:500;line-height:22px;letter-spacing:-0.016px;}&&{color:",";background-color:transparent;padding:0.5rem 0px;}&:hover{text-decoration:underline;}"],(e=>"dark"===e.theme?"var(--privy-color-foreground-2)":"var(--privy-color-accent)")),Mt=/*#__PURE__*/f.styled.div.withConfig({displayName:"IconWrapper",componentId:"sc-ba98f772-16"})(["display:flex;align-items:center;justify-content:center;color:var(--privy-color-accent);width:100%;> svg{z-index:2;width:3rem;height:3rem;}"]),Nt=/*#__PURE__*/f.styled.div.withConfig({displayName:"ErrorMessage",componentId:"sc-ba98f772-17"})(["color:var(--privy-color-error);"]),jt=({handleClose:t,user:r,onSelect:n})=>/*#__PURE__*/e.jsxs(s.ScreenLayout,{title:"Verify your identity",subtitle:"Choose a verification method",icon:ie.default,iconVariant:"subtle",onClose:t,showClose:!0,watermark:!0,children:[/*#__PURE__*/e.jsxs(Tt,{children:[r.mfaMethods.includes("totp")&&/*#__PURE__*/e.jsxs(s.LoginMethodButton,{onClick:()=>n("totp"),children:[/*#__PURE__*/e.jsx(s.LoginMethodIconWrapper,{children:/*#__PURE__*/e.jsx(te.default,{})}),"Authenticator app"]},"totp"),r.mfaMethods.includes("sms")&&/*#__PURE__*/e.jsxs(s.LoginMethodButton,{onClick:()=>n("sms"),children:[/*#__PURE__*/e.jsx(s.LoginMethodIconWrapper,{children:/*#__PURE__*/e.jsx(ne.default,{})}),"SMS"]},"sms"),r.mfaMethods.includes("passkey")&&/*#__PURE__*/e.jsxs(s.LoginMethodButton,{onClick:()=>n("passkey"),children:[/*#__PURE__*/e.jsx(s.LoginMethodIconWrapper,{children:/*#__PURE__*/e.jsx(re.default,{})}),"Passkey"]},"passkey")]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}),Ft=({pendingTransaction:t})=>{let{wallets:n}=s.useWallets(),{walletProxy:i,rpcConfig:a,chains:o,appId:l,nativeTokenSymbolForChainId:c}=v.usePrivyInternal(),[d,u]=r.useState(null),[h,p]=r.useState(t),{tokenPrice:y}=s.useGetTokenPrice(h.chainId),m=c(t.chainId)||"ETH",w=r.useMemo((()=>n.find((e=>"privy"===e.walletClientType))),[n]);return r.useEffect((()=>{(async function(){if(!i||!w)return h;let e=s.getPublicClient(h.chainId,o,a,{appId:l}),t=await s.prepareTransactionRequest(h,e,w.address);return u(T.toHex(BigInt(t.gas??0))),t})().then(p).catch(console.error)}),[i]),w?/*#__PURE__*/e.jsx(Lt,{children:/*#__PURE__*/e.jsx(s.TransactionDetails,{from:w.address,to:h.to,txn:h,gas:d??void 0,tokenPrice:y,tokenSymbol:m})}):null};let Lt=/*#__PURE__*/f.styled.div.withConfig({displayName:"TransactionInfoWrapper",componentId:"sc-8d9a2f57-0"})(["width:100%;padding:1rem 0;"]);const Dt=({style:t,...r})=>/*#__PURE__*/e.jsx("svg",{x:0,y:0,width:"65",height:"64",viewBox:"0 0 65 64",style:{height:"64px",width:"65px",...t},fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M3.71369 17.5625V10.375C3.71369 6.44625 6.85845 3.25 10.7238 3.25H17.7953C18.6783 3.25 19.3941 2.52244 19.3941 1.625C19.3941 0.727562 18.6783 0 17.7953 0H10.7238C5.09529 0 0.516113 4.65419 0.516113 10.375V17.5625C0.516113 18.4599 1.23194 19.1875 2.1149 19.1875C2.99787 19.1875 3.71369 18.4599 3.71369 17.5625ZM17.7953 60.7501C18.6783 60.7501 19.3941 61.4777 19.3941 62.3751C19.3941 63.2726 18.6783 64.0001 17.7953 64.0001H10.7238C5.09529 64.0001 0.516113 59.3459 0.516113 53.6251V46.4376C0.516113 45.5402 1.23194 44.8126 2.1149 44.8126C2.99787 44.8126 3.71369 45.5402 3.71369 46.4376V53.6251C3.71369 57.5538 6.85845 60.7501 10.7238 60.7501H17.7953ZM63.4839 46.4376V53.6251C63.4839 59.3459 58.9048 64.0001 53.2763 64.0001H46.2047C45.3217 64.0001 44.6059 63.2726 44.6059 62.3751C44.6059 61.4777 45.3217 60.7501 46.2047 60.7501H53.2763C57.1416 60.7501 60.2864 57.5538 60.2864 53.6251V46.4376C60.2864 45.5402 61.0022 44.8126 61.8851 44.8126C62.7681 44.8126 63.4839 45.5402 63.4839 46.4376ZM63.4839 10.375V17.5625C63.4839 18.4599 62.7681 19.1875 61.8851 19.1875C61.0022 19.1875 60.2864 18.4599 60.2864 17.5625V10.375C60.2864 6.44625 57.1416 3.25 53.2763 3.25H46.2047C45.3217 3.25 44.6059 2.52244 44.6059 1.625C44.6059 0.727562 45.3217 0 46.2047 0H53.2763C58.9048 0 63.4839 4.65419 63.4839 10.375ZM43.0331 47.3022C43.7067 46.6698 43.7483 45.6022 43.1262 44.9176C42.5039 44.233 41.4536 44.1906 40.78 44.823C38.3832 47.0732 35.265 48.3125 31.9997 48.3125C28.7344 48.3125 25.6162 47.0732 23.2194 44.823C22.5457 44.1906 21.4955 44.233 20.8732 44.9176C20.251 45.6022 20.2927 46.6698 20.9663 47.3022C23.9784 50.1301 27.8968 51.6875 31.9997 51.6875C36.1026 51.6875 40.021 50.1301 43.0331 47.3022ZM35.3207 24.1249V36.1249C35.3207 38.5029 33.4173 40.4374 31.0777 40.4374H29.7249C28.8079 40.4374 28.0646 39.6819 28.0646 38.7499C28.0646 37.8179 28.8079 37.0624 29.7249 37.0624H31.0777C31.5863 37.0624 32.0001 36.6419 32.0001 36.1249V24.1249C32.0001 23.1929 32.7434 22.4374 33.6604 22.4374C34.5774 22.4374 35.3207 23.1929 35.3207 24.1249ZM46.7581 28.8437V24.0312C46.7581 23.151 46.056 22.4374 45.19 22.4374C44.324 22.4374 43.622 23.151 43.622 24.0312V28.8437C43.622 29.7239 44.324 30.4374 45.19 30.4374C46.056 30.4374 46.7581 29.7239 46.7581 28.8437ZM17.6109 28.8437C17.6109 29.7239 18.313 30.4374 19.1789 30.4374C20.0449 30.4374 20.747 29.7239 20.747 28.8437V24.0312C20.747 23.151 20.0449 22.4374 19.1789 22.4374C18.313 22.4374 17.6109 23.151 17.6109 24.0312V28.8437Z"})}),qt=({hasBlockingError:t,error:r,onClose:n,onBack:i,handleSubmit:a,account:o,submitSuccess:l})=>{let{pendingTransaction:c}=v.usePrivyInternal();/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:n},"header"),/*#__PURE__*/e.jsx(s.e$2,{children:/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(s.ConnectionLoader,{success:l,fail:!!r}),r?/*#__PURE__*/e.jsx(oe.default,{style:{width:"38px",height:"38px"}}):/*#__PURE__*/e.jsx(Dt,{style:{width:"38px",height:"38px"}})]})}),/*#__PURE__*/e.jsx(Ct,{style:{marginTop:"1rem"},children:"Verifying with passkey"}),/*#__PURE__*/e.jsxs(Pt,{children:[/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(ie.default,{})}),"Approve this action using your touch, face, PIN, or hardware key."]}),/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(ae.default,{})}),"You last added a passkey on"," ",o?.firstVerifiedAt?.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),"."]})]}),c&&/*#__PURE__*/e.jsx(At,{children:/*#__PURE__*/e.jsx(Ft,{pendingTransaction:c})}),r&&/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(Nt,{style:{marginTop:"1.25rem"},children:r.message}),/*#__PURE__*/e.jsx(s.PrimaryButton,{disabled:t,onClick:a,style:{margin:"1.25rem auto 0"},children:"Try again"})]}),i&&/*#__PURE__*/e.jsx(Ot,{style:{marginTop:"1rem"},onClick:i,children:"Choose another method"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})};let Ht=Array(6).fill("");var Bt,zt=((Bt=zt||{})[Bt.RESET_AFTER_DELAY=0]="RESET_AFTER_DELAY",Bt[Bt.CLEAR_ON_NEXT_VALID_INPUT=1]="CLEAR_ON_NEXT_VALID_INPUT",Bt);function Kt(e){return/^[0-9]{1}$/.test(e)}function Vt(e){return 6===e.length&&e.every(Kt)}const $t=({onChange:t,disabled:i,errorReasonOverride:a,success:o})=>{let[s,l]=r.useState(Ht),[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(Kt(t))),0),i=r.split(""),a=!i.every(Kt),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(),Vt(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(Yt,{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()}Vt(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(Gt,{$fail:!!a||!!c,children:a||c})})]})})};let Yt=/*#__PURE__*/f.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);}}"]),Gt=/*#__PURE__*/f.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 Zt=({selectedMethod:t,submitSuccess:r,hasBlockingError:n,onClose:i,onBack:a,handleSubmitCode:o})=>{let l=s.useAppConfig(),{pendingTransaction:c}=v.usePrivyInternal();switch(t){case"sms":/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:i},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ne.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Enter verification code"}),/*#__PURE__*/e.jsxs(At,{children:[/*#__PURE__*/e.jsx($t,{success:r,disabled:n,onChange:o}),/*#__PURE__*/e.jsxs(Et,{children:["To continue, please enter the 6-digit code sent to your ",/*#__PURE__*/e.jsx("strong",{children:"mobile device"})]}),c&&/*#__PURE__*/e.jsx(Ft,{pendingTransaction:c})]}),a&&/*#__PURE__*/e.jsx(Ot,{theme:l?.appearance.palette.colorScheme,onClick:a,children:"Choose another method"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:i,children:"Cancel"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});case"totp":/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:i},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(te.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Enter verification code"}),/*#__PURE__*/e.jsxs(At,{children:[/*#__PURE__*/e.jsx($t,{success:r,disabled:n,onChange:o}),/*#__PURE__*/e.jsxs(Et,{children:["To continue, please enter the 6-digit code generated from your"," ",/*#__PURE__*/e.jsx("strong",{children:"authenticator app"})]}),c&&/*#__PURE__*/e.jsx(Ft,{pendingTransaction:c})]}),a&&/*#__PURE__*/e.jsx(Ot,{theme:l?.appearance.palette.colorScheme,onClick:a,children:"Choose another method"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:i,children:"Cancel"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});default:return null}},Jt=e=>s.errorIndicatesMaxMfaRetries(e)?{isBlocking:!0,error:Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.")}:s.errorIndicatesMfaVerificationFailed(e)?{isBlocking:!1,error:Error("The code you entered is not valid")}:s.errorIndicatesMfaTimeout(e)?{isBlocking:!0,error:Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.")}:(console.error(e),{isBlocking:!1,error:Error("Something went wrong.")}),Xt={component:()=>{let{user:t}=d.usePrivyContext(),{data:n}=s.usePrivyModal(),[i,a]=r.useState(t?.mfaMethods[0]),[o,l]=r.useState(!1),[c,u]=r.useState(),[h,p]=r.useState();if(r.useEffect((()=>{a(t?.mfaMethods[0])}),[t?.mfaMethods]),!n?.mfaVerify)throw Error("Missing modal data for MFA verification screen.");let{onFailure:y,onSuccess:m,generateOptions:w,verifyTotpCode:g,verifyPasskey:f,verifySmsCode:v,sendSmsCode:C}=n.mfaVerify,E=async e=>{if("passkey"!==e)try{a(e),"sms"===e&&(a(e),await C()),"totp"===e&&a(e)}catch(e){console.error(e)}else try{a(e);let t=await w();if(!t)throw Error("something went wrong");u(t),await f(t),l(!0),p(void 0),m()}catch(e){p(Jt(e))}},A=async e=>{p(void 0);try{if(!e||!i)return;if("passkey"===i){if(!c)throw Error("Missing passkey challenge");await f(c)}else"sms"===i?await v(e):"totp"===i&&await g(e);p(void 0),l(!0),m()}catch(e){throw Jt(e).error}},P=()=>{h||!o?y(h?.error??Error("Canceled MFA verification.")):m()},k=r.useRef(!1);return r.useEffect((()=>{!k.current&&i&&(k.current=!0,E(i).finally((()=>{k.current=!1})))}),[open]),t?"passkey"===i?/*#__PURE__*/e.jsx(qt,{account:t.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],submitSuccess:o,hasBlockingError:h?.isBlocking??!1,error:h?.error,onClose:P,onBack:()=>{a(void 0),p(void 0)},handleSubmit:()=>A(c).catch(p)}):"sms"===i||"totp"===i?/*#__PURE__*/e.jsx(Zt,{selectedMethod:i,submitSuccess:o,hasBlockingError:h?.isBlocking??!1,handleSubmitCode:A,onClose:P,onBack:t.mfaMethods.length>1?()=>a(void 0):void 0}):/*#__PURE__*/e.jsx(jt,{user:t,onSelect:E,handleClose:P}):null}};function Qt(){let{promptMfa:e,init:t,submit:n,cancel:i,mfaMethods:a}=r.useContext(d.PrivyContext);return{promptMfa:e,init:t,submit:n,cancel:i,mfaMethods:a}}const er=({onClose:t})=>{let{user:n}=d.usePrivyContext(),[i,a]=r.useState(n?.mfaMethods[0]??null),{init:o,cancel:s,submit:l}=Qt(),[c,u]=r.useState(!1),[h,p]=r.useState(null),[y,m]=r.useState();r.useEffect((()=>{a(n?.mfaMethods[0]??null)}),[n?.mfaMethods]);let w=r.useRef(!1);async function g(e){m(void 0);try{if(!e||!i)return;await l(i,e),u(!0),m(void 0),t()}catch(e){throw Jt(e).error}}async function f(e){if("passkey"!==e)try{a(e),await o(e)}catch(e){console.error(e)}else try{a(e);let r=await o(e);if(!r)throw Error("something went wrong");p(r),await l(e,r),u(!0),m(void 0),t()}catch(e){m(Jt(e))}}r.useEffect((()=>{!w.current&&i&&(w.current=!0,f(i).finally((()=>{w.current=!1})))}),[]);let v=()=>{a(null),m(void 0),s(),t()};return n?"passkey"===i?/*#__PURE__*/e.jsx(qt,{account:n.linkedAccounts.filter((e=>"passkey"===e.type&&e.enrolledInMfa)).sort(((e,t)=>t.firstVerifiedAt.valueOf()-e.firstVerifiedAt.valueOf()))[0],submitSuccess:c,hasBlockingError:y?.isBlocking??!1,error:y?.error,onClose:v,onBack:()=>{a(null),m(void 0)},handleSubmit:()=>g(h).catch(m)}):i?/*#__PURE__*/e.jsx(Zt,{submitSuccess:c,hasBlockingError:y?.isBlocking??!1,handleSubmitCode:g,selectedMethod:i,onClose:v,onBack:n.mfaMethods.length>1?()=>a(null):void 0}):/*#__PURE__*/e.jsx(jt,{user:n,onSelect:f,handleClose:v}):null},tr=w.create((()=>({inProgressMfaFlow:void 0})));const rr=/*#__PURE__*/f.createGlobalStyle([":root{","};"],(e=>nr(e.palette)));const nr=e=>
2
+ /*#__PURE__*/f.css(["",""],Object.entries(function(e){return{"--privy-color-background":e.background,"--privy-color-background-2":e.background2,"--privy-color-background-3":e.background3,"--privy-color-foreground":e.foreground,"--privy-color-foreground-2":e.foreground2,"--privy-color-foreground-3":e.foreground3,"--privy-color-foreground-4":e.foreground4,"--privy-color-foreground-accent":e.foregroundAccent,"--privy-color-accent":e.accent,"--privy-color-accent-light":e.accentLight,"--privy-color-accent-hover":e.accentHover,"--privy-color-accent-dark":e.accentDark,"--privy-color-accent-darkest":e.accentDarkest,"--privy-color-success":e.success,"--privy-color-success-dark":e.successDark,"--privy-color-success-light":e.successLight,"--privy-color-success-bg":e.successBg,"--privy-color-error":e.error,"--privy-color-error-light":e.errorLight,"--privy-color-error-bg":e.errorBg,"--privy-color-error-bg-hover":e.errorBgHover,"--privy-color-warn":e.warn,"--privy-color-warn-light":e.warnLight,"--privy-color-warn-bg":e.warnBg,"--privy-color-warning-dark":e.warningDark,"--privy-color-error-dark":e.errorDark,"--privy-color-info-bg":e.infoBg,"--privy-color-info-bg-hover":e.infoBgHover,"--privy-color-border-default":e.borderDefault,"--privy-color-border-hover":e.borderHover,"--privy-color-border-focus":e.borderFocus,"--privy-color-border-error":e.borderError,"--privy-color-border-success":e.borderSuccess,"--privy-color-border-warning":e.borderWarning,"--privy-color-border-info":e.borderInfo,"--privy-color-border-interactive":e.borderInteractive,"--privy-color-border-interactive-hover":e.borderInteractiveHover,"--privy-color-background-hover":e.backgroundHover,"--privy-color-background-clicked":e.backgroundClicked,"--privy-color-background-disabled":e.backgroundDisabled,"--privy-color-background-interactive":e.backgroundInteractive,"--privy-color-background-interactive-hover":e.backgroundInteractiveHover,"--privy-color-background-interactive-clicked":e.backgroundInteractiveClicked,"--privy-color-background-interactive-disabled":e.backgroundInteractiveDisabled,"--privy-color-foreground-hover":e.foregroundHover,"--privy-color-foreground-clicked":e.foregroundClicked,"--privy-color-foreground-disabled":e.foregroundDisabled,"--privy-color-foreground-interactive":e.foregroundInteractive,"--privy-color-foreground-interactive-hover":e.foregroundInteractiveHover,"--privy-link-navigation-color":e.linkNavigationColor,"--privy-link-navigation-decoration":e.linkNavigationDecoration,"--privy-accent-has-good-contrast":e.accentHasGoodContrast,"--privy-color-icon-default":e.iconDefault,"--privy-color-icon-muted":e.iconMuted,"--privy-color-icon-subtle":e.iconSubtle,"--privy-color-icon-inverse":e.iconInverse,"--privy-color-icon-success":e.iconSuccess,"--privy-color-icon-warning":e.iconWarning,"--privy-color-icon-error":e.iconError,"--privy-color-icon-interactive":e.iconInteractive,"--privy-color-icon-default-hover":e.iconDefaultHover,"--privy-color-icon-muted-hover":e.iconMutedHover,"--privy-color-icon-subtle-hover":e.iconSubtleHover,"--privy-color-icon-default-clicked":e.iconDefaultClicked,"--privy-color-icon-muted-clicked":e.iconMutedClicked,"--privy-color-icon-subtle-clicked":e.iconSubtleClicked,"--privy-color-icon-default-disabled":e.iconDefaultDisabled,"--privy-color-icon-muted-disabled":e.iconMutedDisabled,"--privy-color-icon-subtle-disabled":e.iconSubtleDisabled,"--privy-color-icon-error-hover":e.iconErrorHover,"--privy-color-icon-interactive-hover":e.iconInteractiveHover,"--privy-color-icon-error-clicked":e.iconErrorClicked,"--privy-color-icon-interactive-clicked":e.iconInteractiveClicked,"--privy-color-icon-muted-disabled-alt":e.iconMutedDisabledAlt,"--privy-color-icon-subtle-disabled-alt":e.iconSubtleDisabledAlt,"--privy-border-radius-xs":"6px","--privy-border-radius-sm":"8px","--privy-border-radius-md":"12px","--privy-border-radius-mdlg":"16px","--privy-border-radius-lg":"24px","--privy-border-radius-full":"9999px","--privy-height-modal-full":"620px","--privy-height-modal-compact":"480px"}}(e)).map((([e,t])=>`${e}: ${t};`)).join("\n")),ir=/*#__PURE__*/f.styled.div.withConfig({displayName:"StylesWrapper",componentId:"sc-188229e4-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 3px var(--privy-color-border-focus);}.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"),ar=({children:t,open:r,onClick:n,...i})=>/*#__PURE__*/e.jsx(S.Transition,{show:r,as:Z.default.Fragment,children:/*#__PURE__*/e.jsxs(S.Dialog,{onClose:n,...i,as:sr,children:[/*#__PURE__*/e.jsx(S.TransitionChild,{as:Z.default.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/e.jsx(or,{id:"privy-dialog-backdrop","aria-hidden":"true"})}),/*#__PURE__*/e.jsx(lr,{children:/*#__PURE__*/e.jsx(S.TransitionChild,{as:Z.default.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/e.jsx(S.DialogPanel,{as:cr,children:t})})})]})});let or=/*#__PURE__*/f.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;}"]),sr=/*#__PURE__*/f.styled.div.withConfig({displayName:"DialogWrapper",componentId:"sc-3cfde0b5-1"})(["position:relative;z-index:999999;"]),lr=/*#__PURE__*/f.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 cr=/*#__PURE__*/f.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);}"]),dr=/*#__PURE__*/f.styled.div.withConfig({displayName:"CenterItem",componentId:"sc-3cfde0b5-4"})(["display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;"]);let ur=()=>{let{ready:t,isModalOpen:n}=d.usePrivyContext(),{headless:i}=s.useAppConfig(),{currentScreen:a}=s.usePrivyModal(),{status:o,execute:l,reset:c,enabled:u}=s.useCaptcha(),h=tr((e=>e.inProgressMfaFlow)),p=()=>tr.setState({inProgressMfaFlow:void 0}),y=n&&a&&a.isCaptchaRequired&&!i&&"ready"===o;return r.useEffect((()=>{y&&l()}),[y]),r.useEffect((()=>{!n&&u&&c()}),[n,u]),a&&!t&&a.isShownBeforeReady?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{}),/*#__PURE__*/e.jsx(s.RefactorSpacerTop,{}),/*#__PURE__*/e.jsx(dr,{children:/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsx(s.RefactorSpacerBottom,{}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):a||"txn"!==h?a?
3
+ /*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.Hide,{$if:!!h,children:/*#__PURE__*/e.jsx(a.component,{})}),"txn"===h&&/*#__PURE__*/e.jsx(er,{onClose:p}),"auth"===h&&/*#__PURE__*/e.jsx(Xt.component,{})]}):null:/*#__PURE__*/e.jsx(er,{onClose:p})},hr=()=>{let t=r.useRef(null);/*#__PURE__*/return e.jsx(mr,{style:{height:C.useElementHeight(t)},id:"privy-modal-content",children:/*#__PURE__*/e.jsx("div",{ref:t,children:/*#__PURE__*/e.jsx(ur,{})})})};const pr=({open:t})=>{let n=s.useAppConfig(),{gracefulClosePrivyModal:i}=(()=>{let{closePrivyModal:e}=v.usePrivyInternal(),{onUserCloseViaDialogOrKeybindRef:t}=s.usePrivyModal();return{gracefulClosePrivyModal:r.useCallback((()=>{if(!t?.current)return e({shouldCallAuthOnSuccess:!1});t.current()}),[e])}})(),a=tr((e=>e.inProgressMfaFlow));return ft({onMfaRequired:()=>{n.mfa.noPromptOnMfaRequired||tr.setState({inProgressMfaFlow:"txn"})}}),n.render.standalone?/*#__PURE__*/e.jsx(ir,{children:/*#__PURE__*/e.jsx(yr,{id:"privy-modal-content",children:/*#__PURE__*/e.jsx(ur,{})})}):/*#__PURE__*/e.jsx(ar,{open:!(!t&&!a),id:"privy-dialog","aria-label":"log in or sign up","aria-labelledby":"privy-dialog-title",onClick:()=>i(),children:/*#__PURE__*/e.jsx(ir,{children:/*#__PURE__*/e.jsx(hr,{})})})};let yr=/*#__PURE__*/f.styled.div.withConfig({displayName:"ContentWrapper",componentId:"sc-b220e1ee-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;"]),mr=/*#__PURE__*/f.styled(yr).withConfig({displayName:"BaseModal",componentId:"sc-b220e1ee-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 wr(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})}const gr=()=>{let{ready:e}=s.useWallets(),{client:t}=v.usePrivyInternal();return r.useEffect((()=>{let r=()=>{if(!t.connectors||!e)return;let r=t.connectors.wallets.map((e=>({address:e.address,connectorType:e.connectorType,walletClientType:e.walletClientType,connectedAt:e.connectedAt,id:e.meta.id})));s.f.put(s.CONNECTIONS_HISTORY_KEY,r)};return t.connectors?.on("walletsUpdated",r),()=>{t.connectors?.off("walletsUpdated",r)}}),[e,t.connectors]),null};async function fr(e,t,r,n,i,a=!1){let o=a,l=async l=>{if(o&&t&&t.length>0){l===(a?0:1)?i("configureMfa","onMfaRequired",{mfaMethods:t}):n.current?.reject(new s.PrivyIframeError("missing_or_invalid_mfa","MFA verification failed, retry."));let o=await new Promise(((e,t)=>{r.current={resolve:e,reject:t},setTimeout((()=>{let e=new s.PrivyIframeError("mfa_timeout","Timed out waiting for MFA code");n.current?.reject(e),t(e)}),3e5)}));return await e(o)}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;o=!0}if(null===c){let e=new s.PrivyIframeError("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw n.current?.reject(e),e}return c}var vr;let Cr=(vr=0,()=>"id-"+vr++);function Er(e){return void 0!==e.error}let Ar=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:user-signer:sign":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={}}},Pr=new Map,kr=(e,t)=>"bigint"==typeof t?t.toString():t;function br(e,t,r,n){let i=r.contentWindow;if(!i)throw Error("iframe not initialized");let a=((e,t)=>`${e}${JSON.stringify(t,kr)}`)(e,t);if("privy:wallet:create"===e){let e=Pr.get(a);if(e)return e}let o=new Promise(((r,a)=>{let o=Cr();Ar.enqueue(o,{resolve:r,reject:a}),i.postMessage({id:o,event:e,data:t},n)})).finally((()=>{Pr.delete(a)}));return Pr.set(a,o),o}function xr(t){let n=s.useIsServerConfigLoaded(),i=r.useRef(null),a=r.useRef(t.mfaMethods),o=s.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=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data);case"privy:user-signer:sign":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:add":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:set-recovery":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:connect":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:recover":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:rpc":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallet:create":let r=Ar.dequeue(e.event,e.id);return Er(e)?r.reject(new s.PrivyIframeError(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallets:import":let n=Ar.dequeue(e.event,e.id);return Er(e)?n.reject(new s.PrivyIframeError(e.error.type,e.error.message)):n.resolve(e.data);case"privy:mfa:verify":let i=Ar.dequeue(e.event,e.id);return Er(e)?i.reject(new s.PrivyIframeError(e.error.type,e.error.message)):i.resolve(e.data);case"privy:mfa:init-enrollment":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:submit-enrollment":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:unenroll":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:clear":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:auth:unlink-passkey":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:solana-wallet:create":let a=Ar.dequeue(e.event,e.id);return Er(e)?a.reject(new s.PrivyIframeError(e.error.type,e.error.message)):a.resolve(e.data);case"privy:farcaster:init-signer":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:sign":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:delegated-actions:consent":{let t=Ar.dequeue(e.event,e.id);return Er(e)?t.reject(new s.PrivyIframeError(e.error.type,e.error.message)):t.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}(e.data)}let n={signWithUserSigner:r=>fr((n=>br("privy:user-signer:sign",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),addWallet:r=>fr((n=>br("privy:wallets:add",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),setRecovery:r=>fr((n=>br("privy:wallets:set-recovery",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),connect:r=>fr((n=>br("privy:wallets:connect",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),recover:r=>fr((n=>br("privy:wallets:recover",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o,!r.recoveryAccessToken&&!r.recoveryPassword&&!r.recoverySecretOverride),rpc:r=>fr((n=>br("privy:wallets:rpc",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),create:r=>br("privy:wallet:create",r,e,t.origin),importWallet:r=>br("privy:wallets:import",r,e,t.origin),createSolana:r=>fr((n=>br("privy:solana-wallet:create",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),createDelegatedAction:r=>br("privy:delegated-actions:consent",r,e,t.origin),verifyMfa:r=>fr((n=>br("privy:mfa:verify",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o,!0),initEnrollMfa:r=>fr((n=>br("privy:mfa:init-enrollment",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),submitEnrollMfa:r=>fr((n=>br("privy:mfa:submit-enrollment",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),unenrollMfa:r=>fr((n=>br("privy:mfa:unenroll",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),clearMfa:r=>br("privy:mfa:clear",r,e,t.origin),unlinkPasskeyAccount:r=>fr((n=>br("privy:auth:unlink-passkey",{...r,...n},e,t.origin)),a.current,t.mfaPromise,t.mfaSubmitPromise,o),initFarcasterSigner:r=>br("privy:farcaster:init-signer",r,e,t.origin),signFarcasterMessage:r=>br("privy:farcaster:sign",r,e,t.origin)};window.addEventListener("message",r);let c=new AbortController;return s.invokeUntilSettled((()=>br("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?
4
+ /*#__PURE__*/e.jsx("iframe",{ref:i,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>c(!0),src:_.constructURL({origin:t.origin,path:`/apps/${t.appId}/embedded-wallets`,query:{caid:t.clientAnalyticsId,client_id:t.appClientId}})}):null}const Tr=({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new o.PrivyClientError("Address to delegate is not associated with current user.");if(!I.isFirstClassChainWallet(r))throw new o.PrivyClientError(`useDelegatedActions is not supported for ${r.chainType} wallets. Use the useSessionSigners hook to provision server side access on behalf of your users.`);return{address:r.address,chainType:r.chainType,walletIndex:r.walletIndex??0}},Sr=({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new o.PrivyClientError("Address to delegate is not associated with current user.");let n=r.imported?r:d.getPrivyPrimaryWallet(t);if(!n)throw new o.PrivyClientError("Unable to determine root address for delegated address.");if(!I.isFirstClassChainWallet(n))throw new o.PrivyClientError(`useDelegatedActions is not supported for ${n.chainType} wallets. Use the useSessionSigners hook to provision server side access on behalf of your users.`);return{address:n.address,chainType:n.chainType,imported:n.imported}},_r=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&e.delegated));const Ir=()=>{let e=s.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=>s.setExternalWalletState({listings:e}))).catch(console.error)}),[e.walletConnectCloudProjectId])},Ur="popup-privy-oauth",Wr="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";class Rr{async authenticate(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw o.formatApiError(e)}}async link(){if(!this.api)throw new o.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(o.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw o.formatApiError(e)}}constructor({authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}){this.meta={authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}}}async function Or({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 o.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,customAuthAuthorizeUrl:n.provider_app_custom_auth_authorize_url,customAuthTransactUrl:n.provider_app_custom_auth_transact_url}}const Mr=async({user:e,address:t,client:r,request:n,requesterAppId:i,reconnect:a})=>{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 o.PrivyClientError("Cannot request a signature with this wallet address");let c=r.getProviderAccessToken(l.providerApp.id),d=await Or({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 o.PrivyClientError("Cannot transact against a read-only provider app");await a({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 o.PrivyClientError("Transactions require a valid token");let u=s.triggerPopup();if(!u)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Missing token",address:t}}),new o.PrivyClientError("Failed to initialize signature request");let h=new URL(d.customAuthTransactUrl||`${d.apiUrl}/oauth/transact`);return h.searchParams.set("token",c||""),h.searchParams.set("request",Nr(n)),u.location=h.href,new Promise(((e,i)=>{let a=setTimeout((()=>{d(),i(new o.PrivyClientError("Request timeout")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Request timeout",address:t}})}),12e4),s=setInterval((()=>{u.closed&&(d(),i(new o.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(a),window.removeEventListener("message",c)}}))};let Nr=e=>JSON.stringify({content:{request:{request:jr(e,T.toHex)}},timestamp:Date.now(),callbackUrl:window.origin});const jr=(e,t)=>"bigint"==typeof e?t(e):Array.isArray(e)?e.map((e=>jr(e,t))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,r])=>[e,jr(r,t)]))):e,Fr=({passkeys:t,isLoading:r,errorReason:n,success:i,expanded:a,onLinkPasskey:o,onUnlinkPasskey:l,onExpand:c,onBack:d,onClose:u})=>i?/*#__PURE__*/e.jsx(s.ScreenLayout,{title:"Passkeys updated",icon:U.CheckCircle,iconVariant:"success",primaryCta:{label:"Done",onClick:u},onClose:u,watermark:!0}):a?/*#__PURE__*/e.jsx(s.ScreenLayout,{icon:U.FingerprintIcon,title:"Your passkeys",onBack:d,onClose:u,watermark:!0,children:/*#__PURE__*/e.jsx(Dr,{passkeys:t,expanded:a,onUnlink:l,onExpand:c})}):/*#__PURE__*/e.jsx(s.ScreenLayout,{icon:U.FingerprintIcon,title:"Set up passkey verification",subtitle:"Verify with passkey",primaryCta:{label:"Add new passkey",onClick:o,loading:r},onClose:u,watermark:!0,helpText:n||void 0,children:0===t.length?/*#__PURE__*/e.jsx(qr,{}):/*#__PURE__*/e.jsx(Lr,{children:/*#__PURE__*/e.jsx(Dr,{passkeys:t,expanded:a,onUnlink:l,onExpand:c})})});let Lr=/*#__PURE__*/f.styled.div.withConfig({displayName:"ContentContainer",componentId:"sc-d4c46a0c-0"})(["margin-bottom:12px;"]),Dr=({passkeys:t,expanded:n,onUnlink:i,onExpand:a})=>{let[o,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($r,{children:"Your passkeys"}),/*#__PURE__*/e.jsxs(Vr,{children:[t.slice(0,c).map((t=>/*#__PURE__*/e.jsxs(Zr,{children:[/*#__PURE__*/e.jsxs("div",{children:[/*#__PURE__*/e.jsx(Yr,{children:d(t)}),/*#__PURE__*/e.jsxs(Gr,{children:["Last used:"," ",(t.latestVerifiedAt??t.firstVerifiedAt)?.toLocaleString()??"N/A"]})]}),/*#__PURE__*/e.jsx(Xr,{disabled:o.includes(t.credentialId),onClick:()=>(async e=>{l((t=>t.concat([e]))),await i(e),l((t=>t.filter((t=>t!==e))))})(t.credentialId),children:o.includes(t.credentialId)?/*#__PURE__*/e.jsx(s.ButtonLoader,{}):/*#__PURE__*/e.jsx(U.Trash2,{size:16})})]},t.credentialId))),t.length>2&&!n&&/*#__PURE__*/e.jsx(Kr,{onClick:a,children:"View all"})]})]})},qr=()=>/*#__PURE__*/e.jsxs(s.TodoList,{style:{color:"var(--privy-color-foreground)"},children:[/*#__PURE__*/e.jsx(s.TodoItem,{children:"Verify with Touch ID, Face ID, PIN, or hardware key"}),/*#__PURE__*/e.jsx(s.TodoItem,{children:"Takes seconds to set up and use"}),/*#__PURE__*/e.jsx(s.TodoItem,{children:"Use your passkey to verify transactions and login to your account"})]});const Hr={component:()=>{let{user:t,unlinkPasskey:n}=d.usePrivyContext(),{linkWithPasskey:i,closePrivyModal:a}=v.usePrivyInternal(),s=t?.linkedAccounts.filter((e=>"passkey"===e.type)),[l,c]=r.useState(!1),[u,h]=r.useState(""),[p,y]=r.useState(!1),[m,w]=r.useState(!1);return r.useEffect((()=>{0===s.length&&w(!1)}),[s.length]),/*#__PURE__*/e.jsx(Fr,{passkeys:s,isLoading:l,errorReason:u,success:p,expanded:m,onLinkPasskey:()=>{c(!0),i().then((()=>y(!0))).catch((e=>{if(e instanceof o.PrivyError){if(e.privyErrorCode===o.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE)return void h("Cannot link more passkeys to account.");if(e.privyErrorCode===o.PrivyErrorCode.PASSKEY_NOT_ALLOWED)return void h("Passkey request timed out or rejected by user.")}h("Unknown error occurred.")})).finally((()=>{c(!1)}))},onUnlinkPasskey:async e=>(c(!0),await n(e).then((()=>y(!0))).catch((e=>{e instanceof o.PrivyError&&e.privyErrorCode===o.PrivyErrorCode.MISSING_MFA_CREDENTIALS?h("Cannot unlink a passkey enrolled in MFA"):h("Unknown error occurred.")})).finally((()=>{c(!1)}))),onExpand:()=>w(!0),onBack:()=>w(!1),onClose:()=>a()})}},Br=/*#__PURE__*/f.styled.div.withConfig({displayName:"DoubleIconWrapper",componentId:"sc-d4c46a0c-1"})(["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 zr=/*#__PURE__*/f.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 Kr=/*#__PURE__*/f.styled.button.withConfig({displayName:"LinkButton",componentId:"sc-d4c46a0c-2"})(["",""],zr);let Vr=/*#__PURE__*/f.styled.div.withConfig({displayName:"List",componentId:"sc-d4c46a0c-3"})(["display:flex;flex-direction:column;align-items:stretch;gap:0.8rem;padding:0.5rem 0rem 0rem;flex-grow:1;width:100%;"]),$r=/*#__PURE__*/f.styled.div.withConfig({displayName:"PasskeyListTitle",componentId:"sc-d4c46a0c-4"})(["line-height:20px;height:20px;font-size:1em;font-weight:450;display:flex;justify-content:flex-beginning;width:100%;"]),Yr=/*#__PURE__*/f.styled.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-d4c46a0c-5"})(["font-size:1em;line-height:1.3em;font-weight:500;color:var(--privy-color-foreground-2);padding:0.2em 0;"]),Gr=/*#__PURE__*/f.styled.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-d4c46a0c-6"})(["font-size:0.875rem;line-height:1rem;color:#64668b;padding:0.2em 0;"]),Zr=/*#__PURE__*/f.styled.div.withConfig({displayName:"PasskeyListItem",componentId:"sc-d4c46a0c-7"})(["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__*/f.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);}"]),Xr=/*#__PURE__*/f.styled.button.withConfig({displayName:"PasskeyItemUnlinkButton",componentId:"sc-d4c46a0c-8"})(["",""],Jr);const Qr=new Map([[s.FundingMethodSelectionScreen,null],[s.TransferFromWalletScreen,"external"],[s.AwaitingExternalTransferScreen,"external"],[s.AwaitingEvmToSolBridgingScreen,"external"],[s.AwaitingSolToEvmBridgingScreen,"external"],[s.ManualTransferScreen,"manual"],[s.MoonpayStatusScreen,"moonpay"]]),en=()=>{let e=s.useAppConfig(),{user:t}=d.usePrivyContext(),{client:n,refreshSessionAndUser:i,walletProxy:a}=v.usePrivyInternal();return{migrate:r.useCallback((async()=>{if("legacy-embedded-wallets-only"===e.embeddedWallets.mode)return{success:!0};if(!t)throw new o.PrivyClientError("User must be authenticated before migrating wallets",o.PrivyErrorCode.MUST_BE_AUTHENTICATED);let r=d.getPrivyPrimaryWallet(t);if(!r||d.getIsUnifiedWallet(r)||!I.isFirstClassChainWallet(r))return{success:!0};if(!a)throw new o.PrivyClientError("Cannot connect to wallet proxy");let l=await n.getAccessToken();if(!l)throw new o.PrivyClientError("User must be authenticated before migrating wallets",o.PrivyErrorCode.MUST_BE_AUTHENTICATED);let c=r.imported?[r]:t.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&!e.imported)).filter(I.isFirstClassChainWallet),{entropyId:u,entropyIdVerifier:h}=s.getEntropyDetailsForUser(t,r);try{await a.connect({accessToken:l,entropyId:u,entropyIdVerifier:h})}catch(e){if(!s.errorIndicatesRecoveryIsNeeded(e)||"privy"!==r.recoveryMethod)throw e;await a.recover({accessToken:l,entropyId:u,entropyIdVerifier:h})}return await a.createDelegatedAction({accessToken:l,rootWallet:{address:r.address,chainType:r.chainType,imported:r.imported},delegatedWallets:c}),await i(),{success:!0}}),[e.embeddedWallets.mode,t,a,n,i])}},tn=({disabled:e})=>{let{migrate:t}=en(),{user:n}=d.usePrivyContext(),{walletProxy:i}=v.usePrivyInternal();return r.useEffect((()=>{!e&&n&&i&&t().catch((e=>{console.debug("Unable to migrate wallets: ",e)}))}),[n,i,e,t]),null},rn=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}),nn=({providerApp:t,success:n,error:i,onClose:a})=>{let{title:o,subtitle:l}=r.useMemo((()=>n?{title:`Successfully connected with ${t.name}`,subtitle:"You're good to go!"}:i?{title:"Authentication failed",subtitle:i.message}:{title:`Connecting to ${t.name}`,subtitle:`Please check the pop-up from ${t.name} to continue`}),[n,i,t.name]);/*#__PURE__*/return e.jsx(s.ScreenLayout,{title:o,subtitle:l,icon:t.logoUrl,iconVariant:"loading",iconLoadingStatus:{success:n,fail:!!i},onBack:a,watermark:!0})},an={component:()=>{let t=s.useAppConfig(),{data:n,navigate:i,setModalData:a,onUserCloseViaDialogOrKeybindRef:l}=s.usePrivyModal(),{crossAppAuthFlow:c,updateWallets:d,closePrivyModal:u,createAnalyticsEvent:h}=v.usePrivyInternal(),{logout:p}=C.useLogout(),[y,m]=r.useState({}),w=n?.crossAppAuth,g={id:w.appId,name:w.name,logoUrl:w.logoUrl},f=new o.PrivyClientError(`There was an issue connecting your ${g.name} account. Please try again.`),E=new s.RunEffectOnce((async e=>{if(w.popup)try{let t=await c({appId:e,popup:w.popup,action:w.action});m({data:t})}catch(e){if(e instanceof o.PrivyClientError)m({error:e});else if(e instanceof o.PrivyApiError){if(e.privyErrorCode===o.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return a({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:`privy:${g.id}`,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void i(s.LinkConflictScreen);w.popup&&w.popup.close(),m({error:f})}else m({error:f})}else m({error:f})})),A=()=>{y.data&&(d(),w.onSuccess(y.data),u({shouldCallAuthOnSuccess:!0,isSuccess:!0})),w.onError(y.error??new o.PrivyClientError("User canceled flow")),u({shouldCallAuthOnSuccess:!1,isSuccess:!1})};return l.current=A,r.useEffect((()=>{g.id.length&&E.execute(g.id)}),[g.id]),r.useEffect((()=>{if(!y.data)return;let e=y.data;if(t.legal.requireUsersAcceptTerms&&!e.hasAcceptedTerms){let e=setTimeout((()=>{i(s.AffirmativeConsentScreen)}),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(s.shouldProceedtoEmbeddedWalletCreationFlow(e,t.embeddedWallets)){let e=setTimeout((()=>{a({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),h({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:`privy:${g.id}`,screen:"CrossAppAuthScreen"}}),p()},callAuthOnSuccessOnClose:!0}}),i(s.EmbeddedWalletOnAccountCreateScreen)}),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}let r=setTimeout(A,s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(r)}),[y.data]),/*#__PURE__*/e.jsx(nn,{providerApp:g,success:!!y.data,error:y.error,onClose:A})}},on=({appName:t,address:r,success:n,error:i,onAccept:a,onDecline:o,onClose:l})=>n||i?/*#__PURE__*/e.jsx(s.ScreenLayout,{title:i?"Something went wrong":"Success!",subtitle:i?"Please try again.":`You've successfully granted delegated action permissions to ${t}.`,icon:i?U.AlertCircle:U.CheckCircle,iconVariant:i?"error":"success",onBack:l,watermark:!0}):/*#__PURE__*/e.jsx(s.ScreenLayout,{title:"Enable offline access",subtitle:`By confirming, ${t} will be able to use your wallet for you even when you're not around. You can revoke this later.`,icon:U.CloudUpload,primaryCta:{label:"Accept",onClick:a},secondaryCta:{label:"Not now",onClick:o},onBack:l,watermark:!0,children:/*#__PURE__*/e.jsx(s.WalletInfoCard,{address:r,title:"Wallet"})}),sn={component:()=>{let{data:t}=s.usePrivyModal(),n=s.useAppConfig(),{closePrivyModal:i}=v.usePrivyInternal(),[a,l]=r.useState(!1),[c,d]=r.useState(),{address:u,onDelegate:h,onSuccess:p,onError:y}=t.delegatedActions.consent,m=async()=>{a?p():y(c??new o.PrivyClientError("User declined delegating actions.")),i({shouldCallAuthOnSuccess:!1})};return r.useEffect((()=>{if(!a&&!c)return;let e=setTimeout(m,s.DEFAULT_SUCCESS_SCREEN_LONG_DURATION_MS);return()=>clearTimeout(e)}),[a,c]),/*#__PURE__*/e.jsx(on,{appName:n.name,address:u,success:a,error:c,onAccept:async()=>{try{await h(),l(!0)}catch(e){d(e)}},onDecline:()=>{m()},onClose:m})}},ln=({appName:t,success:r,error:n,onRevoke:i,onDeny:a,onClose:o})=>r||n?/*#__PURE__*/e.jsx(s.ScreenLayout,{title:n?"Something went wrong":"Success!",subtitle:n?"Please try again.":"You've successfully revoked permissions.",icon:n?U.AlertCircle:U.CheckCircle,iconVariant:n?"error":"success",onBack:o,watermark:!0}):/*#__PURE__*/e.jsx(s.ScreenLayout,{title:"Revoke offline access to wallet",subtitle:`By confirming, ${t} will no longer be able to use this wallet on your behalf when you are not online.`,icon:U.Ban,primaryCta:{label:"Confirm",onClick:i},secondaryCta:{label:"Deny",onClick:a},onBack:o,watermark:!0}),cn={component:()=>{let{data:t}=s.usePrivyModal(),n=s.useAppConfig(),{closePrivyModal:i}=v.usePrivyInternal(),[a,l]=r.useState(!1),[c,d]=r.useState(),{onRevoke:u,onSuccess:h,onError:p}=t.delegatedActions.revoke,y=async()=>{a?h():p(c??new o.PrivyClientError("User declined revoking access to their delegated wallet.")),i({shouldCallAuthOnSuccess:!1})};return r.useEffect((()=>{if(!a&&!c)return;let e=setTimeout(y,s.DEFAULT_SUCCESS_SCREEN_LONG_DURATION_MS);return()=>clearTimeout(e)}),[a,c]),/*#__PURE__*/e.jsx(ln,{appName:n.name,success:a,error:c,onRevoke:async()=>{try{await u(),l(!0)}catch(e){d(e)}},onDeny:()=>{y()},onClose:y})}};let dn="#8a63d2";const un=({appName:t,loading:r,success:i,errorMessage:a,connectUri:o,onBack:l,onClose:c,onOpenFarcaster:d})=>n.isMobile||r?n.isIOS?/*#__PURE__*/e.jsx(s.ScreenLayout,{title:a?a.message:"Add a signer to Farcaster",subtitle:a?a.detail:`This will allow ${t} to add casts, likes, follows, and more on your behalf.`,icon:s.Farcaster,iconVariant:"loading",iconLoadingStatus:{success:i,fail:!!a},primaryCta:o&&d?{label:"Open Farcaster app",onClick:d}:void 0,onBack:l,onClose:c,watermark:!0}):/*#__PURE__*/e.jsx(s.ScreenLayout,{title:a?a.message:"Requesting signer from Farcaster",subtitle:a?a.detail:"This should only take a moment",icon:s.Farcaster,iconVariant:"loading",iconLoadingStatus:{success:i,fail:!!a},onBack:l,onClose:c,watermark:!0,children:o&&n.isMobile&&/*#__PURE__*/e.jsx(hn,{children:/*#__PURE__*/e.jsx(s.OpenLinkButton,{text:"Take me to Farcaster",url:o,color:dn})})}):
5
+ /*#__PURE__*/e.jsx(s.ScreenLayout,{title:"Add a signer to Farcaster",subtitle:`This will allow ${t} to add casts, likes, follows, and more on your behalf.`,onBack:l,onClose:c,watermark:!0,children:/*#__PURE__*/e.jsxs(pn,{children:[/*#__PURE__*/e.jsx(yn,{children:o?/*#__PURE__*/e.jsx(s.QrCode,{url:o,size:275,squareLogoElement:s.Farcaster}):/*#__PURE__*/e.jsx(gn,{children:/*#__PURE__*/e.jsx(s.Loader,{})})}),/*#__PURE__*/e.jsxs(mn,{children:[/*#__PURE__*/e.jsx(wn,{children:"Or copy this link and paste it into a phone browser to open the Farcaster app."}),o&&/*#__PURE__*/e.jsx(s.CopytoClipboardButton,{text:o,itemName:"link",color:dn})]})]})});let hn=/*#__PURE__*/f.styled.div.withConfig({displayName:"MobileLinkContainer",componentId:"sc-75c99bb6-0"})(["margin-top:24px;"]),pn=/*#__PURE__*/f.styled.div.withConfig({displayName:"ContentContainer",componentId:"sc-75c99bb6-1"})(["display:flex;flex-direction:column;align-items:center;gap:24px;"]),yn=/*#__PURE__*/f.styled.div.withConfig({displayName:"QrContainer",componentId:"sc-75c99bb6-2"})(["padding:24px;position:relative;display:flex;align-items:center;justify-content:center;min-height:275px;"]),mn=/*#__PURE__*/f.styled.div.withConfig({displayName:"InstructionsContainer",componentId:"sc-75c99bb6-3"})(["display:flex;flex-direction:column;align-items:center;gap:16px;"]),wn=/*#__PURE__*/f.styled.div.withConfig({displayName:"InstructionText",componentId:"sc-75c99bb6-4"})(["font-size:0.875rem;text-align:center;color:var(--privy-color-foreground-2);"]),gn=/*#__PURE__*/f.styled.div.withConfig({displayName:"LoaderWrapper",componentId:"sc-75c99bb6-5"})(["position:relative;width:82px;height:82px;"]);const fn={component:()=>{let{lastScreen:t,navigateBack:n,data:i}=s.usePrivyModal(),a=s.useAppConfig(),{requestFarcasterSignerStatus:o,closePrivyModal:l}=v.usePrivyInternal(),[c,d]=r.useState(void 0),[u,h]=r.useState(!1),[p,y]=r.useState(!1),m=r.useRef([]),w=i?.farcasterSigner;r.useEffect((()=>{let e=Date.now(),t=setInterval((async()=>{if(!w?.public_key)return clearInterval(t),void d({retryable:!0,message:"Connect failed",detail:"Something went wrong. Please try again."});"approved"===w.status&&(clearInterval(t),h(!1),y(!0),m.current.push(setTimeout((()=>l({shouldCallAuthOnSuccess:!1,isSuccess:!0})),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS)));let r=await o(w?.public_key),n=Date.now()-e;"approved"===r.status?(clearInterval(t),h(!1),y(!0),m.current.push(setTimeout((()=>l({shouldCallAuthOnSuccess:!1,isSuccess:!0})),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS))):n>3e5?(clearInterval(t),d({retryable:!0,message:"Connect failed",detail:"The request timed out. Try again."})):"revoked"===r.status&&(clearInterval(t),d({retryable:!0,message:"Request rejected",detail:"The request was rejected. Please try again."}))}),2e3);return()=>{clearInterval(t),m.current.forEach((e=>clearTimeout(e)))}}),[]);let g="pending_approval"===w?.status?w.signer_approval_url:void 0;/*#__PURE__*/return e.jsx(un,{appName:a.name,loading:u,success:p,errorMessage:c,connectUri:g,onBack:t?n:void 0,onClose:l,onOpenFarcaster:()=>{g&&(window.location.href=g)}})}},vn=({onClose:t})=>/*#__PURE__*/e.jsx(s.ScreenLayout,{title:"Could not log in with provider",subtitle:"It looks like you're using an in-app browser. To log in, please try again using an external browser.",icon:U.ExternalLink,primaryCta:{label:"Close",onClick:t},watermark:!0}),Cn={component:()=>{let{closePrivyModal:t}=v.usePrivyInternal();/*#__PURE__*/return e.jsx(vn,{onClose:()=>t()})}},En=({title:t="Connect your email",subtitle:r="Add your email to your account"})=>/*#__PURE__*/e.jsx(s.ScreenLayout,{title:t,subtitle:r,icon:se.default,watermark:!0,children:/*#__PURE__*/e.jsx(s.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(s.ConnectEmailForm,{stacked:!0})})}),An={component:()=>{let t=s.useAppConfig();/*#__PURE__*/return e.jsx(En,{subtitle:`Add your email to your ${t?.name} account`})}},Pn=({title:t="Connect your phone",subtitle:n="Add your number to your account",onSubmit:i,isSubmitting:a=!1})=>{let[o,l]=r.useState(null),c=async()=>{o?.qualifiedPhoneNumber&&await i(o)};/*#__PURE__*/return e.jsx(s.ScreenLayout,{title:t,subtitle:n,icon:ne.default,primaryCta:{label:a?"Submitting":"Submit",onClick:c,disabled:!o?.isValid||a},watermark:!0,children:/*#__PURE__*/e.jsx(s.ConnectPhoneNumberForm,{onChange:e=>{l(e)},onSubmit:c,noIncludeSubmitButton:!0,hideRecent:!0})})},kn={component:()=>{let{currentScreen:t,data:n,navigate:i,setModalData:a}=s.usePrivyModal(),o=s.useAppConfig(),{initLoginWithSms:l}=v.usePrivyInternal(),[c,d]=r.useState(!1);/*#__PURE__*/return e.jsx(Pn,{subtitle:`Add your number to your ${o?.name} account`,onSubmit:async e=>{d(!0);try{await l({phoneNumber:e.qualifiedPhoneNumber,withPrivyUi:!0}),i(s.AwaitingPasswordlessCodeScreen)}catch(e){a({errorModalData:{error:e,previousScreen:n?.errorModalData?.previousScreen||t||kn}}),i(s.ErrorScreen)}finally{d(!1)}},isSubmitting:c})}},bn=({title:t="Could not connect with wallet",subtitle:r="Please check that Phantom multichain is enabled and try again.",primaryCtaText:n="Try again",secondaryCtaText:i="Cancel",onTryAgain:a,onCancel:o})=>/*#__PURE__*/e.jsx(s.ScreenLayout,{title:t,subtitle:r,icon:U.XCircle,iconVariant:"error",primaryCta:{label:n,onClick:a},secondaryCta:{label:i,onClick:o},watermark:!0}),xn={component:()=>{let{closePrivyModal:t}=v.usePrivyInternal(),{navigate:r}=s.usePrivyModal();/*#__PURE__*/return e.jsx(bn,{onTryAgain:()=>{r(s.LandingScreen)},onCancel:async()=>{await t()}})}};function Tn(){let{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:n,submitEnrollmentWithSms:i,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:o,unenroll:s,enrollInMfa:l}=r.useContext(d.PrivyContext);return{initEnrollmentWithSms:e,initEnrollmentWithTotp:t,initEnrollmentWithPasskey:n,submitEnrollmentWithSms:i,submitEnrollmentWithTotp:a,submitEnrollmentWithPasskey:o,unenrollWithSms:()=>s("sms"),unenrollWithTotp:()=>s("totp"),unenrollWithPasskey:e=>s("passkey",e),showMfaEnrollmentModal:()=>l(!0),closeMfaEnrollmentModal:()=>l(!1)}}const Sn=t=>/*#__PURE__*/e.jsxs(_n,{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 _n=/*#__PURE__*/f.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 In=({showIntro:t,userMfaMethods:r,appMfaMethods:n,userHasAuthSms:i,isTotpLoading:a,isPasskeyLoading:o,error:l,onClose:c,backFn: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(s.ModalHeader,{backFn:t?d:void 0,onClose:c},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ie.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Choose a verification method"}),r.length>0?/*#__PURE__*/e.jsx(Et,{children:"To add or delete verification methods, verification is required."}):/*#__PURE__*/e.jsx(Et,{children:"How would you like to verify your identity?"}),l&&/*#__PURE__*/e.jsx(Nt,{style:{marginTop:"1.25rem"},children:l.message}),/*#__PURE__*/e.jsxs(Tt,{children:[(y.passkey||p.passkey)&&/*#__PURE__*/e.jsxs(St,{children:[/*#__PURE__*/e.jsx(s.LoginMethodButton,{style:{justifyContent:"center"},onClick:()=>u("passkey"),disabled:p.passkey||o,children:o?/*#__PURE__*/e.jsx(s.Loader,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/e.jsxs(Wt,{children:[/*#__PURE__*/e.jsxs(It,{children:[/*#__PURE__*/e.jsx(re.default,{}),"Passkey"]}),p.passkey?/*#__PURE__*/e.jsx(Un,{color:"green",children:"Enabled"}):/*#__PURE__*/e.jsx(Ut,{$isAccent:!0,children:/*#__PURE__*/e.jsx(ue.default,{})})]})}),p.passkey&&/*#__PURE__*/e.jsx(_t,{style:{position:"absolute",right:0},onClick:()=>h("passkey"),children:/*#__PURE__*/e.jsx(he.default,{})})]},"passkey"),(y.totp||p.totp)&&/*#__PURE__*/e.jsxs(St,{children:[/*#__PURE__*/e.jsx(s.LoginMethodButton,{style:{justifyContent:"center"},disabled:p.totp||a,onClick:()=>u("totp"),children:a?/*#__PURE__*/e.jsx(s.Loader,{style:{height:24,width:24,borderWidth:2},color:"var(--privy-color-foreground-3)"}):/*#__PURE__*/e.jsxs(Wt,{children:[/*#__PURE__*/e.jsxs(It,{children:[/*#__PURE__*/e.jsx(te.default,{}),"Authenticator app"]}),p.totp&&/*#__PURE__*/e.jsx(Un,{color:"green",children:"Enabled"})]})}),p.totp&&/*#__PURE__*/e.jsx(_t,{style:{position:"absolute",right:0},onClick:()=>h("totp"),children:/*#__PURE__*/e.jsx(he.default,{})})]},"totp"),(y.sms||p.sms)&&/*#__PURE__*/e.jsxs(St,{children:[/*#__PURE__*/e.jsx(s.LoginMethodButton,{disabled:p.sms||i,onClick:()=>u("sms"),children:/*#__PURE__*/e.jsxs(Wt,{children:[/*#__PURE__*/e.jsxs(It,{children:[/*#__PURE__*/e.jsx(ne.default,{}),"SMS"]}),p.sms&&/*#__PURE__*/e.jsx(Un,{color:"green",children:"Enabled"}),i&&/*#__PURE__*/e.jsx(Ut,{children:"Disabled"})]})}),p.sms&&/*#__PURE__*/e.jsx(_t,{style:{position:"absolute",right:0},onClick:()=>h("sms"),children:/*#__PURE__*/e.jsx(he.default,{})})]},"sms")]}),/*#__PURE__*/e.jsx(Wn,{children:"You can always change your selection later"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})};let Un=/*#__PURE__*/f.styled(s.Chip).withConfig({displayName:"StyledChip",componentId:"sc-5f06df7f-0"})(["margin-right:1.5rem;"]),Wn=/*#__PURE__*/f.styled(Rt).withConfig({displayName:"StyledTerms",componentId:"sc-5f06df7f-1"})(["&&{margin-top:1rem;}text-align:center;"]);const Rn=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{x:0,y:0,width:"65",height:"64",viewBox:"0 0 65 64",style:{height:"64px",width:"65px",...t},xmlns:"http://www.w3.org/2000/svg",...r,children:[/*#__PURE__*/e.jsxs("g",{clipPath:"url(#clip0_113_33841)",children:[/*#__PURE__*/e.jsx("path",{d:"M39.1193 0.943398C34.636 -0.174912 29.9185 -0.334713 25.328 0.656273C24.9732 0.732859 24.7477 1.08253 24.8243 1.43729C24.9009 1.79205 25.2506 2.01756 25.6053 1.94097C30.0015 0.991934 34.53 1.14842 38.8375 2.22802C49.1385 4.80983 57.7129 12.5548 60.9786 22.6718C62.2416 26.5843 62.7781 30.7505 62.8855 35.1167C62.8945 35.4795 63.1958 35.7664 63.5586 35.7575C63.9215 35.7485 64.2083 35.4472 64.1994 35.0843C64.0905 30.6582 63.5477 26.3849 62.2536 22.3432C58.8621 11.7515 49.9005 3.63265 39.1193 0.943398Z"}),/*#__PURE__*/e.jsx("path",{d:"M21.9931 2.93163C22.343 2.83511 22.5484 2.47325 22.4518 2.12339C22.3553 1.77352 21.9935 1.56815 21.6436 1.66466C16.8429 2.98903 10.0898 7.56519 5.91628 13.6786C5.91465 13.681 5.91304 13.6834 5.91145 13.6858C2.24684 19.2083 -0.0503572 26.1484 0.591012 32.8828C0.591623 32.8892 0.592328 32.8956 0.593127 32.902C0.746837 34.1317 1.00488 35.3591 1.26323 36.5879C1.80735 39.1761 2.35282 41.7706 1.92765 44.4064C1.86986 44.7647 2.11347 45.102 2.47177 45.1598C2.83007 45.2176 3.16738 44.974 3.22518 44.6157C3.66961 41.8605 3.11776 39.173 2.56581 36.4851C2.31054 35.2419 2.05525 33.9987 1.89847 32.7486C1.29525 26.3851 3.46802 19.7466 7.00418 14.416C11.0189 8.5373 17.5201 4.16562 21.9931 2.93163Z"}),/*#__PURE__*/e.jsx("path",{d:"M30.6166 4.39985C38.8671 3.89603 47.1159 7.26314 52.6556 13.7139C52.8921 13.9893 52.8605 14.4042 52.5852 14.6406C52.3099 14.8771 51.895 14.8455 51.6585 14.5702C46.3904 8.43576 38.541 5.23144 30.6927 5.71195C30.6899 5.71212 30.6871 5.71227 30.6843 5.71241C20.7592 6.19265 11.4643 12.9257 8.04547 22.3603C7.92183 22.7016 7.54498 22.8779 7.20375 22.7543C6.86253 22.6306 6.68616 22.2538 6.80981 21.9126C10.4114 11.9735 20.1717 4.90702 30.6166 4.39985Z"}),/*#__PURE__*/e.jsx("path",{d:"M54.6576 16.5848C54.4553 16.2836 54.047 16.2033 53.7457 16.4057C53.4444 16.608 53.3642 17.0163 53.5665 17.3176C56.6376 21.8904 57.9074 26.8665 58.4094 32.7717C58.4401 33.1333 58.7582 33.4016 59.1199 33.3708C59.4815 33.3401 59.7497 33.022 59.719 32.6604C59.206 26.6261 57.8965 21.4076 54.6576 16.5848Z"}),/*#__PURE__*/e.jsx("path",{d:"M59.2796 35.4504C59.6419 35.4277 59.9539 35.703 59.9765 36.0653C60.2242 40.0279 60.2265 44.5112 59.7881 47.8243C59.7405 48.1841 59.4102 48.4372 59.0504 48.3896C58.6906 48.342 58.4376 48.0117 58.4852 47.6519C58.9077 44.4586 58.91 40.0704 58.6648 36.1473C58.6421 35.785 58.9174 35.473 59.2796 35.4504Z"}),/*#__PURE__*/e.jsx("path",{d:"M7.05311 25.5432C7.13829 25.1904 6.92135 24.8354 6.56855 24.7502C6.21576 24.665 5.86071 24.882 5.77553 25.2348C5.2932 27.2325 5.0428 29.2847 5.03288 31.3388C5.02266 33.4559 5.41742 35.5225 5.81234 37.5899C6.1354 39.2811 6.45855 40.9728 6.5602 42.6932C6.69373 44.9531 6.21839 47.2163 5.39698 49.3703C5.26766 49.7094 5.43774 50.0891 5.77685 50.2184C6.11596 50.3477 6.4957 50.1777 6.62502 49.8386C7.49325 47.5617 8.01954 45.1092 7.87221 42.6157C7.77126 40.9071 7.44813 39.2252 7.12512 37.5439C6.73099 35.4925 6.33704 33.442 6.34716 31.3451C6.35659 29.3933 6.59455 27.4425 7.05311 25.5432Z"}),/*#__PURE__*/e.jsx("path",{d:"M24.2964 10.94C24.4317 11.2768 24.2683 11.6595 23.9315 11.7947C17.1187 14.5307 12.0027 20.7047 10.959 27.9852C10.523 31.0269 10.9941 34.0398 11.465 37.052C11.7303 38.7483 11.9954 40.4443 12.0985 42.1451C12.3221 45.833 11.902 49.8839 9.50192 53.5696C9.30387 53.8737 8.89677 53.9597 8.59264 53.7617C8.28851 53.5636 8.20251 53.1565 8.40056 52.8524C10.5873 49.4944 11.0012 45.7644 10.7867 42.2246C10.6821 40.499 10.4185 38.7833 10.1552 37.0686C9.68265 33.9923 9.21067 30.9195 9.65804 27.7987C10.7724 20.025 16.221 13.4748 23.4417 10.5751C23.7785 10.4399 24.1612 10.6032 24.2964 10.94Z"}),/*#__PURE__*/e.jsx("path",{d:"M47.3662 14.6814C41.9915 9.64741 34.2017 7.89046 27.122 9.4433C26.7675 9.52105 26.5432 9.87147 26.6209 10.226C26.6987 10.5805 27.0491 10.8048 27.4036 10.7271C34.1075 9.25665 41.4426 10.934 46.4677 15.6406C50.7033 19.6077 53.1628 25.38 53.8066 31.6779C53.8435 32.0389 54.1661 32.3017 54.5272 32.2648C54.8883 32.2279 55.151 31.9053 55.1141 31.5442C54.4456 25.0047 51.8822 18.9111 47.3662 14.6814Z"}),/*#__PURE__*/e.jsx("path",{d:"M54.9766 34.6738C55.3376 34.6368 55.6604 34.8994 55.6975 35.2604C56.3216 41.337 56.0526 47.9003 55.1104 54.2496C55.0571 54.6086 54.7229 54.8565 54.3639 54.8032C54.0049 54.7499 53.7571 54.4157 53.8103 54.0567C54.7394 47.7957 55.001 41.3439 54.39 35.3947C54.353 35.0336 54.6156 34.7109 54.9766 34.6738Z"}),/*#__PURE__*/e.jsx("path",{d:"M32.0659 13.3553C21.9959 13.3553 13.814 21.3892 13.814 31.3219C13.814 32.3829 13.9081 33.4225 14.0876 34.4334C14.1511 34.7907 14.4922 35.029 14.8495 34.9655C15.2069 34.9021 15.4451 34.561 15.3817 34.2036C15.2155 33.2677 15.1283 32.305 15.1283 31.3219C15.1283 22.1352 22.7014 14.6696 32.0659 14.6696C36.2978 14.6696 40.1642 16.1949 43.1319 18.7152C43.4086 18.9501 43.8233 18.9163 44.0582 18.6396C44.2931 18.363 44.2593 17.9483 43.9827 17.7134C40.7847 14.9975 36.6188 13.3553 32.0659 13.3553Z"}),/*#__PURE__*/e.jsx("path",{d:"M45.455 20.1635C45.717 19.9123 46.133 19.921 46.3842 20.183C49.2843 23.2072 50.2126 27.9605 50.8269 31.9494C51.5188 36.4426 51.6244 40.826 51.6244 42.8585C51.6244 43.2214 51.3302 43.5156 50.9673 43.5156C50.6044 43.5156 50.3101 43.2214 50.3101 42.8585C50.3101 40.8589 50.2055 36.5497 49.5279 32.1494C48.9577 28.4462 48.1356 23.9082 45.4356 21.0927C45.1844 20.8307 45.1931 20.4147 45.455 20.1635Z"}),/*#__PURE__*/e.jsx("path",{d:"M51.4576 46.6219C51.4864 46.2601 51.2165 45.9435 50.8547 45.9146C50.493 45.8858 50.1763 46.1557 50.1474 46.5175C49.8247 50.5654 49.403 54.6088 48.5474 58.3439C48.4663 58.6977 48.6874 59.0502 49.0412 59.1312C49.3949 59.2123 49.7474 58.9912 49.8285 58.6374C50.7067 54.8039 51.134 50.6806 51.4576 46.6219Z"}),/*#__PURE__*/e.jsx("path",{d:"M15.1454 36.852C15.5015 36.7819 15.847 37.0137 15.9171 37.3698C17.3066 44.4257 16.3467 50.8355 12.6672 56.4502C12.4682 56.7537 12.0609 56.8385 11.7573 56.6396C11.4538 56.4407 11.369 56.0333 11.5679 55.7298C15.0299 50.4469 15.9617 44.3985 14.6276 37.6238C14.5575 37.2677 14.7893 36.9221 15.1454 36.852Z"}),/*#__PURE__*/e.jsx("path",{d:"M32.0659 17.631C25.5291 17.631 19.1165 22.691 18.462 29.0504C18.1754 31.8345 18.578 34.5769 18.9807 37.3204C19.3323 39.7159 19.684 42.1124 19.5772 44.5381C19.3328 50.0898 17.7039 54.6726 14.905 58.4471C14.6888 58.7386 14.7499 59.1502 15.0414 59.3663C15.333 59.5825 15.7445 59.5214 15.9607 59.2299C18.9293 55.2266 20.6354 50.386 20.8903 44.5959C20.9966 42.1811 20.6438 39.7923 20.2912 37.4051C19.888 34.6752 19.4851 31.9473 19.7694 29.1849C20.3444 23.5983 26.0946 18.9453 32.0659 18.9453C34.851 18.9453 42.057 20.4534 44.3492 27.9205C45.7856 32.5998 46.1774 38.9326 45.8295 45.0849C45.4816 51.2364 44.3994 57.12 42.9442 60.8928C42.8136 61.2314 42.9822 61.6118 43.3208 61.7424C43.6594 61.873 44.0398 61.7044 44.1704 61.3658C45.6929 57.4186 46.7895 51.386 47.1417 45.1591C47.4938 38.9329 47.1068 32.4249 45.6056 27.5348C43.0612 19.2461 35.0851 17.631 32.0659 17.631Z"}),/*#__PURE__*/e.jsx("path",{d:"M21.9529 56.4512C22.2569 56.6494 22.3426 57.0566 22.1444 57.3606C21.7369 57.9854 21.3784 58.6391 21.0199 59.2928C20.6614 59.9465 20.3028 60.6004 19.8953 61.2253C19.697 61.5293 19.2898 61.615 18.9858 61.4167C18.6819 61.2184 18.5962 60.8113 18.7944 60.5073C19.2019 59.8825 19.5604 59.2288 19.9189 58.5751C20.2774 57.9213 20.636 57.2675 21.0435 56.6426C21.2418 56.3386 21.649 56.2529 21.9529 56.4512Z"}),/*#__PURE__*/e.jsx("path",{d:"M27.5799 24.4525C27.8816 24.2508 27.9625 23.8426 27.7608 23.541C27.559 23.2393 27.1509 23.1583 26.8492 23.3601C24.247 25.1006 22.6505 27.494 22.6505 31.0002C22.6505 33.088 23.0203 34.7946 23.3997 36.5449C23.9674 39.1641 24.3524 41.7777 24.2832 44.468C24.1992 47.7349 23.56 50.7201 22.3313 53.564C22.1873 53.8971 22.3407 54.2839 22.6739 54.4278C23.0071 54.5718 23.3938 54.4184 23.5378 54.0852C24.8369 51.0784 25.509 47.9266 25.5971 44.5018C25.6689 41.7062 25.2732 38.9892 24.6845 36.267C24.3042 34.509 23.9648 32.9394 23.9648 31.0002C23.9648 27.9961 25.2863 25.9866 27.5799 24.4525Z"}),/*#__PURE__*/e.jsx("path",{d:"M30.1447 22.1436C32.8717 21.5877 35.8061 22.2746 37.966 24.0228C41.8241 27.1455 42.3372 32.8403 42.753 37.4549L42.7742 37.69C43.3115 43.6385 42.6964 49.4163 41.4575 55.2186C41.3817 55.5736 41.0326 55.7999 40.6776 55.7241C40.3227 55.6483 40.0964 55.2991 40.1722 54.9442C41.3926 49.2288 41.9873 43.5885 41.4652 37.8082C41.4479 37.6169 41.4307 37.4228 41.4133 37.2264L41.4131 37.2235C41.0438 33.0534 40.5812 27.8304 37.1392 25.0444C35.2926 23.5498 32.7599 22.9518 30.4073 23.4314C30.0517 23.5039 29.7046 23.2744 29.6321 22.9188C29.5596 22.5632 29.7891 22.2161 30.1447 22.1436Z"}),/*#__PURE__*/e.jsx("path",{d:"M40.5287 58.4885C40.6183 58.1368 40.4057 57.7791 40.054 57.6896C39.7023 57.6 39.3446 57.8126 39.2551 58.1643C38.8578 59.7247 38.2456 61.1333 37.4695 62.4301C37.2831 62.7415 37.3844 63.145 37.6958 63.3314C38.0072 63.5178 38.4108 63.4165 38.5972 63.1051C39.4336 61.7075 40.0977 60.1816 40.5287 58.4885Z"}),/*#__PURE__*/e.jsx("path",{d:"M37.3152 48.9521C37.6756 48.9948 37.9332 49.3215 37.8906 49.682C37.2699 54.9267 35.8688 59.6042 33.6205 63.6613C33.4446 63.9787 33.0446 64.0934 32.7272 63.9175C32.4097 63.7416 32.295 63.3417 32.4709 63.0242C34.6226 59.1416 35.9811 54.6339 36.5854 49.5275C36.6281 49.1671 36.9548 48.9095 37.3152 48.9521Z"}),/*#__PURE__*/e.jsx("path",{d:"M37.1798 30.6556C36.7242 28.2212 34.6349 26.3591 32.0985 26.3591C28.6638 26.3591 26.254 29.8212 27.1032 33.0422C28.54 38.7279 28.7759 44.2077 27.8032 49.4855L27.8025 49.4893C26.9584 54.228 25.3374 58.4908 23.1263 62.1031C22.9368 62.4127 23.0342 62.8172 23.3437 63.0067C23.6533 63.1962 24.0578 63.0988 24.2473 62.7893C26.5488 59.0292 28.2249 54.6109 29.0961 49.7218C30.106 44.2403 29.8558 38.5684 28.3765 32.7168L28.3748 32.7099C27.7378 30.3005 29.5133 27.6734 32.0985 27.6734C33.9641 27.6734 35.5393 29.0459 35.8871 30.8929C36.8436 36.4411 37.3418 41.5862 36.9871 46.016C36.9581 46.3778 37.2279 46.6945 37.5897 46.7235C37.9515 46.7525 38.2682 46.4827 38.2972 46.1209C38.6649 41.5294 38.1459 36.2576 37.1815 30.6648C37.1809 30.6617 37.1804 30.6586 37.1798 30.6556Z"}),/*#__PURE__*/e.jsx("path",{d:"M30.1376 59.1171C30.4604 59.283 30.5876 59.6792 30.4217 60.002L28.6804 63.3906C28.5145 63.7134 28.1184 63.8406 27.7956 63.6747C27.4728 63.5088 27.3456 63.1127 27.5114 62.7899L29.2527 59.4013C29.4186 59.0785 29.8147 58.9513 30.1376 59.1171Z"}),/*#__PURE__*/e.jsx("path",{d:"M32.5872 31.2892C32.5042 30.9359 32.1505 30.7168 31.7972 30.7998C31.4439 30.8828 31.2247 31.2365 31.3077 31.5898C33.5238 41.0232 33.2194 49.3066 30.5201 56.363C30.3905 56.702 30.5602 57.0819 30.8991 57.2115C31.2381 57.3412 31.618 57.1715 31.7477 56.8326C34.5622 49.475 34.8483 40.9141 32.5872 31.2892Z"})]}),/*#__PURE__*/e.jsx("defs",{children:/*#__PURE__*/e.jsx("clipPath",{id:"clip0_113_33841",children:/*#__PURE__*/e.jsx("rect",{width:"64",height:"64",fill:"white",transform:"translate(0.483887)"})})})]}),On=({onClose:t,onReset:n,submitEnrollmentWithPasskey:i})=>{let{user:a}=d.usePrivyContext(),{initLinkWithPasskey:o,linkWithPasskey:l}=v.usePrivyInternal(),c=s.useAppConfig(),[u,h]=r.useState(!1),[p,y]=r.useState(!1),[m,w]=r.useState(null),g=r.useMemo((()=>a?.linkedAccounts.filter((e=>"passkey"===e.type))??[]),[a]),f=async e=>{h(!0);try{await i(e)}catch(e){w(e)}finally{h(!1)}},C=async()=>{y(!0),w(null);try{await o();let e=await l(),t=e?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];await f(t)}catch(e){w(e)}finally{y(!1)}};return 0===g.length||p?/*#__PURE__*/e.jsx(Mn,{onReset:n,onClose:t,onClick:C,isCreating:p}):m?/*#__PURE__*/e.jsx(s.ErrorScreenView,{allowlistConfig:c.allowlistConfig,error:m,onBack:()=>w(null),onRetry:()=>w(null)}):/*#__PURE__*/e.jsx(Nn,{passkeys:g,isSubmitting:u,isCreating:p,onReset:n,onClose:t,onSubmitEnrollment:()=>f(g.map((e=>e.credentialId))),onAddPasskey:C})};let Mn=({onReset:t,onClose:r,onClick:n,isCreating:i})=>/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:t,onClose:r},"header"),/*#__PURE__*/e.jsx(vt,{children:/*#__PURE__*/e.jsxs(Br,{children:[/*#__PURE__*/e.jsx(Dt,{}),/*#__PURE__*/e.jsx(Rn,{})]})}),/*#__PURE__*/e.jsx(Ct,{children:"Set up passkey verification"}),/*#__PURE__*/e.jsxs(Pt,{children:[/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(ie.default,{})}),"Verify with Touch ID, Face ID, PIN, or hardware key"]}),/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(ye.default,{})}),"Takes seconds to set up and use"]}),/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(pe.default,{})}),"Use your passkey to verify transactions and login to your account"]})]}),/*#__PURE__*/e.jsx(s.PrimaryButton,{style:{marginTop:"2.25rem"},onClick:n,loading:i,children:"Add a new passkey"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}),Nn=({onReset:t,onClose:n,onAddPasskey:i,onSubmitEnrollment:a,passkeys:o,isSubmitting:l,isCreating:c})=>{let[d,u]=r.useState(!1),h=d?o.length:o.length>3?2:3;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:d?()=>u(!1):t,onClose:n},"header"),!d&&/*#__PURE__*/e.jsx(vt,{children:/*#__PURE__*/e.jsxs(Br,{children:[/*#__PURE__*/e.jsx(Dt,{}),/*#__PURE__*/e.jsx(Rn,{})]})}),/*#__PURE__*/e.jsx(Ct,{children:"Enable your passkeys for verification"}),/*#__PURE__*/e.jsxs(Pt,{children:[o.slice(0,h).map((t=>/*#__PURE__*/e.jsxs(jn,{children:[/*#__PURE__*/e.jsx(Fn,{children:Dn(t)}),/*#__PURE__*/e.jsxs(Ln,{children:["Last used: ",t.latestVerifiedAt?.toLocaleString()]})]},t.credentialId))),!d&&o.length>3&&/*#__PURE__*/e.jsx(qn,{onClick:()=>u(!0),children:"View All"})]}),/*#__PURE__*/e.jsx(s.PrimaryButton,{style:{marginTop:"1.5rem"},onClick:a,loading:l,children:"Enable passkeys"}),o.length<5&&/*#__PURE__*/e.jsx(qn,{style:{marginTop:"0.5rem"},onClick:i,disabled:c,children:c?/*#__PURE__*/e.jsx(s.Loader,{style:{height:"1rem",width:"1rem",borderWidth:2}}):"Add new passkey"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},jn=/*#__PURE__*/f.styled.div.withConfig({displayName:"PasskeyItem",componentId:"sc-23451ce2-0"})(["&&{padding:0.75rem 1rem;text-align:left;border-radius:0.5rem;border:1px solid var(--privy-color-foreground-4);width:100%;}"]),Fn=/*#__PURE__*/f.styled.div.withConfig({displayName:"PasskeyItemTitle",componentId:"sc-23451ce2-1"})(["font-size:0.875rem;line-height:1.375rem;font-weight:500;color:var(--privy-color-foreground-1);"]),Ln=/*#__PURE__*/f.styled.div.withConfig({displayName:"PasskeyItemSubtitle",componentId:"sc-23451ce2-2"})(["font-size:0.75rem;font-weight:400;line-height:1.125rem;color:var(--privy-color-foreground-2);"]),Dn=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 qn=/*#__PURE__*/f.styled.button.withConfig({displayName:"StyledLink",componentId:"sc-23451ce2-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;}}"]),Hn=({appName:t,onComplete:n,onReset:i,onClose:o})=>{let[l,c]=r.useState(""),[d,u]=r.useState(!1),[h,p]=r.useState(null),[y,m]=r.useState("enroll"),{initEnrollmentWithSms:w,submitEnrollmentWithSms:g}=Tn(),{data:f}=s.usePrivyModal(),v=s.useAppConfig();function C(){f?.mfaEnrollmentFlow?.onSuccess(),n()}return h?/*#__PURE__*/e.jsx(s.ErrorScreenView,{allowlistConfig:v.allowlistConfig,error:h,onBack:()=>p(null),onRetry:()=>p(null)}):"enroll"===y?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:i,onClose:o},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ne.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Set up SMS verification"}),/*#__PURE__*/e.jsxs(Et,{children:["We'll text a verification code to this mobile device whenever you use your ",t," ","wallet."]}),/*#__PURE__*/e.jsxs(At,{children:[/*#__PURE__*/e.jsx(s.ConnectPhoneNumberForm,{onSubmit:async function({qualifiedPhoneNumber:e}){try{await w({phoneNumber:e}),c(e),m("verify")}catch(e){p(e)}},hideRecent:!0}),/*#__PURE__*/e.jsxs(Rt,{children:["By providing your mobile number, you agree to receive text messages from ",v?.name,". Some carrier charges may apply"]})]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):d?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:C},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(me.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"SMS verification added"}),/*#__PURE__*/e.jsxs(Et,{children:["From now on, you'll enter the verification code sent to your mobile device whenever you use your ",t," wallet."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:C,children:"Done"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:function(){"verify"===y?m("enroll"):i()},onClose:o},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ne.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Enter enrollment code"}),/*#__PURE__*/e.jsxs(At,{children:[/*#__PURE__*/e.jsx($t,{onChange:async function(e){try{if(!e)return;await g({phoneNumber:l,mfaCode:e}),u(!0)}catch(e){if(s.errorIndicatesMfaRateLimit(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(s.errorIndicatesMfaVerificationFailed(e))throw Error("The code you entered is not valid");if(s.errorIndicatesMfaTimeout(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw s.errorIndicatesMfaCanceled(e)?Error("Verification canceled"):Error("Unknown error")}}}),/*#__PURE__*/e.jsxs(Et,{children:["To continue, enter the 6-digit code sent to ",/*#__PURE__*/e.jsx("strong",{children:a.lastFourDigits(l)})]})]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},Bn=({size:t,authUrl:r})=>/*#__PURE__*/e.jsx(s.QrCode,{url:r,squareLogoElement:we.default,size:t,fgColor:"#1F1F1F"}),zn=({onClose:t,onReset:n,totpInfo:i,submitEnrollmentWithTotp:a,error:o})=>{let[l,c]=r.useState("enroll");return"enroll"===l?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:n,onClose:t},"header"),/*#__PURE__*/e.jsx(s.Title,{children:"Scan QR code"}),/*#__PURE__*/e.jsx(s.Subtitle,{children:"Open your authenticator app and scan this code to continue"}),/*#__PURE__*/e.jsx(s.CenteredItemWithPadding,{children:/*#__PURE__*/e.jsx(Bn,{authUrl:i.authUrl,size:240})}),/*#__PURE__*/e.jsx(s.LabelXs,{style:{textAlign:"left"},children:"Setup key"}),/*#__PURE__*/e.jsxs(s.Box,{style:{marginTop:"0.25rem"},children:[/*#__PURE__*/e.jsx(C.Column,{children:"•".repeat(16)}),/*#__PURE__*/e.jsx(s.CopytoClipboardButton,{itemName:" ",text:i.secret})]}),/*#__PURE__*/e.jsx(s.PrimaryButton,{style:{marginTop:"1rem"},onClick:function(){c("verify")},children:"Continue"}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:function(){"verify"===l?c("enroll"):n()},onClose:t},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(te.default,{})}),/*#__PURE__*/e.jsx(s.Title,{children:"Enter enrollment code"}),/*#__PURE__*/e.jsx(s.Subtitle,{children:"To continue, enter the 6-digit code generated from your authenticator app"}),/*#__PURE__*/e.jsx(At,{children:/*#__PURE__*/e.jsx($t,{onChange:async function(e){try{if(!e)return;await a({mfaCode:e})}catch(e){if(s.errorIndicatesMfaRateLimit(e))throw Error("You have exceeded the maximum number of attempts. Please close this window and try again in 10 seconds.");if(s.errorIndicatesMfaVerificationFailed(e))throw Error("The code you entered is not valid");if(s.errorIndicatesMfaTimeout(e))throw Error("You have exceeded the time limit for code entry. Please try again in 30 seconds.");throw s.errorIndicatesMfaCanceled(e)?Error("Verification canceled"):Error("Unknown error")}},errorReasonOverride:o?.message})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})},Kn={component:()=>{let{user:t,enrollInMfa:n,ready:i}=d.usePrivyContext(),[a,o]=r.useState(null),{unenrollWithSms:l,unenrollWithTotp:c,unenrollWithPasskey:u,submitEnrollmentWithTotp:h,initEnrollmentWithPasskey:p,submitEnrollmentWithPasskey:y,initEnrollmentWithTotp:m}=Tn(),{data:w,onUserCloseViaDialogOrKeybindRef:g}=s.usePrivyModal(),f=s.useAppConfig(),{closePrivyModal:C}=v.usePrivyInternal(),{promptMfa:E}=Qt(),[A,P]=r.useState(!1),[k,b]=r.useState(null),[x,T]=r.useState(null),S=()=>{C({shouldCallAuthOnSuccess:!0}),n(!1),setTimeout((()=>{o(null),b(null)}),500)},[_,I]=r.useState(!1),[U,W]=r.useState();g.current=S;let R=t?.mfaMethods.includes("sms"),O=!!t?.phone,M=t?.mfaMethods.includes("totp"),N=t?.mfaMethods.includes("passkey"),j=R||M||N,F=t?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function L(){o(null),b(null)}async function D(e=F){I(!0);try{return await p(),await y({credentialIds:e},{removeForLogin:w?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa}),w?.mfaEnrollmentFlow?.onSuccess(),S()}catch(e){W(e)}finally{I(!1)}}if(r.useEffect((()=>{j&&P(!0)}),[j]),!i||!t||!f/*#__PURE__*/)return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:S},"header"),/*#__PURE__*/e.jsx(vt,{children:/*#__PURE__*/e.jsx(Sn,{})}),/*#__PURE__*/e.jsx(At,{children:/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("sms"===a)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:L,onClose:S},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(le.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Remove SMS verification?"}),/*#__PURE__*/e.jsxs(Et,{children:["MFA adds an extra layer of security to your ",f?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{$warn:!0,onClick:async function(){o(null);try{await l()}catch(e){o(null)}},children:"Remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("totp"===a)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:L,onClose:S},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(le.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Remove authenticator app verification?"}),/*#__PURE__*/e.jsxs(Et,{children:["MFA adds an extra layer of security to your ",f?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{$warn:!0,onClick:async function(){o(null);try{await c()}catch(e){o(null)}},children:"Remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("passkey"===a){let t=w?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:L,onClose:S},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(le.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/e.jsx(Et,{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(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{$warn:!0,onClick:async function(){o(null);try{await u({removeForLogin:w?.mfaEnrollmentFlow?.shouldUnlinkOnUnenrollMfa})}catch(e){o(null)}},children:"Remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})}if(0===w.mfaEnrollmentFlow.mfaMethods.length&&!j)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:S},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ie.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Add more security"}),/*#__PURE__*/e.jsxs(Et,{children:[f?.name," does not have any verification methods enabled."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:S,children:"Close"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});let q=!j&&!A;return q?/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:S},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ie.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Transaction Protection"}),/*#__PURE__*/e.jsx(Et,{children:"Set up transaction protection to add an extra layer of security to your account"}),/*#__PURE__*/e.jsxs(Pt,{children:[/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(ce.default,{})}),"Enable 2-Step verification for your ",f?.name," wallet."]}),/*#__PURE__*/e.jsxs(bt,{children:[/*#__PURE__*/e.jsx(kt,{children:/*#__PURE__*/e.jsx(de.default,{})}),"You'll be prompted to authenticate to complete transactions."]})]}),/*#__PURE__*/e.jsxs(xt,{children:[/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:()=>P(!0),children:"Continue"}),/*#__PURE__*/e.jsx(s.SecondaryButton,{onClick:S,children:"Not now"})]}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]}):"sms"===k?/*#__PURE__*/e.jsx(Hn,{appName:f?.name||"Privy",onComplete:S,onReset:L,onClose:S}):"totp"===k&&x?/*#__PURE__*/e.jsx(zn,{onClose:S,onReset:L,submitEnrollmentWithTotp:({mfaCode:e})=>async function(e){try{return W(void 0),await h({mfaCode:e}),w?.mfaEnrollmentFlow?.onSuccess(),S()}catch(e){W(e)}finally{o(null)}}(e),totpInfo:{...x,appName:f?.name||"Privy"}}):"passkey"===k?/*#__PURE__*/e.jsx(On,{onReset:L,onClose:S,submitEnrollmentWithPasskey:D}):/*#__PURE__*/e.jsx(In,{showIntro:q,userMfaMethods:t.mfaMethods,appMfaMethods:f.mfa.methods,userHasAuthSms:O,backFn:function(){P(!1)},handleSelectMethod:async function(e){try{await E()}catch(e){return void W(e)}return"totp"===e?(b(e),T(null),void m().then((e=>{T(e)})).catch((()=>{T(null),L()}))):"passkey"===e&&1===F.length?await D():void b(e)},isTotpLoading:"totp"===k&&!x,isPasskeyLoading:_,error:U,onClose:S,setRemovingMfaMethod:async e=>{try{await E()}catch(e){return void W(e)}o(e)}})}},Vn=({providerName:t,ProviderLogo:r,success:n,errorMessage:i,onRetry:a})=>{let o=n?`Successfully connected with ${t}`:i?i.message:`Verifying connection to ${t}`;/*#__PURE__*/return e.jsx(s.ScreenLayout,{title:o,subtitle:n?"You're good to go!":i?i.detail:"Just a few moments more",icon:r,iconVariant:"loading",iconLoadingStatus:{success:n,fail:!!i},secondaryCta:i?.retryable&&a?{label:"Retry",onClick:a}:void 0,watermark:!0})},$n={component:()=>{let{authenticated:t,logout:n,ready:i,user:a}=d.usePrivyContext(),{setModalData:l,navigate:c,resetNavigation:u}=s.usePrivyModal(),h=s.useAppConfig(),{getAuthMeta:p,initLoginWithOAuth:y,loginWithOAuth:m,updateWallets:w,setReadyToTrue:g,closePrivyModal:f,createAnalyticsEvent:C}=v.usePrivyInternal(),[E,A]=r.useState(!1),[P,k]=r.useState(void 0),b=p()?.provider||"google",{name:x,component:T}=Ie(b,h.customOAuthProviders);return r.useEffect((()=>{m(b).then((()=>{A(!0),g(!0)})).catch((e=>{if(g(!1),e?.privyErrorCode===o.PrivyErrorCode.ALLOWLIST_REJECTED)return k(void 0),u(),void c(s.AllowlistRejectionScreen);if(e?.privyErrorCode===o.PrivyErrorCode.USER_LIMIT_REACHED)return console.error(new o.PrivyUserLimitReachedError(e).toString()),k(void 0),u(),void c(s.UserLimitReachedScreen);if(e?.privyErrorCode===o.PrivyErrorCode.USER_DOES_NOT_EXIST)return k(void 0),u(),void c(s.AccountNotFoundScreen);if(e?.privyErrorCode===o.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return k(void 0),u(),l({accountTransfer:{nonce:e.data?.data?.nonce,account:e.data?.data?.subject,displayName:e.data?.data?.account?.displayName,linkMethod:p()?.provider,embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress,oAuthUserInfo:e.data?.data?.otherUser?.oAuthUserInfo}}),void c(s.LinkConflictScreen);let{retryable:t,detail:r}=function(e,t,r){let n={detail:"",retryable:!1},i=s.e(t);if(e?.privyErrorCode===o.PrivyErrorCode.LINKED_TO_ANOTHER_USER&&(n.detail="This account has already been linked to another user."),e?.privyErrorCode===o.PrivyErrorCode.INVALID_CREDENTIALS&&(n.retryable=!0,n.detail="Something went wrong. Try again."),e.privyErrorCode===o.PrivyErrorCode.OAUTH_USER_DENIED&&(n.detail=`Retry and check ${i} to finish connecting your account.`,n.retryable=!0),e?.privyErrorCode===o.PrivyErrorCode.TOO_MANY_REQUESTS&&(n.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===o.PrivyErrorCode.TOO_MANY_REQUESTS&&e.message.includes("provider rate limit")){let e=Ie(t,r).name;n.detail=`Request limit reached for ${e}. Please wait a moment and try again.`}if(e?.privyErrorCode===o.PrivyErrorCode.OAUTH_ACCOUNT_SUSPENDED){let e=Ie(t,r).name;n.detail=`Your ${e} account is suspended. Please try another login method.`}return e?.privyErrorCode===o.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE&&(n.detail="You cannot authorize more than one account for this user."),e?.privyErrorCode===o.PrivyErrorCode.OAUTH_UNEXPECTED&&t.startsWith("privy:")&&(n.detail="Something went wrong. Please try again."),n}(e,b,h.customOAuthProviders);k({retryable:t,detail:r,message:"Authentication failed"})})).finally((()=>{s.stripUrlOAuthParamsAndRemoveStateCode()}))}),[x,b]),r.useEffect((()=>{if(i&&t&&E&&a){if(h?.legal.requireUsersAcceptTerms&&!a.hasAcceptedTerms){let e=setTimeout((()=>{c(s.AffirmativeConsentScreen)}),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}if(s.shouldProceedtoEmbeddedWalletCreationFlow(a,h.embeddedWallets)){let e=setTimeout((()=>{l({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),C({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,provider:b,screen:"OAuthStatusScreen"}}),n()},callAuthOnSuccessOnClose:!0}}),c(s.EmbeddedWalletOnAccountCreateScreen)}),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return()=>clearTimeout(e)}{let e=setTimeout((()=>f({shouldCallAuthOnSuccess:!0,isSuccess:!0})),s.DEFAULT_SUCCESS_SCREEN_DURATION_MS);return w(),()=>clearTimeout(e)}}}),[i,t,E,a]),/*#__PURE__*/e.jsx(Vn,{providerName:x,ProviderLogo:T,success:E,errorMessage:P,onRetry:P?.retryable?()=>{s.stripUrlOAuthParamsAndRemoveStateCode(),y(b),k(void 0)}:void 0})}},Yn=/*#__PURE__*/r.forwardRef(((t,n)=>{let[i,a]=r.useState(""),[o,l]=r.useState(""),[c,u]=r.useState(!1),{authenticated:h,user:p}=d.usePrivyContext(),{initUpdateEmail:y}=v.usePrivyInternal(),{navigate:m,setModalData:w,currentScreen:g}=s.usePrivyModal(),{enabled:f,token:C}=s.useCaptcha(),E=s.useAppConfig(),A=s.validateEmail(i)&&(E.disablePlusEmails&&i.includes("+")?(o||l("Please enter a valid email address without a '+'."),!1):(o&&l(""),!0)),P=c||!A,k=()=>{!f||C||h?(async e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");u(!0);try{await y({oldAddress:p.email.address,newAddress:i,captchaToken:e}),m(s.AwaitingPasswordlessCodeScreen)}catch(e){w({errorModalData:{error:e,previousScreen:g||s.LandingScreen}}),m(s.ErrorScreen)}u(!1)})(C):(w({captchaModalData:{callback:e=>{if(!p?.email)throw Error("User is required to have an email address to update it.");return y({oldAddress:p.email.address,newAddress:i,captchaToken:e})},userIntentRequired:!1,onSuccessNavigateTo:s.AwaitingPasswordlessCodeScreen,onErrorNavigateTo:s.ErrorScreen}}),m(s.CaptchaScreen))};/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsxs(Gn,{children:[o&&/*#__PURE__*/e.jsx(s.ErrorMessage,{style:{marginTop:"0.25rem",textAlign:"left"},children:o}),/*#__PURE__*/e.jsxs(Zn,{$error:!!o,children:[/*#__PURE__*/e.jsx(s.LoginMethodIconWrapper,{children:/*#__PURE__*/e.jsx(U.Mail,{})}),/*#__PURE__*/e.jsx("input",{ref:n,id:"email-input",type:"email",placeholder:"your@email.com",onChange:e=>a(e.target.value),onKeyUp:e=>{"Enter"===e.key&&k()},value:i,autoComplete:"email"}),t.stacked?null:/*#__PURE__*/e.jsx(s.EmbeddedButton,{isSubmitting:c,onClick:k,disabled:P,children:"Submit"})]})]}),t.stacked?/*#__PURE__*/e.jsx(s.PrimaryButton,{loadingText:null,loading:c,disabled:P,onClick:k,style:{width:"100%"},children:"Submit"}):null]})}));let Gn=s.InputContainerForm,Zn=s.EmailUpdateForm;const Jn=({title:t="Update your email",subtitle:r="Add the email address you'd like to use going forward. We'll send you a confirmation code"})=>/*#__PURE__*/e.jsx(s.ScreenLayout,{title:t,subtitle:r,icon:se.default,watermark:!0,children:/*#__PURE__*/e.jsx(s.BottomPusherContainer,{children:/*#__PURE__*/e.jsx(Yn,{stacked:!0})})}),Xn={component:()=>/*#__PURE__*/e.jsx(Jn,{})},Qn=({title:t="Update your phone number",subtitle:n="Add the phone number you'd like to use going forward. We'll send you a confirmation code",onSubmit:i,isSubmitting:a=!1})=>{let[o,l]=r.useState(null);/*#__PURE__*/return e.jsx(s.ScreenLayout,{title:t,subtitle:n,icon:ne.default,primaryCta:{label:a?"Submitting":"Update",onClick:async()=>{o?.qualifiedPhoneNumber&&await i(o)},disabled:!o?.isValid||a},watermark:!0,children:/*#__PURE__*/e.jsx(s.ConnectPhoneNumberForm,{onChange:e=>{l(e)},onSubmit:async()=>{},noIncludeSubmitButton:!0,hideRecent:!0})})},ei={component:()=>{let{currentScreen:t,data:n,navigate:i,setModalData:a}=s.usePrivyModal(),{user:o}=d.usePrivyContext(),{initUpdatePhone:l}=v.usePrivyInternal(),[c,u]=r.useState(!1);/*#__PURE__*/return e.jsx(Qn,{onSubmit:async e=>{u(!0);try{if(!o?.phone?.number)throw Error("User is required to have an phone number to update it.");await l(o?.phone?.number,e.qualifiedPhoneNumber),i(s.AwaitingPasswordlessCodeScreen)}catch(e){a({errorModalData:{error:e,previousScreen:n?.errorModalData?.previousScreen||t||kn}}),i(s.ErrorScreen)}finally{u(!1)}},isSubmitting:c})}};function ti({subscribe:e,getExternalJwt:t,enabled:n=!0,onAuthenticated:i,onUnauthenticated:a,onError:s}){let{client:l,onCustomAuthAuthenticated:c}=v.usePrivyInternal(),{logout:d,authenticated:u,ready:h}=I.usePrivy();if(!l)throw new o.PrivyClientError("`useSyncJwtBasedAuthState` must be used within a `PrivyProvider`");let[p,y]=r.useState({status:"initial"}),m=r.useRef(),w=r.useRef(!1),g=r.useRef(t);r.useEffect((()=>{g.current=t}),[t]);let f=r.useRef(i);r.useEffect((()=>{f.current=i}),[i]);let C=r.useRef(a);r.useEffect((()=>{C.current=a}),[a]);let E=r.useRef(s);return r.useEffect((()=>{E.current=s}),[s]),r.useEffect((()=>{if(!n||!h)return;let t=async()=>{if(!w.current){w.current=!0;try{y({status:"loading"});let e=await g.current();if(void 0!==m.current&&m.current===e)return void y({status:"done"});if(!e)return u&&(await d(),C.current?.()),m.current=e,void y({status:"done"});l.startAuthFlow(new at(e));let{user:t,isNewUser:r=!1}=await l.authenticate();if(!t)throw new o.PrivyClientError("Failed to sync with custom auth provider");f.current?.({user:t,isNewUser:r}),c(t,r),m.current=e,y({status:"done"})}catch(e){if(console.warn(e),await d().catch((()=>{})),C.current?.(),e instanceof o.PrivyApiError&&e.privyErrorCode===o.PrivyErrorCode.LINKED_TO_ANOTHER_USER)return y({status:"initial"}),void setTimeout((()=>{t()}),0);E.current?.(e),y({status:"error",error:e})}finally{w.current=!1}}};return t(),e(t)}),[e,l,c,u,d,n,h]),n?{state:p}:{state:{status:"not-enabled"}}}let ri=w.create((()=>({jwtAuthFlowState:{status:"not-enabled"}})));function ni({customAuth:e}){let{jwtAuthFlowState:t}=function({customAuth:e}){let t=s.useEmitPrivyEvent(),n=r.useRef(),i=r.useCallback((e=>(n.current=e,()=>{n.current=void 0})),[]),a=e?.getCustomAccessToken??(()=>Promise.resolve(void 0)),{state:l}=ti({enabled:!0===e?.enabled,subscribe:i,getExternalJwt:a,onAuthenticated:({user:e,isNewUser:r})=>{t("login","onComplete",{user:e,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),t("customAuth","onAuthenticated",{user:e})},onUnauthenticated:()=>{t("customAuth","onUnauthenticated")},onError:e=>{t("login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}});return r.useEffect((()=>{(async()=>{e&&!e.isLoading&&n.current?.()})()}),[e?.enabled,e?.getCustomAccessToken,e?.isLoading]),{jwtAuthFlowState:l}}({customAuth:e});return r.useEffect((()=>{ri.setState({jwtAuthFlowState:t})}),[t]),null}const ii=/*#__PURE__*/r.createContext(!1);let ai,oi,si,li,ci,di;async function ui(){return ai?ai.getAccessToken():Promise.resolve(s.f.get(s.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||s.f.get(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const hi=(e,t)=>oi(e,t),pi=(e,t)=>si(e,t),yi=(e,t)=>li(e,t),mi=(e,t)=>ci(e,t),wi=e=>di(e);let gi=l=>{let c=l.client,u=l.privy,h=s.usePlugins();Ir();let[p,y]=r.useState(!1),m=tr((e=>e.inProgressMfaFlow)),[w,g]=r.useState(!1),[f,C]=r.useState(!1),[E,A]=r.useState(null),[P,k]=r.useState([]),[b,x]=r.useState(void 0),[T,S]=r.useState(!1),[_,U]=r.useState(null),[W,R]=r.useState(!1),[O,M]=r.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:v.notImplemented}),[N,j]=r.useState({status:"initial"}),[F,L]=r.useState({status:"initial"}),[D,q]=r.useState({status:"initial"}),[H,B]=r.useState({status:"initial"}),[z,K]=r.useState({status:"initial"}),[V,$]=r.useState({status:"initial"}),[Y,G]=r.useState(null),Z=s.useAppConfig(),J=s.useIsServerConfigLoaded(),[X,Q]=r.useState({}),[ee,te]=r.useState(null),re=r.useRef(null),[ne,ie]=r.useState(!1),[ae,oe]=r.useState(!1),se=r.useRef(null),le=r.useRef(null),ce=r.useRef(s.privyEventsDefault),[de,ue]=r.useState(!1);c.onStoreCustomerAccessToken=e=>{e&&s.emitPrivyEvent(ce,"accessToken","onAccessTokenGranted",{accessToken:e})},c.onDeleteCustomerAccessToken=()=>{A(null),C(!1),s.emitPrivyEvent(ce,"accessToken","onAccessTokenRemoved")};let he=r.useRef(null),pe=r.useRef(null),ye=r.useRef(!1),me=({showWalletUIs:e})=>ye.current?ye.current:void 0!==e?!e:!Z.embeddedWallets.showWalletUIs,we=e=>{U(e),setTimeout((()=>{y(!0)}),15)};r.useEffect((()=>{if(!E)return void c.connectors?.removeEmbeddedWalletConnectors();let e=d.getPrivyEthereumWallet(E),t=d.getPrivyEthereumHDWallets(E),r=d.getImportedPrivyEthereumWallets(E);e&&t.length||c.connectors?.removeEmbeddedWalletConnectors(),r.length||c.connectors?.removeImportedWalletConnectors(),c.connectors?Y?(e&&c.connectors.addEmbeddedWalletConnectors({walletProxy:Y,user:E,embeddedWallets:t,defaultChain:Z.defaultChain,appId:l.appId,privyClient:u}),r.forEach((e=>c.connectors?.addImportedWalletConnector(Y,e.address,Z.defaultChain,l.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")}),[Y,E]),r.useEffect((()=>{Y&&re.current?.(Y)}),[Y]);let ge=r.useCallback(((e,t)=>{A(e),S(t),C(!0),oe(!0)}),[]);r.useEffect((()=>{ae&&Y&&E&&(async()=>{let e=s.shouldCreateEmbeddedEthWallet(E,Z.embeddedWallets.ethereum.createOnLogin),t=s.shouldCreateEmbeddedSolWallet(E,Z.embeddedWallets.solana.createOnLogin),r=await ui();if(r){if(e&&t){let e=await Y.create({accessToken:r});return await Y.createSolana({accessToken:r,ethereumAddress:e?.address}),void oe(!1)}if(t)return await Y.createSolana({accessToken:r,ethereumAddress:d.getPrivyEthereumWallet(E)?.address}),await Ke.refreshSessionAndUser(),void oe(!1);if(e)return await Y.create({accessToken:r}),void oe(!1)}})().catch(console.error)}),[ae&&Y&&E]),r.useEffect((()=>{if(Z.externalWallets.solana.connectors)return Z.externalWallets.solana.connectors.onMount(),()=>Z.externalWallets.solana.connectors?.onUnmount()}),[Z.externalWallets.solana.connectors]),r.useEffect((()=>{!w&&J&&async function(){let e,r=fe(),n=Ae(),i=t.createStore();c.initializeConnectorManager({walletConnectCloudProjectId:Z.walletConnectCloudProjectId,rpcConfig:Z.rpcConfig,chains:Z.chains,defaultChain:Z.defaultChain,store:i,walletList:Z.appearance.walletList,shouldEnforceDefaultChainOnConnect:Z.shouldEnforceDefaultChainOnConnect,externalWalletConfig:Z.externalWallets,appName:Z.name??"Privy",walletChainType:Z.appearance.walletChainType,setBaseAccountSdk:x}),c.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=c.connectors.walletConnectors.length,r=c.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?ue(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),ue(!0)}),1500)})),c.connectors?.initialize().then((()=>{Ie()}));let a=await c.getAuthenticatedUser(),o=!!a;Z.legal.requireUsersAcceptTerms&&a&&!a.hasAcceptedTerms?(await c.logout(),Ke.setReadyToTrue(!0),s.emitPrivyEvent(ce,"logout","onSuccess")):(Z.customAuth?.enabled||(C(!!a),a&&s.emitPrivyEvent(ce,"login","onComplete",{user:a,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),A(a)),r?pe.current=o?"link":"login":n&&!o?(pe.current="login",Q({telegramAuthModalData:{seamlessAuth:!0}}),we(s.TelegramAuthScreen)):Ke.setReadyToTrue(!!a))}()}),[c,ee,w,J]),r.useEffect((()=>{if(w){if(!E||!E.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void ie(!!Y);if([...P].some((e=>"privy"===e.walletClientType)))return void ie(!0);ie(!!Y)}}),[w,E,P,Y]),r.useEffect((()=>{c.connectors?.setWalletList(Z.appearance.walletList)}),[Z.appearance.walletList.join()]);let fe=()=>{let e=Ue();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(Ur).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(c.startAuthFlow(new xe({...e,customOAuthRedirectUrl:Z.customOAuthRedirectUrl})),we($n),!0))},Ae=()=>{let e=s.detectCompletingTelegramFlow();if(!e||!Z.loginMethods.telegram||!Z.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new s.TelegramAuthFlow;return c.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},Pe=async(e,t,r,n)=>{if("solana_adapter"!==e)Te(await(c.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,n);else{let e=c.connectors?.findSolanaWalletConnector(t);if(!e)return;Te(e,t,r,n)}};async function Te(e,t,r,n){if(!e)return M({status:"disconnected",connectedWallet:null,connectError:new o.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:v.notImplemented}),n?.(null,r);M({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:v.notImplemented}),e instanceof s.WalletConnectV2WalletConnector&&t&&await e.resetConnection(t),M({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Te(e,t,r,n)});try{let t=await e.connect({showPrompt:!0});if((!t||s.isBaseConnectedEthereumWallet(t))&&Z.shouldEnforceDefaultChainOnConnect&&!Z.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){M((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:v.notImplemented})));try{await(t?.switchChain(Z.defaultChain.id)),t&&(t.chainId=s.formatChainIdToCAIP2(i.toHex(Z.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${Z.defaultChain.id}`)}}return M((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:v.notImplemented}))),t&&s.emitPrivyEvent(ce,"connectWallet","onSuccess",{wallet:t}),n?.(t,r)}catch(e){return e instanceof o.PrivyError?(console.warn(e.cause?e.cause:e.message),s.emitPrivyEvent(ce,"connectWallet","onError",e.privyErrorCode||o.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),s.emitPrivyEvent(ce,"connectWallet","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),M((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Se=async(e,t,r)=>{if(null===e||!s.isBaseConnectedEthereumWallet(e))return;let n=new s.SiweFlow(c,e,t,r);c.startAuthFlow(n)},_e=async(e,t,r,n="plain")=>{let i=h(s.SOLANA_LEDGER_PLUGIN_ID);if("transaction"===n&&!i)throw new o.PrivyClientError("useSolanaLedger plugin hook must be mounted");if(null===e||!s.isBaseConnectedSolanaWallet(e))return;let a=new s.SiwsFlow(e,c,t,r,n,i);c.startAuthFlow(a)},Ie=()=>{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=s.getWalletConfigForConnector({connectorType:t,walletClientType:r});if(!i||!i.isInstalled)return we(xn);if(!c.connectors)throw new o.PrivyClientError("Connector not initialized");we(n?s.ConnectOnlyStatusScreen:s.ConnectionStatusScreen);let a=new URL(window.location.href);a.searchParams.delete("privy_connector"),a.searchParams.delete("privy_wallet_client"),a.searchParams.delete("privy_connect_only"),window.history.pushState({},"",a),Pe(t,r,void 0,n?void 0:"solana_adapter"===t?_e:Se)};r.useEffect((()=>{w&&f&&null===E&&c.getAuthenticatedUser().then(A)}),[w,f,E,c]);let Me=e=>{if(!f)throw s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new o.PrivyClientError("User must be authenticated before linking an account.")},Ne=e=>{if(!f||!E)return!1;if("privy"===e.walletClientType)return!0;for(let t of E.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},je=()=>{k((e=>{let t=c.connectors?.wallets.filter(s.isBaseConnectedEthereumWallet).map((e=>({...e,linked:Ne(e),loginOrLink:async()=>{if(!await e.isConnected())throw new o.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot link or login with embedded wallet");(async e=>{let t;if(!c.connectors)throw new o.PrivyClientError("Connector not initialized");t="ethereum"===e.type?c.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:c.connectors.findSolanaWalletConnector(e.walletClientType)||null,M((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:v.notImplemented}))),Z.captchaEnabled&&!f?(Q({captchaModalData:{callback:t=>s.isBaseConnectedEthereumWallet(e)?Se(e,t):_e(e,t),userIntentRequired:!1,onSuccessNavigateTo:s.ConnectionStatusScreen,onErrorNavigateTo:s.ErrorScreen}}),we(s.CaptchaScreen)):(s.isBaseConnectedEthereumWallet(e)?await Se(e):await _e(e),we(s.ConnectionStatusScreen))})(e)},fund:async t=>{await Ke.fundWallet(e.address,t)},unlink:async()=>{if(!f)throw new o.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new o.PrivyClientError("Cannot unlink an embedded wallet");A(await c.unlinkEthereumWallet(e.address))}})))||[];return s.areWalletArraysEqual(e,t)?e:t}))};r.useEffect((()=>{je()}),[E?.linkedAccounts,f,w]),r.useEffect((()=>{if(w){if(!c.connectors)throw new o.PrivyClientError("Connector not initialized");je(),c.connectors.on("walletsUpdated",je)}}),[w]),r.useEffect((()=>{[...Z.loginMethodsAndOrder?.primary??[],...Z.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>c.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!c]);let Fe=({transaction:e,sponsor:t,uiOptions:r,fundWalletConfig:n,address:h,signOnly:p})=>new Promise((async(y,m)=>{let{requesterAppId:w}=r||{},g=p?"signTransaction":"sendTransaction",v=h?d.getPrivyWalletWithAddress(E,h):d.getPrivyEthereumWallet(E);if(!v&&h){let r=d.getConnectedWalletWithAddress(P,h);if(r){if(t)throw new o.PrivyClientError("Cannot sponsor transactions for externally connected wallet.");try{let t=await r.getEthereumProvider(),n={...e,from:h,chainId:e.chainId||Number(r.chainId.replace("eip155:","")),value:void 0!==e.value?i.toHex(e.value):void 0},a=await t.request({method:"sendTransaction"===g?"eth_sendTransaction":"eth_signTransaction",params:[n]});return s.emitPrivyEvent(ce,g,"onSuccess",{hash:a}),void y({hash:a})}catch(e){return s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.TRANSACTION_FAILURE),void m(e??new s.PrivyProviderRpcError("Unable to "+g+e))}}}if(!v)return s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void m(new o.PrivyClientError("No embedded or connected wallet found for address."));if(!f||!E)return s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void m(Error("User must be authenticated before signing with a Privy wallet"));let C=v.address,A=v.walletIndex??0,{entropyId:k,entropyIdVerifier:b}=s.getEntropyDetailsForUser(E,v),x=Ve.wallets.find((e=>"privy"===e.walletClientType&&i.getAddress(e.address)===i.getAddress(C)));if(!x)return s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void m(Error("Must have a Privy wallet before signing"));let T=await x.getEthereumProvider(),S=await T.request({method:"eth_chainId"}),_=e.chainId?Number(e.chainId):I.extractChainIdFromCAIP2(S);(e=>{if(!Z.chains.map((e=>e.id)).includes(e))throw new o.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,o.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(_);let U={...e,from:e.from??C,chainId:_},W=await ui();if(!W||!Y)return s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void m(Error("Must have valid access token and Privy wallet to send transaction"));let R=s.getPublicClient(U.chainId,Z.chains,Z.rpcConfig,{appId:l.appId}),O=d.getIsUnifiedWallet(v),M=async({transactionRequest:e})=>{try{let r;if(!await Ke.recoverEmbeddedWallet({address:C}))throw s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),m(Error("Unable to connect to wallet")),Error("Unable to connect to wallet");if(t){let t=await(async({transactionRequest:e})=>{if(!O)throw new o.PrivyClientError("Sponsoring is only supported for wallets on the TEE stack");if(p)throw new o.PrivyClientError("Cannot sponsor a sign transaction request");let t=e=>null==e?void 0:i.toHex(e),r=await a.rpc(u,(async({message:e})=>await Y.signWithUserSigner({accessToken:W,requesterAppId:w,message:e})),{chain_type:"ethereum",method:"eth_sendTransaction",caip2:s.formatChainIdToCAIP2(i.toHex(e.chainId)),sponsor:!0,params:{transaction:{from:e.from,to:e.to,chain_id:t(e.chainId),data:i.isHex(e.data)?e.data?e.data:i.toHex(Uint8Array.from(e.data)):void 0,value:t(e.value)}},wallet_id:v.id});if(r.data&&"hash"in r.data)return r.data.hash;throw new s.PrivyProviderRpcError("Unable to sign transaction")})({transactionRequest:e});return s.emitPrivyEvent(ce,"sendTransaction","onSuccess",{hash:t}),t}if(O){let t=e=>null==e?void 0:i.toHex(e),n=await a.rpc(u,(async({message:e})=>await Y.signWithUserSigner({accessToken:W,requesterAppId:w,message:e})),{chain_type:"ethereum",method:"eth_signTransaction",params:{transaction:{from:e.from,to:e.to,nonce:t(e.nonce),chain_id:t(e.chainId),data:i.isHex(e.data)?e.data?e.data:i.toHex(Uint8Array.from(e.data)):void 0,value:t(e.value),type:e.type,gas_limit:t(e.gasLimit??e.gas),gas_price:t(e.gasPrice??e.gas),max_fee_per_gas:t(e.maxFeePerGas),max_priority_fee_per_gas:t(e.maxPriorityFeePerGas)}},wallet_id:v.id});if(!n.data||!("signed_transaction"in n.data))throw new s.PrivyProviderRpcError("Unable to sign transaction");r=n.data.signed_transaction}else r=await async function({accessToken:e,entropyId:t,entropyIdVerifier:r,transactingWalletIndex:n,walletProxy:i,transactionRequest:a,requesterAppId:o}){return(await i.rpc({entropyId:t,entropyIdVerifier:r,hdWalletIndex:n??0,chainType:"ethereum",accessToken:e,requesterAppId:o,request:{method:"eth_signTransaction",params:[a]}})).response.data}({accessToken:W,entropyId:k,entropyIdVerifier:b,transactingWalletIndex:A,walletProxy:Y,transactionRequest:e,requesterAppId:w});if(p)return s.emitPrivyEvent(ce,"signTransaction","onSuccess",{signature:r}),r;{let e=await R.sendRawTransaction({serializedTransaction:r});return s.emitPrivyEvent(ce,"sendTransaction","onSuccess",{hash:e}),e}}catch(e){throw s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.TRANSACTION_FAILURE),e}};if(me({showWalletUIs:r?.showWalletUIs})){let e=p||t?U:await s.prepareTransactionRequest(U,R,U.from);try{let t=await M({transactionRequest:e});p?s.emitPrivyEvent(ce,"signTransaction","onSuccess",{signature:t}):s.emitPrivyEvent(ce,"sendTransaction","onSuccess",{hash:t}),y({hash:t})}catch(e){s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.TRANSACTION_FAILURE),m(e)}}else{let e={connectingWalletAddress:C,recoveryMethod:v.recoveryMethod,entropyId:k,entropyIdVerifier:b,onCompleteNavigateTo:s.SendTransactionScreen,isUnifiedWallet:O,onFailure:e=>{s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),m(e)}},i=(e=>!!e.fundingConfig&&I.filterSupportedOptions(e.fundingConfig.options).length>=1)(Z)?I.prepareFundingModalData({address:C,appConfig:Z,fundWalletConfig:n,methodScreen:s.FundingMethodSelectionScreen,chainIdOverride:U.chainId,comingFromSendTransactionScreen:!0}):void 0;Q({connectWallet:e,sendTransaction:{transactionRequest:U,transactingWalletIndex:A,transactingWalletAddress:C,entropyId:k,entropyIdVerifier:b,signOnly:p,scanTransaction:async()=>{let e=await s.prepareTransactionRequest(U,R,U.from);return await c.scanTransaction({metadata:{domain:Z.embeddedWallets.transactionScanning.domain},chain_id:e.chainId.toString(),request:{method:"eth_sendTransaction",params:[{from:e.from,to:e.to,value:e.value?.toString(),gas:e.gas?.toString(),gasPrice:e.gasPrice?.toString(),nonce:e.nonce?.toString(),data:e.data}]}})},getIsSponsored:async()=>!!t,onConfirm:({transactionRequest:e})=>M({transactionRequest:e}),onSuccess:e=>{p?s.emitPrivyEvent(ce,"signTransaction","onSuccess",{signature:e.hash}):s.emitPrivyEvent(ce,"sendTransaction","onSuccess",{hash:e.hash}),y(e)},onFailure:e=>{s.emitPrivyEvent(ce,g,"onError",o.PrivyErrorCode.TRANSACTION_FAILURE),m(e)},uiOptions:r||{},fundWalletConfig:n,requesterAppId:w},funding:i}),we(s.EmbeddedWalletConnectingScreen)}}));function Le(){return new Promise((async(e,t)=>{let r=await ui();if(!r||!Y)throw Error("Must have valid access token to enroll in MFA");try{await Y.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let De=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],qe=e=>{let t=E?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=s.toDisplayFromAccountType(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:n}),new o.PrivyClientError(`User already has an account of type ${r} linked.`)};async function He({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){U(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!f||!E)throw s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=d.getPrivyPrimaryWallet(E);if(!n||!Y)throw s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");let i=d.getIsUnifiedWallet(n);if(i)throw s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.UNSUPPORTED_WALLET_TYPE),new o.PrivyClientError("User owned wallet recovery is only supported for on-device execution and this app uses TEE execution. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");try{await Le()}catch(e){throw s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((a,l)=>{let c="user-passcode"===n.recoveryMethod,d=s.toEmbeddedWalletSetRecoveryScreen({walletAction:"update",availableRecoveryMethods:Z.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:c,showAutomaticRecovery:e}),{entropyId:u,entropyIdVerifier:h}=s.getEntropyDetailsForUser(E),p={recoveryMethod:n.recoveryMethod,connectingWalletAddress:n.address,onCompleteNavigateTo:d,shouldForceMFA:!1,entropyId:u,isUnifiedWallet:i,entropyIdVerifier:h,onFailure:e=>{s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),l(e)}};Q({setWalletPassword:{onSuccess:e=>{s.emitPrivyEvent(ce,r,"onSuccess",{method:"user-passcode",wallet:e}),a(e)},onFailure:e=>{s.emitPrivyEvent(ce,r,"onError",o.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),l(e)},callAuthOnSuccessOnClose:!1},recoverWallet:{entropyId:u,entropyIdVerifier:h,onFailure:l},connectWallet:p,recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:c,shouldCreateEth:!1,shouldCreateSol:!1}}),we(s.EmbeddedWalletConnectingScreen)}))}async function Be({appId:e,action:t}){let r=await ui();if("link"===t&&!r)throw s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new o.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw s.emitPrivyEvent(ce,"login","onError",o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new o.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");he.current=`privy:${e}`,pe.current=t;let n=s.triggerPopup();return c.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,i)=>{let{name:a,logoUrl:o}=await Or({api:c.api,providerAppId:e,requesterAppId:Z.id});Q({crossAppAuth:{appId:e,name:a,logoUrl:o,action:t,popup:n,onSuccess:r,onError:i}}),we(an)}))}let ze={ready:w,authenticated:f,user:E,walletConnectors:c.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),Q({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,walletChainType:e?.walletChainType,description:e?.description}}),we(s.ConnectOnlyLandingScreen)},linkWallet:e=>{e&&"target"in e&&e&&(e=void 0),Me("siwe"),he.current="siwe",pe.current="link",Q({...X,externalConnectWallet:{...X.externalConnectWallet,walletList:e?.walletList,walletChainType:e?.walletChainType,description:e?.description||`Link a wallet to your ${Z?.name} account`}}),we(s.AuthenticateWithWalletScreen)},startCrossAppAuthFlow:Be,linkEmail:()=>{Me("email"),qe("email"),he.current="email",pe.current="link",we(An)},linkPhone:()=>{Me("sms"),qe("phone"),he.current="sms",pe.current="link",we(kn)},linkGoogle:async()=>{Me("google"),qe("google_oauth"),pe.current="link",await Ke.initLoginWithOAuth("google")},linkTwitter:async()=>{Me("twitter"),qe("twitter_oauth"),pe.current="link",await Ke.initLoginWithOAuth("twitter")},linkTwitch:async()=>{Me("twitch"),qe("twitch_oauth"),pe.current="link",await Ke.initLoginWithOAuth("twitch")},linkDiscord:async()=>{Me("discord"),qe("discord_oauth"),pe.current="link",await Ke.initLoginWithOAuth("discord")},linkGithub:async()=>{Me("github"),qe("github_oauth"),pe.current="link",await Ke.initLoginWithOAuth("github")},linkSpotify:async()=>{Me("spotify"),qe("spotify_oauth"),pe.current="link",await Ke.initLoginWithOAuth("spotify")},linkInstagram:async()=>{Me("instagram"),qe("instagram_oauth"),pe.current="link",await Ke.initLoginWithOAuth("instagram")},linkTiktok:async()=>{Me("tiktok"),qe("tiktok_oauth"),pe.current="link",await Ke.initLoginWithOAuth("tiktok")},linkLine:async()=>{Me("line"),qe("line_oauth"),pe.current="link",await Ke.initLoginWithOAuth("line")},linkLinkedIn:async()=>{Me("linkedin"),qe("linkedin_oauth"),pe.current="link",await Ke.initLoginWithOAuth("linkedin")},linkApple:async()=>{Me("apple"),qe("apple_oauth"),pe.current="link",await Ke.initLoginWithOAuth("apple")},linkPasskey:async()=>{Me("passkey"),qe("passkey"),await Ke.initLinkWithPasskey(),we(Hr)},linkTelegram:async e=>{if(Me("telegram"),qe("telegram"),pe.current="link",he.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new s.TelegramAuthFlow;c.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=s.convertInitDataRawToTelegramWebAppData(e.launchParams.initDataRaw),Q({telegramAuthModalData:{seamlessAuth:!0}}),we(s.TelegramAuthScreen)}else s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await Ke.initLoginWithTelegram();we(s.TelegramAuthScreen)},linkFarcaster:async()=>{Me("farcaster"),qe("farcaster"),await Ke.initLoginWithFarcaster(),pe.current="link",he.current="farcaster",we(s.FarcasterConnectStatusScreen)},updateEmail:()=>{if(Me("email"),!E?.email)throw new o.PrivyClientError("User does not have an email linked to their account.");pe.current="update",he.current="email",we(Xn)},updatePhone:()=>{if(Me("sms"),!E?.phone)throw new o.PrivyClientError("User does not have a phone number linked to their account.");pe.current="update",he.current="sms",we(ei)},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(!w){let e=await new Promise((e=>{te((t=>e.bind(t)))}));if(te(null),e)return void console.warn(t)}!E||E.isGuest?(pe.current="login",Q({login:e}),we(s.LandingScreen)):console.warn(t)},connectOrCreateWallet:async()=>{w||(await new Promise((e=>{te((()=>e))})),te(null)),f?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(pe.current="connect-or-create",we(s.ConnectOrCreateScreen))},logout:async()=>{if(pe.current=null,he.current=null,E&&c.clearProviderAcccessTokens(E),U(null),await c.logout(),E&&Y)try{await Y.clearMfa({userId:E.id})}catch(e){}A(null),C(!1),L({status:"initial"}),q({status:"initial"}),j({status:"initial"}),B({status:"initial"}),K({status:"initial"}),$({status:"initial"}),s.emitPrivyEvent(ce,"logout","onSuccess"),y(!1),s.f.del(s.CLIENT_ANALYTICS_ID_KEY),s.f.del(s.getGuestCredentialStorageKey(Z.id))},getAccessToken:r.useCallback((()=>c.getCustomerAccessToken()),[c]),unlinkWallet:async e=>{let t;return A(t=e.startsWith("0x")?await c.unlinkEthereumWallet(e):await c.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await c.unlinkEmail(e);return A(t),t},unlinkPhone:async e=>{let t=await c.unlinkPhone(e);return A(t),t},unlinkGoogle:async e=>{let t=await c.unlinkOAuth("google",e);return A(t),t},unlinkTwitter:async e=>{let t=await c.unlinkOAuth("twitter",e);return A(t),t},unlinkTwitch:async e=>{let t=await c.unlinkOAuth("twitch",e);return A(t),t},unlinkDiscord:async e=>{let t=await c.unlinkOAuth("discord",e);return A(t),t},unlinkGithub:async e=>{let t=await c.unlinkOAuth("github",e);return A(t),t},unlinkSpotify:async e=>{let t=await c.unlinkOAuth("spotify",e);return A(t),t},unlinkInstagram:async e=>{let t=await c.unlinkOAuth("instagram",e);return A(t),t},unlinkTiktok:async e=>{let t=await c.unlinkOAuth("tiktok",e);return A(t),t},unlinkLine:async e=>{let t=await c.unlinkOAuth("line",e);return A(t),t},unlinkLinkedIn:async e=>{let t=await c.unlinkOAuth("linkedin",e);return A(t),t},unlinkApple:async e=>{let t=await c.unlinkOAuth("apple",e);return A(t),t},unlinkFarcaster:async e=>{let t=await c.unlinkFarcaster(e);return A(t),t},unlinkTelegram:async e=>{let t=await c.unlinkTelegram(e);return A(t),t},unlinkPasskey:async e=>{let t=await ui();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!Y)throw Error("Wallet proxy not initialized.");let r=Z.passkeys.shouldUnenrollMfaOnUnlink;await Y.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let n=await c.getAuthenticatedUser();return A(n),n},unlinkCrossAppAccount:async({subject:e})=>{let t=E?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new o.PrivyClientError("Invalid subject");c.storeProviderAccessToken(t.id,null);let r=await c.unlinkOAuth(`privy:${t.id}`,e);return A(r),r},setWalletRecovery:async e=>He({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>He({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(r,n)=>{let{requesterAppId:l}=t?.uiOptions||{},h=e.message,p=t?.address?d.getPrivyWalletWithAddress(E,t.address):d.getPrivyEthereumWallet(E);if(!p&&void 0!==t?.address){let e=d.getConnectedWalletWithAddress(P,t.address);if(e)try{let t=await e.getEthereumProvider(),n=await t.request({method:"personal_sign",params:[h,e.address]});return s.emitPrivyEvent(ce,"signMessage","onSuccess",{signature:n}),void r({signature:n})}catch(e){return s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),void n(e??new s.PrivyProviderRpcError("Unable to sign message"))}}if(!p)throw new o.PrivyClientError("No embedded or connected wallet found for address.");if(!f||!E)return s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let y=p.address,m=p.walletIndex??0,{entropyId:w,entropyIdVerifier:g}=s.getEntropyDetailsForUser(E,p),v=d.getIsUnifiedWallet(p);if("string"!=typeof h||h.length<1)return s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.INVALID_MESSAGE),void n(Error("Message must be a non-empty string"));let C=async()=>{let t;if(!f)throw Error("User must be authenticated before signing with a Privy wallet");let r=await ui();if(!Y||!r||!await Ke.recoverEmbeddedWallet({address:y}))throw Error("Unable to connect to wallet");if(c.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:y,requesterAppId:l}}),v){let n=i.isHex(e.message,{strict:!0}),o=await a.rpc(u,(async({message:e})=>await Y.signWithUserSigner({accessToken:r,requesterAppId:l,message:e})),{chain_type:"ethereum",method:"personal_sign",params:n?{message:h.slice(2),encoding:"hex"}:{message:h,encoding:"utf-8"},wallet_id:p.id});if(!o.data||!("signature"in o.data))throw new s.PrivyProviderRpcError("Unable to sign message");t=o.data.signature}else{let{response:e}=await Y.rpc({accessToken:r,entropyId:w,entropyIdVerifier:g,chainType:"ethereum",hdWalletIndex:m,requesterAppId:l,request:{method:"personal_sign",params:[h,y]}});t=e.data}return c.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:y,requesterAppId:l}}),t};if(me({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await C();s.emitPrivyEvent(ce,"signMessage","onSuccess",{signature:e}),r({signature:e})}catch(e){s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new s.PrivyProviderRpcError("Unable to sign message"))}else Q({signMessage:{method:"personal_sign",data:h,confirmAndSign:C,onSuccess:e=>{s.emitPrivyEvent(ce,"signMessage","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:p.recoveryMethod,connectingWalletAddress:y,entropyId:w,entropyIdVerifier:g,onCompleteNavigateTo:s.SignRequestScreen,isUnifiedWallet:v,onFailure:e=>{s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),we(s.EmbeddedWalletConnectingScreen)})),signTypedData:(e,t)=>new Promise((async(r,n)=>{let{requesterAppId:i}=t?.uiOptions||{},l=t?.address?d.getPrivyWalletWithAddress(E,t.address):d.getPrivyEthereumWallet(E);if(!l&&t?.address){let i=d.getConnectedWalletWithAddress(P,t.address);if(i)try{let t=await i.getEthereumProvider(),n=s.generateTypedDataWithDomainType(e),a=await t.request({method:"eth_signTypedData_v4",params:[i.address,n]});return s.emitPrivyEvent(ce,"signTypedData","onSuccess",{signature:a}),void r({signature:a})}catch(e){return s.emitPrivyEvent(ce,"signTypedData","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),void n(e??new s.PrivyProviderRpcError("Unable to sign typed data "+e))}}if(!l)throw new o.PrivyClientError("No embedded or connected wallet found for address.");if(!f||!E)return s.emitPrivyEvent(ce,"signTypedData","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED),void n(Error("User must be authenticated before signing with a Privy wallet"));let h=l.address,p=l.walletIndex??0,{entropyId:y,entropyIdVerifier:m}=s.getEntropyDetailsForUser(E,l),w=d.getIsUnifiedWallet(l),g=s.generateTypedDataWithDomainType(e),v=async()=>{let e;if(!f)throw Error("User must be authenticated before signing with a Privy wallet");let t=await ui();if(!Y||!t||!await Ke.recoverEmbeddedWallet({address:h}))throw Error("Unable to connect to wallet");if(c.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:h,requesterAppId:i}}),w){let{domain:r,types:n,primaryType:o,message:c}=g,d=await a.rpc(u,(async({message:e})=>await Y.signWithUserSigner({accessToken:t,requesterAppId:i,message:e})),{chain_type:"ethereum",method:"eth_signTypedData_v4",params:{typed_data:{domain:r,types:n,primary_type:o,message:c}},wallet_id:l.id});if(!d.data||!("signature"in d.data))throw new s.PrivyProviderRpcError("Unable to sign message");e=d.data.signature}else{let{response:r}=await Y.rpc({accessToken:t,entropyId:y,entropyIdVerifier:m,chainType:"ethereum",hdWalletIndex:p,requesterAppId:i,request:{method:"eth_signTypedData_v4",params:[h,g]}});e=r.data}return c.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:h,requesterAppId:i}}),e};if(me({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await v();s.emitPrivyEvent(ce,"signTypedData","onSuccess",{signature:e}),r({signature:e})}catch(e){s.emitPrivyEvent(ce,"signTypedData","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),n(e??new s.PrivyProviderRpcError("Unable to sign message"))}else Q({signMessage:{method:"eth_signTypedData_v4",data:g,confirmAndSign:v,onSuccess:e=>{s.emitPrivyEvent(ce,"signTypedData","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{s.emitPrivyEvent(ce,"signTypedData","onError",o.PrivyErrorCode.UNABLE_TO_SIGN),n(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:l.recoveryMethod,connectingWalletAddress:l.address,entropyId:y,isUnifiedWallet:w,entropyIdVerifier:m,onCompleteNavigateTo:s.SignRequestScreen,onFailure:e=>{s.emitPrivyEvent(ce,"signMessage","onError",o.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),n(e)}}}),we(s.EmbeddedWalletConnectingScreen)})),sendTransaction:async(e,t)=>await Fe({transaction:e,sponsor:t?.sponsor,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await Fe({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:e=>new Promise((async(t,r)=>{if(!f||!E)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?d.getPrivyWalletWithAddress(E,e.address):d.getPrivyEthereumWallet(E);if(!n)return void r(new o.PrivyClientError("User must have an embedded wallet."));let a=n.address,{entropyId:u,entropyIdVerifier:h}=s.getEntropyDetailsForUser(E,n),p=d.getIsUnifiedWallet(n);if(!a)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(a))return void r(Error("Must provide a valid Ethereum address."));let y={recoveryMethod:n.recoveryMethod,connectingWalletAddress:n.address,isUnifiedWallet:p,entropyId:u,entropyIdVerifier:h,onCompleteNavigateTo:s.EmbeddedWalletKeyExportScreen,onFailure:r,shouldForceMFA:!0};Q(X),await ui()&&Y?Y?I.isFirstClassChainWallet(n)?(Q({keyExport:{appId:l.appId,appClientId:l.clientId,origin:c.apiUrl,address:n.address,entropyId:u,entropyIdVerifier:h,hdWalletIndex:n.walletIndex,chainType:n.chainType,walletId:n.id,isUnifiedWallet:p,imported:n.imported,onSuccess:t,onFailure:r},connectWallet:y}),we(s.EmbeddedWalletConnectingScreen)):r(Error(`Export is not supported for ${n.chainType} wallets`)):r(Error("Must have a Privy wallet before exporting")):r(Error("Must have valid access token to enroll in MFA"))})),promptMfa:Le,async init(e){switch(e){case"sms":return void await c.initMfaSmsVerification();case"passkey":return await c.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 o.PrivyClientError("Invalid MFA code");se.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{le.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new o.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),n=rn(await r.startAuthentication(t));se.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{le.current={resolve:e,reject:t}}));break;default:throw se.current?.reject(new o.PrivyClientError("Unsupported MFA method")),new o.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){se.current?.reject(new o.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await ui();if(!t||!Y)throw Error("Must have valid access token to enroll in MFA");await Y.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return Ke.closePrivyModal(),void t();Z.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."),Q({mfaEnrollmentFlow:{mfaMethods:Z.mfa.methods,shouldUnlinkOnUnenrollMfa:Z.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),we(Kn)})),async initEnrollmentWithTotp(){let e=await ui();if(!e||!Y)throw Error("Must have valid access token to enroll in MFA");let t=await Y.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await ui();if(!t||!Y)throw Error("Must have valid access token to enroll in MFA");await Y.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),A(await c.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await ui();if(!t||!Y)throw Error("Must have valid access token to enroll in MFA");await Y.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),A(await c.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await ui();if(!r||!Y)throw Error("Must have valid access token to enroll in MFA");await Y.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),A(await c.getAuthenticatedUser())},async unenroll(e,t={}){let r=await ui();if(!r||!Y)throw Error("Must have valid access token to remove MFA");"passkey"===e?await Y.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await Y.unenrollMfa({method:e,accessToken:r}),A(await c.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await ui(),t=E?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!Y||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(d.getIsUnifiedWallet(t))throw new o.PrivyClientError("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!E?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverEmbeddedWallet({address:t.address}))throw Error("Unable to connect to wallet");let r=await Y.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&A(await c.getAuthenticatedUser()||E||null),Q({farcasterSigner:r}),we(fn)},getFarcasterSignerPublicKey:async()=>{let e,t=await ui(),r=E?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Y||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(d.getIsUnifiedWallet(r))throw new o.PrivyClientError("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!E?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!E.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=E.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await ui(),r=E?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Y||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(d.getIsUnifiedWallet(r))throw new o.PrivyClientError("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!E?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await Ke.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!E.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let n=await import("@simplewebauthn/browser"),i=await Y.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:n.bufferToBase64URLString(e)},fid:BigInt(E.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(i.signature))},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let n=E?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Mr({user:E,client:c,address:t,requesterAppId:Z.id,request:{method:n?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:Be})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let n=E?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),i=s.generateTypedDataWithDomainType(e);return Mr({user:E,client:c,address:t,requesterAppId:Z.id,request:{method:n?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,i],chainId:r},reconnect:Be})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=E?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Mr({user:E,client:c,address:t,requesterAppId:Z.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:Be})},signTransactionWithCrossAppWallet(e,{address:t}){let r=E?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Mr({user:E,client:c,address:t,requesterAppId:Z.id,request:{method:r?"privy_signSmartWalletTx":"eth_signTransaction",params:[e],chainId:e.chainId},reconnect:Be})},isModalOpen:p||!!m,mfaMethods:Z.mfa.methods};oi=ze.signMessage,si=ze.signTypedData,ci=async(e,t)=>await Fe({transaction:e,...t,signOnly:!1}),li=async(e,t)=>({signature:(await Fe({transaction:e,...t,signOnly:!0})).hash});let Ke={privy:u,setAuthenticated:C,setUser:A,setIsNewUser:S,isNewUserThisSession:T,pendingTransaction:null,walletConnectionStatus:O,setWalletConnectionStatus:M,connectors:c.connectors?.walletConnectors??[],rpcConfig:Z.rpcConfig,chains:Z.chains,appId:l.appId,showFiatPrices:"native-token"!==Z.embeddedWallets.priceDisplay.primary,clientAnalyticsId:c.clientAnalyticsId,onCustomAuthAuthenticated:ge,hideWalletUIs:ye,isHeadlessSigning:r.useCallback(me,[Z.embeddedWallets.showWalletUIs]),emailOtpState:F,setEmailOtpState:L,smsOtpState:D,setSmsOtpState:q,oAuthState:z,setOAuthState:K,telegramAuthState:V,setTelegramAuthState:$,siweState:H,setSiweState:B,isHeadlessOAuthLoading:W,baseAccountSdk:b,setBaseAccountSdk:x,nativeTokenSymbolForChainId:e=>Z.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(Y)return Y;let t=new Promise((e=>{re.current=e})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return re.current=null,n},getAuthFlow:()=>c.authFlow,getAuthMeta:()=>c.authFlow?.meta,client:c,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=w&&f&&E;r&&he.current&&(t=De(E)),"login"===pe.current?e.shouldCallAuthOnSuccess&&r&&he.current?s.emitPrivyEvent(ce,"login","onComplete",{user:E,isNewUser:T,wasAlreadyAuthenticated:!1,loginMethod:he.current,loginAccount:t??null}):s.emitPrivyEvent(ce,"login","onError",o.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===pe.current&&t?e.isSuccess&&r&&he.current?s.emitPrivyEvent(ce,"linkAccount","onSuccess",{user:E,linkMethod:he.current,linkedAccount:t}):he.current&&s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:he.current}):"update"===pe.current&&t?e.isSuccess&&r&&he.current?s.emitPrivyEvent(ce,"update","onSuccess",{user:E,updateMethod:he.current,updatedAccount:t}):he.current&&s.emitPrivyEvent(ce,"update","onError",o.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:he.current}):"connect-or-create"===pe.current&&(P[0]?s.emitPrivyEvent(ce,"connectOrCreateWallet","onSuccess",{wallet:P[0]}):s.emitPrivyEvent(ce,"connectOrCreateWallet","onError",o.PrivyErrorCode.USER_EXITED_AUTH_FLOW));let n=_&&Qr.has(_),i=_===s.ErrorScreen&&X.errorModalData&&Qr.has(X.errorModalData.previousScreen);if((n||i)&&X.funding){let e,t=Qr.get(_)??null;if("solana"===X.funding.chainType){let r=Z.solanaRpcs[X.funding.chain];if(!r)return void console.warn("Unable to load solana rpc, skipping balance");if(h(s.SOLANA_FUNDING_PLUGIN_ID))try{e=await s.fetchWalletBalance({rpc:r.rpc,address:X.funding.address})}catch{console.error("Unable to pull wallet balance")}else console.warn("Unable to load solana plugin, skipping balance");s.emitPrivyEvent(ce,"fundSolanaWallet","onUserExited",{address:X.funding.address,fundingMethod:t,chain:X.funding.chain,balance:e})}else{let r=s.getPublicClient(X.funding.chain.id,Z.chains,Z.rpcConfig,{appId:l.appId});try{e=await r.getBalance({address:X.funding.address})}catch{console.error("Unable to pull wallet balance")}s.emitPrivyEvent(ce,"fundWallet","onUserExited",{address:X.funding.address,chain:X.funding.chain,fundingMethod:t,balance:e})}}Q((e=>({...e,externalConnectWallet:{}}))),pe.current=null,he.current=null,S(!1),y(!1),setTimeout((()=>{c.authFlow=void 0}),200)},openPrivyModal:we,connectWallet:Te,initLoginWithWallet:async(e,t,r,n)=>{s.isBaseConnectedEthereumWallet(e)?(he.current="siwe",Se(e,t,r)):(he.current="siws",_e(e,t,r,n))},loginWithWallet:async()=>{let e,t,r;if(!w)throw new o.PrivyNotReadyError;if(c.authFlow instanceof s.SiweFlow?e="siwe":c.authFlow instanceof s.SiwsFlow&&(e="siws"),!e)throw new o.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await c.getAccessToken())try{({user:t}=await c.link()),he.current=e}catch(t){throw s.emitPrivyEvent(ce,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await c.authenticate()),he.current=e}catch(e){throw s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}A(t||E||null),S(r||!1),C(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(n,i)=>{let a=await ui();if(!f||!E||!a)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new o.PrivyClientError("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let s=Ke.walletProxy??await Ke.initializeWalletProxy(15e3);if(!s)throw new o.PrivyClientError("Wallet proxy not initialized.");if((({address:e,user:t})=>!!_r(t).find((t=>t.address===e)))({address:e,user:E}))return n();let l=d.getPrivyWalletWithAddress(E,e);if(!l)throw new o.PrivyClientError("Address to delegate is not associated with current user.");if(d.getIsUnifiedWallet(l))throw new o.PrivyClientError("useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");let c=Tr({address:e,user:E}),u=Sr({address:e,user:E}),h=async()=>{await s.createDelegatedAction({accessToken:a,rootWallet:u,delegatedWallets:[c]}),await Ke.refreshSessionAndUser()};if(await Ke.recoverEmbeddedWallet({address:e}),r)Q({delegatedActions:{consent:{address:e,onDelegate:h,onSuccess:async()=>{n()},onError:async e=>{i(e)}}}}),we(sn);else try{await h(),n()}catch(e){i(e)}})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!f||!E)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");let n=_r(E);if(0===n.length)throw new o.PrivyClientError("User has no delegated wallets to revoke.");if(n.some(d.getIsUnifiedWallet))throw new o.PrivyClientError("useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");let i=async()=>{await c.revokeDelegatedWallet(),await Ke.refreshSessionAndUser()};if(e)Q({delegatedActions:{revoke:{onRevoke:i,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),we(cn);else try{await i(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new Ee(e,t);c.startAuthFlow(r);try{he.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===pe.current?s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===pe.current&&s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!w)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof Ee))throw new o.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await c.getAccessToken())try{({user:e}=await c.link()),he.current="farcaster"}catch(e){throw s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await c.authenticate()),he.current="farcaster"}catch(e){throw s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}A(e||null),S(t||!1),C(!0)},async crossAppAuthFlow({appId:e,popup:t,action:r}){let n=`privy:${e}`;he.current=n;let{url:i,stateCode:a,codeVerifier:l}=await async function({api:e,appId:t}){let r=s.createCodeVerifier(),n=s.createStateCode(),i=await s.deriveCodeChallengeFromCodeVerifier(r);try{let{url:a}=await e.post(o.oAuthInitPath,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:i,state_code:n});return{url:a,stateCode:n,codeVerifier:r}}catch(e){throw o.formatApiError(e)}}({api:c.api,appId:e});if(!i)throw c.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new o.PrivyClientError("No authorization URL returned for cross-app auth.");try{let s=await async function({url:e,popup:t}){return t.location=e,new Promise(((e,r)=>{let n,i=setTimeout((()=>{r(new o.PrivyClientError("Authorization request timed out after 2 minutes.")),a()}),12e4);function a(){t?.close(),window.removeEventListener("message",l)}let s=setInterval((()=>{t?.closed&&!n&&(a(),clearInterval(s),clearTimeout(i),r(new o.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),a()),"PRIVY_OAUTH_ERROR"===t.data.type&&(clearTimeout(i),r(new o.PrivyClientError(t.data.error)),a()),t.data.type===Wr&&((n=new BroadcastChannel(Ur)).onmessage=l))}window.addEventListener("message",l)}))}({url:i,popup:t,provider:n}),d=s.stateCode,u=s.authorizationCode;if(d!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:n,storedStateCode:a??"",returnedStateCode:d??""}}),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);let h=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:i,client:a}){if(!n||!t)throw new o.PrivyClientError("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===n)throw new o.PrivyClientError("User denied confirmation during cross-app auth flow");try{let o=new Rr({authorizationCode:n,stateCode:t,codeVerifier:r,provider:`privy:${e}`});a.startAuthFlow(o);let s="link"===i?await a.link():await a.authenticate(),l=s.oAuthTokens?.accessToken;return console.debug(),l}catch(e){let t=o.formatApiError(e);if(t.privyErrorCode===o.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED)throw t;if(t.privyErrorCode)throw new o.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 o.PrivyClientError("Invalid code during cross-app auth flow.",void 0,o.PrivyErrorCode.OAUTH_USER_DENIED);throw new o.PrivyClientError("Invalid code during cross-app auth flow.",void 0,o.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:l,stateCode:d,authorizationCode:u,action:r,client:c});h&&c.storeProviderAccessToken(e,h);let p=await Ke.refreshSessionAndUser();if(!p)throw new o.PrivyClientError("Unable to update user");return c.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),p}catch(e){throw c.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:n}}),e}},async initLoginWithOAuth(e,t,r){if(he.current=e,!s.e$1())return void we(Cn);if("google"===e&&s.e$3(window.navigator.userAgent))return void we(Cn);"twitter"===e&&window.opener&&window.opener.postMessage({type:Wr},"*"),s.f.del(s.HEADLESS_OAUTH_KEY),s.f.del(s.OAUTH_DISABLE_SIGNUP_KEY);let i=new xe({provider:e,disableSignup:!!r,withPrivyUi:!0,customOAuthRedirectUrl:Z.customOAuthRedirectUrl});t&&i.addCaptchaToken(t),c.startAuthFlow(i);let a=await c.authFlow.getAuthorizationUrl();if(a&&a.url)if("twitter"===e&&n.isAndroid&&(a.url=a.url.replace("x.com","twitter.com")),"chrome-extension:"===window.location.protocol&&ke())try{let{privyOAuthCode:e,privyOAuthState:t}=await be(a.url);we($n),i.meta.stateCode=t,i.meta.authorizationCode=e}catch(e){throw console.error("OAuth in chrome extension flow failed:",e),e}else window.location.assign(a.url)},async initLoginWithTelegram(e,t){if(!w)throw new o.PrivyNotReadyError;he.current="telegram";let r=new s.TelegramAuthFlow(e,t);c.startAuthFlow(r),$({status:"loading"}),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>Z.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:Z.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):("link"===pe.current?s.emitPrivyEvent(ce,"linkAccount","onError",o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}):"login"===pe.current?s.emitPrivyEvent(ce,"login","onError",o.PrivyErrorCode.INVALID_CREDENTIALS):"update"===pe.current&&s.emitPrivyEvent(ce,"login","onError",o.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT),t(new o.PrivyClientError("Telegram auth failed or was canceled by the client"))))):t(new o.PrivyClientError("Telegram was not initialized")):t(new o.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(c.authFlow instanceof s.TelegramAuthFlow))throw new o.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");c.authFlow.meta.captchaToken||=e?.captchaToken;let n=await ui(),i=e?.intent||pe.current;if("login"===i)try{let e=await c.authenticate();t=e.user,r=e.isNewUser,he.current="telegram"}catch(e){throw s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==i)throw new o.PrivyClientError("Unknown auth intent");try{t=(await c.link()).user,he.current="telegram"}catch(e){throw s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}A(t),S(r||!1),C(!0),$({status:"done"});let a=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,loginAccount:a}},async loginWithOAuth(e){let t,r,n;if(!(c.authFlow instanceof xe))throw new o.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let i=s.f.get(s.STATE_CODE_KEY),a=c.authFlow.meta.stateCode;if(i!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:i??"",returnedStateCode:a??""}}),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await c.getAccessToken())try{let r=await c.link();t=r.user,n=r.oAuthTokens,he.current=e}catch(t){throw s.emitPrivyEvent(ce,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let i=await c.authenticate();t=i.user,r=i.isNewUser,n=i.oAuthTokens,he.current=e}catch(t){throw"login"===pe.current?s.emitPrivyEvent(ce,"login","onError",t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===pe.current&&s.emitPrivyEvent(ce,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return A(t),S(r||!1),C(!0),n&&t&&s.emitPrivyEvent(ce,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),n},passkeyAuthState:N,setPasskeyAuthState:j,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new We({captchaToken:e,setPasskeyAuthState:j});c.startAuthFlow(r),pe.current="login";try{he.current="passkey",j({status:"generating-challenge"}),await r.initRegisterFlow(t),j({status:"awaiting-passkey"})}catch(e){throw j({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!w)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof We))throw new o.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==he.current){let e=new o.PrivyClientError("Must init login with Passkey flow first.");throw j({status:"error",error:e}),e}let r=await ui();try{he.current="passkey",j({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await c.authenticate())}catch(e){throw j({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}A(e),S(t||!1),C(!0),j({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 We({captchaToken:e,setPasskeyAuthState:j});c.startAuthFlow(r),pe.current="login";try{he.current="passkey",j({status:"generating-challenge"}),await r.initAuthenticationFlow(t),j({status:"awaiting-passkey"})}catch(e){throw j({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,r;if(!w)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof We))throw new o.PrivyClientError("Must initialize Passkey flow first.");if(e?.credentialIds&&(c.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==he.current){let e=new o.PrivyClientError("Must init login with Passkey flow first.");throw j({status:"error",error:e}),e}let n=await ui();try{he.current="passkey",j({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await c.authenticate())}catch(e){throw j({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}A(t),S(r||!1),C(!0),j({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 We({captchaToken:e});c.startAuthFlow(t),pe.current="link",he.current="passkey",j({status:"generating-challenge"});try{await t.initLinkFlow(),j({status:"awaiting-passkey"})}catch(e){throw s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),j({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!w)throw new o.PrivyNotReadyError;if(!(c.authFlow instanceof We))throw new o.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==he.current)throw new o.PrivyClientError("Must init login with Passkey flow first.");try{he.current="passkey",({user:e}=await c.link())}catch(e){throw s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return A(e||E||null),j({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!s.e$1())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&&s.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 xe({provider:e,withPrivyUi:!1,disableSignup:r??!1,customOAuthRedirectUrl:Z.customOAuthRedirectUrl});t&&n.addCaptchaToken(t),K({status:"loading"});let i=await c.startAuthFlow(n).getAuthorizationUrl();if(i?.url)if("chrome-extension:"===window.location.protocol&&ke())try{let{privyOAuthCode:e,privyOAuthState:t}=await be(i.url);n.meta.stateCode=t,n.meta.authorizationCode=e,await this.loginWithHeadlessOAuth(n.meta)}catch(e){throw K({status:"error",error:e}),e}else window.location.assign(i.url)},async loginWithHeadlessOAuth(e){let t,r,n;R(!0),K({status:"loading"}),c.startAuthFlow(new xe({...e,customOAuthRedirectUrl:Z.customOAuthRedirectUrl}));let i=s.f.get(s.STATE_CODE_KEY),a=e.stateCode;if(i!==a)throw c.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:i??"",returnedStateCode:a??""}}),R(!1),new o.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,o.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await c.getAccessToken())try{({user:t,oAuthTokens:n}=await c.link()),he.current=e.provider;let r=De(t);t&&r&&s.emitPrivyEvent(ce,"linkAccount","onSuccess",{user:t,linkMethod:he.current,linkedAccount:r})}catch(t){throw R(!1),s.emitPrivyEvent(ce,"linkAccount","onError",t.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:n}=await c.authenticate()),he.current=e.provider;let i=De(t);t&&i&&void 0!==r&&s.emitPrivyEvent(ce,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:he.current,loginAccount:i})}catch(e){throw R(!1),K({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return A(t),S(r||!1),C(!0),R(!1),K({status:"done"}),n&&t&&s.emitPrivyEvent(ce,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{let i=new ve({email:e,captchaToken:t,disableSignup:r});c.startAuthFlow(i);try{he.current="email",L({status:"sending-code"}),await i.sendCodeEmail({withPrivyUi:n}),L({status:"awaiting-code-input"})}catch(e){throw L({status:"error",error:e}),"login"===pe.current?s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===pe.current&&s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async({oldAddress:e,newAddress:t,captchaToken:r})=>{let n=new Ce(e,t,r);c.startAuthFlow(n);try{await n.sendCodeEmail({withPrivyUi:!0})}catch(e){throw s.emitPrivyEvent(ce,"update","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:he.current}),e}},initUpdatePhone:async(e,t,r)=>{let n=new Oe(e,t,r);c.startAuthFlow(n);try{await n.sendSmsCode({withPrivyUi:!0})}catch(e){s.emitPrivyEvent(ce,"update","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:he.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{q({status:"sending-code"});let i=new Re({phoneNumber:e,captchaToken:t,disableSignup:r});c.startAuthFlow(i);try{he.current="sms",await i.sendSmsCode({withPrivyUi:n}),q({status:"awaiting-code-input"})}catch(e){throw q({status:"error",error:e}),"login"===pe.current?s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===pe.current&&s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(c.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(c.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function n(e){c.authFlow instanceof ve?L(e):c.authFlow instanceof Re&&q(e)}if(n({status:"submitting-code"}),!w){let e=new o.PrivyNotReadyError;throw n({status:"error",error:e}),e}if(c.authFlow instanceof ve)c.authFlow.meta.emailCode=e.trim();else{if(!(c.authFlow instanceof Re)){let e=new o.PrivyClientError("Must initialize a passwordless code flow first");throw n({status:"error",error:e}),e}c.authFlow.meta.smsCode=e.trim()}let i=await ui();if("link"===pe.current)try{({user:t}=await c.link())}catch(e){throw n({status:"error",error:e}),s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:he.current}),e}else if("update"===pe.current)try{({user:t}=await c.link())}catch(e){throw n({status:"error",error:e}),s.emitPrivyEvent(ce,"update","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:he.current}),e}else try{({user:t,isNewUser:r}=await c.authenticate())}catch(e){throw n({status:"error",error:e}),s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let a=t||E;A(a||null),S(r||!1),C(!0),n({status:"done"});let l=null;return c.authFlow instanceof ve?l=a?.linkedAccounts.find((({type:e})=>"email"===e))||null:c.authFlow instanceof Re&&(l=a?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:a,isNewUser:r||!1,wasAlreadyAuthenticated:!!i,linkedAccount:l}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{pe.current=f?"link":"login",he.current="siwe",B({status:"generating-message"});let n=await c.generateSiweNonce({address:e,captchaToken:r});return B({status:"awaiting-signature"}),s.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:n})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await c.generateSiweNonce({address:e});return s.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r,smartWalletVersion:n})=>{let i;i=await c.linkSmartWallet({message:e,signature:t,smartWalletType:r,smartWalletVersion:n}),A((i=await Ke.refreshSessionAndUser()??i)||E||null)},loginWithSiwe:async({message:e,signature:t,captchaToken:r,disableSignup:n})=>{let i,a=null;try{if(E)throw Error("User already authenticated");let o=new s.SiweFlow(c,void 0,r,n,{message:e,signature:t});c.startAuthFlow(o),he.current="siwe",pe.current="login",B({status:"submitting-signature"});let l=await c.authenticate();if(({user:a,isNewUser:i}=l),!a)throw Error("Authentication failed - no user returned")}catch(e){throw s.emitPrivyEvent(ce,"login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),B({status:"error",error:e}),e}return A(a),S(i||!1),C(!0),B({status:"done"}),pe.current=null,he.current=null,{user:a,isNewUser:i||!1}},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})=>{let a;Me("siwe");let l=null;try{B({status:"submitting-signature"}),a=await c.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}),a=await Ke.refreshSessionAndUser()??a,B({status:"done"}),(l=De(a)||null)&&s.emitPrivyEvent(ce,"linkAccount","onSuccess",{user:a,linkMethod:"siwe",linkedAccount:l})}catch(e){throw s.emitPrivyEvent(ce,"linkAccount","onError",e.privyErrorCode||o.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),pe.current=null,he.current=null,B({status:"error",error:e}),e}let d=a||E;return A(d||null),pe.current=null,he.current=null,{user:d,linkedAccount:l}},refreshSessionAndUser:async()=>{let e=await c.getAuthenticatedUser();return C(!!e),A(e),e},walletProxy:Y,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>c.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await c.acceptTerms();return A(e),e},getUsdTokenPrice:e=>c.getUsdTokenPrice(e),getUsdPriceForSol:()=>c.getUsdPriceForSol(),getSplTokenMetadata:e=>c.getSplTokenMetadata(e),recoverEmbeddedWallet:async e=>new Promise((async(t,r)=>{if(!E)return void t(!0);let n=e?.address?d.getPrivyWalletWithAddress(E,e.address):d.getPrivyPrimaryWallet(E)||d.getImportedPrivyEthereumWallets(E).at(0)||d.getImportedPrivySolanaWallets(E).at(0);if(!n||d.getIsUnifiedWallet(n))return void t(!0);let i=await ui();if(!i||!Y||!n)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));let{entropyId:a,entropyIdVerifier:o}=s.getEntropyDetailsForUser(E,n);try{await Y.connect({accessToken:i,entropyId:a,entropyIdVerifier:o}),t(!0)}catch(e){if(s.errorIndicatesRecoveryIsNeeded(e)&&"privy"===n.recoveryMethod){let e;c.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:n.address}});try{e=await Y.recover({entropyId:a,entropyIdVerifier:o,accessToken:i})}catch(e){return void r(e)}e.entropyId||r(Error("Unable to recover wallet")),c.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:n.address}}),t(!0)}else s.errorIndicatesRecoveryIsNeeded(e)&&"privy"!==n.recoveryMethod&&"privy-v2"!==n.recoveryMethod?(Q({recoverWallet:{entropyId:a,entropyIdVerifier:o,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:n.recoveryMethod,action:"recover",shouldCreateEth:!1,shouldCreateSol:!1}}),we(s.embeddedWalletRecoveryScreen(n.recoveryMethod))):r(e)}})),setReadyToTrue:e=>{g(!0),ee?.(e)},updateWallets:()=>je(),fundWallet:async(e,t)=>{Q({funding:I.prepareFundingModalData({address:e,appConfig:Z,fundWalletConfig:t,methodScreen:s.FundingMethodSelectionScreen})}),we(s.FundingMethodSelectionScreen)},openModal:we,requestFarcasterSignerStatus:async e=>{let t=await ui(),r=E?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Y||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!E?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let n=await c.requestFarcasterSignerStatus(e);return"approved"===n.status&&A(await c.getAuthenticatedUser()||E||null),n},connectCoinbaseSmartWallet:async()=>{Z.externalWallets.coinbaseWallet.config.preference={...Z.externalWallets.coinbaseWallet.config.preference,options:"smartWalletOnly"};let e=c.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||c.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Te(e);await Pe("coinbase_wallet","coinbase_smart_wallet")},connectBaseAccount:async()=>{let e=c.connectors?.findWalletConnector("base_account","base_account");if(e)return Te(e);await Pe("base_account","base_account")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,telegramWebAppData:a,farcasterEmbeddedAddress:o,oAuthUserInfo:s})=>{let l=await c.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,telegramWebAppData:a,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return A(l),l},inProgressAuthFlowRef:pe,inProgressLoginOrLinkMethodRef:he};di=Ke.recoverEmbeddedWallet,Ke.recoverEmbeddedWallet;let Ve=r.useMemo((()=>({wallets:P,ready:ne&&de})),[P,ne,de]),$e=c.authFlow instanceof s.TelegramAuthFlow,Ye=!Z.headless&&Z.captchaEnabled&&!f&&(w||$e);/*#__PURE__*/return e.jsx(ii.Provider,{value:!0,children:/*#__PURE__*/e.jsx(d.PrivyContext.Provider,{value:ze,children:/*#__PURE__*/e.jsx(s.PrivyEventsContext.Provider,{value:ce,children:/*#__PURE__*/e.jsx(s.UseWalletsContext.Provider,{value:Ve,children:/*#__PURE__*/e.jsx(s.CaptchaProvider,{...Z,children:/*#__PURE__*/e.jsxs(v.InternalPrivyContext.Provider,{value:Ke,children:[/*#__PURE__*/e.jsx(s.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(s.ModalProvider,{data:X,setModalData:Q,setInitialScreen:U,initialScreen:_,authenticated:f,open:p,children:[l.children,/*#__PURE__*/e.jsx(ni,{customAuth:Z.customAuth}),Ye&&/*#__PURE__*/e.jsx(gt,{delayedExecution:!1}),/*#__PURE__*/e.jsx(gr,{}),/*#__PURE__*/e.jsx(tn,{disabled:Z.embeddedWallets.disableAutomaticMigration}),/*#__PURE__*/e.jsx(rr,{palette:Z.appearance.palette||{}}),!Z.render.standalone&&/*#__PURE__*/e.jsx(pr,{open:p})]})}),/*#__PURE__*/e.jsx(xr,{appId:l.appId,appClientId:l.clientId,clientAnalyticsId:c.clientAnalyticsId,origin:c.apiUrl,mfaMethods:E?.mfaMethods,mfaPromise:se,mfaSubmitPromise:le,onLoad:G,onLoadFailed:()=>null}),Z.loginConfig.telegramAuthConfiguration&&
6
+ /*#__PURE__*/e.jsx(s.Hide,{$if:!0,children:/*#__PURE__*/e.jsx(wr,{scriptHost:l.apiUrl||s.DEFAULT_PRIVY_API_URL,botUsername:Z.loginConfig.telegramAuthConfiguration.botName})})]})})})})})})};const fi=()=>{let{setModalData:e}=s.usePrivyModal(),{openModal:t,privy:n,closePrivyModal:i}=v.usePrivyInternal(),{user:a}=d.usePrivyContext();return r.useMemo((()=>({verify:async({standalone:r=!0}={standalone:!0})=>new Promise(((o,s)=>a?0===a.mfaMethods.length?o():(e((e=>({...e,mfaVerify:{onSuccess:async()=>{r?await i({shouldCallAuthOnSuccess:!1,isSuccess:!0}):tr.setState({inProgressMfaFlow:void 0}),o()},onFailure:async e=>{r?await i({shouldCallAuthOnSuccess:!1,isSuccess:!1}):tr.setState({inProgressMfaFlow:void 0}),s(e)},sendSmsCode:async()=>{throw Error("Not enabled")},verifySmsCode:async()=>{throw Error("Not enabled")},verifyTotpCode:async e=>{await n.fetchPrivyRoute(z.MfaAuthTotpVerify,{body:{code:e}})},generateOptions:async()=>it((await n.fetchPrivyRoute(z.MfaAuthPasskeyInit,{body:{}})).options),verifyPasskey:async e=>{let t=await import("@simplewebauthn/browser"),r=await t.startAuthentication(e);await n.fetchPrivyRoute(z.MfaAuthPasskeyVerify,{body:{authenticator_response:rn(r)}})}}}))),void(r?t(Xt):tr.setState({inProgressMfaFlow:"auth"}))):s(Error("Must be logged in to verify MFA"))))})),[n,e,t,i])},vi={component:()=>{let{user:t,ready:n}=d.usePrivyContext(),{data:i,onUserCloseViaDialogOrKeybindRef:a}=s.usePrivyModal(),o=s.useAppConfig(),[l,c]=r.useState(null),[u,h]=r.useState(null),[p,y]=r.useState(null),[m,w]=r.useState(!1),[g,f]=r.useState(!1),[v,C]=r.useState(),E=async()=>{v?A(v):t?await P({user:t}):A(Error("Must be logged in to manage MFA")),setTimeout((()=>{c(null),h(null)}),500)};if(a.current=E,!i?.mfaEnroll)throw Error("Missing modal data for MFA enrollment screen.");let{onFailure:A,onSuccess:P,onBack:k,mfaMethods:b,verify:x,generateTotpSecret:T,enrollTotp:S,unenrollTotp:_,enrollPasskey:I}=i.mfaEnroll,U=t?.mfaMethods.includes("sms"),W=t?.mfaMethods.includes("totp"),R=t?.mfaMethods.includes("passkey"),O=!!t?.phone,M=t?.linkedAccounts.filter((e=>"passkey"===e.type)).map((e=>e.credentialId))??[];function N(){c(null),h(null),C(void 0)}async function j(e=M){try{C(void 0),f(!0);let t=await I(e);return await P({user:t})}catch(e){C(e)}finally{f(!1),w(!1)}}if(!n||!t||!o)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:E,backFn:k},"header"),/*#__PURE__*/e.jsx(vt,{children:/*#__PURE__*/e.jsx(Sn,{})}),/*#__PURE__*/e.jsx(At,{children:/*#__PURE__*/e.jsx(s.Loader,{})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("sms"===l)return null;if("totp"===l)/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:N,onClose:E},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(le.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Remove authenticator app verification?"}),/*#__PURE__*/e.jsxs(Et,{children:["MFA adds an extra layer of security to your ",o?.name," account. Make sure you have other methods to secure your account."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{$warn:!0,onClick:async function(){try{C(void 0),f(!0);let e=await _();return await P({user:e})}catch(e){C(e)}finally{f(!1),c(null)}},loading:g,children:"Remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]});if("passkey"===l){let t=i.mfaEnroll.shouldUnlinkOnUnenrollMfa??!0;/*#__PURE__*/return e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{backFn:N,onClose:E},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(le.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Are you sure you want to remove this passkey?"}),/*#__PURE__*/e.jsx(Et,{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(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{$warn:!0,onClick:async function(){try{C(void 0),f(!0);let e=await I([]);return await P({user:e})}catch(e){C(e)}finally{f(!1),c(null)}},loading:g,children:"Remove"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})}return 0!==b.length||U||W||R?"sms"===u?null:"totp"===u&&p?/*#__PURE__*/e.jsx(zn,{onClose:E,onReset:N,submitEnrollmentWithTotp:e=>async function(e){try{C(void 0),f(!0);let t=await S(e);return await P({user:t})}catch(e){C(e)}finally{f(!1),c(null)}}(e.mfaCode),error:v,totpInfo:{...p,appName:o?.name||"Privy"}}):"passkey"===u?/*#__PURE__*/e.jsx(On,{onReset:N,onClose:E,submitEnrollmentWithPasskey:j}):/*#__PURE__*/e.jsx(In,{showIntro:!0,userMfaMethods:t.mfaMethods,appMfaMethods:o.mfa.methods,userHasAuthSms:O,backFn:k,handleSelectMethod:async function(e){C(void 0);try{await x()}catch(e){return void C(e)}return"totp"===e?(h(e),y(null),void T().then((({totpSecret:e,totpAuthUrl:t})=>{y({authUrl:t,secret:e})})).catch((()=>{y(null),N()}))):"passkey"===e&&1===M.length?await j():void h(e)},isTotpLoading:"totp"===u&&!p,isPasskeyLoading:m,error:v,onClose:E,setRemovingMfaMethod:async function(e){C(void 0);try{await x()}catch(e){return void C(e)}c(e)}}):/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(s.ModalHeader,{onClose:E,backFn:k},"header"),/*#__PURE__*/e.jsx(Mt,{style:{marginBottom:"1.5rem"},children:/*#__PURE__*/e.jsx(ie.default,{})}),/*#__PURE__*/e.jsx(Ct,{children:"Add more security"}),/*#__PURE__*/e.jsxs(Et,{children:[o?.name," does not have any verification methods enabled."]}),/*#__PURE__*/e.jsx(xt,{children:/*#__PURE__*/e.jsx(s.PrimaryButton,{onClick:E,children:"Close"})}),/*#__PURE__*/e.jsx(s.ModalFooter,{})]})}};let Ci=async(e,t,r,n,i)=>{if(!e)throw n("linkAccount","onError",o.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:i}),new o.PrivyClientError("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(i))))throw new o.PrivyClientError(`OAuth account of type ${i} not linked to the account.`);await r(i)};Object.defineProperty(exports,"SUPPORTED_CHAINS",{enumerable:!0,get:function(){return a.DEFAULT_SUPPORTED_CHAINS}}),Object.defineProperty(exports,"addPrivyRpcToChain",{enumerable:!0,get:function(){return a.addPrivyRpcToChain}}),Object.defineProperty(exports,"addRpcUrlOverrideToChain",{enumerable:!0,get:function(){return a.addRpcUrlOverrideToChain}}),exports.EthereumWalletConnector=s.EthereumWalletConnector,exports.VERSION=s.VERSION,exports.WalletConnector=s.WalletConnector,exports.errorIndicatesMaxMfaRetries=s.errorIndicatesMaxMfaRetries,exports.errorIndicatesMfaTimeout=s.errorIndicatesMfaTimeout,exports.errorIndicatesMfaVerificationFailed=s.errorIndicatesMfaVerificationFailed,exports.useWallets=s.useWallets,exports.useActiveWallet=C.useActiveWallet,exports.useConnectWallet=C.useConnectWallet,exports.useFundWallet=C.useFundWallet,exports.useLogin=C.useLogin,exports.useLogout=C.useLogout,exports.useCreateWallet=I.useCreateWallet,exports.useImportWallet=I.useImportWallet,exports.usePrivy=I.usePrivy,exports.getEmbeddedConnectedWallet=V.getEmbeddedConnectedWallet,exports.Captcha=gt,exports.ConnectorManager=Xe,exports.LoginModal=pr,exports.PrivyClient=mt,exports.PrivyProvider=({config:t,...n})=>{var i;if((()=>{if(r.useContext(ii))throw new o.PrivyClientError("Multiple PrivyProvider instances found","Found multiple instances of PrivyProvider, ensure there is only one mounted in your application tree.")})(),"undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol&&"chrome-extension:"!==window.location.protocol)throw new o.PrivyClientError("Embedded wallet is only available over HTTPS");if("string"!=typeof(i=n.appId)||25!==i.length)throw new o.PrivyClientError("Cannot initialize the Privy provider with an invalid Privy app ID");ai||(ai=new mt({appId:n.appId,appClientId:n.clientId,apiUrl:n.apiUrl}));let a=Object.assign({},t),l=r.useMemo((()=>new J.default({appId:n.appId,clientId:n.clientId,storage:s.f,baseUrl:n.apiUrl,sdkVersion:"react-auth:3.4.0"})),[]);/*#__PURE__*/
7
+ return e.jsx(s.PrivyAppConfigProvider,{client:l,legacyClient:ai,appClientId:n.clientId,clientConfig:a,children:/*#__PURE__*/e.jsx(s.PrivyPluginProvider,{children:/*#__PURE__*/e.jsx(gi,{...n,client:ai,privy:l})})})},exports.getAccessToken=function(){return ai?ai.getCustomerAccessToken():Promise.resolve(s.f.get(s.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.toViemAccount=async({wallet:e})=>{let t=await e.getEthereumProvider();return $.toAccount({address:e.address,sign:async({hash:r})=>{if("privy"!==e.walletClientType)throw new a.PrivyClientError({error:"Unprefixed signing is not supported by external wallets.",code:"unsupported_wallet_type"});return await t.request({method:"secp256k1_sign",params:[r]})},signMessage:async({message:r})=>await t.request({method:"personal_sign",params:[r,e.address]}),signTypedData:async r=>await t.request({method:"eth_signTypedData_v4",params:[e.address,r]}),signTransaction:async e=>await t.request({method:"eth_signTransaction",params:[e]})})},exports.useAuthMfa=fi,exports.useAuthMfaEnrollment=()=>{let e=s.useAppConfig(),{setModalData:t}=s.usePrivyModal(),{verify:n}=fi(),{openModal:i,privy:a,closePrivyModal:o,refreshSessionAndUser:l,setUser:c}=v.usePrivyInternal();return r.useMemo((()=>({enroll:async r=>new Promise(((s,d)=>{t({mfaEnroll:{onSuccess:async e=>{await o({shouldCallAuthOnSuccess:!1,isSuccess:!0}),s(e)},onFailure:async e=>{await o({shouldCallAuthOnSuccess:!1,isSuccess:!1}),d(e)},onBack:r?.onBack?async()=>{await o({shouldCallAuthOnSuccess:!1,isSuccess:!1}),d(Error("User canceled MFA enrollment flow.")),r.onBack?.()}:void 0,verify:()=>n({standalone:!1}),shouldUnlinkOnUnenrollMfa:!0,mfaMethods:e.mfa.methods,sendSmsCode:async()=>{throw Error("Not enabled")},enrollSms:async()=>{throw Error("Not enabled")},unenrollSms:async()=>{throw Error("Not enabled")},generateTotpSecret:async()=>await a.fetchPrivyRoute(z.MfaAuthTotpInit,{body:{}}),enrollTotp:async e=>{await a.fetchPrivyRoute(z.MfaAuthTotpEnroll,{body:{code:e}});let t=await l();return c(t),t},unenrollTotp:async()=>{await a.fetchPrivyRoute(z.MfaAuthTotpUnenroll,{body:{}});let e=await l();return c(e),e},enrollPasskey:async e=>{await a.fetchPrivyRoute(z.MfaAuthPasskeyEnrollment,{body:{credential_ids:e,remove_for_login:!0}});let t=await l();return c(t),t}}}),i(vi)}))})),[a,t,i,o])},exports.useAuthorizationSignature=()=>{let{signWithUserSigner:e}=K.useSignWithUserSigner();return r.useMemo((()=>({async generateAuthorizationSignature(t){let{signature:r}=await a.generateAuthorizationSignature(e,t);return{signature:r}}})),[e])},exports.useBaseAccountSdk=()=>{let{baseAccountSdk:e}=v.usePrivyInternal();return{baseAccountSdk:e}},exports.useConnectBaseAccount=()=>{let{connectBaseAccount:e}=v.usePrivyInternal();return{connectBaseAccount:e}},exports.useConnectCoinbaseSmartWallet=()=>{let{connectCoinbaseSmartWallet:e}=v.usePrivyInternal();return{connectCoinbaseSmartWallet:e}},exports.useConnectOrCreateWallet=e=>{let{connectOrCreateWallet:t}=d.usePrivyContext();return s.usePrivyEventSubscription("connectOrCreateWallet",e),{connectOrCreateWallet:t}},exports.useCrossAppAccounts=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:n,sendTransactionWithCrossAppWallet:i,signTransactionWithCrossAppWallet:a}=d.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,signTransaction:a}},exports.useCustomAuth=e=>{let t=ri((e=>e.jwtAuthFlowState));return s.usePrivyEventSubscription("customAuth",e),{status:t}},exports.useDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=v.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}=d.usePrivyContext();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}},exports.useGetAccessTokenForProvider=()=>r.useMemo((()=>({getAccessTokenForProvider:({appId:e})=>{try{let t=s.f.get(s.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return{token:null};{let r=new Me(t);return r.isExpired()?(s.f.del(s.getProviderAccessTokenStorageKey(e)),{token:null}):{token:r.value}}}catch(e){return console.error(e),{token:null}}}})),[]),exports.useGuestAccounts=function(){let e=s.useAppConfig(),t=s.useEmitPrivyEvent(),{client:r,setUser:n,setAuthenticated:i,setIsNewUser:a,initializeWalletProxy:l}=v.usePrivyInternal(),{create:c}=I.useCreateWalletInternal();return{createGuestAccount:async()=>{if(!e.id||!r)throw Error("SDK not yet ready");r.startAuthFlow(new ot(e.id));try{let d=await r.authenticate(),u=d.user,h=d.isNewUser??!1;if(!u)throw new o.PrivyClientError("Unable to authenticate guest account");let p=await r.getAccessToken(),y=await l(s.WALLET_PROXY_TIMEOUT);if(p&&y)try{let t=s.shouldCreateEmbeddedEthWallet(u,e.embeddedWallets.ethereum.createOnLogin),r=s.shouldCreateEmbeddedSolWallet(u,e.embeddedWallets.solana.createOnLogin);t&&r?(u=(await c({chainType:"ethereum",latestUser:u})).user,u=(await c({chainType:"solana",latestUser:u})).user):r?u=(await c({chainType:"solana",latestUser:u})).user:t?u=(await c({chainType:"ethereum",latestUser:u})).user:n(u)}catch(e){n(u),console.warn("Unable to create embedded wallet for guest account")}return a(h),i(!0),t("login","onComplete",{user:u,isNewUser:h,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),u}catch(e){throw t("login","onError",e.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}}}},exports.useHeadlessDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=v.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}=lt();return{identityToken:e}},exports.useLinkAccount=function(e){let{linkEmail:t,linkPhone:n,linkWallet:i,linkGoogle:a,linkApple:o,linkTwitter:l,linkTwitch:c,linkDiscord:u,linkGithub:h,linkLinkedIn:p,linkTiktok:y,linkLine:m,linkSpotify:w,linkInstagram:g,linkTelegram:f,linkFarcaster:v,linkPasskey:C}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("linkAccount",e),{linkEmail:t,linkPhone:n,linkWallet:i,linkGoogle:a,linkApple:o,linkTwitter:l,linkTwitch:c,linkDiscord:u,linkGithub:h,linkLinkedIn:p,linkTiktok:y,linkLine:m,linkSpotify:w,linkInstagram:g,linkFarcaster:v,linkTelegram:f,linkPasskey:C}},exports.useLinkJwtAccount=function(e){let{client:t}=v.usePrivyInternal(),[n,i]=r.useState({status:"initial"});return{linkWithCustomJwt:r.useCallback((async r=>{try{i({status:"initial"}),t.startAuthFlow(new at(r)),i({status:"loading"});let{user:n}=await t.link();if(!n)throw Error("Error, user not found");let a=n.linkedAccounts.filter((e=>"custom_auth"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime())).at(0);return i({status:"done"}),e?.onSuccess?.({user:n,linkMethod:"custom",linkedAccount:a}),{user:n}}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"custom"}),r}}),[t.startAuthFlow,t.link]),state:n}},exports.useLinkWithPasskey=e=>{let{initLinkWithPasskey:t,linkWithPasskey:n,passkeyAuthState:i,setPasskeyAuthState:a}=v.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 a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[n]),state:i}},exports.useLinkWithSiwe=e=>{let t=s.useCaptcha(),{siweState:n,setSiweState:i,linkWithSiwe:a,generateSiweMessage:l}=v.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||o.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 s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:i,linkedAccount:u}=await a({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||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[a,t.status]),state:n}},exports.useLinkWithSiws=()=>{let e=s.useCaptcha(),{client:t,setUser:n,refreshSessionAndUser:i}=v.usePrivyInternal(),{authenticated:a}=I.usePrivy();return{generateSiwsMessage:r.useCallback((async({address:r})=>{let n;if(e.enabled&&"error"===e.status)throw new s.CaptchaError(e.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),n=await e.waitForResult());let i=await t.generateSiwsNonce({address:r,captchaToken:n});return s.prepareSiwsMessageWithNonce({address:r,nonce:i})}),[e,t]),linkWithSiws:r.useCallback((async({signature:r,message:l,walletClientType:c,connectorType:d})=>{if(!a)throw Error("User must be authenticated before linking");if(e.enabled&&"error"===e.status)throw new s.CaptchaError(e.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let u=await t.linkWithSiws({message:l,signature:r,walletClientType:c,connectorType:d,messageType:"plain"}),h=(e=>{if(!e)return;let t=e.linkedAccounts;return t&&0!==t.length?t[t.length-1]:void 0})(u=await i()??u)||null;return n(u||null),{user:u,linkedAccount:h}}),[a,e,t,i,n])}},exports.useLoginWithEmail=e=>{let t=s.useCaptcha(),{emailOtpState:n,setEmailOtpState:i,initLoginWithEmail:a,loginWithCode:l}=v.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 s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a({email:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:r.useCallback((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:c}=await l(r);e?.onComplete?.({user:n,isNewUser:i,wasAlreadyAuthenticated:a,loginMethod:"email",loginAccount:c})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t.status]),state:n}},exports.useLoginWithFarcasterV2=()=>{let{client:e,setAuthenticated:t,setUser:n}=v.usePrivyInternal();return r.useMemo((()=>({init:async()=>{if(!e)throw new o.PrivyClientError("Must initialize Privy client first.");let t=new B.FarcasterFramesFlow;return e.startAuthFlow(t),await t.init()},login:async({fid:r,message:i,signature:a})=>{if(!e)throw new o.PrivyClientError("Must initialize Privy client first.");if(!(e.authFlow instanceof B.FarcasterFramesFlow))throw new o.PrivyClientError("Must initialize Farcaster Mini App flow first.");e.authFlow.setAuthData({message:i,signature:a,fid:r});let{user:s}=await e.authenticate();if(!s)throw new o.PrivyClientError("Failed to login with Farcaster V2");return n(s),t(!0),{user:s}}})),[e,n,t])},exports.useLoginWithOAuth=e=>{s.usePrivyEventSubscription("login",e);let t=s.useCaptcha(),n=s.useIsServerConfigLoaded(),{ready:i,user:a}=d.usePrivyContext(),{initLoginWithHeadlessOAuth:l,loginWithHeadlessOAuth:c,oAuthState:u,setOAuthState:h,isHeadlessOAuthLoading:p}=v.usePrivyInternal(),y=r.useCallback((async e=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return await l(e.provider,t.token,e.disableSignup)}catch(e){throw h({status:"error",error:e}),e}}),[l,t]),m=r.useCallback((async()=>{let e=Ue();try{if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");let t=e.provider;if(d.isCustomOAuthProvider(t)){if(a&&a.linkedAccounts.some((e=>e.type===t)))return console.warn("User is already logged in with this OAuth provider"),a}else if(a&&t in a&&a[t])return console.warn("User is already logged in with this OAuth provider"),a;if(e.popupFlow)return}catch(e){throw h({status:"error",error:e}),e}try{return await c(e)}catch(e){throw h({status:"error",error:e}),e}finally{s.stripUrlOAuthParamsAndRemoveStateCode()}}),[c]);return r.useEffect((()=>{let e=Ue();i&&n&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&m().catch((()=>{}))}),[i,n]),{initOAuth:y,loading:p,state:u}},exports.useLoginWithPasskey=e=>{let t=s.useCaptcha(),{initLoginWithPasskey:n,loginWithPasskey:i,passkeyAuthState:a,setPasskeyAuthState:l}=v.usePrivyInternal();return{loginWithPasskey:r.useCallback((async r=>{try{let a;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),a=await t.waitForResult()),await n({captchaToken:a,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||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[i,t.status]),state:a}},exports.useLoginWithSiwe=e=>{let t=s.useCaptcha(),{siweState:n,setSiweState:i,client:a,generateSiweMessage:l,loginWithSiwe:c}=v.usePrivyInternal();return{generateSiweNonce:r.useCallback((async r=>{try{let e;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),i({status:"generating-message"});let n=await a.generateSiweNonce({address:r?.address,captchaToken:e});return i({status:"awaiting-signature"}),n}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a,t]),generateSiweMessage:r.useCallback((async({address:r,chainId:n})=>{try{let e;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await l({address:r,chainId:n,captchaToken:e})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t]),loginWithSiwe:r.useCallback((async({message:r,signature:n,disableSignup:a})=>{try{let i;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),i=await t.waitForResult());let{user:l,isNewUser:d}=await c({message:r,signature:n,captchaToken:i,disableSignup:a});return e?.onComplete?.({user:l,isNewUser:d,wasAlreadyAuthenticated:!1,loginMethod:"siwe",loginAccount:null}),l}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[c,t.status]),state:n}},exports.useLoginWithSiws=()=>{let e=s.useCaptcha(),{client:t,setAuthenticated:n,setUser:i,setIsNewUser:a}=v.usePrivyInternal(),{authenticated:l}=I.usePrivy();return{generateSiwsMessage:r.useCallback((async({address:r})=>{let n;if(e.enabled&&"error"===e.status)throw new s.CaptchaError(e.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),n=await e.waitForResult());let i=await t.generateSiwsNonce({address:r,captchaToken:n});return s.prepareSiwsMessageWithNonce({address:r,nonce:i})}),[e,t]),loginWithSiws:r.useCallback((async({message:r,signature:c,disableSignup:d})=>{if(l)throw Error("User already authenticated");if(e.enabled&&"error"===e.status)throw new s.CaptchaError(e.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),await e.waitForResult());let{user:u,isNewUser:h}=await t.authenticateWithSiws({message:r,signature:c,mode:d?"no-signup":"login-or-sign-up",messageType:"plain"});if(!u)throw Error("Authentication failed - no user returned");return i(u),a(h||!1),n(!0),u}),[l,e,t,n,i,a])}},exports.useLoginWithSms=e=>{let t=s.useCaptcha(),{smsOtpState:n,setSmsOtpState:i,initLoginWithSms:a,loginWithCode:l}=v.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 s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await a({phoneNumber:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[a]),loginWithCode:r.useCallback((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:c}=await l(r);e?.onComplete?.({user:n,isNewUser:i,wasAlreadyAuthenticated:a,loginMethod:"sms",loginAccount:c})}catch(r){throw i({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[l,t.status]),state:n}},exports.useLoginWithTelegram=e=>{let t=s.useCaptcha(),{initLoginWithTelegram:n,loginWithTelegram:i,telegramAuthState:a,setTelegramAuthState:l}=v.usePrivyInternal();return{login:r.useCallback((async r=>{try{if(t.enabled&&"success"!==t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);await n(t.token,r?.disableSignup);let{user:a,isNewUser:l,loginAccount:c,wasAlreadyAuthenticated:d}=await i({intent:"login"});e?.onComplete?.({user:a,isNewUser:l,wasAlreadyAuthenticated:d,loginMethod:"telegram",loginAccount:c})}catch(r){throw l({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),r}}),[n,i,t]),state:a}},exports.useMfa=Qt,exports.useMfaEnrollment=Tn,exports.useMigrateWallets=en,exports.useModalStatus=()=>{let{isModalOpen:e}=r.useContext(d.PrivyContext);return{isOpen:e}},exports.useOAuthTokens=function(e){let{authenticated:t,user:r}=d.usePrivyContext(),{initLoginWithOAuth:n}=v.usePrivyInternal(),i=s.useEmitPrivyEvent();return s.usePrivyEventSubscription("oAuthAuthorization",e),{reauthorize:e=>Ci(t,r,n,i,e.provider)}},exports.useRecoverEmbeddedWallet=()=>{let{user:e}=d.usePrivyContext(),{walletProxy:t}=v.usePrivyInternal();return{recover:r.useCallback((async r=>{if(!t)throw Error("Wallet proxy is not ready");let n=await ui();if(!e||!n)throw new o.PrivyClientError("User must be logged in before attempting to modify the recovery method.");let{entropyId:i,entropyIdVerifier:a}=s.getEntropyDetailsForUser(e);try{await t.recover({entropyId:i,entropyIdVerifier:a,accessToken:n,...r})}catch{throw new o.PrivyClientError("Unable to recover wallets")}}),[t,e])}},exports.useRegisterMfaListener=ft,exports.useSendTransaction=function(e){let{sendTransaction:t}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("sendTransaction",e),{sendTransaction:t}},exports.useSessionSigners=()=>{let{addSessionSignersInternal:e,removeSessionSignersInternal:t}=(()=>{let{user:e}=d.usePrivyContext(),t=v.usePrivyInternal(),{signWithUserSigner:r}=K.useSignWithUserSigner(),n=async({wallet:n,additional_signers:i})=>{let s=await t.client.getAccessToken();if(!e||!s)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if(!n.id)throw new o.PrivyClientError("Wallet to add signers to must have ID on server");if(!t.walletProxy)throw new o.PrivyClientError("Wallet proxy not initialized.");await a.updateWallet(t.privy,{wallet_id:n.id},r,{additional_signers:i})};return{addSessionSignersInternal:async({address:r,signers:i})=>{let l=await t.client.getAccessToken();if(!e||!l)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to add a session signer.");let c=t.walletProxy??await t.initializeWalletProxy(15e3);if(!c)throw new o.PrivyClientError("Wallet proxy not initialized.");let u=d.getPrivyWalletWithAddress(e,r);if(!u)throw new o.PrivyClientError("Address to add signers too is not associated with current user.");if(d.getIsUnifiedWallet(u)){if(0===i.length)throw new o.PrivyClientError("Must specify at least one signer to add.");let e=[...(await a.getWallet(t.privy,{wallet_id:u.id})).additional_signers,...s.parseAdditionalSigners(i)];await n({wallet:u,additional_signers:e})}else{if(u.delegated)return{user:e};if(i.length>0)throw new o.PrivyClientError("Specifying signers in addSessionSigners is only supported for TEE execution and this app uses On-device execution. Pass an empty array for signers instead. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let n=Tr({address:r,user:e}),a=Sr({address:r,user:e});await t.recoverEmbeddedWallet({address:r}),await c.createDelegatedAction({accessToken:l,rootWallet:a,delegatedWallets:[n]})}let h=await t.refreshSessionAndUser();if(!h)throw Error("Could not refresh user");return{user:h}},removeSessionSignersInternal:async({address:r})=>{let i=await t.client.getAccessToken();if(!e||!i)throw new o.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if(!(t.walletProxy??await t.initializeWalletProxy(15e3)))throw new o.PrivyClientError("Wallet proxy not initialized.");let a=d.getPrivyWalletWithAddress(e,r);if(!a)throw new o.PrivyClientError("Address to remove signers from is not associated with current user.");d.getIsUnifiedWallet(a)?await n({wallet:a,additional_signers:[]}):await t.client.revokeDelegatedWallet();let s=await t.refreshSessionAndUser();if(!s)throw Error("Could not refresh user");return{user:s}}}})();return{addSessionSigners:async({address:t,signers:r})=>e({address:t,signers:r}),removeSessionSigners:async({address:e})=>t({address:e})}},exports.useSetWalletRecovery=function(e){let{setWalletRecovery:t}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("setWalletRecovery",e),{setWalletRecovery:t}},exports.useSign7702Authorization=()=>{let{ready:e,wallets:t}=s.useWallets(),{user:n}=d.usePrivyContext(),{rpcConfig:a,chains:o,appId:l}=v.usePrivyInternal();return{signAuthorization:r.useCallback((async(r,c)=>{let u;if(!n)throw Error("User must be authenticated before signing with a Privy wallet");if(!e)throw Error("Wallets are not ready");let h=c?.address??d.getPrivyEthereumWallet(n)?.address??T.zeroAddress,p=t.find((e=>T.getAddress(e.address)===T.getAddress(h)));if(!p)throw Error("Signing wallet not found.");let y=r.chainId??Number(p.chainId.split(":")[1]);if(0===y)u={chainId:0,address:r.contractAddress,nonce:r.nonce??0};else{let e=o.find((e=>e.id===y));if(!e)throw Error("Error, chain not configured in PrivyProvider config");let t=T.createWalletClient({account:h,chain:e,transport:T.http(s.getJsonRpcEndpointFromChain(e,a,l))});u=await t.prepareAuthorization({...r})}let m=await p.getEthereumProvider(),w=await m.request({method:"secp256k1_sign",params:[i.hashAuthorization(u)]});return{...u,...T.parseSignature(w)}}),[e,t,n,o])}},exports.useSignMessage=function(e){let{signMessage:t}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("signMessage",e),{signMessage:t}},exports.useSignTransaction=function(){let{signTransaction:e}=r.useContext(d.PrivyContext);return{signTransaction:e}},exports.useSignTypedData=function(e){let{signTypedData:t}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("signTypedData",e),{signTypedData:t}},exports.useSignupWithPasskey=e=>{let t=s.useCaptcha(),{initSignupWithPasskey:n,signupWithPasskey:i,passkeyAuthState:a,setPasskeyAuthState:l}=v.usePrivyInternal();return{signupWithPasskey:r.useCallback((async()=>{try{let r;if(t.enabled&&"error"===t.status)throw new s.CaptchaError(t.error,null,o.PrivyErrorCode.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),r=await t.waitForResult()),await n({captchaToken:r,withPrivyUi:!1});let{user:a,isNewUser:l,wasAlreadyAuthenticated:c,loginAccount:d}=await i();e?.onComplete?.({user:a,isNewUser:l,wasAlreadyAuthenticated:c,loginMethod:"passkey",loginAccount:d})}catch(t){throw l({status:"error",error:t}),e?.onError?.(t.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[i,t.status]),state:a}},exports.useSubscribeToJwtAuthWithFlag=function({isAuthenticated:e,isLoading:t,...n}){let i=r.useRef();r.useEffect((()=>{t||i.current?.()}),[e,t]);let a=r.useCallback((e=>(i.current=e,()=>{i.current=void 0})),[]);return ti({...n,subscribe:a})},exports.useSyncJwtBasedAuthState=ti,exports.useToken=function(e){let{getAccessToken:t}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("accessToken",e),{getAccessToken:t}},exports.useUpdateAccount=function(e){let{updateEmail:t,updatePhone:n}=r.useContext(d.PrivyContext);return s.usePrivyEventSubscription("update",e),{updateEmail:t,updatePhone:n}},exports.useUpdateEmail=e=>{let{user:t}=d.usePrivyContext(),{loginWithCode:n,emailOtpState:i,setEmailOtpState:a,client:s,inProgressAuthFlowRef:l,inProgressLoginOrLinkMethodRef:c}=v.usePrivyInternal();return{state:i,sendCode:r.useCallback((async({newEmailAddress:r})=>{try{if(!t?.email)throw Error("User is required to have an email address to update it.");let e=new Ce(t.email.address,r);s.startAuthFlow(e),await e.sendCodeEmail({withPrivyUi:!1})}catch(r){a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[t?.email]),verifyCode:r.useCallback((async({code:r})=>{try{if(!t?.email)throw Error("User is required to have an email address to update it.");l.current="update",c.current="email";let{user:i,linkedAccount:a}=await n(r);return e?.onSuccess?.({user:i,updateMethod:"email",updatedAccount:a}),{user:i}}catch(r){a({status:"error",error:r}),e?.onError?.(r.privyErrorCode||o.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[t?.email])}},exports.useUser=()=>{let{setUser:e,client:t}=r.useContext(v.InternalPrivyContext),{user:n}=r.useContext(d.PrivyContext);return{user:n,refreshUser:r.useCallback((async()=>{let r=await(t?.updateUserAndIdToken());return e(r??null),r}),[t,e])}};