@privy-io/react-auth 2.4.0 → 2.4.1

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.
@@ -1,3 +1,3 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("mipd"),r=require("react"),a=require("react-device-detect"),n=require("viem/utils"),i=require("./auth-flows/custom-jwt-account.js"),o=require("./auth-flows/email.js"),s=require("./auth-flows/farcaster.js"),l=require("./auth-flows/guest.js"),c=require("./auth-flows/passkey.js"),d=require("./auth-flows/siwe.js"),u=require("./auth-flows/siws.js"),h=require("./auth-flows/sms.js"),y=require("./auth-flows/telegram.js"),p=require("uuid"),w=require("./accessToken.js"),E=require("./client/user.js"),v=require("eventemitter3"),m=require("./constants.js"),g=require("./storage.js"),f=require("./utils/index.js"),C=require("./connectors/coinbase.js"),A=require("./connectors/embedded.js"),P=require("./embedded-wallets/rpc/types.js"),_=require("./components/Captcha.js"),T=require("./components/LoginModal.js"),I=require("./components/TelegramLoginButton.js"),W=require("./configuration/context.js"),S=require("./connectors/areWalletArraysEqual.js"),N=require("./connectors/errors.js"),k=require("./connectors/isBaseConnectedEthereumWallet.js"),U=require("./connectors/mobile-wallets.js"),O=require("./connectors/solana/index.js"),b=require("./connectors/walletconnect-v2.js"),R=require("./embedded-wallets/EmbeddedWalletIframe.js"),M=require("./embedded-wallets/delegated-actions.js"),D=require("./embedded-wallets/errors.js"),L=require("./embedded-wallets/rpc/index.js"),F=require("./errors.js"),x=require("./embedded-wallets/solana/transaction.js"),q=require("./lib/caip2.js"),j=require("./lib/cross-app/index.js"),B=require("./lib/cross-app/authFlow.js"),H=require("./lib/cross-app/popupCrossAppAuthFlow.js"),K=require("./lib/cross-app/sendCrossAppRequest.js"),V=require("./lib/embeddedWalletRecovery.js"),G=require("./lib/funding/index.js"),z=require("./lib/funding/isFundingEnabled.js"),Y=require("./lib/isEmbeddedWebview.js"),$=require("./lib/popup/triggerPopup.js"),X=require("./lib/popupOAuthFlow.js"),J=require("./lib/siwe.js"),Q=require("./lib/solana/transaction.js"),Z=require("./lib/toDisplayFromAccountType.js"),ee=require("./lib/user/shouldCreateEmbeddedEthWallet.js"),te=require("./lib/user/shouldCreateEmbeddedSolWallet.js"),re=require("./lib/viem/prepareTransactionRequest.js"),ae=require("./passkeys/transformResponseToSnakeCase.js"),ne=require("./plugins/context/PrivyPluginContext.js"),ie=require("./plugins/solana-funding/id.js"),oe=require("./recent-login/context.js"),se=require("./screens/index.js"),le=require("./screens/LandingScreen/styles.js"),ce=require("./styles.js"),de=require("./utils/eth/getPublicClient.js"),ue=require("./hooks/index.js"),he=require("./hooks/captcha-context.js"),ye=require("./hooks/events-context.js"),pe=require("./hooks/internal-context.js"),we=require("./hooks/modal-context.js"),Ee=require("./hooks/privy-context.js"),ve=require("./hooks/useWallets.js"),me=require("./lib/funding/prepareFundingModalData.js"),ge=require("./auth-flows/oauth/detectCompletingOAuthFlow.js"),fe=require("./auth-flows/oauth/OAuthFlow.js"),Ce=require("./lib/viem/toViemTransactionSerializable.js"),Ae=require("./connectors/getRpcTimeout.js"),Pe=require("./connectors/providerTypes.js"),_e=require("./connectors/ethereum/index.js"),Te=require("./connectors/ethereum/EthereumNullConnector.js"),Ie=require("./connectors/injected.js"),We=require("./connectors/metamask.js"),Se=require("./connectors/privyProxyProvider.js"),Ne=require("./connectors/solana/SolanaNullConnector.js"),ke=require("./connectors/stored-connection.js"),Ue=require("./http.js"),Oe=require("./lib/smart-wallet-helpers.js"),be=require("./passkeys/transformOptionsToCamelCase.js"),Re=require("./paths.js"),Me=require("./session.js");function De(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var Le=/*#__PURE__*/De(v);class Fe extends Le.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Pe.EmbeddedProviderError(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await et()||!this.address)throw new Pe.EmbeddedProviderError("Disconnected",4900);let{hash:r}=await nt(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Pe.EmbeddedProviderError(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await et()||!this.address)throw new Pe.EmbeddedProviderError("Disconnected",4900);let{signature:r}=await at(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new Pe.EmbeddedProviderError(`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 Pe.EmbeddedProviderError(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=de.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:a}=await tt({message:t},{address:r});return a}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:a}=await rt(f.generateTypedDataWithDomainType(r),{address:t});return a}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:f.toHex(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...Ce.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 f.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(!P.isSupportedEthereumRpcMethod(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await et();if(await it(),!t||!this.address)throw new Pe.EmbeddedProviderError("Disconnected",4900);try{return(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:{method:e.method,params:e.params}})).response.data}catch(e){throw console.error(e),new Pe.EmbeddedProviderError("Disconnected",4900)}}}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:a,rpcConfig:n,chains:i,appId:o,chainId:s=1,walletIndex:l}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=a,this.chainId=s,this.rpcConfig=n,this.chains=i,this.publicClient=de.getPublicClient(s,this.chains,n,{appId:o}),this.rpcTimeoutDuration=Ae.getRpcTimeout(n,"privy"),this.appId=o,this.walletIndex=l}}class xe extends Le.default{get wallets(){let e=new Set,t=this.walletConnectors.flatMap((e=>e.wallets)).sort(((e,t)=>e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0)).filter((t=>{let r=`${t.address}${t.walletClientType}${t.connectorType}${t.meta.id}`;return!e.has(r)&&(e.add(r),!0)})),r=t.findIndex((e=>e.address===(this.activeWallet?this.activeWallet:"unknown")));return r>=0&&t.unshift(t.splice(r,1)[0]),t}async initialize(e){if(this.initialized&&!e)return;e&&this.removeAllConnectors(),g.default.get(m.CONNECTORS_STATE_KEY)&&(g.default.getKeys().forEach((e=>{e.startsWith("walletconnect")&&g.default.del(e)})),g.default.del(m.CONNECTORS_STATE_KEY));let t=f.detectInjectedConnectors({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:r})=>{this.createEthereumWalletConnector({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:r}})}))}));for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),Object.values(U.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.addWalletConnector(new Ne.SolanaNullConnector({id:e.client,name:e.name,icon:e.logoDataUri})));this.externalWalletConfig.walletConnect.enabled&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"unknown"}),this.externalWalletConfig.solana.connectors?.get().forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{e?.forEach(this.addSolanaWalletConnector)})),await t,this.initialized=!0}findWalletConnector(e,t){return"wallet_connect_v2"===e?this.walletConnectors.filter(_e.isEthereumWalletConnector).find((t=>t.connectorType===e))??null:this.walletConnectors.filter(_e.isEthereumWalletConnector).find((r=>r.connectorType===e&&r.walletClientType===t))??null}findSolanaWalletConnector(e,t){return this.walletConnectors.filter(O.isSolanaWalletConnector).find((r=>r.connectorType===e&&("unknown"===r.walletClientType?r.walletBranding.id===t:r.walletClientType===t)))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}onInitialized(e){e.wallets.forEach((e=>{let t=this.storedConnections.find((t=>t.address===e.address&&t.connectorType===e.connectorType&&("solana"===e.type&&"unknown"===t.walletClientType&&"unknown"===e.walletClientType?e.meta.id===t.id:t.walletClientType===e.walletClientType)));t&&(e.connectedAt=t.connectedAt)})),this.saveConnectionHistory(),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&(this.saveConnectionHistory(),this.emit("walletsUpdated"))}addEmbeddedWalletConnectors({walletProxy:e,rootWallet:t,embeddedWallets:r,defaultChain:a,appId:n}){for(let i of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===i.walletIndex));if(r&&_e.isEthereumWalletConnector(r))r.proxyProvider.walletProxy=e;else{let{entropyId:r,entropyIdVerifier:o}=E.getEntropyDetailsFromAccount(t),s=new A.EmbeddedWalletConnector({provider:new Fe({walletProxy:e,address:i.address,entropyId:r,entropyIdVerifier:o,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:a.id,walletIndex:i.walletIndex}),chains:this.chains,defaultChain:a,rpcConfig:this.rpcConfig,imported:!1,walletIndex:i.walletIndex});this.addWalletConnector(s)}}}addImportedWalletConnector(e,t,r,a){let n=this.findWalletConnector("embedded_imported","privy");if(n&&_e.isEthereumWalletConnector(n))n.proxyProvider.walletProxy=e;else{let n=new A.EmbeddedWalletConnector({provider:new Fe({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:a,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(n)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.saveConnectionHistory(),this.storedConnections=ke.loadConnectionHistory(),this.emit("walletsUpdated")}removeImportedWalletConnector(){let e=this.findWalletConnector("embedded_imported","privy");if(e){let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1),this.saveConnectionHistory(),this.storedConnections=ke.loadConnectionHistory(),this.emit("walletsUpdated")}}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:a}){let n=this.findWalletConnector(e,t);if(n&&_e.isEthereumWalletConnector(n))return n instanceof b.WalletConnectV2WalletConnector&&n.resetConnection(t),n;let i=(()=>"injected"!==e?"coinbase_wallet"===e?new C.CoinbaseWalletConnector(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):"null"!==e?new b.WalletConnectV2WalletConnector(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,t):a?new Te.EthereumNullConnector({id:a.client,name:a.name,icon:a.logoDataUri,defaultChain:this.defaultChain,walletClientType:a.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new We.MetamaskWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Ie.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Ie.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Ie.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new Ie.Injected6963WalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,t):void 0)();return i&&this.addWalletConnector(i),i||null}addWalletConnector(e){this.walletConnectors.push(e),e.on("initialized",(()=>this.onInitialized(e))),e.on("walletsUpdated",(()=>this.onWalletsUpdated(e))),e.initialize().catch((e=>{console.debug("Failed to initialize connector",e)}))}saveConnectionHistory(){let e=this.wallets.map((e=>({address:e.address,connectorType:e.connectorType,walletClientType:e.walletClientType,connectedAt:e.connectedAt,id:e.meta.id})));g.default.put(m.CONNECTIONS_HISTORY_KEY,e)}async activeWalletSign(e){let t=this.wallets,r=t.length>0?t[0]:null;return r&&k.isBaseConnectedEthereumWallet(r)?r.sign(e):null}setActiveWallet(e){this.activeWallet=n.getAddress(e),this.emit("walletsUpdated")}setWalletList(e){this.walletList=e,this.initialized&&this.initialize(!0).catch(console.error)}removeAllConnectors(){for(let e of this.walletConnectors)e.removeAllListeners();this.walletConnectors=[]}constructor(e,t,r,a,n,i,o,s,l,c,d,u){super(),this.addSolanaWalletConnector=async e=>{this.findSolanaWalletConnector("solana_adapter",e.walletClientType)||this.addWalletConnector(e)},this.getEthereumProvider=()=>{let e=this.wallets[0],t=this.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return e&&t?t.proxyProvider:new Se.PrivyProxyProvider},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=a,this.defaultChain=n,this.walletConnectors=[],this.initialized=!1,this.store=i,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=s,this.externalWalletConfig=l,this.privyAppName=c,this.privyAppLogo=d,this.walletChainType=u||"ethereum-only",this.storedConnections=ke.loadConnectionHistory()}}let qe;var je=0,Be="__private_"+je+++"__getOrGenerateClientAnalyticsId";class He{initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:a,store:n,walletList:i,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c}){this.connectors||(this.connectors=new xe(this.appId,e,t,r,a,n,i,o,s,l,void 0,c))}generateApi(){let e=new Ue.Http({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 F.PrivyClientError("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new F.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(Re.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw F.formatApiError(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(Re.mfaPasskeyInitPath,{});return be.transformOptionsToCamelCase(e.options)}catch(e){throw F.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(Re.acceptTermsPath,{});return E.convertUserResponseToUser(e)}catch(e){throw F.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(Re.unlinkEmailPath,{address:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async unlinkPhone(e){try{let t=await this.api.post(Re.unlinkPhonePath,{phoneNumber:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(Re.unlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(Re.siwsUnlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(Re.unlinkOAuthPath,{provider:e,subject:t});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(r)}catch(e){throw F.formatPrivyError(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(Re.unlinkFarcasterPath,{fid:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async unlinkTelegram(e){try{let t=await this.api.post(Re.telegramAccountUnlinkPath,{telegram_user_id:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async revokeDelegatedWallet(){try{await this.api.post(Re.delegatedActionsRevokePath,{})}catch(e){throw F.formatPrivyError(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:r,options:a}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(Re.analyticsEventsPath,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:r?r.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:a?.keepAlive??!1})}catch(e){}}async signMoonpayOnRampUrl(e){try{return this.api.post(Re.moonpayPluginOnRampPath,e)}catch(e){throw F.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(Re.coinbaseOnRampInitPath,e)}catch(e){throw F.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${Re.coinbaseOnRampStatusPath}?partnerUserId=${e}`)}catch(e){throw F.formatPrivyError(e)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()||this.session.hasRecoveryCredentials()?this.session.refresh():null}async getAccessToken(e){return await this.getPrivyAccessToken(e)||await this.getCustomerAccessToken(e)}async getCustomerAccessToken(e){return await this._getToken(Me.AccessTokenTypes.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(Me.AccessTokenTypes.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?w.AccessToken.parse(this.session.getToken(e))?.appId!==this.appId?(await this.logout(),null):this.session.getToken(e):(this.session.destroyLocalState(),null):!t?.disableAutoRefresh&&this.session.hasRefreshCredentials(e)?(await this.session.refresh(),this.session.getToken(e)):null:null}async getSmartWalletsConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}/smart_wallets`,{baseURL:this.fallbackApiUrl,headers:e});return r.enabled?{enabled:r.enabled,smartWalletType:r.smart_wallet_type,configuredNetworks:r.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:Oe.getPaymasterContext(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw F.formatPrivyError(e)}}async getServerConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}`,{baseURL:this.fallbackApiUrl,headers:e}),a=r.telegram_auth_config?{botId:r.telegram_auth_config.bot_id,botName:r.telegram_auth_config.bot_name,linkEnabled:r.telegram_auth_config.link_enabled,seamlessAuthEnabled:r.telegram_auth_config.seamless_auth_enabled}:void 0,n=r.funding_config?{methods:r.funding_config.methods,options:r.funding_config.options,defaultRecommendedAmount:r.funding_config.default_recommended_amount,defaultRecommendedCurrency:r.funding_config.default_recommended_currency,promptFundingOnWalletCreation:r.funding_config.prompt_funding_on_wallet_creation,crossChainBridgingEnabled:r.funding_config.cross_chain_bridging_enabled}:void 0;return{id:r.id,name:r.name,verificationKey:r.verification_key,logoUrl:r.logo_url||void 0,accentColor:r.accent_color||void 0,showWalletLoginFirst:r.show_wallet_login_first,allowlistConfig:{errorTitle:r.allowlist_config.error_title,errorDetail:r.allowlist_config.error_detail,errorCtaText:r.allowlist_config.cta_text,errorCtaLink:r.allowlist_config.cta_link},walletAuth:r.wallet_auth,solanaWalletAuth:r.solana_wallet_auth,emailAuth:r.email_auth,smsAuth:r.sms_auth,googleOAuth:r.google_oauth,twitterOAuth:r.twitter_oauth,discordOAuth:r.discord_oauth,githubOAuth:r.github_oauth,spotifyOAuth:r.spotify_oauth,instagramOAuth:r.instagram_oauth,tiktokOAuth:r.tiktok_oauth,linkedinOAuth:r.linkedin_oauth,appleOAuth:r.apple_oauth,farcasterAuth:r.farcaster_auth,passkeyAuth:r.passkey_auth,passkeysForSignupEnabled:r.passkeys_for_signup_enabled,telegramAuth:r.telegram_auth,disablePlusEmails:r.disable_plus_emails,termsAndConditionsUrl:r.terms_and_conditions_url,embeddedWalletConfig:{createOnLogin:r.embedded_wallet_config?.create_on_login,userOwnedRecoveryOptions:r.embedded_wallet_config.user_owned_recovery_options,requireUserOwnedRecoveryOnCreate:r.embedded_wallet_config.require_user_owned_recovery_on_create},privacyPolicyUrl:r.privacy_policy_url,requireUsersAcceptTerms:r.require_users_accept_terms,customApiUrl:r.custom_api_url,walletConnectCloudProjectId:r.wallet_connect_cloud_project_id,fiatOnRampEnabled:r.fiat_on_ramp_enabled,captchaEnabled:r.captcha_enabled,captchaSiteKey:r.captcha_site_key,createdAt:new Date(1e3*r.created_at),updatedAt:new Date(1e3*r.updated_at),mfaMethods:r.mfa_methods,enforceWalletUis:r.enforce_wallet_uis,legacyWalletUiConfig:r.legacy_wallet_ui_config,telegramAuthConfiguration:a,fundingConfig:n}}catch(e){throw F.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 forkSession(){return await this.session.forkSession()}async generateSiweNonce({address:e,captchaToken:t}){try{return(await this.api.post(Re.siweInitPath,{address:e,token:t})).nonce}catch(e){throw F.formatPrivyError(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n,mode:i}){return await this.api.post(Re.siweAuthenticatePath,{message:e,signature:t,chainId:r,walletClientType:a,connectorType:n,mode:i})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}){return await this.api.post(Re.siweLinkPath,{message:e,signature:t,chainId:r,walletClientType:a,connectorType:n})}async linkSmartWallet({message:e,signature:t,smartWalletType:r}){try{let a=await this.api.post(Re.smartWalletLinkPath,{message:e,signature:t,smart_wallet_type:r});return E.convertUserResponseToUser(a)}catch(e){throw F.formatPrivyError(e)}}async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}){try{let i=await this.linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n});return E.convertUserResponseToUser(i)}catch(e){throw F.formatPrivyError(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(Re.siwsInitPath,{address:e,token:t})).nonce}catch(e){throw F.formatPrivyError(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a,mode:n}){return await this.api.post(Re.siwsAuthenticatePath,{message:e,signature:t,walletClientType:r,connectorType:a,mode:n})}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s}){try{let l,c;switch(r){case"email":l=Re.transferEmailPath,c={nonce:e,email:t};break;case"sms":l=Re.transferPhonePath,c={nonce:e,phoneNumber:t};break;case"siwe":if(l=Re.transferWalletPath,!a)throw Error("Wallet parameters must be defined");c={nonce:e,address:t,...a};break;case"farcaster":l=Re.transferFarcasterPath,c={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":l=Re.telegramAccountTransferPath,c={nonce:e,telegram_auth_result:n,telegram_web_app_data:i};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:l=Re.transferOAuthPath,c={nonce:e,userInfo:s}}let d=await this.api.post(l,c);return await this.getAuthenticatedUser()??E.convertUserResponseToUser(d)}catch(e){throw F.formatPrivyError(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a}){return await this.api.post(Re.siwsLinkPath,{message:e,signature:t,walletClientType:r,connectorType:a})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:a}){try{let n=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a});return E.convertUserResponseToUser(n)}catch(e){throw F.formatPrivyError(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(Re.usersMePath);return this.session.updateIdentityToken(e.identity_token),E.convertUserResponseToUser(e.user)}catch(e){throw F.formatPrivyError(e)}}async scanTransaction(e){try{return await this.api.post(Re.transactionScanningPath,e)}catch(e){throw F.formatPrivyError(e)}}constructor({apiUrl:e=m.DEFAULT_PRIVY_API_URL,appId:t,appClientId:r,timeout:a=m.DEFAULT_API_TIMEOUT_MS}){Object.defineProperty(this,Be,{value:Ke}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==m.DEFAULT_PRIVY_API_URL&&e.startsWith("https://privy."),this.timeout=a,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,Be)[Be](),qe||(qe=new Me.Session),this.session=qe,this.api=this.generateApi(),this.session.client=this}}function Ke(){if("undefined"==typeof window)return null;try{let e=g.default.get(m.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=p.v4();try{return g.default.put(m.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}class Ve{async handleSignMessage(e){if(!e.params||"string"!=typeof e.params.message)throw Error("Message must be provided as a string for Solana signMessage RPC");return await st({message:e.params.message,options:{address:this.address,uiOptions:{}}})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await et())throw Error("User must be authenticated to use embedded Solana wallet");if(!await ot())throw new F.PrivyClientError("Unable to connect to Solana embedded wallet");if("signMessage"===e.method)return await this.handleSignMessage(e);throw Error("Embedded Solana provider does not yet support this RPC method.")}constructor(e,t){this.walletProxy=e,this.address=t}}let Ge,ze,Ye,$e,Xe,Je,Qe,Ze;async function et(){return Ge?Ge.getAccessToken():Promise.resolve(g.default.get(m.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||g.default.get(m.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const tt=(e,t)=>ze(e,t),rt=(e,t)=>Ye(e,t),at=(e,t)=>$e(e,t),nt=(e,t)=>Xe(e,t),it=()=>Je(),ot=()=>Qe(),st=({message:e,address:t})=>Ze({message:e,options:{address:t,uiOptions:{}}});let lt=p=>{let w=p.client,v=ne.usePlugins(),[C,A]=r.useState(!1),[P,Ce]=r.useState(!1),[Ae,Pe]=r.useState(!1),[_e,Te]=r.useState(null),[Ie,We]=r.useState([]),[Se,Ne]=r.useState([]),[ke,Ue]=r.useState([]),[Oe,be]=r.useState(!1),[Re,Me]=r.useState(null),[De,Le]=r.useState(!1),[Fe,xe]=r.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:ue.notImplemented}),[qe,je]=r.useState({status:"initial"}),[Be,He]=r.useState({status:"initial"}),[Ke,tt]=r.useState({status:"initial"}),[rt,at]=r.useState({status:"initial"}),[nt,it]=r.useState({status:"initial"}),[ot,st]=r.useState({status:"initial"}),[lt,ct]=r.useState(null),dt=W.useAppConfig(),ut=W.useIsServerConfigLoaded(),[ht,yt]=r.useState(!0),[pt,wt]=r.useState({}),[Et,vt]=r.useState(null),[mt,gt]=r.useState(null),[ft,Ct]=r.useState(!1),[At,Pt]=r.useState(!1),[_t,Tt]=r.useState(dt.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),It=r.useRef(null),Wt=r.useRef(null),St=r.useRef(ye.privyEventsDefault),[Nt,kt]=r.useState(!1);w.onStoreCustomerAccessToken=e=>{e&&ye.emitPrivyEvent(St,"accessToken","onAccessTokenGranted",{accessToken:e})},w.onDeleteCustomerAccessToken=()=>{Te(null),Pe(!1),ye.emitPrivyEvent(St,"accessToken","onAccessTokenRemoved")};let Ut=r.useRef(null),Ot=r.useRef(null),bt=r.useRef(!1),Rt=({showWalletUIs:e})=>bt.current?bt.current:void 0!==e?!e:!dt.embeddedWallets.showWalletUIs,Mt=e=>{Me(e),setTimeout((()=>{A(!0)}),15),w.createAnalyticsEvent({eventName:"modal_open",payload:{initialScreen:e}})},Dt=e=>{("off"!==dt.embeddedWallets.ethereum.createOnLogin||"off"!==dt.embeddedWallets.solana.createOnLogin)&&yt(!0),Mt(e)};r.useEffect((()=>{let e=[...E.getPrivySolanaHDWallets(_e),E.getImportedPrivySolanaWallet(_e)].filter((e=>!!e));lt&&Ue(e.map((e=>({type:"solana",imported:e.imported,address:e.address,connectedAt:Date.now(),walletClientType:"privy",connectorType:"embedded",walletIndex:e.walletIndex??void 0,meta:{name:"Privy Wallet",icon:void 0,id:"io.privy.solana.wallet"},linked:!0,fund(){throw new F.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:()=>{throw new F.PrivyClientError("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new Ve(lt,e.address),async signMessage(t){let r=await et();if(!r||!lt)throw new F.PrivyClientError("Must have valid access token and Privy wallet to send transaction",F.PrivyErrorCode.MUST_BE_AUTHENTICATED);let a=e.imported?E.getImportedPrivySolanaWallet(_e):E.getPrivyPrimaryWallet(_e);if(!a)throw new F.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(a);if(!await lr.recoverPrimaryWallet().catch((()=>!1)))throw new F.PrivyClientError("Wallet couldn't be connected",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);if(!_e)throw new F.PrivyClientError("Attempting to sign a transaction with no user initialized");let{response:o}=await lt.rpc({accessToken:r,entropyId:n,entropyIdVerifier:i,chainType:"solana",hdWalletIndex:e.walletIndex??0,request:{method:"signMessage",params:{message:Buffer.from(t).toString("base64")}}});return Buffer.from(o.data.signature,"base64")},async sendTransaction(e,t,r){let{signature:a}=await tr({transaction:e,connection:t,transactionOptions:r,wallet:this,signOnly:!1});return a},async signTransaction(t){let r=await et();if(!r||!lt)throw new F.PrivyClientError("Must have valid access token and Privy wallet to send transaction",F.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await lr.recoverPrimaryWallet().catch((()=>!1)))throw new F.PrivyClientError("Wallet couldn't be connected",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let a=e.imported?e:E.getPrivyPrimaryWallet(_e);if(!a)throw new F.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(a);return await x.signSolanaTransaction({tx:t,accessToken:r,walletProxy:lt,entropyId:n,entropyIdVerifier:i,transactingWalletAddress:e.address,transactingWalletIndex:e.walletIndex??0}),t},loginOrLink:async()=>{throw new F.PrivyClientError("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{},isConnected:async()=>!0}))))}),[lt,_e]),r.useEffect((()=>{if(!_e)return void w.connectors?.removeEmbeddedWalletConnectors();let e=E.getPrivyEthereumWallet(_e),t=E.getPrivyEthereumHDWallets(_e),r=E.getImportedPrivyEthereumWallet(_e);e&&t.length||w.connectors?.removeEmbeddedWalletConnectors(),r||w.connectors?.removeImportedWalletConnector(),w.connectors?lt?(e&&w.connectors.addEmbeddedWalletConnectors({walletProxy:lt,rootWallet:e,embeddedWallets:t,defaultChain:dt.defaultChain,appId:p.appId}),r&&w.connectors.addImportedWalletConnector(lt,r.address,dt.defaultChain,p.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")}),[lt,_e]),r.useEffect((()=>{lt&&mt?.(lt)}),[lt]);let Lt=r.useRef();r.useEffect((()=>{(async()=>{if(!dt.customAuth?.enabled)return void Tt({status:"not-enabled"});yt(!0);let{getCustomAccessToken:e,isLoading:t}=dt.customAuth;if(P&&!t&&"loading"!==_t.status){Tt({status:"loading"});try{let t=await e();if(t===Lt.current)return void Tt({status:"done"});if(!t&&Ae)return Lt.current=t,await sr.logout(),Tt({status:"done"}),void ye.emitPrivyEvent(St,"customAuth","onUnauthenticated");if(!t)return Lt.current=t,void Tt({status:"done"});w.startAuthFlow(new i.CustomJwtAccountFlow(t));let{user:r,isNewUser:a}=await w.authenticate();if(!r)return await sr.logout(),Tt({status:"error",error:new F.PrivyClientError("Failed to sync with custom auth provider")}),void ye.emitPrivyEvent(St,"customAuth","onUnauthenticated");void 0!==a&&ye.emitPrivyEvent(St,"login","onComplete",{user:r,isNewUser:a,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),Lt.current=t,ye.emitPrivyEvent(St,"customAuth","onAuthenticated",{user:r}),Tt({status:"done"}),Te(r||null),be(a||!1),Pe(!0),Pt(!0)}catch(e){if(console.warn(e),await sr.logout(),ye.emitPrivyEvent(St,"customAuth","onUnauthenticated"),"User already exists with provided custom JWT account."===e.message)return void Tt({status:"initial"});ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),Tt({status:"error",error:e})}}})()}),["initial"===_t.status,dt.customAuth?.enabled,dt.customAuth?.getCustomAccessToken,dt.customAuth?.isLoading,P,Ae]),r.useEffect((()=>{At&&lt&&_e&&(async()=>{let e=ee.shouldCreateEmbeddedEthWallet(_e,dt.embeddedWallets.ethereum.createOnLogin),t=te.shouldCreateEmbeddedSolWallet(_e,dt.embeddedWallets.solana.createOnLogin),r=await et();if(r){if(e&&t){let e=await $t(_e,m.WALLET_PROXY_TIMEOUT);return await lt.createSolana({accessToken:r,ethereumAddress:e?.address}),void Pt(!1)}if(t)return await lt.createSolana({accessToken:r,ethereumAddress:E.getPrivyEthereumWallet(_e)?.address}),await lr.refreshSessionAndUser(),void Pt(!1);if(e)return await $t(_e,m.WALLET_PROXY_TIMEOUT),void Pt(!1)}})().catch(console.error)}),[At&&lt&&_e]),r.useEffect((()=>{if(dt.externalWallets.solana.connectors)return dt.externalWallets.solana.connectors.onMount(),()=>dt.externalWallets.solana.connectors?.onUnmount()}),[dt.externalWallets.solana.connectors]),r.useEffect((()=>{!P&&ut&&async function(){let e,r=Ft(),a=xt();(()=>{let e=new URLSearchParams(window.location.search).get("privy_token");if(!e)return;g.default.put(m.FORKED_TOKEN_STORAGE_KEY,e);let t=new URL(window.location.href);t.searchParams.delete("privy_token"),window.history.pushState({},"",t)})();let n=t.createStore();w.initializeConnectorManager({walletConnectCloudProjectId:dt.walletConnectCloudProjectId,rpcConfig:dt.rpcConfig,chains:dt.chains,defaultChain:dt.defaultChain,store:n,walletList:dt.appearance.walletList,shouldEnforceDefaultChainOnConnect:dt.shouldEnforceDefaultChainOnConnect,externalWalletConfig:dt.externalWallets,appName:dt.name??"Privy",walletChainType:dt.appearance.walletChainType}),w.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=w.connectors.walletConnectors.length,r=w.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?kt(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),kt(!0)}),1500)})),w.connectors?.initialize().then((()=>{Kt()}));let i=await w.getAuthenticatedUser(),o=!!i;dt.legal.requireUsersAcceptTerms&&i&&!i.hasAcceptedTerms?(await w.logout(),lr.setReadyToTrue(!0),ye.emitPrivyEvent(St,"logout","onSuccess")):(dt.customAuth?.enabled||(Pe(!!i),i&&ye.emitPrivyEvent(St,"login","onComplete",{user:i,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),Te(i)),r?Ot.current=o?"link":"login":a&&!o?(Ot.current="login",wt({telegramAuthModalData:{seamlessAuth:!0}}),Dt(se.ModalScreen.TELEGRAM_AUTH_SCREEN)):lr.setReadyToTrue(!!i))}()}),[w,Et,P,ut]),r.useEffect((()=>{if(P){if(!_e||!_e.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void Ct(!0);Ct([...Ie,...ke].some((e=>"privy"===e.walletClientType)))}}),[P,_e,Ie,ke]),r.useEffect((()=>{w.connectors?.setWalletList(dt.appearance.walletList)}),[dt.appearance.walletList.join()]);let Ft=()=>{let e=ge.detectCompletingOAuthFlow();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&&j.isPrivyTheOAuthProvider(e.provider)&&!e.popupFlow&&(new BroadcastChannel(j.CROSS_APP_BROADCAST_CHANNEL_NAME).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(w.startAuthFlow(new fe.OAuthFlow(e)),Dt(se.ModalScreen.AWAITING_OAUTH_SCREEN),!0))},xt=()=>{let e=y.detectCompletingTelegramFlow();if(!e||!dt.loginMethods.telegram||!dt.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new y.TelegramAuthFlow;return w.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},qt=async(e,t,r,a)=>{if("solana_adapter"!==e)jt(await(w.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,a);else{let n=w.connectors?.findSolanaWalletConnector(e,t);if(!n)return;jt(n,t,r,a)}};async function jt(e,t,r,a){if(!e)return xe({status:"disconnected",connectedWallet:null,connectError:new F.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:ue.notImplemented}),a?.(null,r);xe({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:ue.notImplemented}),e instanceof b.WalletConnectV2WalletConnector&&t&&await e.resetConnection(t),xe({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>jt(e,t,r,a)});try{let t=await e.connect({showPrompt:!0});if((!t||k.isBaseConnectedEthereumWallet(t))&&dt.shouldEnforceDefaultChainOnConnect&&!dt.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){xe((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:ue.notImplemented})));try{await(t?.switchChain(dt.defaultChain.id)),t&&(t.chainId=f.formatChainIdToCAIP2(f.toHex(dt.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${dt.defaultChain.id}`)}}return xe((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:ue.notImplemented}))),t&&ye.emitPrivyEvent(St,"connectWallet","onSuccess",{wallet:t}),a?.(t,r)}catch(e){return e instanceof F.PrivyError?(console.warn(e.cause?e.cause:e.message),ye.emitPrivyEvent(St,"connectWallet","onError",e.privyErrorCode||F.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),ye.emitPrivyEvent(St,"connectWallet","onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),xe((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),a?.(null,r)}}let Bt=async(e,t,r)=>{if(null===e||!k.isBaseConnectedEthereumWallet(e))return;let a=new d.SiweFlow(e,w,t,r);w.startAuthFlow(a)},Ht=async(e,t,r)=>{if(null===e||!O.isBaseConnectedSolanaWallet(e))return;let a=new u.SiwsFlow(e,w,t,r);w.startAuthFlow(a)},Kt=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client"),a="true"===e.get("privy_connect_only");if(!t||!r)return;let n=U.getWalletConfigForConnector({connectorType:t,walletClientType:r});if(!n||!n.isInstalled)return Dt(se.ModalScreen.LOGIN_FAILED_SCREEN);if(!w.connectors)throw new F.PrivyClientError("Connector not initialized");Mt(a?se.ModalScreen.AWAITING_CONNECT_ONLY_CONNECTION:se.ModalScreen.AWAITING_CONNECTION);let i=new URL(window.location.href);i.searchParams.delete("privy_connector"),i.searchParams.delete("privy_wallet_client"),i.searchParams.delete("privy_connect_only"),window.history.pushState({},"",i),qt(t,r,void 0,a?void 0:"solana_adapter"===t?Ht:Bt)};r.useEffect((()=>{P&&Ae&&null===_e&&w.getAuthenticatedUser().then(Te)}),[P,Ae,_e,w]);let Vt=e=>{if(!Ae)throw ye.emitPrivyEvent(St,"linkAccount","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new F.PrivyClientError("User must be authenticated before linking an account.")},Gt=e=>{if(!Ae||!_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},zt=async e=>{let t;if(!w.connectors)throw new F.PrivyClientError("Connector not initialized");t="ethereum"===e.type?w.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:w.connectors.findSolanaWalletConnector(e.connectorType,e.walletClientType)||null,xe((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:ue.notImplemented}))),dt.captchaEnabled&&!Ae?(wt({captchaModalData:{callback:t=>k.isBaseConnectedEthereumWallet(e)?Bt(e,t):Ht(e,t),userIntentRequired:!1,onSuccessNavigateTo:se.ModalScreen.AWAITING_CONNECTION,onErrorNavigateTo:se.ModalScreen.ERROR_SCREEN}}),Dt(se.ModalScreen.CAPTCHA_SCREEN)):(k.isBaseConnectedEthereumWallet(e)?await Bt(e):await Ht(e),Dt(se.ModalScreen.AWAITING_CONNECTION))},Yt=()=>{We((e=>{let t=w.connectors?.wallets.filter(k.isBaseConnectedEthereumWallet).map((e=>({...e,linked:Gt(e),loginOrLink:async()=>{if(!await e.isConnected())throw new F.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new F.PrivyClientError("Cannot link or login with embedded wallet");zt(e)},fund:async t=>{await lr.fundWallet(e.address,t)},unlink:async()=>{if(!Ae)throw new F.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new F.PrivyClientError("Cannot unlink an embedded wallet");Te(await w.unlinkEthereumWallet(e.address))}})))||[];return S.areWalletArraysEqual(e,t)?e:t})),Ne((e=>{let t=(w.connectors?.wallets??[]).filter(O.isBaseConnectedSolanaWallet).map((e=>({...e,linked:Gt(e),loginOrLink:async()=>{if(!await e.isConnected())throw new F.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new F.PrivyClientError("Cannot link or login with embedded wallet");zt(e)},fund:async()=>{throw new F.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:async()=>{if(!Ae)throw new F.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new F.PrivyClientError("Cannot unlink an embedded wallet");Te(await w.unlinkSolanaWallet(e.address))}})));return S.areWalletArraysEqual(e,t)?e:t}))};r.useEffect((()=>{Yt()}),[_e?.linkedAccounts,Ae,P]),r.useEffect((()=>{if(P){if(!w.connectors)throw new F.PrivyClientError("Connector not initialized");Yt(),w.connectors.on("walletsUpdated",Yt)}}),[P]),r.useEffect((()=>{[...dt.loginMethodsAndOrder?.primary??[],...dt.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>w.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!w]);let $t=async(e,t,r)=>{let a=E.getPrivyEthereumWallet(e),n=E.getPrivySolanaWallet(e);if(r&&"walletIndex"in r&&"number"==typeof r.walletIndex)return Jt(e,t,r.walletIndex,a,n);let i=r&&"createAdditional"in r&&r.createAdditional;if(a&&!i)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[o,s]=await Promise.all([lr.initializeWalletProxy(t),et()]);if(!o&&dt.customAuth?.enabled)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!o||!s||dt.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return Xt();if(!a)return n&&await lr.recoverPrimaryWallet(),await o.create({accessToken:s,solanaAddress:n?.address}),Zt(0,"ethereum");{let t=(E.getLatestPrivyEthereumWallet(e)?.walletIndex??0)+1,{entropyId:r,entropyIdVerifier:a}=E.getEntropyDetailsFromAccount(E.getPrivyPrimaryWallet(e));return await lr.recoverPrimaryWallet(),await o.addWallet({accessToken:s,entropyId:r,entropyIdVerifier:a,chainType:"ethereum",hdWalletIndex:t}),Zt(t,"ethereum")}},Xt=async()=>new Promise(((e,t)=>{yt(!0),wt({createWallet:{onSuccess:t=>{ye.emitPrivyEvent(St,"createWallet","onSuccess",{wallet:t}),e(t)},onFailure:e=>{ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),Mt(se.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)})),Jt=async(e,t,r,a,n)=>{if(r<0)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${r}) is invalid.`);let[i,o]=await Promise.all([lr.initializeWalletProxy(t),et()]);if(!i&&dt.customAuth?.enabled)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!i||!o||dt.embeddedWallets?.requireUserOwnedRecoveryOnCreate){if(0==r)return Xt();throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Create wallet UI can only be displayed when walletIndex is 0.")}if(0==r){if(a)return a;await i.create({accessToken:o,solanaAddress:n?.address})}else{if(!a)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error("A user must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let t=E.getPrivyEthereumHDWallets(e).find((e=>e.walletIndex===r));if(t)return t;let{entropyId:n,entropyIdVerifier:s}=E.getEntropyDetailsFromAccount(E.getPrivyPrimaryWallet(e));await lr.recoverPrimaryWallet(),await i.addWallet({accessToken:o,entropyId:n,entropyIdVerifier:s,chainType:"ethereum",hdWalletIndex:r})}return Zt(r,"ethereum")},Qt=async({user:e,wp:t,accessToken:r,walletIndex:a,ethereumWallet:n})=>{let i=E.getPrivySolanaHDWallets(e).find((e=>e.walletIndex===a));if(i)return i;if(0===a)n&&await lr.recoverPrimaryWallet(),await t.createSolana({accessToken:r,ethereumAddress:n?.address});else{let n=E.getPrivyPrimaryWallet(e);if(!n)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error("User must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let{entropyId:i,entropyIdVerifier:o}=E.getEntropyDetailsFromAccount(n);await lr.recoverPrimaryWallet(),await t.addWallet({accessToken:r,entropyId:i,entropyIdVerifier:o,chainType:"solana",hdWalletIndex:a})}return Zt(a,"solana")},Zt=async(e,t)=>{let r=await lr.refreshSessionAndUser(),a=("ethereum"===t?E.getPrivyEthereumHDWallets(r):E.getPrivySolanaHDWallets(r)).find((t=>t.walletIndex===e));if(!a)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return ye.emitPrivyEvent(St,"createWallet","onSuccess",{wallet:a}),a},er=({transaction:e,uiOptions:t,fundWalletConfig:r,address:a,signOnly:i})=>new Promise((async(o,s)=>{let{requesterAppId:l}=t||{},c=i?"signTransaction":"sendTransaction";if(!Ae||!_e)return ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),void s(Error("User must be authenticated before signing with a Privy wallet"));let d=a??E.getPrivyEthereumWallet(_e)?.address;if(!d)throw new F.PrivyClientError("User must have an embedded wallet to send a transaction.");let{signingWallet:u,rootWallet:h}=E.getEthereumSigningAndRootWallet(_e,d);if(!h||!u)return ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(Error("Must have a Privy wallet before signing"));yt(!0);let y=cr.wallets.find((e=>"privy"===e.walletClientType&&n.getAddress(e.address)===n.getAddress(u.address))),w=await(y?.getEthereumProvider());if(!y||!w)throw new F.PrivyClientError(`Cannot sendTransaction before embedded wallet ${u.address} is connected`);let v=e.chainId?Number(e.chainId):q.extractChainIdFromCAIP2(y.chainId);(e=>{if(!dt.chains.map((e=>e.id)).includes(e))throw new F.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,F.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(v);let m={...e,from:e.from??u.address,chainId:v},g=await et();if(!g||!lt)return ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(Error("Must have valid access token and Privy wallet to send transaction"));let f=de.getPublicClient(m.chainId,dt.chains,dt.rpcConfig,{appId:p.appId});if(Rt({showWalletUIs:t?.showWalletUIs}))(async()=>{try{if(!await lr.recoverPrimaryWallet())return ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void s(Error("Unable to connect to wallet"));let e=await re.prepareTransactionRequest(m,f,m.from),{entropyId:t,entropyIdVerifier:r}=E.getEntropyDetailsFromAccount(h),a=i?await L.signTransaction({accessToken:g,entropyId:t,entropyIdVerifier:r,transactingWallet:u,walletProxy:lt,transactionRequest:m,requesterAppId:l}):await L.sendTransaction({accessToken:g,entropyId:t,entropyIdVerifier:r,transactingWallet:u,walletProxy:lt,transactionRequest:e,publicClient:f,requesterAppId:l});i?ye.emitPrivyEvent(St,"signTransaction","onSuccess",{signature:a}):ye.emitPrivyEvent(St,"sendTransaction","onSuccess",{hash:a}),o({hash:a})}catch(e){ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.TRANSACTION_FAILURE),s(e)}})();else{let{entropyId:e,entropyIdVerifier:a}=E.getEntropyDetailsFromAccount(h),n={entropyId:e,entropyIdVerifier:a,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN,onFailure:e=>{ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},d=z.isFundingEnabled(dt)?me.prepareFundingModalData({address:u.address,appConfig:dt,fundWalletConfig:r,methodScreen:se.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,chainIdOverride:m.chainId,comingFromSendTransactionScreen:!0}):void 0;wt({connectWallet:n,sendTransaction:{transactionRequest:m,transactingWallet:u,entropyId:e,entropyIdVerifier:a,signOnly:i,onConfirm:i?async()=>await L.signTransaction({accessToken:g,entropyId:e,entropyIdVerifier:a,transactingWallet:u,walletProxy:lt,transactionRequest:m,requesterAppId:l}):void 0,onSuccess:e=>{i?ye.emitPrivyEvent(St,"signTransaction","onSuccess",{signature:e.hash}):ye.emitPrivyEvent(St,"sendTransaction","onSuccess",{hash:e.hash}),o(e)},onFailure:e=>{ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.TRANSACTION_FAILURE),s(e)},uiOptions:t||{},fundWalletConfig:r,requesterAppId:l},funding:d}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),tr=({transaction:e,connection:t,transactionOptions:r,fundWalletConfig:a,uiOptions:n,wallet:i,signOnly:o})=>new Promise((async(s,l)=>{let{requesterAppId:c}=n||{},d=o?"signSolanaTransaction":"sendSolanaTransaction";if(!Ae||!_e)return ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),void l(new F.PrivyClientError("User must be authenticated before signing with a Privy wallet",F.PrivyErrorCode.MUST_BE_AUTHENTICATED));let u=i?_e.linkedAccounts.find((e=>"wallet"===e.type&&e.address===i.address)):E.getPrivySolanaWallet(_e);if(!u)return ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void l(new F.PrivyClientError("Must have a Privy wallet before signing",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));yt(!0);let{rootWallet:h}=E.getSolanaSigningAndRootWallet(_e,u.address);if(!await lr.recoverPrimaryWallet().catch((()=>!1))||!h)throw ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new F.PrivyClientError(`Cannot sendSolanaTransaction before embedded wallet ${u.address} is connected`,F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);if(Rt({showWalletUIs:n?.showWalletUIs}))(async()=>{let a=await et();if(!a||!lt)return ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void l(new F.PrivyClientError("Must have valid access token and Privy wallet to send transaction",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));try{let i;if(!await lr.recoverPrimaryWallet())return ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void l(new F.PrivyClientError("Unable to connect to wallet",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR));if(Rt({showWalletUIs:n?.showWalletUIs}))try{if(!await Q.hasSufficientFunds(e,t))return ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.INSUFFICIENT_BALANCE),void l(new F.PrivyClientError("Solana wallet has insufficient funds for this transaction.",F.PrivyErrorCode.INSUFFICIENT_BALANCE))}catch(e){return console.error(e),ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.TRANSACTION_FAILURE),void l(new F.PrivyClientError(e instanceof Error?e.message:"Transaction failed.",F.PrivyErrorCode.TRANSACTION_FAILURE))}let{entropyId:c,entropyIdVerifier:h}=E.getEntropyDetailsFromUser(_e);if(o)await x.signSolanaTransaction({accessToken:a,tx:e,walletProxy:lt,entropyId:c,entropyIdVerifier:h,transactingWalletAddress:u.address,transactingWalletIndex:u.walletIndex??0}),i=Q.createSolanaTransactionReceipt("",e,null),ye.emitPrivyEvent(St,"signSolanaTransaction","onSuccess",{signedTransaction:e});else{let{signature:n,receipt:o}=await x.sendSolanaTransaction({accessToken:a,tx:e,connection:t,walletProxy:lt,transactionOptions:r,entropyId:c,entropyIdVerifier:h,transactingWalletAddress:u.address,transactingWalletIndex:u.walletIndex??0});i=Q.createSolanaTransactionReceipt(n,e,o),ye.emitPrivyEvent(St,"sendSolanaTransaction","onSuccess",{response:i})}s(i)}catch(e){ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.TRANSACTION_FAILURE),l(e)}})();else{let{entropyId:i,entropyIdVerifier:y}=E.getEntropyDetailsFromAccount(h),p={entropyId:i,entropyIdVerifier:y,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN,onFailure:e=>{ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),l(e)}},w=z.isFundingEnabled(dt)?me.prepareSolanaFundingModalData({address:u.address,appConfig:dt,methodScreen:se.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,fundWalletConfig:a,comingFromSendTransactionScreen:!0}):void 0;wt({connectWallet:p,sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:r,transactingWallet:u,onSuccess:e=>{o?ye.emitPrivyEvent(St,"signSolanaTransaction","onSuccess",{signedTransaction:e.signedTransaction}):ye.emitPrivyEvent(St,"sendSolanaTransaction","onSuccess",{response:e}),s(e)},onFailure:e=>{ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.TRANSACTION_FAILURE),l(e)},uiOptions:n||{},requesterAppId:c,signOnly:o},funding:w}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}}));function rr(){return new Promise((async(e,t)=>{let r=await et();if(!r||!lt)throw Error("Must have valid access token to enroll in MFA");try{await lt.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let ar=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],nr=e=>{let t=_e?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:a}=Z.toDisplayFromAccountType(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw ye.emitPrivyEvent(St,"linkAccount","onError",F.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:a}),new F.PrivyClientError(`User already has an account of type ${r} linked.`)};async function ir({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){Me(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!Ae||!_e)throw ye.emitPrivyEvent(St,r,"onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let a=E.getPrivyPrimaryWallet(_e);if(!a||!lt)throw ye.emitPrivyEvent(St,r,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");try{await rr()}catch(e){throw ye.emitPrivyEvent(St,r,"onError",F.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((n,i)=>{yt(!0);let o={onSuccess:e=>{ye.emitPrivyEvent(St,r,"onSuccess",{method:"user-passcode",wallet:e}),n(e)},onFailure:e=>{ye.emitPrivyEvent(St,r,"onError",F.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),i(e)},callAuthOnSuccessOnClose:!1},s="user-passcode"===a.recoveryMethod,l=V.toEmbeddedWalletSetRecoveryScreen({walletAction:"update",availableRecoveryMethods:dt.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:s,showAutomaticRecovery:e}),{entropyId:c,entropyIdVerifier:d}=E.getEntropyDetailsFromAccount(a);wt({setWalletPassword:o,recoverWallet:{entropyId:c,entropyIdVerifier:d,onFailure:i},createWallet:o,connectWallet:{onCompleteNavigateTo:l,shouldForceMFA:!1,entropyId:c,entropyIdVerifier:d,onFailure:e=>{ye.emitPrivyEvent(St,r,"onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),i(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:s}}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}))}async function or({appId:e,action:t}){let r=await et();if("link"===t&&!r)throw ye.emitPrivyEvent(St,"linkAccount","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new F.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw ye.emitPrivyEvent(St,"login","onError",F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new F.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");Ut.current=`privy:${e}`,Ot.current=t;let a=$.triggerPopup();return w.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,n)=>{let{name:i,logoUrl:o}=await B.getProviderAppMetadata({api:w.api,providerAppId:e,requesterAppId:dt.id});wt({crossAppAuth:{appId:e,name:i,logoUrl:o,action:t,popup:a,onSuccess:r,onError:n}}),Dt(se.ModalScreen.CROSS_APP_AUTH_SCREEN)}))}let sr={ready:P,authenticated:Ae,user:_e,walletConnectors:w.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),wt({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress,walletChainType:e?.walletChainType}}),Mt(Ae?se.ModalScreen.CONNECT_ONLY_AUTHENTICATED_SCREEN:se.ModalScreen.CONNECT_ONLY_LANDING_SCREEN)},linkWallet:e=>{e&&"target"in e&&e&&(e=void 0),Vt("siwe"),Ut.current="siwe",Ot.current="link",wt({...pt,externalConnectWallet:{...pt.externalConnectWallet,suggestedAddress:e?.suggestedAddress,walletList:e?.walletList,walletChainType:e?.walletChainType}}),Mt(se.ModalScreen.LINK_WALLET_SCREEN)},startCrossAppAuthFlow:or,linkEmail:()=>{Vt("email"),nr("email"),Ut.current="email",Ot.current="link",Mt(se.ModalScreen.LINK_EMAIL_SCREEN)},linkPhone:()=>{Vt("sms"),nr("phone"),Ut.current="sms",Ot.current="link",Mt(se.ModalScreen.LINK_PHONE_SCREEN)},linkGoogle:async()=>{Vt("google"),nr("google_oauth"),Ot.current="link",await lr.initLoginWithOAuth("google")},linkTwitter:async()=>{Vt("twitter"),nr("twitter_oauth"),Ot.current="link",await lr.initLoginWithOAuth("twitter")},linkDiscord:async()=>{Vt("discord"),nr("discord_oauth"),Ot.current="link",await lr.initLoginWithOAuth("discord")},linkGithub:async()=>{Vt("github"),nr("github_oauth"),Ot.current="link",await lr.initLoginWithOAuth("github")},linkSpotify:async()=>{Vt("spotify"),nr("spotify_oauth"),Ot.current="link",await lr.initLoginWithOAuth("spotify")},linkInstagram:async()=>{Vt("instagram"),nr("instagram_oauth"),Ot.current="link",await lr.initLoginWithOAuth("instagram")},linkTiktok:async()=>{Vt("tiktok"),nr("tiktok_oauth"),Ot.current="link",await lr.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{Vt("linkedin"),nr("linkedin_oauth"),Ot.current="link",await lr.initLoginWithOAuth("linkedin")},linkApple:async()=>{Vt("apple"),nr("apple_oauth"),Ot.current="link",await lr.initLoginWithOAuth("apple")},linkPasskey:async()=>{Vt("passkey"),nr("passkey"),await lr.initLinkWithPasskey(),Mt(se.ModalScreen.LINK_PASSKEY_SCREEN)},linkTelegram:async e=>{if(Vt("telegram"),nr("telegram"),Ot.current="link",Ut.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new y.TelegramAuthFlow;w.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=y.convertInitDataRawToTelegramWebAppData(e.launchParams.initDataRaw),wt({telegramAuthModalData:{seamlessAuth:!0}}),Dt(se.ModalScreen.TELEGRAM_AUTH_SCREEN)}else ye.emitPrivyEvent(St,"linkAccount","onError",F.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await lr.initLoginWithTelegram();Mt(se.ModalScreen.TELEGRAM_AUTH_SCREEN)},linkFarcaster:async()=>{Vt("farcaster"),nr("farcaster"),await lr.initLoginWithFarcaster(),Ot.current="link",Ut.current="farcaster",Mt(se.ModalScreen.AWAITING_FARCASTER_CONNECTION)},updateEmail:()=>{if(Vt("email"),!_e?.email)throw new F.PrivyClientError("User does not have an email linked to their account.");Ot.current="update",Ut.current="email",Mt(se.ModalScreen.UPDATE_EMAIL_SCREEN)},updatePhone:()=>{if(Vt("sms"),!_e?.phone)throw new F.PrivyClientError("User does not have a phone number linked to their account.");Ot.current="update",Ut.current="sms",Mt(se.ModalScreen.UPDATE_PHONE_SCREEN)},login:async e=>{e&&"target"in e&&e&&(e=void 0);let t="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!P){let e=await new Promise((e=>{vt((t=>e.bind(t)))}));if(vt(null),e)return void console.warn(t)}!_e||_e.isGuest?(Ot.current="login",wt({login:e}),Dt(se.ModalScreen.LANDING)):console.warn(t)},connectOrCreateWallet:async()=>{P||(await new Promise((e=>{vt((()=>e))})),vt(null)),Ae?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(Ot.current="login",Dt(se.ModalScreen.CONNECT_OR_CREATE))},logout:async()=>{if(Ot.current=null,Ut.current=null,_e&&w.clearProviderAcccessTokens(_e),Me(null),await w.logout(),_e&&lt)try{await lt.clearMfa({userId:_e.id})}catch(e){}Te(null),Pe(!1),ye.emitPrivyEvent(St,"logout","onSuccess"),A(!1),g.default.del(m.CLIENT_ANALYTICS_ID_KEY),g.default.del(m.getGuestCredentialStorageKey(dt.id))},getAccessToken:()=>w.getCustomerAccessToken(),unlinkWallet:async e=>{let t;return Te(t=e.startsWith("0x")?await w.unlinkEthereumWallet(e):await w.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await w.unlinkEmail(e);return Te(t),t},unlinkPhone:async e=>{let t=await w.unlinkPhone(e);return Te(t),t},unlinkGoogle:async e=>{let t=await w.unlinkOAuth("google",e);return Te(t),t},unlinkTwitter:async e=>{let t=await w.unlinkOAuth("twitter",e);return Te(t),t},unlinkDiscord:async e=>{let t=await w.unlinkOAuth("discord",e);return Te(t),t},unlinkGithub:async e=>{let t=await w.unlinkOAuth("github",e);return Te(t),t},unlinkSpotify:async e=>{let t=await w.unlinkOAuth("spotify",e);return Te(t),t},unlinkInstagram:async e=>{let t=await w.unlinkOAuth("instagram",e);return Te(t),t},unlinkTiktok:async e=>{let t=await w.unlinkOAuth("tiktok",e);return Te(t),t},unlinkLinkedIn:async e=>{let t=await w.unlinkOAuth("linkedin",e);return Te(t),t},unlinkApple:async e=>{let t=await w.unlinkOAuth("apple",e);return Te(t),t},unlinkFarcaster:async e=>{let t=await w.unlinkFarcaster(e);return Te(t),t},unlinkTelegram:async e=>{let t=await w.unlinkTelegram(e);return Te(t),t},unlinkPasskey:async e=>{let t=await et();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!lt)throw Error("Wallet proxy not initialized.");let r=dt.passkeys.shouldUnenrollMfaOnUnlink;await lt.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let a=await w.getAuthenticatedUser();return Te(a),a},unlinkCrossAppAccount:async({subject:e})=>{let t=_e?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new F.PrivyClientError("Invalid subject");w.storeProviderAccessToken(t.id,null);let r=await w.unlinkOAuth(`privy:${t.id}`,e);return Te(r),r},createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let t=await lr.refreshSessionAndUser();if(!t)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return $t(t,15e3,e)},setWalletRecovery:async e=>ir({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>ir({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(r,a)=>{let{requesterAppId:n}=t?.uiOptions||{},i=e.message;if(!Ae||!_e)return ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let o=t?.address??E.getPrivyEthereumWallet(_e)?.address;if(!o)throw new F.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:s,rootWallet:l}=E.getEthereumSigningAndRootWallet(_e,o);if(!s||!l)return ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));if("string"!=typeof i||i.length<1)return ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));yt(!0);let c=async()=>{if(!Ae)throw Error("User must be authenticated before signing with a Privy wallet");let e=await et();if(!lt||!e||!await lr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:s.address,requesterAppId:n}});let{entropyId:t,entropyIdVerifier:r}=E.getEntropyDetailsFromAccount(l),{response:a}=await lt.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:s.walletIndex??0,requesterAppId:n,request:{method:"personal_sign",params:[i,s.address]}}),o=a.data;return w.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:s.address,requesterAppId:n}}),o};if(Rt({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await c();ye.emitPrivyEvent(St,"signMessage","onSuccess",{signature:e}),r({signature:e})}catch(e){ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.UNABLE_TO_SIGN),a(e??new N.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"personal_sign",data:i,confirmAndSign:c,onSuccess:e=>{ye.emitPrivyEvent(St,"signMessage","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},{entropyId:n,entropyIdVerifier:o}=E.getEntropyDetailsFromAccount(l);wt({signMessage:e,connectWallet:{entropyId:n,entropyIdVerifier:o,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signTypedData:(e,t)=>new Promise((async(r,a)=>{let{requesterAppId:n}=t?.uiOptions||{};if(!Ae||!_e)return ye.emitPrivyEvent(St,"signTypedData","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let i=t?.address??E.getPrivyEthereumWallet(_e)?.address;if(!i)throw new F.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:o,rootWallet:s}=E.getEthereumSigningAndRootWallet(_e,i);if(!s||!o)return ye.emitPrivyEvent(St,"signTypedData","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));yt(!0);let l=f.generateTypedDataWithDomainType(e),c=async()=>{if(!Ae)throw Error("User must be authenticated before signing with a Privy wallet");let e=await et();if(!lt||!e||!await lr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:o.address,requesterAppId:n}});let{entropyId:t,entropyIdVerifier:r}=E.getEntropyDetailsFromAccount(s),{response:a}=await lt.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:o.walletIndex??0,requesterAppId:n,request:{method:"eth_signTypedData_v4",params:[o.address,l]}}),i=a.data;return w.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:o.address,requesterAppId:n}}),i};if(Rt({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await c();ye.emitPrivyEvent(St,"signTypedData","onSuccess",{signature:e}),r({signature:e})}catch(e){ye.emitPrivyEvent(St,"signTypedData","onError",F.PrivyErrorCode.UNABLE_TO_SIGN),a(e??new N.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"eth_signTypedData_v4",data:l,confirmAndSign:c,onSuccess:e=>{ye.emitPrivyEvent(St,"signTypedData","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{ye.emitPrivyEvent(St,"signTypedData","onError",F.PrivyErrorCode.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},{entropyId:n,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(s);wt({signMessage:e,connectWallet:{entropyId:n,entropyIdVerifier:i,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),sendTransaction:async(e,t)=>await er({transaction:e,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await er({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:e=>new Promise((async(t,r)=>{if(!Ae||!_e)return void r(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let a=e?.address??E.getPrivyEthereumWallet(_e)?.address;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`."));let{signingWallet:n,rootWallet:i}=E.getEthereumSigningAndRootWallet(_e,a);if(!n||!i)return void r(Error("Must have a Privy wallet before exporting"));yt(!0);let{entropyId:o,entropyIdVerifier:s}=E.getEntropyDetailsFromAccount(i),l={entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0};wt(pt),await et()&&lt?lt?(wt({keyExport:{appId:p.appId,appClientId:p.clientId,origin:w.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:r},connectWallet:l}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)):r(Error("Must have a Privy wallet before exporting")):r(Error("Must have valid access token to enroll in MFA"))})),promptMfa:rr,async init(e){switch(e){case"sms":return void await w.initMfaSmsVerification();case"passkey":return await w.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 F.PrivyClientError("Invalid MFA code");It.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{Wt.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new F.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),a=ae.transformResponseToSnakeCase(await r.startAuthentication(t));It.current?.resolve({mfaMethod:e,mfaCode:a,relyingParty:window.origin}),await new Promise(((e,t)=>{Wt.current={resolve:e,reject:t}}));break;default:throw It.current?.reject(new F.PrivyClientError("Unsupported MFA method")),new F.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){It.current?.reject(new F.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await et();if(!t||!lt)throw Error("Must have valid access token to enroll in MFA");await lt.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return lr.closePrivyModal(),void t();dt.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."),wt({mfaEnrollmentFlow:{mfaMethods:dt.mfa.methods,shouldUnlinkOnUnenrollMfa:dt.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),Mt(se.ModalScreen.MFA_ENROLLMENT_FLOW_SCREEN)})),async initEnrollmentWithTotp(){let e=await et();if(!e||!lt)throw Error("Must have valid access token to enroll in MFA");let t=await lt.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await et();if(!t||!lt)throw Error("Must have valid access token to enroll in MFA");await lt.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),Te(await w.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await et();if(!t||!lt)throw Error("Must have valid access token to enroll in MFA");await lt.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),Te(await w.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await et();if(!r||!lt)throw Error("Must have valid access token to enroll in MFA");await lt.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),Te(await w.getAuthenticatedUser())},async unenroll(e,t={}){let r=await et();if(!r||!lt)throw Error("Must have valid access token to remove MFA");"passkey"===e?await lt.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await lt.unenrollMfa({method:e,accessToken:r}),Te(await w.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await et(),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(!lt||!t)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");if(!await lr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");let r=await lt.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&Te(await w.getAuthenticatedUser()||_e||null),wt({farcasterSigner:r}),Mt(se.ModalScreen.AWAITING_FARCASTER_SIGNER)},getFarcasterSignerPublicKey:async()=>{let e,t=await et(),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(!lt||!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");if(!await lr.recoverPrimaryWallet())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 et(),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(!lt||!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");if(!await lr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!_e.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let a=await import("@simplewebauthn/browser"),n=await lt.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:a.bufferToBase64URLString(e)},fid:BigInt(_e.farcaster.fid),relyingParty:window.origin});return new Uint8Array(a.base64URLStringToBuffer(n.signature))},createGuestAccount:async()=>{if(_e&&!_e.isGuest)throw Error("User cannot already be authenticated to create a guest account");return _e?.isGuest?_e:lr.loginWithGuestAccountFlow()},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let a=_e?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return K.sendCrossAppRequest({user:_e,client:w,address:t,requesterAppId:dt.id,request:{method:a?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:or})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let a=_e?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),n=f.generateTypedDataWithDomainType(e);return K.sendCrossAppRequest({user:_e,client:w,address:t,requesterAppId:dt.id,request:{method:a?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,n],chainId:r},reconnect:or})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=_e?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return K.sendCrossAppRequest({user:_e,client:w,address:t,requesterAppId:dt.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:or})},isModalOpen:C,mfaMethods:dt.mfa.methods};ze=sr.signMessage,Ye=sr.signTypedData,Xe=async(e,t)=>await er({transaction:e,...t,signOnly:!1}),$e=async(e,t)=>({signature:(await er({transaction:e,...t,signOnly:!0})).hash});let lr={setAuthenticated:Pe,setUser:Te,isNewUserThisSession:Oe,pendingTransaction:null,walletConnectionStatus:Fe,connectors:w.connectors?.walletConnectors??[],solanaWallets:Se,rpcConfig:dt.rpcConfig,chains:dt.chains,appId:p.appId,showFiatPrices:"native-token"!==dt.embeddedWallets.priceDisplay.primary,clientAnalyticsId:w.clientAnalyticsId,customAuthStatus:_t,hideWalletUIs:bt,emailOtpState:Be,setEmailOtpState:He,smsOtpState:Ke,setSmsOtpState:tt,oAuthState:nt,setOAuthState:it,telegramAuthState:ot,setTelegramAuthState:st,siweState:rt,setSiweState:at,isHeadlessOAuthLoading:De,nativeTokenSymbolForChainId:e=>dt.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(lt)return lt;let t=new Promise((e=>{gt((()=>t=>e(t)))})),r=new Promise((t=>setTimeout((()=>t(null)),e))),a=await Promise.race([t,r]);return gt(null),a},getAuthFlow:()=>w.authFlow,getAuthMeta:()=>w.authFlow?.meta,client:w,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=P&&Ae&&_e;r&&Ut.current&&(t=ar(_e)),"login"===Ot.current?e.shouldCallAuthOnSuccess&&r&&Ut.current?ye.emitPrivyEvent(St,"login","onComplete",{user:_e,isNewUser:Oe,wasAlreadyAuthenticated:!1,loginMethod:Ut.current,loginAccount:t??null}):ye.emitPrivyEvent(St,"login","onError",F.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===Ot.current&&t?e.isSuccess&&r&&Ut.current?ye.emitPrivyEvent(St,"linkAccount","onSuccess",{user:_e,linkMethod:Ut.current,linkedAccount:t}):Ut.current&&ye.emitPrivyEvent(St,"linkAccount","onError",F.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:Ut.current}):"update"===Ot.current&&t&&(e.isSuccess&&r&&Ut.current?ye.emitPrivyEvent(St,"update","onSuccess",{user:_e,updateMethod:Ut.current,updatedAccount:t}):Ut.current&&ye.emitPrivyEvent(St,"update","onError",F.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:Ut.current}));let a=Re&&G.FUNDING_SCREENS.includes(Re),n=Re===se.ModalScreen.ERROR_SCREEN&&pt.errorModalData&&G.FUNDING_SCREENS.includes(pt.errorModalData.previousScreen);if((a||n)&&pt.funding){let e,t=G.fundingScreenMethodMap[Re]??null;if("solana"===pt.funding.chainType){let r=v(ie.SOLANA_FUNDING_PLUGIN_ID);if(!r)return void console.warn("Unable to load solana plugin, skipping balance");try{e=BigInt(await r.getBalance({address:pt.funding.address,cluster:pt.funding.cluster}))}catch{console.error("Unable to pull wallet balance")}ye.emitPrivyEvent(St,"fundSolanaWallet","onUserExited",{address:pt.funding.address,cluster:pt.funding.cluster,fundingMethod:t,balance:e})}else{let r=de.getPublicClient(pt.funding.chain.id,dt.chains,dt.rpcConfig,{appId:p.appId});try{e=await r.getBalance({address:pt.funding.address})}catch{console.error("Unable to pull wallet balance")}ye.emitPrivyEvent(St,"fundWallet","onUserExited",{address:pt.funding.address,chain:pt.funding.chain,fundingMethod:t,balance:e})}}wt({...pt,externalConnectWallet:{suggestedAddress:void 0}}),Ot.current=null,Ut.current=null,be(!1),A(!1),setTimeout((()=>{w.authFlow=void 0}),200),w.createAnalyticsEvent({eventName:"modal_closed"})},solanaSignMessage:({message:e,options:t})=>new Promise((async(r,a)=>{if(!Ae||!_e)return ye.emitPrivyEvent(St,"signSolanaMessage","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let n=t?.address??E.getPrivySolanaWallet(_e)?.address;if(!n)throw new F.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:i,rootWallet:o}=E.getSolanaSigningAndRootWallet(_e,n);if(!i||!o)return ye.emitPrivyEvent(St,"signSolanaMessage","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));yt(!0);let s=async()=>{if(!Ae)throw Error("User must be authenticated before signing with a Privy wallet");let t=await w.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");let r=lr.walletProxy??await lr.initializeWalletProxy(15e3);if(!r)throw Error("Failed to initialize embedded wallet proxy.");if(!await lr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!o)throw Error("No root wallet for signing wallet found");let{entropyId:a,entropyIdVerifier:n}=E.getEntropyDetailsFromAccount(o),{response:s}=await r.rpc({accessToken:t,entropyId:a,entropyIdVerifier:n,chainType:"solana",hdWalletIndex:i.walletIndex??0,request:{method:"signMessage",params:{message:e}}});return s.data.signature};if(Rt({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await s();ye.emitPrivyEvent(St,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),r({signature:e})}catch(e){a(e)}else{let n={method:"solana_signMessage",data:e,confirmAndSign:s,onSuccess:e=>{ye.emitPrivyEvent(St,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),r({signature:e})},onFailure:e=>{a(e)},uiOptions:t?.uiOptions},{entropyId:i,entropyIdVerifier:l}=E.getEntropyDetailsFromAccount(o);wt({signMessage:n,connectWallet:{entropyId:i,entropyIdVerifier:l,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{ye.emitPrivyEvent(St,"signSolanaMessage","onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Dt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:a,address:n})=>{let i=n?ke.find((e=>e.address===n)):ke.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!i)throw ye.emitPrivyEvent(St,"signSolanaTransaction","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new F.PrivyClientError("Embedded wallet not found",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);let{signedTransaction:o}=await tr({transaction:e,connection:t,transactionOptions:a,uiOptions:r,wallet:i,signOnly:!0});return o},sendSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:a,fundWalletConfig:n,address:i})=>{let o=i?ke.find((e=>e.address===i)):ke.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!o)throw ye.emitPrivyEvent(St,"sendSolanaTransaction","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new F.PrivyClientError("Embedded wallet not found",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);return await tr({transaction:e,connection:t,transactionOptions:a,uiOptions:r,fundWalletConfig:n,wallet:o,signOnly:!1})},openPrivyModal:Mt,connectWallet:jt,initLoginWithWallet:async(e,t,r)=>{k.isBaseConnectedEthereumWallet(e)?(Ut.current="siwe",Bt(e,t,r)):(Ut.current="siws",Ht(e,t,r))},loginWithWallet:async()=>{let e,t,r;if(!P)throw new F.PrivyNotReadyError;if(w.authFlow instanceof d.SiweFlow?e="siwe":w.authFlow instanceof u.SiwsFlow&&(e="siws"),!e)throw new F.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await w.getAccessToken())try{({user:t}=await w.link()),Ut.current=e}catch(t){throw ye.emitPrivyEvent(St,"linkAccount","onError",t.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await w.authenticate()),Ut.current=e}catch(e){throw ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}Te(t||_e||null),be(r||!1),Pe(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(a,n)=>{let i=await et();if(!Ae||!_e||!i)throw new F.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new F.PrivyClientError("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let o=lr.walletProxy??await lr.initializeWalletProxy(15e3);if(!o)throw new F.PrivyClientError("Wallet proxy not initialized.");if(M.isWalletDelegated({address:e,chainType:t,user:_e}))return a();let s=M.getDelegatedWalletsData({address:e,user:_e}),l=M.getRootWalletDataForDelegation({address:e,user:_e}),c=async()=>{await o.createDelegatedAction({accessToken:i,rootWallet:l,delegatedWallets:[s]}),await lr.refreshSessionAndUser()};if(!r){try{await c(),a()}catch(e){n(e)}return}await lr.recoverPrimaryWallet(),wt({delegatedActions:{consent:{address:e,onDelegate:c,onSuccess:async()=>{a()},onError:async e=>{n(e)}}}}),Mt(se.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN)})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!Ae||!_e)throw new F.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");if(0===M.getDelegatedWalletsForUser(_e).length)throw new F.PrivyClientError("User has no delegated wallets to revoke.");let a=async()=>{await w.revokeDelegatedWallet(),await lr.refreshSessionAndUser()};if(e)wt({delegatedActions:{revoke:{onRevoke:a,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),Mt(se.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_REVOKE_SCREEN);else try{await a(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new s.FarcasterFlow(e,t);w.startAuthFlow(r);try{Ut.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===Ot.current?ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Ot.current&&ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!P)throw new F.PrivyNotReadyError;if(!(w.authFlow instanceof s.FarcasterFlow))throw new F.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await w.getAccessToken())try{({user:e}=await w.link()),Ut.current="farcaster"}catch(e){throw ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await w.authenticate()),Ut.current="farcaster"}catch(e){throw ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Te(e||null),be(t||!1),Pe(!0)},async loginWithGuestAccountFlow(){let e=new l.GuestFlow(this.appId);w.startAuthFlow(e);try{Ot.current="login",Ut.current="guest";let{user:e,isNewUser:t}=await w.authenticate();if(t=t||!1,!e)throw new F.PrivyClientError("Unable to authenticate guest account");let r=await et(),a=await lr.initializeWalletProxy(m.WALLET_PROXY_TIMEOUT);if(r&&a)try{let t=ee.shouldCreateEmbeddedEthWallet(e,dt.embeddedWallets.ethereum.createOnLogin),n=te.shouldCreateEmbeddedSolWallet(e,dt.embeddedWallets.solana.createOnLogin);if(t&&n){let t=await $t(e,m.WALLET_PROXY_TIMEOUT);await a.createSolana({accessToken:r,ethereumAddress:t?.address}),e=await lr.refreshSessionAndUser()}else n?(await a.createSolana({accessToken:r,ethereumAddress:E.getPrivyEthereumWallet(e)?.address}),e=await lr.refreshSessionAndUser()):t?(await $t(e,m.WALLET_PROXY_TIMEOUT),e=await lr.refreshSessionAndUser()):Te(e)}catch(t){Te(e),console.warn("Unable to create embedded wallet for guest account")}return be(t),Pe(!0),ye.emitPrivyEvent(St,"login","onComplete",{user:e,isNewUser:t,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),e}catch(e){throw ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:r}){let a=`privy:${e}`;Ut.current=a;let{url:n,stateCode:i,codeVerifier:o}=await B.getCrossAppAuthorizationUrl({api:w.api,appId:e});if(!n)throw w.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new F.PrivyClientError("No authorization URL returned for cross-app auth.");try{let s=await H.popupCrossAppAuthFlow({url:n,popup:t,provider:a}),l=s.stateCode,c=s.authorizationCode;if(l!==i)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:a,storedStateCode:i??"",returnedStateCode:l??""}}),new F.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,F.PrivyErrorCode.OAUTH_UNEXPECTED);let d=await B.authenticateCrossAppAccount({appId:e,codeVerifier:o,stateCode:l,authorizationCode:c,action:r,client:w});d&&w.storeProviderAccessToken(e,d);let u=await lr.refreshSessionAndUser();if(!u)throw new F.PrivyClientError("Unable to update user");return w.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),u}catch(e){throw w.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:a}}),e}},async initLoginWithOAuth(e,t,r){if(Ut.current=e,!g.isLocalStorageAccessible())return void Dt(se.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);if("google"===e&&Y.default(window.navigator.userAgent))return void Dt(se.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);"twitter"===e&&window.opener&&window.opener.postMessage({type:j.USE_BROADCAST_CHANNEL_EVENT_TYPE},"*"),g.default.del(m.HEADLESS_OAUTH_KEY),g.default.del(m.OAUTH_DISABLE_SIGNUP_KEY);let n=new fe.OAuthFlow({provider:e,disableSignup:!!r,withPrivyUi:!0});t&&n.addCaptchaToken(t),w.startAuthFlow(n);let i=await w.authFlow.getAuthorizationUrl();i&&i.url&&("twitter"===e&&a.isAndroid&&(i.url=i.url.replace("x.com","twitter.com")),window.location.assign(i.url))},async initLoginWithTelegram(e,t){if(!P)throw new F.PrivyNotReadyError;Ut.current="telegram";let r=new y.TelegramAuthFlow(e,t);w.startAuthFlow(r),st({status:"loading"}),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>dt.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:dt.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):t(new F.PrivyClientError("Telegram auth failed or was canceled by the client")))):t(new F.PrivyClientError("Telegram was not initialized")):t(new F.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(w.authFlow instanceof y.TelegramAuthFlow))throw new F.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");w.authFlow.meta.captchaToken||=e?.captchaToken;let a=await et(),n=e?.intent||Ot.current;if("login"===n)try{let e=await w.authenticate();t=e.user,r=e.isNewUser,Ut.current="telegram"}catch(e){throw ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==n)throw new F.PrivyClientError("Unknown auth intent");try{t=(await w.link()).user,Ut.current="telegram"}catch(e){throw ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}Te(t),be(r||!1),Pe(!0),st({status:"done"});let i=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,loginAccount:i}},async recoveryOAuthFlow(e,t,r){let a,n;function i(t){if(!t)throw w.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new F.PrivyClientError("Recovery OAuth failed")}switch(e){case"google-drive":{let t,o,{url:s,codeVerifier:l,stateCode:c}=await V.getRecoveryAuthorizationUrl({api:Ge.api,provider:e});i(s);try{let a=await X.popupOAuthFlow({url:s,popup:r,provider:e});if(t=a.stateCode,o=a.authorizationCode,t!==c)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:c??"",returnedStateCode:t??""}}),new F.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,F.PrivyErrorCode.OAUTH_UNEXPECTED)}catch(t){throw w.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new F.PrivyClientError("Recovery OAuth failed")}[a,n]=await Promise.all([et(),V.authenticateRecovery({api:Ge.api,provider:e,codeVerifier:l,stateCode:t,authorizationCode:o})]);break}case"icloud":{let{url:t}=await V.getRecoveryAuthorizationUrl({api:Ge.api,provider:e});i(t);let{ckWebAuthToken:o}=await X.popupOAuthFlow({url:t,popup:r,provider:e});n=o,a=await et()}}if(!lt)throw new F.PrivyClientError("Cannot connect to wallet proxy");if(!a)throw new F.PrivyClientError("Unable to authorize user");switch(t){case"recover":{let t=pt.recoverWallet?.entropyId,r=pt.recoverWallet?.entropyIdVerifier;if(!t||!r)throw new F.PrivyClientError("Recovery OAuth failed");w.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await lt.recover({accessToken:a,entropyId:t,entropyIdVerifier:r,recoveryAccessToken:n}),w.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break}case"create-wallet":{w.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await lt.create({accessToken:a,recoveryAccessToken:n,recoveryMethod:e});let t=E.getPrivyEthereumWallet(await lr.refreshSessionAndUser());if(!t)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.address}}),ye.emitPrivyEvent(St,"createWallet","onSuccess",{wallet:t});break}case"set-recovery":{let t=E.getPrivyPrimaryWallet(_e);if(!t)throw ye.emitPrivyEvent(St,"setWalletRecovery","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");w.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}});let{entropyId:r,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(t);await lt.setRecovery({accessToken:a,entropyId:r,entropyIdVerifier:i,recoveryMethod:e,recoveryAccessToken:n});let o=E.getPrivyPrimaryWallet(await lr.refreshSessionAndUser());if(!o)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}}),ye.emitPrivyEvent(St,"setWalletRecovery","onSuccess",{method:e,wallet:o});break}default:throw new F.PrivyClientError("Unsupported recovery action")}},async loginWithOAuth(e){let t,r,a;if(!(w.authFlow instanceof fe.OAuthFlow))throw new F.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let n=g.default.get(m.STATE_CODE_KEY),i=w.authFlow.meta.stateCode;if(n!==i)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:n??"",returnedStateCode:i??""}}),new F.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,F.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await w.getAccessToken())try{let r=await w.link();t=r.user,a=r.oAuthTokens,Ut.current=e}catch(t){throw ye.emitPrivyEvent(St,"linkAccount","onError",t.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let n=await w.authenticate();t=n.user,r=n.isNewUser,a=n.oAuthTokens,Ut.current=e}catch(t){throw"login"===Ot.current?ye.emitPrivyEvent(St,"login","onError",t.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Ot.current&&ye.emitPrivyEvent(St,"linkAccount","onError",t.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return Te(t),be(r||!1),Pe(!0),a&&t&&ye.emitPrivyEvent(St,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),a},passkeyAuthState:qe,setPasskeyAuthState:je,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new c.PasskeyFlow({captchaToken:e,setPasskeyAuthState:je});w.startAuthFlow(r),Ot.current="login";try{Ut.current="passkey",je({status:"generating-challenge"}),await r.initRegisterFlow(t),je({status:"awaiting-passkey"})}catch(e){throw je({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!P)throw new F.PrivyNotReadyError;if(!(w.authFlow instanceof c.PasskeyFlow))throw new F.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Ut.current){let e=new F.PrivyClientError("Must init login with Passkey flow first.");throw je({status:"error",error:e}),e}let r=await et();try{Ut.current="passkey",je({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await w.authenticate())}catch(e){throw je({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Te(e),be(t||!1),Pe(!0),je({status:"done"});let a=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:a}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new c.PasskeyFlow({captchaToken:e,setPasskeyAuthState:je});w.startAuthFlow(r),Ot.current="login";try{Ut.current="passkey",je({status:"generating-challenge"}),await r.initAuthenticationFlow(t),je({status:"awaiting-passkey"})}catch(e){throw je({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,r;if(!P)throw new F.PrivyNotReadyError;if(!(w.authFlow instanceof c.PasskeyFlow))throw new F.PrivyClientError("Must initialize Passkey flow first.");if(e?.credentialIds&&(w.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==Ut.current){let e=new F.PrivyClientError("Must init login with Passkey flow first.");throw je({status:"error",error:e}),e}let a=await et();try{Ut.current="passkey",je({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await w.authenticate())}catch(e){throw je({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Te(t),be(r||!1),Pe(!0),je({status:"done"});let n=t?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,loginAccount:n}},async initLinkWithPasskey(e){let t=new c.PasskeyFlow({captchaToken:e});w.startAuthFlow(t),Ot.current="link",Ut.current="passkey",je({status:"generating-challenge"});try{await t.initLinkFlow(),je({status:"awaiting-passkey"})}catch(e){throw ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),je({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!P)throw new F.PrivyNotReadyError;if(!(w.authFlow instanceof c.PasskeyFlow))throw new F.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Ut.current)throw new F.PrivyClientError("Must init login with Passkey flow first.");try{Ut.current="passkey",({user:e}=await w.link())}catch(e){throw ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return Te(e||_e||null),je({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!g.isLocalStorageAccessible())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&&Y.default(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 a=new fe.OAuthFlow({provider:e,withPrivyUi:!1,disableSignup:r??!1});t&&a.addCaptchaToken(t),it({status:"loading"});let n=await w.startAuthFlow(a).getAuthorizationUrl();n?.url&&window.location.assign(n.url)},async loginWithHeadlessOAuth(e){let t,r,a;Le(!0),it({status:"loading"}),w.startAuthFlow(new fe.OAuthFlow(e));let n=g.default.get(m.STATE_CODE_KEY),i=e.stateCode;if(n!==i)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:n??"",returnedStateCode:i??""}}),Le(!1),new F.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,F.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await w.getAccessToken())try{({user:t,oAuthTokens:a}=await w.link()),Ut.current=e.provider;let r=ar(t);t&&r&&ye.emitPrivyEvent(St,"linkAccount","onSuccess",{user:t,linkMethod:Ut.current,linkedAccount:r})}catch(t){throw Le(!1),ye.emitPrivyEvent(St,"linkAccount","onError",t.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:a}=await w.authenticate()),Ut.current=e.provider;let n=ar(t);t&&n&&void 0!==r&&ye.emitPrivyEvent(St,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:Ut.current,loginAccount:n})}catch(e){throw Le(!1),it({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return Te(t),be(r||!1),Pe(!0),Le(!1),it({status:"done"}),a&&t&&ye.emitPrivyEvent(St,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{let n=new o.EmailFlow({email:e,captchaToken:t,disableSignup:r});w.startAuthFlow(n);try{Ut.current="email",He({status:"sending-code"}),await n.sendCodeEmail({withPrivyUi:a}),He({status:"awaiting-code-input"})}catch(e){throw He({status:"error",error:e}),"login"===Ot.current?ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Ot.current&&ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,r)=>{let a=new o.UpdateEmailFlow(e,t,r);w.startAuthFlow(a);try{await a.sendCodeEmail({withPrivyUi:!0})}catch(e){ye.emitPrivyEvent(St,"update","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:Ut.current})}},initUpdatePhone:async(e,t,r)=>{let a=new h.UpdateSmsFlow(e,t,r);w.startAuthFlow(a);try{await a.sendSmsCode({withPrivyUi:!0})}catch(e){ye.emitPrivyEvent(St,"update","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:Ut.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{tt({status:"sending-code"});let n=new h.SmsFlow({phoneNumber:e,captchaToken:t,disableSignup:r});w.startAuthFlow(n);try{Ut.current="sms",await n.sendSmsCode({withPrivyUi:a}),tt({status:"awaiting-code-input"})}catch(e){throw tt({status:"error",error:e}),"login"===Ot.current?ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Ot.current&&ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(w.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(w.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function a(e){w.authFlow instanceof o.EmailFlow?He(e):w.authFlow instanceof h.SmsFlow&&tt(e)}if(a({status:"submitting-code"}),!P){let e=new F.PrivyNotReadyError;throw a({status:"error",error:e}),e}if(w.authFlow instanceof o.EmailFlow)w.authFlow.meta.emailCode=e.trim();else{if(!(w.authFlow instanceof h.SmsFlow)){let e=new F.PrivyClientError("Must initialize a passwordless code flow first");throw a({status:"error",error:e}),e}w.authFlow.meta.smsCode=e.trim()}let n=await et();if("link"===Ot.current)try{({user:t}=await w.link())}catch(e){throw a({status:"error",error:e}),ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:Ut.current}),e}else if("update"===Ot.current)try{({user:t}=await w.link())}catch(e){throw a({status:"error",error:e}),ye.emitPrivyEvent(St,"update","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:Ut.current}),e}else try{({user:t,isNewUser:r}=await w.authenticate())}catch(e){throw a({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let i=t||_e;Te(i||null),be(r||!1),Pe(!0),a({status:"done"});let s=null;return w.authFlow instanceof o.EmailFlow?s=i?.linkedAccounts.find((({type:e})=>"email"===e))||null:w.authFlow instanceof h.SmsFlow&&(s=i?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:i,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,linkedAccount:s}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{Ot.current="link",Ut.current="siwe",at({status:"generating-message"});let a=await w.generateSiweNonce({address:e,captchaToken:r});return at({status:"awaiting-signature"}),J.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:a})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await w.generateSiweNonce({address:e});return J.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r})=>{let a;a=await w.linkSmartWallet({message:e,signature:t,smartWalletType:r}),Te((a=await lr.refreshSessionAndUser()??a)||_e||null)},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n})=>{let i;Vt("siwe");let o=null;try{at({status:"submitting-signature"}),i=await w.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}),i=await lr.refreshSessionAndUser()??i,at({status:"done"}),(o=ar(i)||null)&&ye.emitPrivyEvent(St,"linkAccount","onSuccess",{user:i,linkMethod:"siwe",linkedAccount:o})}catch(e){throw ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),Ot.current=null,Ut.current=null,at({status:"error",error:e}),e}let s=i||_e;return Te(s||null),Ot.current=null,Ut.current=null,{user:s,linkedAccount:o}},refreshSessionAndUser:async()=>{let e=await w.getAuthenticatedUser();return Pe(!!e),Te(e),e},walletProxy:lt,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>w.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await w.acceptTerms();return Te(e),e},getUsdTokenPrice:e=>w.getUsdTokenPrice(e),getUsdPriceForSol:()=>w.getUsdPriceForSol(),getSplTokenMetadata:e=>w.getSplTokenMetadata(e),recoverPrimaryWallet:async e=>new Promise((async(t,r)=>{let a=E.getPrivyPrimaryWallet(e?.user??_e)||E.getImportedPrivyEthereumWallet(e?.user??_e)||E.getImportedPrivySolanaWallet(e?.user??_e);a||t(!0);let n=await et();if(!n||!lt||!a)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));yt(!0);let{entropyId:i,entropyIdVerifier:o}=E.getEntropyDetailsFromAccount(a);try{await lt.connect({accessToken:n,entropyId:i,entropyIdVerifier:o}),t(!0)}catch(e){D.errorIndicatesRecoveryIsNeeded(e)&&"privy"===a.recoveryMethod?(w.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:a.address}}),(await lt.recover({entropyId:i,entropyIdVerifier:o,accessToken:n})).entropyId||r(Error("Unable to recover wallet")),w.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:a.address}}),t(!0)):D.errorIndicatesRecoveryIsNeeded(e)&&"privy"!==a.recoveryMethod?(wt({recoverWallet:{entropyId:i,entropyIdVerifier:o,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:a.recoveryMethod,action:"recover"}}),Mt(V.embeddedWalletRecoveryScreen(a.recoveryMethod))):r(e)}})),embeddedSolanaWallets:ke,createEmbeddedSolanaWallet:async e=>{e&&"target"in e&&(e=void 0);let t=await lr.refreshSessionAndUser();if(!t)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return(async(e,t,r)=>{let a=E.getPrivyEthereumWallet(e),n=E.getPrivySolanaWallet(e),i=r&&"createAdditional"in r&&r.createAdditional,o=r&&"walletIndex"in r?r.walletIndex:void 0,s=(E.getLatestPrivySolanaWallet(e)?.walletIndex??-1)+1;if(n&&!i&&"number"!=typeof o)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");if("number"==typeof o&&o<0)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${o}) is invalid.`);let[l,c]=await Promise.all([lr.initializeWalletProxy(t),et()]);if(!l||!c)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return await Qt({user:e,wp:l,accessToken:c,walletIndex:o??s,ethereumWallet:a})})(t,15e3,e)},exportSolanaWallet:e=>new Promise((async(t,r)=>{if(!Ae||!_e)return void r(Error("User must be authenticated before exporting their Privy wallet"));let a=e?.address??E.getPrivySolanaWallet(_e)?.address;if(!a)return void r(Error("User does not have an HD Solana wallet."));let{signingWallet:n,rootWallet:i}=E.getSolanaSigningAndRootWallet(_e,a);if(!n||!i)return void r(Error("Must have a Privy wallet before exporting"));if(yt(!0),!await et()||!lt)return void r(Error("Must have valid access token to enroll in MFA"));if(!lt)return void r(Error("Must have a Privy wallet before exporting"));let{entropyId:o,entropyIdVerifier:s}=E.getEntropyDetailsFromAccount(i);wt({connectWallet:{entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0},keyExport:{appId:p.appId,appClientId:p.clientId,origin:w.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:r}}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)})),setReadyToTrue:e=>{Ce(!0),Et?.(e)},updateWallets:()=>Yt(),fundWallet:async(e,t)=>{let r=se.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN;wt({funding:me.prepareFundingModalData({address:e,appConfig:dt,fundWalletConfig:t,methodScreen:r})}),Mt(r)},openModal:Mt,requestFarcasterSignerStatus:async e=>{let t=await et(),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(!lt||!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 a=await w.requestFarcasterSignerStatus(e);return"approved"===a.status&&Te(await w.getAuthenticatedUser()||_e||null),a},connectCoinbaseSmartWallet:async()=>{dt.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=w.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||w.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),jt(e);await qt("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s})=>{let l=await w.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return Te(l),l}};Je=lr.recoverPrimaryWallet,Qe=lr.recoverPrimaryWallet,Ze=lr.solanaSignMessage;let cr=r.useMemo((()=>({wallets:Ie,ready:ft&&Nt})),[Ie,ft,Nt]),dr=w.authFlow instanceof y.TelegramAuthFlow,ur=!dt.headless&&dt.captchaEnabled&&!Ae&&(P||dr);/*#__PURE__*/return e.jsx(Ee.PrivyContext.Provider,{value:sr,children:/*#__PURE__*/e.jsx(ye.PrivyEventsContext.Provider,{value:St,children:/*#__PURE__*/e.jsx(ve.UseWalletsContext.Provider,{value:cr,children:/*#__PURE__*/e.jsx(he.CaptchaProvider,{...dt,children:/*#__PURE__*/e.jsxs(pe.InternalPrivyContext.Provider,{value:lr,children:[/*#__PURE__*/e.jsx(oe.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(we.ModalProvider,{data:pt,setModalData:wt,setInitialScreen:Me,initialScreen:Re,authenticated:Ae,open:C,children:[p.children,ur&&/*#__PURE__*/e.jsx(_.Captcha,{delayedExecution:!1}),/*#__PURE__*/e.jsx(ce.GlobalStyle,{theme:{...dt.appearance.palette||{}}}),!dt.render.standalone&&/*#__PURE__*/e.jsx(T.LoginModal,{open:C})]})}),ht&&ut?/*#__PURE__*/e.jsx(R.EmbeddedWalletIframe,{appId:p.appId,appClientId:p.clientId,clientAnalyticsId:w.clientAnalyticsId,origin:w.apiUrl,mfaMethods:_e?.mfaMethods,mfaPromise:It,mfaSubmitPromise:Wt,onLoad:ct,onLoadFailed:()=>null}):null,dt.loginConfig.telegramAuthConfiguration&&
1
+ "use strict";var e=require("react/jsx-runtime"),t=require("mipd"),r=require("react"),a=require("react-device-detect"),n=require("viem/utils"),i=require("./auth-flows/custom-jwt-account.js"),o=require("./auth-flows/email.js"),s=require("./auth-flows/farcaster.js"),l=require("./auth-flows/guest.js"),c=require("./auth-flows/passkey.js"),d=require("./auth-flows/siwe.js"),u=require("./auth-flows/siws.js"),h=require("./auth-flows/sms.js"),y=require("./auth-flows/telegram.js"),p=require("uuid"),w=require("./accessToken.js"),E=require("./client/user.js"),v=require("eventemitter3"),m=require("./constants.js"),g=require("./storage.js"),f=require("./utils/index.js"),C=require("./connectors/coinbase.js"),A=require("./connectors/embedded.js"),P=require("./embedded-wallets/rpc/types.js"),_=require("./components/Captcha.js"),T=require("./components/LoginModal.js"),I=require("./components/TelegramLoginButton.js"),W=require("./configuration/context.js"),S=require("./connectors/areWalletArraysEqual.js"),k=require("./connectors/errors.js"),N=require("./connectors/isBaseConnectedEthereumWallet.js"),U=require("./connectors/mobile-wallets.js"),O=require("./connectors/solana/index.js"),b=require("./connectors/walletconnect-v2.js"),R=require("./embedded-wallets/EmbeddedWalletIframe.js"),M=require("./embedded-wallets/delegated-actions.js"),D=require("./embedded-wallets/errors.js"),L=require("./embedded-wallets/rpc/index.js"),F=require("./errors.js"),x=require("./embedded-wallets/solana/transaction.js"),q=require("./lib/caip2.js"),j=require("./lib/cross-app/index.js"),B=require("./lib/cross-app/authFlow.js"),H=require("./lib/cross-app/popupCrossAppAuthFlow.js"),K=require("./lib/cross-app/sendCrossAppRequest.js"),V=require("./lib/embeddedWalletRecovery.js"),G=require("./lib/funding/index.js"),z=require("./lib/funding/isFundingEnabled.js"),Y=require("./lib/isEmbeddedWebview.js"),$=require("./lib/popup/triggerPopup.js"),X=require("./lib/popupOAuthFlow.js"),J=require("./lib/siwe.js"),Q=require("./lib/solana/transaction.js"),Z=require("./lib/toDisplayFromAccountType.js"),ee=require("./lib/user/shouldCreateEmbeddedEthWallet.js"),te=require("./lib/user/shouldCreateEmbeddedSolWallet.js"),re=require("./lib/viem/prepareTransactionRequest.js"),ae=require("./passkeys/transformResponseToSnakeCase.js"),ne=require("./plugins/context/PrivyPluginContext.js"),ie=require("./plugins/solana-funding/id.js"),oe=require("./recent-login/context.js"),se=require("./screens/index.js"),le=require("./screens/LandingScreen/styles.js"),ce=require("./styles.js"),de=require("./utils/eth/getPublicClient.js"),ue=require("./hooks/index.js"),he=require("./hooks/captcha-context.js"),ye=require("./hooks/events-context.js"),pe=require("./hooks/internal-context.js"),we=require("./hooks/modal-context.js"),Ee=require("./hooks/privy-context.js"),ve=require("./hooks/useWallets.js"),me=require("./lib/funding/prepareFundingModalData.js"),ge=require("./auth-flows/oauth/detectCompletingOAuthFlow.js"),fe=require("./auth-flows/oauth/OAuthFlow.js"),Ce=require("./lib/viem/toViemTransactionSerializable.js"),Ae=require("./connectors/getRpcTimeout.js"),Pe=require("./connectors/providerTypes.js"),_e=require("./connectors/ethereum/index.js"),Te=require("./connectors/ethereum/EthereumNullConnector.js"),Ie=require("./connectors/injected.js"),We=require("./connectors/metamask.js"),Se=require("./connectors/privyProxyProvider.js"),ke=require("./connectors/solana/SolanaNullConnector.js"),Ne=require("./connectors/stored-connection.js"),Ue=require("./http.js"),Oe=require("./lib/smart-wallet-helpers.js"),be=require("./passkeys/transformOptionsToCamelCase.js"),Re=require("./paths.js"),Me=require("./session.js");function De(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var Le=/*#__PURE__*/De(v);class Fe extends Le.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Pe.EmbeddedProviderError(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await et()||!this.address)throw new Pe.EmbeddedProviderError("Disconnected",4900);let{hash:r}=await nt(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new Pe.EmbeddedProviderError(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await et()||!this.address)throw new Pe.EmbeddedProviderError("Disconnected",4900);let{signature:r}=await at(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new Pe.EmbeddedProviderError(`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 Pe.EmbeddedProviderError(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=de.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:a}=await tt({message:t},{address:r});return a}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:a}=await rt(f.generateTypedDataWithDomainType(r),{address:t});return a}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:f.toHex(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...Ce.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 f.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(!P.isSupportedEthereumRpcMethod(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await et();if(await it(),!t||!this.address)throw new Pe.EmbeddedProviderError("Disconnected",4900);try{return(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:{method:e.method,params:e.params}})).response.data}catch(e){throw console.error(e),new Pe.EmbeddedProviderError("Disconnected",4900)}}}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:a,rpcConfig:n,chains:i,appId:o,chainId:s=1,walletIndex:l}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=a,this.chainId=s,this.rpcConfig=n,this.chains=i,this.publicClient=de.getPublicClient(s,this.chains,n,{appId:o}),this.rpcTimeoutDuration=Ae.getRpcTimeout(n,"privy"),this.appId=o,this.walletIndex=l}}class xe extends Le.default{get wallets(){let e=new Set,t=this.walletConnectors.flatMap((e=>e.wallets)).sort(((e,t)=>e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0)).filter((t=>{let r=`${t.address}${t.walletClientType}${t.connectorType}${t.meta.id}`;return!e.has(r)&&(e.add(r),!0)})),r=t.findIndex((e=>e.address===(this.activeWallet?this.activeWallet:"unknown")));return r>=0&&t.unshift(t.splice(r,1)[0]),t}async initialize(e){if(this.initialized&&!e)return;e&&this.removeAllConnectors(),g.default.get(m.CONNECTORS_STATE_KEY)&&(g.default.getKeys().forEach((e=>{e.startsWith("walletconnect")&&g.default.del(e)})),g.default.del(m.CONNECTORS_STATE_KEY));let t=f.detectInjectedConnectors({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:r})=>{this.createEthereumWalletConnector({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:r}})}))}));for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),Object.values(U.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.addWalletConnector(new ke.SolanaNullConnector({id:e.client,name:e.name,icon:e.logoDataUri})));this.externalWalletConfig.walletConnect.enabled&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"unknown"}),this.externalWalletConfig.solana.connectors?.get().forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{e?.forEach(this.addSolanaWalletConnector)})),await t,this.initialized=!0}findWalletConnector(e,t){return"wallet_connect_v2"===e?this.walletConnectors.filter(_e.isEthereumWalletConnector).find((t=>t.connectorType===e))??null:this.walletConnectors.filter(_e.isEthereumWalletConnector).find((r=>r.connectorType===e&&r.walletClientType===t))??null}findSolanaWalletConnector(e,t){return this.walletConnectors.filter(O.isSolanaWalletConnector).find((r=>r.connectorType===e&&("unknown"===r.walletClientType?r.walletBranding.id===t:r.walletClientType===t)))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}onInitialized(e){e.wallets.forEach((e=>{let t=this.storedConnections.find((t=>t.address===e.address&&t.connectorType===e.connectorType&&("solana"===e.type&&"unknown"===t.walletClientType&&"unknown"===e.walletClientType?e.meta.id===t.id:t.walletClientType===e.walletClientType)));t&&(e.connectedAt=t.connectedAt)})),this.saveConnectionHistory(),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&(this.saveConnectionHistory(),this.emit("walletsUpdated"))}addEmbeddedWalletConnectors({walletProxy:e,rootWallet:t,embeddedWallets:r,defaultChain:a,appId:n}){for(let i of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===i.walletIndex));if(r&&_e.isEthereumWalletConnector(r))r.proxyProvider.walletProxy=e;else{let{entropyId:r,entropyIdVerifier:o}=E.getEntropyDetailsFromAccount(t),s=new A.EmbeddedWalletConnector({provider:new Fe({walletProxy:e,address:i.address,entropyId:r,entropyIdVerifier:o,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:a.id,walletIndex:i.walletIndex}),chains:this.chains,defaultChain:a,rpcConfig:this.rpcConfig,imported:!1,walletIndex:i.walletIndex});this.addWalletConnector(s)}}}addImportedWalletConnector(e,t,r,a){let n=this.findWalletConnector("embedded_imported","privy");if(n&&_e.isEthereumWalletConnector(n))n.proxyProvider.walletProxy=e;else{let n=new A.EmbeddedWalletConnector({provider:new Fe({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:a,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(n)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.saveConnectionHistory(),this.storedConnections=Ne.loadConnectionHistory(),this.emit("walletsUpdated")}removeImportedWalletConnector(){let e=this.findWalletConnector("embedded_imported","privy");if(e){let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1),this.saveConnectionHistory(),this.storedConnections=Ne.loadConnectionHistory(),this.emit("walletsUpdated")}}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:a}){let n=this.findWalletConnector(e,t);if(n&&_e.isEthereumWalletConnector(n))return n instanceof b.WalletConnectV2WalletConnector&&n.resetConnection(t),n;let i=(()=>"injected"!==e?"coinbase_wallet"===e?new C.CoinbaseWalletConnector(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig,this.privyAppName,this.privyAppLogo):"null"!==e?new b.WalletConnectV2WalletConnector(this.walletConnectCloudProjectId,this.rpcConfig,this.chains,this.defaultChain,this.shouldEnforceDefaultChainOnConnect,this.privyAppId,this.privyAppName,t):a?new Te.EthereumNullConnector({id:a.client,name:a.name,icon:a.logoDataUri,defaultChain:this.defaultChain,walletClientType:a.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new We.MetamaskWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Ie.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Ie.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Ie.LegacyInjectedWalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new Ie.Injected6963WalletConnector(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,t):void 0)();return i&&this.addWalletConnector(i),i||null}addWalletConnector(e){this.walletConnectors.push(e),e.on("initialized",(()=>this.onInitialized(e))),e.on("walletsUpdated",(()=>this.onWalletsUpdated(e))),e.initialize().catch((e=>{console.debug("Failed to initialize connector",e)}))}saveConnectionHistory(){let e=this.wallets.map((e=>({address:e.address,connectorType:e.connectorType,walletClientType:e.walletClientType,connectedAt:e.connectedAt,id:e.meta.id})));g.default.put(m.CONNECTIONS_HISTORY_KEY,e)}async activeWalletSign(e){let t=this.wallets,r=t.length>0?t[0]:null;return r&&N.isBaseConnectedEthereumWallet(r)?r.sign(e):null}setActiveWallet(e){this.activeWallet=n.getAddress(e),this.emit("walletsUpdated")}setWalletList(e){this.walletList=e,this.initialized&&this.initialize(!0).catch(console.error)}removeAllConnectors(){for(let e of this.walletConnectors)e.removeAllListeners();this.walletConnectors=[]}constructor(e,t,r,a,n,i,o,s,l,c,d,u){super(),this.addSolanaWalletConnector=async e=>{this.findSolanaWalletConnector("solana_adapter",e.walletClientType)||this.addWalletConnector(e)},this.getEthereumProvider=()=>{let e=this.wallets[0],t=this.walletConnectors.find((t=>t.wallets.find((t=>t.address===e?.address))));return e&&t?t.proxyProvider:new Se.PrivyProxyProvider},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=a,this.defaultChain=n,this.walletConnectors=[],this.initialized=!1,this.store=i,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=s,this.externalWalletConfig=l,this.privyAppName=c,this.privyAppLogo=d,this.walletChainType=u||"ethereum-only",this.storedConnections=Ne.loadConnectionHistory()}}let qe;var je=0,Be="__private_"+je+++"__getOrGenerateClientAnalyticsId";class He{initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:a,store:n,walletList:i,shouldEnforceDefaultChainOnConnect:o,externalWalletConfig:s,appName:l,walletChainType:c}){this.connectors||(this.connectors=new xe(this.appId,e,t,r,a,n,i,o,s,l,void 0,c))}generateApi(){let e=new Ue.Http({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 F.PrivyClientError("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new F.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(Re.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw F.formatApiError(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(Re.mfaPasskeyInitPath,{});return be.transformOptionsToCamelCase(e.options)}catch(e){throw F.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(Re.acceptTermsPath,{});return E.convertUserResponseToUser(e)}catch(e){throw F.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(Re.unlinkEmailPath,{address:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async unlinkPhone(e){try{let t=await this.api.post(Re.unlinkPhonePath,{phoneNumber:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(Re.unlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(Re.siwsUnlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(Re.unlinkOAuthPath,{provider:e,subject:t});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(r)}catch(e){throw F.formatPrivyError(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(Re.unlinkFarcasterPath,{fid:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async unlinkTelegram(e){try{let t=await this.api.post(Re.telegramAccountUnlinkPath,{telegram_user_id:e});return await this.getAuthenticatedUser()??E.convertUserResponseToUser(t)}catch(e){throw F.formatPrivyError(e)}}async revokeDelegatedWallet(){try{await this.api.post(Re.delegatedActionsRevokePath,{})}catch(e){throw F.formatPrivyError(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:r,options:a}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(Re.analyticsEventsPath,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:r?r.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:a?.keepAlive??!1})}catch(e){}}async signMoonpayOnRampUrl(e){try{return this.api.post(Re.moonpayPluginOnRampPath,e)}catch(e){throw F.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(Re.coinbaseOnRampInitPath,e)}catch(e){throw F.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${Re.coinbaseOnRampStatusPath}?partnerUserId=${e}`)}catch(e){throw F.formatPrivyError(e)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()||this.session.hasRecoveryCredentials()?this.session.refresh():null}async getAccessToken(e){return await this.getPrivyAccessToken(e)||await this.getCustomerAccessToken(e)}async getCustomerAccessToken(e){return await this._getToken(Me.AccessTokenTypes.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(Me.AccessTokenTypes.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?w.AccessToken.parse(this.session.getToken(e))?.appId!==this.appId?(await this.logout(),null):this.session.getToken(e):(this.session.destroyLocalState(),null):!t?.disableAutoRefresh&&this.session.hasRefreshCredentials(e)?(await this.session.refresh(),this.session.getToken(e)):null:null}async getSmartWalletsConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}/smart_wallets`,{baseURL:this.fallbackApiUrl,headers:e});return r.enabled?{enabled:r.enabled,smartWalletType:r.smart_wallet_type,configuredNetworks:r.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:Oe.getPaymasterContext(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw F.formatPrivyError(e)}}async getServerConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}`,{baseURL:this.fallbackApiUrl,headers:e}),a=r.telegram_auth_config?{botId:r.telegram_auth_config.bot_id,botName:r.telegram_auth_config.bot_name,linkEnabled:r.telegram_auth_config.link_enabled,seamlessAuthEnabled:r.telegram_auth_config.seamless_auth_enabled}:void 0,n=r.funding_config?{methods:r.funding_config.methods,options:r.funding_config.options,defaultRecommendedAmount:r.funding_config.default_recommended_amount,defaultRecommendedCurrency:r.funding_config.default_recommended_currency,promptFundingOnWalletCreation:r.funding_config.prompt_funding_on_wallet_creation,crossChainBridgingEnabled:r.funding_config.cross_chain_bridging_enabled}:void 0;return{id:r.id,name:r.name,verificationKey:r.verification_key,logoUrl:r.logo_url||void 0,accentColor:r.accent_color||void 0,showWalletLoginFirst:r.show_wallet_login_first,allowlistConfig:{errorTitle:r.allowlist_config.error_title,errorDetail:r.allowlist_config.error_detail,errorCtaText:r.allowlist_config.cta_text,errorCtaLink:r.allowlist_config.cta_link},walletAuth:r.wallet_auth,solanaWalletAuth:r.solana_wallet_auth,emailAuth:r.email_auth,smsAuth:r.sms_auth,googleOAuth:r.google_oauth,twitterOAuth:r.twitter_oauth,discordOAuth:r.discord_oauth,githubOAuth:r.github_oauth,spotifyOAuth:r.spotify_oauth,instagramOAuth:r.instagram_oauth,tiktokOAuth:r.tiktok_oauth,linkedinOAuth:r.linkedin_oauth,appleOAuth:r.apple_oauth,farcasterAuth:r.farcaster_auth,passkeyAuth:r.passkey_auth,passkeysForSignupEnabled:r.passkeys_for_signup_enabled,telegramAuth:r.telegram_auth,disablePlusEmails:r.disable_plus_emails,termsAndConditionsUrl:r.terms_and_conditions_url,embeddedWalletConfig:{createOnLogin:r.embedded_wallet_config?.create_on_login,userOwnedRecoveryOptions:r.embedded_wallet_config.user_owned_recovery_options,requireUserOwnedRecoveryOnCreate:r.embedded_wallet_config.require_user_owned_recovery_on_create},privacyPolicyUrl:r.privacy_policy_url,requireUsersAcceptTerms:r.require_users_accept_terms,customApiUrl:r.custom_api_url,walletConnectCloudProjectId:r.wallet_connect_cloud_project_id,fiatOnRampEnabled:r.fiat_on_ramp_enabled,captchaEnabled:r.captcha_enabled,captchaSiteKey:r.captcha_site_key,createdAt:new Date(1e3*r.created_at),updatedAt:new Date(1e3*r.updated_at),mfaMethods:r.mfa_methods,enforceWalletUis:r.enforce_wallet_uis,legacyWalletUiConfig:r.legacy_wallet_ui_config,telegramAuthConfiguration:a,fundingConfig:n}}catch(e){throw F.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 forkSession(){return await this.session.forkSession()}async generateSiweNonce({address:e,captchaToken:t}){try{return(await this.api.post(Re.siweInitPath,{address:e,token:t})).nonce}catch(e){throw F.formatPrivyError(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n,mode:i}){return await this.api.post(Re.siweAuthenticatePath,{message:e,signature:t,chainId:r,walletClientType:a,connectorType:n,mode:i})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}){return await this.api.post(Re.siweLinkPath,{message:e,signature:t,chainId:r,walletClientType:a,connectorType:n})}async linkSmartWallet({message:e,signature:t,smartWalletType:r}){try{let a=await this.api.post(Re.smartWalletLinkPath,{message:e,signature:t,smart_wallet_type:r});return E.convertUserResponseToUser(a)}catch(e){throw F.formatPrivyError(e)}}async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}){try{let i=await this.linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n});return E.convertUserResponseToUser(i)}catch(e){throw F.formatPrivyError(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(Re.siwsInitPath,{address:e,token:t})).nonce}catch(e){throw F.formatPrivyError(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a,mode:n}){return await this.api.post(Re.siwsAuthenticatePath,{message:e,signature:t,walletClientType:r,connectorType:a,mode:n})}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s}){try{let l,c;switch(r){case"email":l=Re.transferEmailPath,c={nonce:e,email:t};break;case"sms":l=Re.transferPhonePath,c={nonce:e,phoneNumber:t};break;case"siwe":if(l=Re.transferWalletPath,!a)throw Error("Wallet parameters must be defined");c={nonce:e,address:t,...a};break;case"farcaster":l=Re.transferFarcasterPath,c={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":l=Re.telegramAccountTransferPath,c={nonce:e,telegram_auth_result:n,telegram_web_app_data:i};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:l=Re.transferOAuthPath,c={nonce:e,userInfo:s}}let d=await this.api.post(l,c);return await this.getAuthenticatedUser()??E.convertUserResponseToUser(d)}catch(e){throw F.formatPrivyError(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a}){return await this.api.post(Re.siwsLinkPath,{message:e,signature:t,walletClientType:r,connectorType:a})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:a}){try{let n=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:a});return E.convertUserResponseToUser(n)}catch(e){throw F.formatPrivyError(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(Re.usersMePath);return this.session.updateIdentityToken(e.identity_token),E.convertUserResponseToUser(e.user)}catch(e){throw F.formatPrivyError(e)}}async scanTransaction(e){try{return await this.api.post(Re.transactionScanningPath,e)}catch(e){throw F.formatPrivyError(e)}}constructor({apiUrl:e=m.DEFAULT_PRIVY_API_URL,appId:t,appClientId:r,timeout:a=m.DEFAULT_API_TIMEOUT_MS}){Object.defineProperty(this,Be,{value:Ke}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==m.DEFAULT_PRIVY_API_URL&&e.startsWith("https://privy."),this.timeout=a,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,Be)[Be](),qe||(qe=new Me.Session),this.session=qe,this.api=this.generateApi(),this.session.client=this}}function Ke(){if("undefined"==typeof window)return null;try{let e=g.default.get(m.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=p.v4();try{return g.default.put(m.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}class Ve{async handleSignMessage(e){if(!e.params||"string"!=typeof e.params.message)throw Error("Message must be provided as a string for Solana signMessage RPC");return await st({message:e.params.message,options:{address:this.address,uiOptions:{}}})}async request(e){if(console.debug("EmbeddedSolanaProvider.request() called with args",e),!await et())throw Error("User must be authenticated to use embedded Solana wallet");if(!await ot())throw new F.PrivyClientError("Unable to connect to Solana embedded wallet");if("signMessage"===e.method)return await this.handleSignMessage(e);throw Error("Embedded Solana provider does not yet support this RPC method.")}constructor(e,t){this.walletProxy=e,this.address=t}}let Ge,ze,Ye,$e,Xe,Je,Qe,Ze;async function et(){return Ge?Ge.getAccessToken():Promise.resolve(g.default.get(m.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||g.default.get(m.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const tt=(e,t)=>ze(e,t),rt=(e,t)=>Ye(e,t),at=(e,t)=>$e(e,t),nt=(e,t)=>Xe(e,t),it=()=>Je(),ot=()=>Qe(),st=({message:e,address:t})=>Ze({message:e,options:{address:t,uiOptions:{}}});let lt=p=>{let w=p.client,v=ne.usePlugins(),[C,A]=r.useState(!1),[P,Ce]=r.useState(!1),[Ae,Pe]=r.useState(!1),[_e,Te]=r.useState(null),[Ie,We]=r.useState([]),[Se,ke]=r.useState([]),[Ne,Ue]=r.useState([]),[Oe,be]=r.useState(!1),[Re,Me]=r.useState(null),[De,Le]=r.useState(!1),[Fe,xe]=r.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:ue.notImplemented}),[qe,je]=r.useState({status:"initial"}),[Be,He]=r.useState({status:"initial"}),[Ke,tt]=r.useState({status:"initial"}),[rt,at]=r.useState({status:"initial"}),[nt,it]=r.useState({status:"initial"}),[ot,st]=r.useState({status:"initial"}),[lt,ct]=r.useState(null),dt=W.useAppConfig(),ut=W.useIsServerConfigLoaded(),[ht,yt]=r.useState(!0),[pt,wt]=r.useState({}),[Et,vt]=r.useState(null),[mt,gt]=r.useState(null),[ft,Ct]=r.useState(!1),[At,Pt]=r.useState(!1),[_t,Tt]=r.useState(dt.customAuth?.enabled?{status:"initial"}:{status:"not-enabled"}),It=r.useRef(null),Wt=r.useRef(null),St=r.useRef(ye.privyEventsDefault),[kt,Nt]=r.useState(!1);w.onStoreCustomerAccessToken=e=>{e&&ye.emitPrivyEvent(St,"accessToken","onAccessTokenGranted",{accessToken:e})},w.onDeleteCustomerAccessToken=()=>{Te(null),Pe(!1),ye.emitPrivyEvent(St,"accessToken","onAccessTokenRemoved")};let Ut=r.useRef(null),Ot=r.useRef(null),bt=r.useRef(!1),Rt=({showWalletUIs:e})=>bt.current?bt.current:void 0!==e?!e:!dt.embeddedWallets.showWalletUIs,Mt=e=>{Me(e),setTimeout((()=>{A(!0)}),15),w.createAnalyticsEvent({eventName:"modal_open",payload:{initialScreen:e}})},Dt=e=>{("off"!==dt.embeddedWallets.ethereum.createOnLogin||"off"!==dt.embeddedWallets.solana.createOnLogin)&&yt(!0),Mt(e)};r.useEffect((()=>{let e=[...E.getPrivySolanaHDWallets(_e),E.getImportedPrivySolanaWallet(_e)].filter((e=>!!e));lt&&Ue(e.map((e=>({type:"solana",imported:e.imported,address:e.address,connectedAt:Date.now(),walletClientType:"privy",connectorType:"embedded",walletIndex:e.walletIndex??void 0,meta:{name:"Privy Wallet",icon:void 0,id:"io.privy.solana.wallet"},linked:!0,fund(){throw new F.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:()=>{throw new F.PrivyClientError("Cannot unlink an embedded Solana wallet")},getProvider:async()=>new Ve(lt,e.address),async signMessage(t){let r=await et();if(!r||!lt)throw new F.PrivyClientError("Must have valid access token and Privy wallet to send transaction",F.PrivyErrorCode.MUST_BE_AUTHENTICATED);let a=e.imported?E.getImportedPrivySolanaWallet(_e):E.getPrivyPrimaryWallet(_e);if(!a)throw new F.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(a);if(!await lr.recoverPrimaryWallet().catch((()=>!1)))throw new F.PrivyClientError("Wallet couldn't be connected",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);if(!_e)throw new F.PrivyClientError("Attempting to sign a transaction with no user initialized");let{response:o}=await lt.rpc({accessToken:r,entropyId:n,entropyIdVerifier:i,chainType:"solana",hdWalletIndex:e.walletIndex??0,request:{method:"signMessage",params:{message:Buffer.from(t).toString("base64")}}});return Buffer.from(o.data.signature,"base64")},async sendTransaction(e,t,r){let{signature:a}=await tr({transaction:e,connection:t,transactionOptions:r,wallet:this,signOnly:!1});return a},async signTransaction(t){let r=await et();if(!r||!lt)throw new F.PrivyClientError("Must have valid access token and Privy wallet to send transaction",F.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!await lr.recoverPrimaryWallet().catch((()=>!1)))throw new F.PrivyClientError("Wallet couldn't be connected",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR);let a=e.imported?e:E.getPrivyPrimaryWallet(_e);if(!a)throw new F.PrivyClientError("Attempting to sign a transaction without a root wallet");let{entropyId:n,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(a);return await x.signSolanaTransaction({tx:t,accessToken:r,walletProxy:lt,entropyId:n,entropyIdVerifier:i,transactingWalletAddress:e.address,transactingWalletIndex:e.walletIndex??0}),t},loginOrLink:async()=>{throw new F.PrivyClientError("Cannot login or link with an embedded Solana wallet")},disconnect:()=>{},isConnected:async()=>!0}))))}),[lt,_e]),r.useEffect((()=>{if(!_e)return void w.connectors?.removeEmbeddedWalletConnectors();let e=E.getPrivyEthereumWallet(_e),t=E.getPrivyEthereumHDWallets(_e),r=E.getImportedPrivyEthereumWallet(_e);e&&t.length||w.connectors?.removeEmbeddedWalletConnectors(),r||w.connectors?.removeImportedWalletConnector(),w.connectors?lt?(e&&w.connectors.addEmbeddedWalletConnectors({walletProxy:lt,rootWallet:e,embeddedWallets:t,defaultChain:dt.defaultChain,appId:p.appId}),r&&w.connectors.addImportedWalletConnector(lt,r.address,dt.defaultChain,p.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")}),[lt,_e]),r.useEffect((()=>{lt&&mt?.(lt)}),[lt]);let Lt=r.useRef();r.useEffect((()=>{(async()=>{if(!dt.customAuth?.enabled)return void Tt({status:"not-enabled"});yt(!0);let{getCustomAccessToken:e,isLoading:t}=dt.customAuth;if(P&&!t&&"loading"!==_t.status){Tt({status:"loading"});try{let t=await e();if(t===Lt.current)return void Tt({status:"done"});if(!t&&Ae)return Lt.current=t,await sr.logout(),Tt({status:"done"}),void ye.emitPrivyEvent(St,"customAuth","onUnauthenticated");if(!t)return Lt.current=t,void Tt({status:"done"});w.startAuthFlow(new i.CustomJwtAccountFlow(t));let{user:r,isNewUser:a}=await w.authenticate();if(!r)return await sr.logout(),Tt({status:"error",error:new F.PrivyClientError("Failed to sync with custom auth provider")}),void ye.emitPrivyEvent(St,"customAuth","onUnauthenticated");void 0!==a&&ye.emitPrivyEvent(St,"login","onComplete",{user:r,isNewUser:a,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),Lt.current=t,ye.emitPrivyEvent(St,"customAuth","onAuthenticated",{user:r}),Tt({status:"done"}),Te(r||null),be(a||!1),Pe(!0),Pt(!0)}catch(e){if(console.warn(e),await sr.logout(),ye.emitPrivyEvent(St,"customAuth","onUnauthenticated"),"User already exists with provided custom JWT account."===e.message)return void Tt({status:"initial"});ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),Tt({status:"error",error:e})}}})()}),["initial"===_t.status,dt.customAuth?.enabled,dt.customAuth?.getCustomAccessToken,dt.customAuth?.isLoading,P,Ae]),r.useEffect((()=>{At&&lt&&_e&&(async()=>{let e=ee.shouldCreateEmbeddedEthWallet(_e,dt.embeddedWallets.ethereum.createOnLogin),t=te.shouldCreateEmbeddedSolWallet(_e,dt.embeddedWallets.solana.createOnLogin),r=await et();if(r){if(e&&t){let e=await $t(_e,m.WALLET_PROXY_TIMEOUT);return await lt.createSolana({accessToken:r,ethereumAddress:e?.address}),void Pt(!1)}if(t)return await lt.createSolana({accessToken:r,ethereumAddress:E.getPrivyEthereumWallet(_e)?.address}),await lr.refreshSessionAndUser(),void Pt(!1);if(e)return await $t(_e,m.WALLET_PROXY_TIMEOUT),void Pt(!1)}})().catch(console.error)}),[At&&lt&&_e]),r.useEffect((()=>{if(dt.externalWallets.solana.connectors)return dt.externalWallets.solana.connectors.onMount(),()=>dt.externalWallets.solana.connectors?.onUnmount()}),[dt.externalWallets.solana.connectors]),r.useEffect((()=>{!P&&ut&&async function(){let e,r=Ft(),a=xt();(()=>{let e=new URLSearchParams(window.location.search).get("privy_token");if(!e)return;g.default.put(m.FORKED_TOKEN_STORAGE_KEY,e);let t=new URL(window.location.href);t.searchParams.delete("privy_token"),window.history.pushState({},"",t)})();let n=t.createStore();w.initializeConnectorManager({walletConnectCloudProjectId:dt.walletConnectCloudProjectId,rpcConfig:dt.rpcConfig,chains:dt.chains,defaultChain:dt.defaultChain,store:n,walletList:dt.appearance.walletList,shouldEnforceDefaultChainOnConnect:dt.shouldEnforceDefaultChainOnConnect,externalWalletConfig:dt.externalWallets,appName:dt.name??"Privy",walletChainType:dt.appearance.walletChainType}),w.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=w.connectors.walletConnectors.length,r=w.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?Nt(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),Nt(!0)}),1500)})),w.connectors?.initialize().then((()=>{Kt()}));let i=await w.getAuthenticatedUser(),o=!!i;dt.legal.requireUsersAcceptTerms&&i&&!i.hasAcceptedTerms?(await w.logout(),lr.setReadyToTrue(!0),ye.emitPrivyEvent(St,"logout","onSuccess")):(dt.customAuth?.enabled||(Pe(!!i),i&&ye.emitPrivyEvent(St,"login","onComplete",{user:i,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),Te(i)),r?Ot.current=o?"link":"login":a&&!o?(Ot.current="login",wt({telegramAuthModalData:{seamlessAuth:!0}}),Dt(se.ModalScreen.TELEGRAM_AUTH_SCREEN)):lr.setReadyToTrue(!!i))}()}),[w,Et,P,ut]),r.useEffect((()=>{if(P){if(!_e||!_e.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void Ct(!0);Ct([...Ie,...Ne].some((e=>"privy"===e.walletClientType)))}}),[P,_e,Ie,Ne]),r.useEffect((()=>{w.connectors?.setWalletList(dt.appearance.walletList)}),[dt.appearance.walletList.join()]);let Ft=()=>{let e=ge.detectCompletingOAuthFlow();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&&j.isPrivyTheOAuthProvider(e.provider)&&!e.popupFlow&&(new BroadcastChannel(j.CROSS_APP_BROADCAST_CHANNEL_NAME).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(w.startAuthFlow(new fe.OAuthFlow(e)),Dt(se.ModalScreen.AWAITING_OAUTH_SCREEN),!0))},xt=()=>{let e=y.detectCompletingTelegramFlow();if(!e||!dt.loginMethods.telegram||!dt.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new y.TelegramAuthFlow;return w.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},qt=async(e,t,r,a)=>{if("solana_adapter"!==e)jt(await(w.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,a);else{let n=w.connectors?.findSolanaWalletConnector(e,t);if(!n)return;jt(n,t,r,a)}};async function jt(e,t,r,a){if(!e)return xe({status:"disconnected",connectedWallet:null,connectError:new F.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:ue.notImplemented}),a?.(null,r);xe({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:ue.notImplemented}),e instanceof b.WalletConnectV2WalletConnector&&t&&await e.resetConnection(t),xe({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>jt(e,t,r,a)});try{let t=await e.connect({showPrompt:!0});if((!t||N.isBaseConnectedEthereumWallet(t))&&dt.shouldEnforceDefaultChainOnConnect&&!dt.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){xe((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:ue.notImplemented})));try{await(t?.switchChain(dt.defaultChain.id)),t&&(t.chainId=f.formatChainIdToCAIP2(f.toHex(dt.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${dt.defaultChain.id}`)}}return xe((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:ue.notImplemented}))),t&&ye.emitPrivyEvent(St,"connectWallet","onSuccess",{wallet:t}),a?.(t,r)}catch(e){return e instanceof F.PrivyError?(console.warn(e.cause?e.cause:e.message),ye.emitPrivyEvent(St,"connectWallet","onError",e.privyErrorCode||F.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),ye.emitPrivyEvent(St,"connectWallet","onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),xe((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),a?.(null,r)}}let Bt=async(e,t,r)=>{if(null===e||!N.isBaseConnectedEthereumWallet(e))return;let a=new d.SiweFlow(e,w,t,r);w.startAuthFlow(a)},Ht=async(e,t,r)=>{if(null===e||!O.isBaseConnectedSolanaWallet(e))return;let a=new u.SiwsFlow(e,w,t,r);w.startAuthFlow(a)},Kt=()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client"),a="true"===e.get("privy_connect_only");if(!t||!r)return;let n=U.getWalletConfigForConnector({connectorType:t,walletClientType:r});if(!n||!n.isInstalled)return Dt(se.ModalScreen.LOGIN_FAILED_SCREEN);if(!w.connectors)throw new F.PrivyClientError("Connector not initialized");Mt(a?se.ModalScreen.AWAITING_CONNECT_ONLY_CONNECTION:se.ModalScreen.AWAITING_CONNECTION);let i=new URL(window.location.href);i.searchParams.delete("privy_connector"),i.searchParams.delete("privy_wallet_client"),i.searchParams.delete("privy_connect_only"),window.history.pushState({},"",i),qt(t,r,void 0,a?void 0:"solana_adapter"===t?Ht:Bt)};r.useEffect((()=>{P&&Ae&&null===_e&&w.getAuthenticatedUser().then(Te)}),[P,Ae,_e,w]);let Vt=e=>{if(!Ae)throw ye.emitPrivyEvent(St,"linkAccount","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new F.PrivyClientError("User must be authenticated before linking an account.")},Gt=e=>{if(!Ae||!_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},zt=async e=>{let t;if(!w.connectors)throw new F.PrivyClientError("Connector not initialized");t="ethereum"===e.type?w.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:w.connectors.findSolanaWalletConnector(e.connectorType,e.walletClientType)||null,xe((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:ue.notImplemented}))),dt.captchaEnabled&&!Ae?(wt({captchaModalData:{callback:t=>N.isBaseConnectedEthereumWallet(e)?Bt(e,t):Ht(e,t),userIntentRequired:!1,onSuccessNavigateTo:se.ModalScreen.AWAITING_CONNECTION,onErrorNavigateTo:se.ModalScreen.ERROR_SCREEN}}),Dt(se.ModalScreen.CAPTCHA_SCREEN)):(N.isBaseConnectedEthereumWallet(e)?await Bt(e):await Ht(e),Dt(se.ModalScreen.AWAITING_CONNECTION))},Yt=()=>{We((e=>{let t=w.connectors?.wallets.filter(N.isBaseConnectedEthereumWallet).map((e=>({...e,linked:Gt(e),loginOrLink:async()=>{if(!await e.isConnected())throw new F.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new F.PrivyClientError("Cannot link or login with embedded wallet");zt(e)},fund:async t=>{await lr.fundWallet(e.address,t)},unlink:async()=>{if(!Ae)throw new F.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new F.PrivyClientError("Cannot unlink an embedded wallet");Te(await w.unlinkEthereumWallet(e.address))}})))||[];return S.areWalletArraysEqual(e,t)?e:t})),ke((e=>{let t=(w.connectors?.wallets??[]).filter(O.isBaseConnectedSolanaWallet).map((e=>({...e,linked:Gt(e),loginOrLink:async()=>{if(!await e.isConnected())throw new F.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new F.PrivyClientError("Cannot link or login with embedded wallet");zt(e)},fund:async()=>{throw new F.PrivyClientError("'fund' is deprecated for Solana wallets - use 'fundWallet' instead")},unlink:async()=>{if(!Ae)throw new F.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new F.PrivyClientError("Cannot unlink an embedded wallet");Te(await w.unlinkSolanaWallet(e.address))}})));return S.areWalletArraysEqual(e,t)?e:t}))};r.useEffect((()=>{Yt()}),[_e?.linkedAccounts,Ae,P]),r.useEffect((()=>{if(P){if(!w.connectors)throw new F.PrivyClientError("Connector not initialized");Yt(),w.connectors.on("walletsUpdated",Yt)}}),[P]),r.useEffect((()=>{[...dt.loginMethodsAndOrder?.primary??[],...dt.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>w.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!w]);let $t=async(e,t,r)=>{let a=E.getPrivyEthereumWallet(e),n=E.getPrivySolanaWallet(e);if(r&&"walletIndex"in r&&"number"==typeof r.walletIndex)return Jt(e,t,r.walletIndex,a,n);let i=r&&"createAdditional"in r&&r.createAdditional;if(a&&!i)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");let[o,s]=await Promise.all([lr.initializeWalletProxy(t),et()]);if(!o&&dt.customAuth?.enabled)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!o||!s||dt.embeddedWallets?.requireUserOwnedRecoveryOnCreate)return Xt();if(!a)return n&&await lr.recoverPrimaryWallet(),await o.create({accessToken:s,solanaAddress:n?.address}),Zt(0,"ethereum");{let t=(E.getLatestPrivyEthereumWallet(e)?.walletIndex??0)+1,{entropyId:r,entropyIdVerifier:a}=E.getEntropyDetailsFromAccount(E.getPrivyPrimaryWallet(e));return await lr.recoverPrimaryWallet(),await o.addWallet({accessToken:s,entropyId:r,entropyIdVerifier:a,chainType:"ethereum",hdWalletIndex:t}),Zt(t,"ethereum")}},Xt=async()=>new Promise(((e,t)=>{yt(!0),wt({createWallet:{onSuccess:t=>{ye.emitPrivyEvent(St,"createWallet","onSuccess",{wallet:t}),e(t)},onFailure:e=>{ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),t(e)},callAuthOnSuccessOnClose:!1}}),Mt(se.ModalScreen.EMBEDDED_WALLET_ON_ACCOUNT_CREATE_SCREEN)})),Jt=async(e,t,r,a,n)=>{if(r<0)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${r}) is invalid.`);let[i,o]=await Promise.all([lr.initializeWalletProxy(t),et()]);if(!i&&dt.customAuth?.enabled)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");if(!i||!o||dt.embeddedWallets?.requireUserOwnedRecoveryOnCreate){if(0==r)return Xt();throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Create wallet UI can only be displayed when walletIndex is 0.")}if(0==r){if(a)return a;await i.create({accessToken:o,solanaAddress:n?.address})}else{if(!a)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error("A user must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let t=E.getPrivyEthereumHDWallets(e).find((e=>e.walletIndex===r));if(t)return t;let{entropyId:n,entropyIdVerifier:s}=E.getEntropyDetailsFromAccount(E.getPrivyPrimaryWallet(e));await lr.recoverPrimaryWallet(),await i.addWallet({accessToken:o,entropyId:n,entropyIdVerifier:s,chainType:"ethereum",hdWalletIndex:r})}return Zt(r,"ethereum")},Qt=async({user:e,wp:t,accessToken:r,walletIndex:a,ethereumWallet:n})=>{let i=E.getPrivySolanaHDWallets(e).find((e=>e.walletIndex===a));if(i)return i;if(0===a)n&&await lr.recoverPrimaryWallet(),await t.createSolana({accessToken:r,ethereumAddress:n?.address});else{let n=E.getPrivyPrimaryWallet(e);if(!n)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error("User must have a wallet at HD index 0 before creating a wallet at greater HD indices.");let{entropyId:i,entropyIdVerifier:o}=E.getEntropyDetailsFromAccount(n);await lr.recoverPrimaryWallet(),await t.addWallet({accessToken:r,entropyId:i,entropyIdVerifier:o,chainType:"solana",hdWalletIndex:a})}return Zt(a,"solana")},Zt=async(e,t)=>{let r=await lr.refreshSessionAndUser(),a=("ethereum"===t?E.getPrivyEthereumHDWallets(r):E.getPrivySolanaHDWallets(r)).find((t=>t.walletIndex===e));if(!a)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");return ye.emitPrivyEvent(St,"createWallet","onSuccess",{wallet:a}),a},er=({transaction:e,uiOptions:t,fundWalletConfig:r,address:a,signOnly:i})=>new Promise((async(o,s)=>{let{requesterAppId:l}=t||{},c=i?"signTransaction":"sendTransaction";if(!Ae||!_e)return ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),void s(Error("User must be authenticated before signing with a Privy wallet"));let d=a??E.getPrivyEthereumWallet(_e)?.address;if(!d)throw new F.PrivyClientError("User must have an embedded wallet to send a transaction.");let{signingWallet:u,rootWallet:h}=E.getEthereumSigningAndRootWallet(_e,d);if(!h||!u)return ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(Error("Must have a Privy wallet before signing"));yt(!0);let y=cr.wallets.find((e=>"privy"===e.walletClientType&&n.getAddress(e.address)===n.getAddress(u.address))),w=await(y?.getEthereumProvider());if(!y||!w)throw new F.PrivyClientError(`Cannot sendTransaction before embedded wallet ${u.address} is connected`);let v=e.chainId?Number(e.chainId):q.extractChainIdFromCAIP2(y.chainId);(e=>{if(!dt.chains.map((e=>e.id)).includes(e))throw new F.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,F.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(v);let m={...e,from:e.from??u.address,chainId:v},g=await et();if(!g||!lt)return ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void s(Error("Must have valid access token and Privy wallet to send transaction"));let f=de.getPublicClient(m.chainId,dt.chains,dt.rpcConfig,{appId:p.appId});if(Rt({showWalletUIs:t?.showWalletUIs}))(async()=>{try{if(!await lr.recoverPrimaryWallet())return ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void s(Error("Unable to connect to wallet"));let e=await re.prepareTransactionRequest(m,f,m.from),{entropyId:t,entropyIdVerifier:r}=E.getEntropyDetailsFromAccount(h),a=i?await L.signTransaction({accessToken:g,entropyId:t,entropyIdVerifier:r,transactingWallet:u,walletProxy:lt,transactionRequest:m,requesterAppId:l}):await L.sendTransaction({accessToken:g,entropyId:t,entropyIdVerifier:r,transactingWallet:u,walletProxy:lt,transactionRequest:e,publicClient:f,requesterAppId:l});i?ye.emitPrivyEvent(St,"signTransaction","onSuccess",{signature:a}):ye.emitPrivyEvent(St,"sendTransaction","onSuccess",{hash:a}),o({hash:a})}catch(e){ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.TRANSACTION_FAILURE),s(e)}})();else{let{entropyId:e,entropyIdVerifier:a}=E.getEntropyDetailsFromAccount(h),n={entropyId:e,entropyIdVerifier:a,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SEND_TRANSACTION_SCREEN,onFailure:e=>{ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}},d=z.isFundingEnabled(dt)?me.prepareFundingModalData({address:u.address,appConfig:dt,fundWalletConfig:r,methodScreen:se.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,chainIdOverride:m.chainId,comingFromSendTransactionScreen:!0}):void 0;wt({connectWallet:n,sendTransaction:{transactionRequest:m,transactingWallet:u,entropyId:e,entropyIdVerifier:a,signOnly:i,onConfirm:i?async()=>await L.signTransaction({accessToken:g,entropyId:e,entropyIdVerifier:a,transactingWallet:u,walletProxy:lt,transactionRequest:m,requesterAppId:l}):void 0,onSuccess:e=>{i?ye.emitPrivyEvent(St,"signTransaction","onSuccess",{signature:e.hash}):ye.emitPrivyEvent(St,"sendTransaction","onSuccess",{hash:e.hash}),o(e)},onFailure:e=>{ye.emitPrivyEvent(St,c,"onError",F.PrivyErrorCode.TRANSACTION_FAILURE),s(e)},uiOptions:t||{},fundWalletConfig:r,requesterAppId:l},funding:d}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),tr=({transaction:e,connection:t,transactionOptions:r,fundWalletConfig:a,uiOptions:n,wallet:i,signOnly:o})=>new Promise((async(s,l)=>{let{requesterAppId:c}=n||{},d=o?"signSolanaTransaction":"sendSolanaTransaction";if(!Ae||!_e)return ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),void l(new F.PrivyClientError("User must be authenticated before signing with a Privy wallet",F.PrivyErrorCode.MUST_BE_AUTHENTICATED));let u=i?_e.linkedAccounts.find((e=>"wallet"===e.type&&e.address===i.address)):E.getPrivySolanaWallet(_e);if(!u)return ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void l(new F.PrivyClientError("Must have a Privy wallet before signing",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));yt(!0);let{rootWallet:h}=E.getSolanaSigningAndRootWallet(_e,u.address);if(!await lr.recoverPrimaryWallet().catch((()=>!1))||!h)throw ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new F.PrivyClientError(`Cannot sendSolanaTransaction before embedded wallet ${u.address} is connected`,F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);if(Rt({showWalletUIs:n?.showWalletUIs}))(async()=>{let a=await et();if(!a||!lt)return ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void l(new F.PrivyClientError("Must have valid access token and Privy wallet to send transaction",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND));try{let i;if(!await lr.recoverPrimaryWallet())return ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),void l(new F.PrivyClientError("Unable to connect to wallet",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR));if(Rt({showWalletUIs:n?.showWalletUIs}))try{if(!await Q.hasSufficientFunds(e,t))return ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.INSUFFICIENT_BALANCE),void l(new F.PrivyClientError("Solana wallet has insufficient funds for this transaction.",F.PrivyErrorCode.INSUFFICIENT_BALANCE))}catch(e){return console.error(e),ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.TRANSACTION_FAILURE),void l(new F.PrivyClientError(e instanceof Error?e.message:"Transaction failed.",F.PrivyErrorCode.TRANSACTION_FAILURE))}let{entropyId:c,entropyIdVerifier:h}=E.getEntropyDetailsFromUser(_e);if(o)await x.signSolanaTransaction({accessToken:a,tx:e,walletProxy:lt,entropyId:c,entropyIdVerifier:h,transactingWalletAddress:u.address,transactingWalletIndex:u.walletIndex??0}),i=Q.createSolanaTransactionReceipt("",e,null),ye.emitPrivyEvent(St,"signSolanaTransaction","onSuccess",{signedTransaction:e});else{let{signature:n,receipt:o}=await x.sendSolanaTransaction({accessToken:a,tx:e,connection:t,walletProxy:lt,transactionOptions:r,entropyId:c,entropyIdVerifier:h,transactingWalletAddress:u.address,transactingWalletIndex:u.walletIndex??0});i=Q.createSolanaTransactionReceipt(n,e,o),ye.emitPrivyEvent(St,"sendSolanaTransaction","onSuccess",{response:i})}s(i)}catch(e){ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.TRANSACTION_FAILURE),l(e)}})();else{let{entropyId:i,entropyIdVerifier:y}=E.getEntropyDetailsFromAccount(h),p={entropyId:i,entropyIdVerifier:y,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SEND_SOLANA_TRANSACTION_SCREEN,onFailure:e=>{ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),l(e)}},w=z.isFundingEnabled(dt)?me.prepareSolanaFundingModalData({address:u.address,appConfig:dt,methodScreen:se.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN,fundWalletConfig:a,comingFromSendTransactionScreen:!0}):void 0;wt({connectWallet:p,sendSolanaTransaction:{transactionRequest:e,connection:t,transactionOptions:r,transactingWallet:u,onSuccess:e=>{o?ye.emitPrivyEvent(St,"signSolanaTransaction","onSuccess",{signedTransaction:e.signedTransaction}):ye.emitPrivyEvent(St,"sendSolanaTransaction","onSuccess",{response:e}),s(e)},onFailure:e=>{ye.emitPrivyEvent(St,d,"onError",F.PrivyErrorCode.TRANSACTION_FAILURE),l(e)},uiOptions:n||{},requesterAppId:c,signOnly:o},funding:w}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}}));function rr(){return new Promise((async(e,t)=>{let r=await et();if(!r||!lt)throw Error("Must have valid access token to enroll in MFA");try{await lt.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let ar=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],nr=e=>{let t=_e?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:a}=Z.toDisplayFromAccountType(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw ye.emitPrivyEvent(St,"linkAccount","onError",F.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:a}),new F.PrivyClientError(`User already has an account of type ${r} linked.`)};async function ir({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){Me(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!Ae||!_e)throw ye.emitPrivyEvent(St,r,"onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let a=E.getPrivyPrimaryWallet(_e);if(!a||!lt)throw ye.emitPrivyEvent(St,r,"onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");try{await rr()}catch(e){throw ye.emitPrivyEvent(St,r,"onError",F.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((n,i)=>{yt(!0);let o={onSuccess:e=>{ye.emitPrivyEvent(St,r,"onSuccess",{method:"user-passcode",wallet:e}),n(e)},onFailure:e=>{ye.emitPrivyEvent(St,r,"onError",F.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),i(e)},callAuthOnSuccessOnClose:!1},s="user-passcode"===a.recoveryMethod,l=V.toEmbeddedWalletSetRecoveryScreen({walletAction:"update",availableRecoveryMethods:dt.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:s,showAutomaticRecovery:e}),{entropyId:c,entropyIdVerifier:d}=E.getEntropyDetailsFromAccount(a);wt({setWalletPassword:o,recoverWallet:{entropyId:c,entropyIdVerifier:d,onFailure:i},createWallet:o,connectWallet:{onCompleteNavigateTo:l,shouldForceMFA:!1,entropyId:c,entropyIdVerifier:d,onFailure:e=>{ye.emitPrivyEvent(St,r,"onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),i(e)}},recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:s}}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}))}async function or({appId:e,action:t}){let r=await et();if("link"===t&&!r)throw ye.emitPrivyEvent(St,"linkAccount","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new F.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw ye.emitPrivyEvent(St,"login","onError",F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new F.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");Ut.current=`privy:${e}`,Ot.current=t;let a=$.triggerPopup();return w.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,n)=>{let{name:i,logoUrl:o}=await B.getProviderAppMetadata({api:w.api,providerAppId:e,requesterAppId:dt.id});wt({crossAppAuth:{appId:e,name:i,logoUrl:o,action:t,popup:a,onSuccess:r,onError:n}}),Dt(se.ModalScreen.CROSS_APP_AUTH_SCREEN)}))}let sr={ready:P,authenticated:Ae,user:_e,walletConnectors:w.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),wt({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,suggestedAddress:e?.suggestedAddress,walletChainType:e?.walletChainType}}),Mt(Ae?se.ModalScreen.CONNECT_ONLY_AUTHENTICATED_SCREEN:se.ModalScreen.CONNECT_ONLY_LANDING_SCREEN)},linkWallet:e=>{e&&"target"in e&&e&&(e=void 0),Vt("siwe"),Ut.current="siwe",Ot.current="link",wt({...pt,externalConnectWallet:{...pt.externalConnectWallet,suggestedAddress:e?.suggestedAddress,walletList:e?.walletList,walletChainType:e?.walletChainType}}),Mt(se.ModalScreen.LINK_WALLET_SCREEN)},startCrossAppAuthFlow:or,linkEmail:()=>{Vt("email"),nr("email"),Ut.current="email",Ot.current="link",Mt(se.ModalScreen.LINK_EMAIL_SCREEN)},linkPhone:()=>{Vt("sms"),nr("phone"),Ut.current="sms",Ot.current="link",Mt(se.ModalScreen.LINK_PHONE_SCREEN)},linkGoogle:async()=>{Vt("google"),nr("google_oauth"),Ot.current="link",await lr.initLoginWithOAuth("google")},linkTwitter:async()=>{Vt("twitter"),nr("twitter_oauth"),Ot.current="link",await lr.initLoginWithOAuth("twitter")},linkDiscord:async()=>{Vt("discord"),nr("discord_oauth"),Ot.current="link",await lr.initLoginWithOAuth("discord")},linkGithub:async()=>{Vt("github"),nr("github_oauth"),Ot.current="link",await lr.initLoginWithOAuth("github")},linkSpotify:async()=>{Vt("spotify"),nr("spotify_oauth"),Ot.current="link",await lr.initLoginWithOAuth("spotify")},linkInstagram:async()=>{Vt("instagram"),nr("instagram_oauth"),Ot.current="link",await lr.initLoginWithOAuth("instagram")},linkTiktok:async()=>{Vt("tiktok"),nr("tiktok_oauth"),Ot.current="link",await lr.initLoginWithOAuth("tiktok")},linkLinkedIn:async()=>{Vt("linkedin"),nr("linkedin_oauth"),Ot.current="link",await lr.initLoginWithOAuth("linkedin")},linkApple:async()=>{Vt("apple"),nr("apple_oauth"),Ot.current="link",await lr.initLoginWithOAuth("apple")},linkPasskey:async()=>{Vt("passkey"),nr("passkey"),await lr.initLinkWithPasskey(),Mt(se.ModalScreen.LINK_PASSKEY_SCREEN)},linkTelegram:async e=>{if(Vt("telegram"),nr("telegram"),Ot.current="link",Ut.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new y.TelegramAuthFlow;w.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=y.convertInitDataRawToTelegramWebAppData(e.launchParams.initDataRaw),wt({telegramAuthModalData:{seamlessAuth:!0}}),Dt(se.ModalScreen.TELEGRAM_AUTH_SCREEN)}else ye.emitPrivyEvent(St,"linkAccount","onError",F.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await lr.initLoginWithTelegram();Mt(se.ModalScreen.TELEGRAM_AUTH_SCREEN)},linkFarcaster:async()=>{Vt("farcaster"),nr("farcaster"),await lr.initLoginWithFarcaster(),Ot.current="link",Ut.current="farcaster",Mt(se.ModalScreen.AWAITING_FARCASTER_CONNECTION)},updateEmail:()=>{if(Vt("email"),!_e?.email)throw new F.PrivyClientError("User does not have an email linked to their account.");Ot.current="update",Ut.current="email",Mt(se.ModalScreen.UPDATE_EMAIL_SCREEN)},updatePhone:()=>{if(Vt("sms"),!_e?.phone)throw new F.PrivyClientError("User does not have a phone number linked to their account.");Ot.current="update",Ut.current="sms",Mt(se.ModalScreen.UPDATE_PHONE_SCREEN)},login:async e=>{e&&"target"in e&&e&&(e=void 0);let t="Attempted to log in, but user is already logged in. Use a `link` helper instead.";if(!P){let e=await new Promise((e=>{vt((t=>e.bind(t)))}));if(vt(null),e)return void console.warn(t)}!_e||_e.isGuest?(Ot.current="login",wt({login:e}),Dt(se.ModalScreen.LANDING)):console.warn(t)},connectOrCreateWallet:async()=>{P||(await new Promise((e=>{vt((()=>e))})),vt(null)),Ae?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(Ot.current="login",Dt(se.ModalScreen.CONNECT_OR_CREATE))},logout:async()=>{if(Ot.current=null,Ut.current=null,_e&&w.clearProviderAcccessTokens(_e),Me(null),await w.logout(),_e&&lt)try{await lt.clearMfa({userId:_e.id})}catch(e){}Te(null),Pe(!1),ye.emitPrivyEvent(St,"logout","onSuccess"),A(!1),g.default.del(m.CLIENT_ANALYTICS_ID_KEY),g.default.del(m.getGuestCredentialStorageKey(dt.id))},getAccessToken:r.useCallback((()=>w.getCustomerAccessToken()),[w]),unlinkWallet:async e=>{let t;return Te(t=e.startsWith("0x")?await w.unlinkEthereumWallet(e):await w.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await w.unlinkEmail(e);return Te(t),t},unlinkPhone:async e=>{let t=await w.unlinkPhone(e);return Te(t),t},unlinkGoogle:async e=>{let t=await w.unlinkOAuth("google",e);return Te(t),t},unlinkTwitter:async e=>{let t=await w.unlinkOAuth("twitter",e);return Te(t),t},unlinkDiscord:async e=>{let t=await w.unlinkOAuth("discord",e);return Te(t),t},unlinkGithub:async e=>{let t=await w.unlinkOAuth("github",e);return Te(t),t},unlinkSpotify:async e=>{let t=await w.unlinkOAuth("spotify",e);return Te(t),t},unlinkInstagram:async e=>{let t=await w.unlinkOAuth("instagram",e);return Te(t),t},unlinkTiktok:async e=>{let t=await w.unlinkOAuth("tiktok",e);return Te(t),t},unlinkLinkedIn:async e=>{let t=await w.unlinkOAuth("linkedin",e);return Te(t),t},unlinkApple:async e=>{let t=await w.unlinkOAuth("apple",e);return Te(t),t},unlinkFarcaster:async e=>{let t=await w.unlinkFarcaster(e);return Te(t),t},unlinkTelegram:async e=>{let t=await w.unlinkTelegram(e);return Te(t),t},unlinkPasskey:async e=>{let t=await et();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!lt)throw Error("Wallet proxy not initialized.");let r=dt.passkeys.shouldUnenrollMfaOnUnlink;await lt.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let a=await w.getAuthenticatedUser();return Te(a),a},unlinkCrossAppAccount:async({subject:e})=>{let t=_e?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new F.PrivyClientError("Invalid subject");w.storeProviderAccessToken(t.id,null);let r=await w.unlinkOAuth(`privy:${t.id}`,e);return Te(r),r},createWallet:async e=>{e&&"target"in e&&e&&(e=void 0);let t=await lr.refreshSessionAndUser();if(!t)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return $t(t,15e3,e)},setWalletRecovery:async e=>ir({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>ir({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(r,a)=>{let{requesterAppId:n}=t?.uiOptions||{},i=e.message;if(!Ae||!_e)return ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let o=t?.address??E.getPrivyEthereumWallet(_e)?.address;if(!o)throw new F.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:s,rootWallet:l}=E.getEthereumSigningAndRootWallet(_e,o);if(!s||!l)return ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));if("string"!=typeof i||i.length<1)return ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));yt(!0);let c=async()=>{if(!Ae)throw Error("User must be authenticated before signing with a Privy wallet");let e=await et();if(!lt||!e||!await lr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:s.address,requesterAppId:n}});let{entropyId:t,entropyIdVerifier:r}=E.getEntropyDetailsFromAccount(l),{response:a}=await lt.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:s.walletIndex??0,requesterAppId:n,request:{method:"personal_sign",params:[i,s.address]}}),o=a.data;return w.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:s.address,requesterAppId:n}}),o};if(Rt({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await c();ye.emitPrivyEvent(St,"signMessage","onSuccess",{signature:e}),r({signature:e})}catch(e){ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.UNABLE_TO_SIGN),a(e??new k.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"personal_sign",data:i,confirmAndSign:c,onSuccess:e=>{ye.emitPrivyEvent(St,"signMessage","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},{entropyId:n,entropyIdVerifier:o}=E.getEntropyDetailsFromAccount(l);wt({signMessage:e,connectWallet:{entropyId:n,entropyIdVerifier:o,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signTypedData:(e,t)=>new Promise((async(r,a)=>{let{requesterAppId:n}=t?.uiOptions||{};if(!Ae||!_e)return ye.emitPrivyEvent(St,"signTypedData","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let i=t?.address??E.getPrivyEthereumWallet(_e)?.address;if(!i)throw new F.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:o,rootWallet:s}=E.getEthereumSigningAndRootWallet(_e,i);if(!s||!o)return ye.emitPrivyEvent(St,"signTypedData","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));yt(!0);let l=f.generateTypedDataWithDomainType(e),c=async()=>{if(!Ae)throw Error("User must be authenticated before signing with a Privy wallet");let e=await et();if(!lt||!e||!await lr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:o.address,requesterAppId:n}});let{entropyId:t,entropyIdVerifier:r}=E.getEntropyDetailsFromAccount(s),{response:a}=await lt.rpc({accessToken:e,entropyId:t,entropyIdVerifier:r,chainType:"ethereum",hdWalletIndex:o.walletIndex??0,requesterAppId:n,request:{method:"eth_signTypedData_v4",params:[o.address,l]}}),i=a.data;return w.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:o.address,requesterAppId:n}}),i};if(Rt({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await c();ye.emitPrivyEvent(St,"signTypedData","onSuccess",{signature:e}),r({signature:e})}catch(e){ye.emitPrivyEvent(St,"signTypedData","onError",F.PrivyErrorCode.UNABLE_TO_SIGN),a(e??new k.PrivyProviderRpcError("Unable to sign message"))}else{let e={method:"eth_signTypedData_v4",data:l,confirmAndSign:c,onSuccess:e=>{ye.emitPrivyEvent(St,"signTypedData","onSuccess",{signature:e}),r({signature:e})},onFailure:e=>{ye.emitPrivyEvent(St,"signTypedData","onError",F.PrivyErrorCode.UNABLE_TO_SIGN),a(e)},uiOptions:t?.uiOptions||{}},{entropyId:n,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(s);wt({signMessage:e,connectWallet:{entropyId:n,entropyIdVerifier:i,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),sendTransaction:async(e,t)=>await er({transaction:e,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await er({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:e=>new Promise((async(t,r)=>{if(!Ae||!_e)return void r(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let a=e?.address??E.getPrivyEthereumWallet(_e)?.address;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`."));let{signingWallet:n,rootWallet:i}=E.getEthereumSigningAndRootWallet(_e,a);if(!n||!i)return void r(Error("Must have a Privy wallet before exporting"));yt(!0);let{entropyId:o,entropyIdVerifier:s}=E.getEntropyDetailsFromAccount(i),l={entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0};wt(pt),await et()&&lt?lt?(wt({keyExport:{appId:p.appId,appClientId:p.clientId,origin:w.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:r},connectWallet:l}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)):r(Error("Must have a Privy wallet before exporting")):r(Error("Must have valid access token to enroll in MFA"))})),promptMfa:rr,async init(e){switch(e){case"sms":return void await w.initMfaSmsVerification();case"passkey":return await w.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 F.PrivyClientError("Invalid MFA code");It.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{Wt.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new F.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),a=ae.transformResponseToSnakeCase(await r.startAuthentication(t));It.current?.resolve({mfaMethod:e,mfaCode:a,relyingParty:window.origin}),await new Promise(((e,t)=>{Wt.current={resolve:e,reject:t}}));break;default:throw It.current?.reject(new F.PrivyClientError("Unsupported MFA method")),new F.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){It.current?.reject(new F.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await et();if(!t||!lt)throw Error("Must have valid access token to enroll in MFA");await lt.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return lr.closePrivyModal(),void t();dt.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."),wt({mfaEnrollmentFlow:{mfaMethods:dt.mfa.methods,shouldUnlinkOnUnenrollMfa:dt.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),Mt(se.ModalScreen.MFA_ENROLLMENT_FLOW_SCREEN)})),async initEnrollmentWithTotp(){let e=await et();if(!e||!lt)throw Error("Must have valid access token to enroll in MFA");let t=await lt.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await et();if(!t||!lt)throw Error("Must have valid access token to enroll in MFA");await lt.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),Te(await w.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await et();if(!t||!lt)throw Error("Must have valid access token to enroll in MFA");await lt.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),Te(await w.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await et();if(!r||!lt)throw Error("Must have valid access token to enroll in MFA");await lt.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),Te(await w.getAuthenticatedUser())},async unenroll(e,t={}){let r=await et();if(!r||!lt)throw Error("Must have valid access token to remove MFA");"passkey"===e?await lt.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await lt.unenrollMfa({method:e,accessToken:r}),Te(await w.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await et(),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(!lt||!t)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");if(!await lr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");let r=await lt.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&Te(await w.getAuthenticatedUser()||_e||null),wt({farcasterSigner:r}),Mt(se.ModalScreen.AWAITING_FARCASTER_SIGNER)},getFarcasterSignerPublicKey:async()=>{let e,t=await et(),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(!lt||!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");if(!await lr.recoverPrimaryWallet())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 et(),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(!lt||!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");if(!await lr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!_e.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let a=await import("@simplewebauthn/browser"),n=await lt.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:a.bufferToBase64URLString(e)},fid:BigInt(_e.farcaster.fid),relyingParty:window.origin});return new Uint8Array(a.base64URLStringToBuffer(n.signature))},createGuestAccount:async()=>{if(_e&&!_e.isGuest)throw Error("User cannot already be authenticated to create a guest account");return _e?.isGuest?_e:lr.loginWithGuestAccountFlow()},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let a=_e?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return K.sendCrossAppRequest({user:_e,client:w,address:t,requesterAppId:dt.id,request:{method:a?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:or})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let a=_e?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),n=f.generateTypedDataWithDomainType(e);return K.sendCrossAppRequest({user:_e,client:w,address:t,requesterAppId:dt.id,request:{method:a?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,n],chainId:r},reconnect:or})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=_e?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return K.sendCrossAppRequest({user:_e,client:w,address:t,requesterAppId:dt.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:or})},isModalOpen:C,mfaMethods:dt.mfa.methods};ze=sr.signMessage,Ye=sr.signTypedData,Xe=async(e,t)=>await er({transaction:e,...t,signOnly:!1}),$e=async(e,t)=>({signature:(await er({transaction:e,...t,signOnly:!0})).hash});let lr={setAuthenticated:Pe,setUser:Te,isNewUserThisSession:Oe,pendingTransaction:null,walletConnectionStatus:Fe,connectors:w.connectors?.walletConnectors??[],solanaWallets:Se,rpcConfig:dt.rpcConfig,chains:dt.chains,appId:p.appId,showFiatPrices:"native-token"!==dt.embeddedWallets.priceDisplay.primary,clientAnalyticsId:w.clientAnalyticsId,customAuthStatus:_t,hideWalletUIs:bt,emailOtpState:Be,setEmailOtpState:He,smsOtpState:Ke,setSmsOtpState:tt,oAuthState:nt,setOAuthState:it,telegramAuthState:ot,setTelegramAuthState:st,siweState:rt,setSiweState:at,isHeadlessOAuthLoading:De,nativeTokenSymbolForChainId:e=>dt.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(lt)return lt;let t=new Promise((e=>{gt((()=>t=>e(t)))})),r=new Promise((t=>setTimeout((()=>t(null)),e))),a=await Promise.race([t,r]);return gt(null),a},getAuthFlow:()=>w.authFlow,getAuthMeta:()=>w.authFlow?.meta,client:w,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=P&&Ae&&_e;r&&Ut.current&&(t=ar(_e)),"login"===Ot.current?e.shouldCallAuthOnSuccess&&r&&Ut.current?ye.emitPrivyEvent(St,"login","onComplete",{user:_e,isNewUser:Oe,wasAlreadyAuthenticated:!1,loginMethod:Ut.current,loginAccount:t??null}):ye.emitPrivyEvent(St,"login","onError",F.PrivyErrorCode.USER_EXITED_AUTH_FLOW):"link"===Ot.current&&t?e.isSuccess&&r&&Ut.current?ye.emitPrivyEvent(St,"linkAccount","onSuccess",{user:_e,linkMethod:Ut.current,linkedAccount:t}):Ut.current&&ye.emitPrivyEvent(St,"linkAccount","onError",F.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:Ut.current}):"update"===Ot.current&&t&&(e.isSuccess&&r&&Ut.current?ye.emitPrivyEvent(St,"update","onSuccess",{user:_e,updateMethod:Ut.current,updatedAccount:t}):Ut.current&&ye.emitPrivyEvent(St,"update","onError",F.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:Ut.current}));let a=Re&&G.FUNDING_SCREENS.includes(Re),n=Re===se.ModalScreen.ERROR_SCREEN&&pt.errorModalData&&G.FUNDING_SCREENS.includes(pt.errorModalData.previousScreen);if((a||n)&&pt.funding){let e,t=G.fundingScreenMethodMap[Re]??null;if("solana"===pt.funding.chainType){let r=v(ie.SOLANA_FUNDING_PLUGIN_ID);if(!r)return void console.warn("Unable to load solana plugin, skipping balance");try{e=BigInt(await r.getBalance({address:pt.funding.address,cluster:pt.funding.cluster}))}catch{console.error("Unable to pull wallet balance")}ye.emitPrivyEvent(St,"fundSolanaWallet","onUserExited",{address:pt.funding.address,cluster:pt.funding.cluster,fundingMethod:t,balance:e})}else{let r=de.getPublicClient(pt.funding.chain.id,dt.chains,dt.rpcConfig,{appId:p.appId});try{e=await r.getBalance({address:pt.funding.address})}catch{console.error("Unable to pull wallet balance")}ye.emitPrivyEvent(St,"fundWallet","onUserExited",{address:pt.funding.address,chain:pt.funding.chain,fundingMethod:t,balance:e})}}wt({...pt,externalConnectWallet:{suggestedAddress:void 0}}),Ot.current=null,Ut.current=null,be(!1),A(!1),setTimeout((()=>{w.authFlow=void 0}),200),w.createAnalyticsEvent({eventName:"modal_closed"})},solanaSignMessage:({message:e,options:t})=>new Promise((async(r,a)=>{if(!Ae||!_e)return ye.emitPrivyEvent(St,"signSolanaMessage","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),void a(Error("User must be authenticated before signing with a Privy wallet"));let n=t?.address??E.getPrivySolanaWallet(_e)?.address;if(!n)throw new F.PrivyClientError("User must have an embedded wallet to sign a message.");let{signingWallet:i,rootWallet:o}=E.getSolanaSigningAndRootWallet(_e,n);if(!i||!o)return ye.emitPrivyEvent(St,"signSolanaMessage","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void a(Error("Must have a Privy wallet before signing"));if("string"!=typeof e||e.length<1)return ye.emitPrivyEvent(St,"signMessage","onError",F.PrivyErrorCode.INVALID_MESSAGE),void a(Error("Message must be a non-empty string"));yt(!0);let s=async()=>{if(!Ae)throw Error("User must be authenticated before signing with a Privy wallet");let t=await w.getAccessToken();if(!t)throw Error("User must be authenticated to use their embedded wallet.");let r=lr.walletProxy??await lr.initializeWalletProxy(15e3);if(!r)throw Error("Failed to initialize embedded wallet proxy.");if(!await lr.recoverPrimaryWallet())throw Error("Unable to connect to wallet");if(!o)throw Error("No root wallet for signing wallet found");let{entropyId:a,entropyIdVerifier:n}=E.getEntropyDetailsFromAccount(o),{response:s}=await r.rpc({accessToken:t,entropyId:a,entropyIdVerifier:n,chainType:"solana",hdWalletIndex:i.walletIndex??0,request:{method:"signMessage",params:{message:e}}});return s.data.signature};if(Rt({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await s();ye.emitPrivyEvent(St,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),r({signature:e})}catch(e){a(e)}else{let n={method:"solana_signMessage",data:e,confirmAndSign:s,onSuccess:e=>{ye.emitPrivyEvent(St,"signSolanaMessage","onSuccess",{signature:new Uint8Array(Buffer.from(e,"base64"))}),r({signature:e})},onFailure:e=>{a(e)},uiOptions:t?.uiOptions},{entropyId:i,entropyIdVerifier:l}=E.getEntropyDetailsFromAccount(o);wt({signMessage:n,connectWallet:{entropyId:i,entropyIdVerifier:l,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_SIGN_REQUEST_SCREEN,onFailure:e=>{ye.emitPrivyEvent(St,"signSolanaMessage","onError",F.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),a(e)}}}),Dt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)}})),signSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:a,address:n})=>{let i=n?Ne.find((e=>e.address===n)):Ne.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!i)throw ye.emitPrivyEvent(St,"signSolanaTransaction","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new F.PrivyClientError("Embedded wallet not found",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);let{signedTransaction:o}=await tr({transaction:e,connection:t,transactionOptions:a,uiOptions:r,wallet:i,signOnly:!0});return o},sendSolanaTransaction:async({transaction:e,connection:t,uiOptions:r,transactionOptions:a,fundWalletConfig:n,address:i})=>{let o=i?Ne.find((e=>e.address===i)):Ne.slice().sort(((e,t)=>(e.walletIndex??0)-(t.walletIndex??0)))[0];if(!o)throw ye.emitPrivyEvent(St,"sendSolanaTransaction","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),new F.PrivyClientError("Embedded wallet not found",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND);return await tr({transaction:e,connection:t,transactionOptions:a,uiOptions:r,fundWalletConfig:n,wallet:o,signOnly:!1})},openPrivyModal:Mt,connectWallet:jt,initLoginWithWallet:async(e,t,r)=>{N.isBaseConnectedEthereumWallet(e)?(Ut.current="siwe",Bt(e,t,r)):(Ut.current="siws",Ht(e,t,r))},loginWithWallet:async()=>{let e,t,r;if(!P)throw new F.PrivyNotReadyError;if(w.authFlow instanceof d.SiweFlow?e="siwe":w.authFlow instanceof u.SiwsFlow&&(e="siws"),!e)throw new F.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await w.getAccessToken())try{({user:t}=await w.link()),Ut.current=e}catch(t){throw ye.emitPrivyEvent(St,"linkAccount","onError",t.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await w.authenticate()),Ut.current=e}catch(e){throw ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}Te(t||_e||null),be(r||!1),Pe(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(a,n)=>{let i=await et();if(!Ae||!_e||!i)throw new F.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new F.PrivyClientError("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let o=lr.walletProxy??await lr.initializeWalletProxy(15e3);if(!o)throw new F.PrivyClientError("Wallet proxy not initialized.");if(M.isWalletDelegated({address:e,chainType:t,user:_e}))return a();let s=M.getDelegatedWalletsData({address:e,user:_e}),l=M.getRootWalletDataForDelegation({address:e,user:_e}),c=async()=>{await o.createDelegatedAction({accessToken:i,rootWallet:l,delegatedWallets:[s]}),await lr.refreshSessionAndUser()};if(!r){try{await c(),a()}catch(e){n(e)}return}await lr.recoverPrimaryWallet(),wt({delegatedActions:{consent:{address:e,onDelegate:c,onSuccess:async()=>{a()},onError:async e=>{n(e)}}}}),Mt(se.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_CONSENT_SCREEN)})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!Ae||!_e)throw new F.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");if(0===M.getDelegatedWalletsForUser(_e).length)throw new F.PrivyClientError("User has no delegated wallets to revoke.");let a=async()=>{await w.revokeDelegatedWallet(),await lr.refreshSessionAndUser()};if(e)wt({delegatedActions:{revoke:{onRevoke:a,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),Mt(se.ModalScreen.EMBEDDED_WALLET_DELEGATED_ACTIONS_REVOKE_SCREEN);else try{await a(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new s.FarcasterFlow(e,t);w.startAuthFlow(r);try{Ut.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===Ot.current?ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Ot.current&&ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!P)throw new F.PrivyNotReadyError;if(!(w.authFlow instanceof s.FarcasterFlow))throw new F.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await w.getAccessToken())try{({user:e}=await w.link()),Ut.current="farcaster"}catch(e){throw ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await w.authenticate()),Ut.current="farcaster"}catch(e){throw ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Te(e||null),be(t||!1),Pe(!0)},async loginWithGuestAccountFlow(){let e=new l.GuestFlow(this.appId);w.startAuthFlow(e);try{Ot.current="login",Ut.current="guest";let{user:e,isNewUser:t}=await w.authenticate();if(t=t||!1,!e)throw new F.PrivyClientError("Unable to authenticate guest account");let r=await et(),a=await lr.initializeWalletProxy(m.WALLET_PROXY_TIMEOUT);if(r&&a)try{let t=ee.shouldCreateEmbeddedEthWallet(e,dt.embeddedWallets.ethereum.createOnLogin),n=te.shouldCreateEmbeddedSolWallet(e,dt.embeddedWallets.solana.createOnLogin);if(t&&n){let t=await $t(e,m.WALLET_PROXY_TIMEOUT);await a.createSolana({accessToken:r,ethereumAddress:t?.address}),e=await lr.refreshSessionAndUser()}else n?(await a.createSolana({accessToken:r,ethereumAddress:E.getPrivyEthereumWallet(e)?.address}),e=await lr.refreshSessionAndUser()):t?(await $t(e,m.WALLET_PROXY_TIMEOUT),e=await lr.refreshSessionAndUser()):Te(e)}catch(t){Te(e),console.warn("Unable to create embedded wallet for guest account")}return be(t),Pe(!0),ye.emitPrivyEvent(St,"login","onComplete",{user:e,isNewUser:t,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),e}catch(e){throw ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async crossAppAuthFlow({appId:e,popup:t,action:r}){let a=`privy:${e}`;Ut.current=a;let{url:n,stateCode:i,codeVerifier:o}=await B.getCrossAppAuthorizationUrl({api:w.api,appId:e});if(!n)throw w.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new F.PrivyClientError("No authorization URL returned for cross-app auth.");try{let s=await H.popupCrossAppAuthFlow({url:n,popup:t,provider:a}),l=s.stateCode,c=s.authorizationCode;if(l!==i)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:a,storedStateCode:i??"",returnedStateCode:l??""}}),new F.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,F.PrivyErrorCode.OAUTH_UNEXPECTED);let d=await B.authenticateCrossAppAccount({appId:e,codeVerifier:o,stateCode:l,authorizationCode:c,action:r,client:w});d&&w.storeProviderAccessToken(e,d);let u=await lr.refreshSessionAndUser();if(!u)throw new F.PrivyClientError("Unable to update user");return w.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),u}catch(e){throw w.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:a}}),e}},async initLoginWithOAuth(e,t,r){if(Ut.current=e,!g.isLocalStorageAccessible())return void Dt(se.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);if("google"===e&&Y.default(window.navigator.userAgent))return void Dt(se.ModalScreen.IN_APP_BROWSER_LOGIN_NOT_POSSIBLE);"twitter"===e&&window.opener&&window.opener.postMessage({type:j.USE_BROADCAST_CHANNEL_EVENT_TYPE},"*"),g.default.del(m.HEADLESS_OAUTH_KEY),g.default.del(m.OAUTH_DISABLE_SIGNUP_KEY);let n=new fe.OAuthFlow({provider:e,disableSignup:!!r,withPrivyUi:!0});t&&n.addCaptchaToken(t),w.startAuthFlow(n);let i=await w.authFlow.getAuthorizationUrl();i&&i.url&&("twitter"===e&&a.isAndroid&&(i.url=i.url.replace("x.com","twitter.com")),window.location.assign(i.url))},async initLoginWithTelegram(e,t){if(!P)throw new F.PrivyNotReadyError;Ut.current="telegram";let r=new y.TelegramAuthFlow(e,t);w.startAuthFlow(r),st({status:"loading"}),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>dt.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:dt.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):t(new F.PrivyClientError("Telegram auth failed or was canceled by the client")))):t(new F.PrivyClientError("Telegram was not initialized")):t(new F.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(w.authFlow instanceof y.TelegramAuthFlow))throw new F.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");w.authFlow.meta.captchaToken||=e?.captchaToken;let a=await et(),n=e?.intent||Ot.current;if("login"===n)try{let e=await w.authenticate();t=e.user,r=e.isNewUser,Ut.current="telegram"}catch(e){throw ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==n)throw new F.PrivyClientError("Unknown auth intent");try{t=(await w.link()).user,Ut.current="telegram"}catch(e){throw ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}Te(t),be(r||!1),Pe(!0),st({status:"done"});let i=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,loginAccount:i}},async recoveryOAuthFlow(e,t,r){let a,n;function i(t){if(!t)throw w.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:e}}),new F.PrivyClientError("Recovery OAuth failed")}switch(e){case"google-drive":{let t,o,{url:s,codeVerifier:l,stateCode:c}=await V.getRecoveryAuthorizationUrl({api:Ge.api,provider:e});i(s);try{let a=await X.popupOAuthFlow({url:s,popup:r,provider:e});if(t=a.stateCode,o=a.authorizationCode,t!==c)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:c??"",returnedStateCode:t??""}}),new F.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,F.PrivyErrorCode.OAUTH_UNEXPECTED)}catch(t){throw w.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:e}}),new F.PrivyClientError("Recovery OAuth failed")}[a,n]=await Promise.all([et(),V.authenticateRecovery({api:Ge.api,provider:e,codeVerifier:l,stateCode:t,authorizationCode:o})]);break}case"icloud":{let{url:t}=await V.getRecoveryAuthorizationUrl({api:Ge.api,provider:e});i(t);let{ckWebAuthToken:o}=await X.popupOAuthFlow({url:t,popup:r,provider:e});n=o,a=await et()}}if(!lt)throw new F.PrivyClientError("Cannot connect to wallet proxy");if(!a)throw new F.PrivyClientError("Unable to authorize user");switch(t){case"recover":{let t=pt.recoverWallet?.entropyId,r=pt.recoverWallet?.entropyIdVerifier;if(!t||!r)throw new F.PrivyClientError("Recovery OAuth failed");w.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:t,recoveryMethod:e}}),await lt.recover({accessToken:a,entropyId:t,entropyIdVerifier:r,recoveryAccessToken:n}),w.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:t,recoveryMethod:e}});break}case"create-wallet":{w.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),await lt.create({accessToken:a,recoveryAccessToken:n,recoveryMethod:e});let t=E.getPrivyEthereumWallet(await lr.refreshSessionAndUser());if(!t)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.address}}),ye.emitPrivyEvent(St,"createWallet","onSuccess",{wallet:t});break}case"set-recovery":{let t=E.getPrivyPrimaryWallet(_e);if(!t)throw ye.emitPrivyEvent(St,"setWalletRecovery","onError",F.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");w.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}});let{entropyId:r,entropyIdVerifier:i}=E.getEntropyDetailsFromAccount(t);await lt.setRecovery({accessToken:a,entropyId:r,entropyIdVerifier:i,recoveryMethod:e,recoveryAccessToken:n});let o=E.getPrivyPrimaryWallet(await lr.refreshSessionAndUser());if(!o)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");w.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:t.address,existingRecoveryMethod:t.recoveryMethod,targetRecoveryMethod:e}}),ye.emitPrivyEvent(St,"setWalletRecovery","onSuccess",{method:e,wallet:o});break}default:throw new F.PrivyClientError("Unsupported recovery action")}},async loginWithOAuth(e){let t,r,a;if(!(w.authFlow instanceof fe.OAuthFlow))throw new F.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let n=g.default.get(m.STATE_CODE_KEY),i=w.authFlow.meta.stateCode;if(n!==i)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:n??"",returnedStateCode:i??""}}),new F.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,F.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await w.getAccessToken())try{let r=await w.link();t=r.user,a=r.oAuthTokens,Ut.current=e}catch(t){throw ye.emitPrivyEvent(St,"linkAccount","onError",t.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let n=await w.authenticate();t=n.user,r=n.isNewUser,a=n.oAuthTokens,Ut.current=e}catch(t){throw"login"===Ot.current?ye.emitPrivyEvent(St,"login","onError",t.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Ot.current&&ye.emitPrivyEvent(St,"linkAccount","onError",t.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return Te(t),be(r||!1),Pe(!0),a&&t&&ye.emitPrivyEvent(St,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),a},passkeyAuthState:qe,setPasskeyAuthState:je,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new c.PasskeyFlow({captchaToken:e,setPasskeyAuthState:je});w.startAuthFlow(r),Ot.current="login";try{Ut.current="passkey",je({status:"generating-challenge"}),await r.initRegisterFlow(t),je({status:"awaiting-passkey"})}catch(e){throw je({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!P)throw new F.PrivyNotReadyError;if(!(w.authFlow instanceof c.PasskeyFlow))throw new F.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Ut.current){let e=new F.PrivyClientError("Must init login with Passkey flow first.");throw je({status:"error",error:e}),e}let r=await et();try{Ut.current="passkey",je({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await w.authenticate())}catch(e){throw je({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Te(e),be(t||!1),Pe(!0),je({status:"done"});let a=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:a}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new c.PasskeyFlow({captchaToken:e,setPasskeyAuthState:je});w.startAuthFlow(r),Ot.current="login";try{Ut.current="passkey",je({status:"generating-challenge"}),await r.initAuthenticationFlow(t),je({status:"awaiting-passkey"})}catch(e){throw je({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,r;if(!P)throw new F.PrivyNotReadyError;if(!(w.authFlow instanceof c.PasskeyFlow))throw new F.PrivyClientError("Must initialize Passkey flow first.");if(e?.credentialIds&&(w.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==Ut.current){let e=new F.PrivyClientError("Must init login with Passkey flow first.");throw je({status:"error",error:e}),e}let a=await et();try{Ut.current="passkey",je({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await w.authenticate())}catch(e){throw je({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Te(t),be(r||!1),Pe(!0),je({status:"done"});let n=t?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,loginAccount:n}},async initLinkWithPasskey(e){let t=new c.PasskeyFlow({captchaToken:e});w.startAuthFlow(t),Ot.current="link",Ut.current="passkey",je({status:"generating-challenge"});try{await t.initLinkFlow(),je({status:"awaiting-passkey"})}catch(e){throw ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),je({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!P)throw new F.PrivyNotReadyError;if(!(w.authFlow instanceof c.PasskeyFlow))throw new F.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Ut.current)throw new F.PrivyClientError("Must init login with Passkey flow first.");try{Ut.current="passkey",({user:e}=await w.link())}catch(e){throw ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return Te(e||_e||null),je({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!g.isLocalStorageAccessible())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&&Y.default(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 a=new fe.OAuthFlow({provider:e,withPrivyUi:!1,disableSignup:r??!1});t&&a.addCaptchaToken(t),it({status:"loading"});let n=await w.startAuthFlow(a).getAuthorizationUrl();n?.url&&window.location.assign(n.url)},async loginWithHeadlessOAuth(e){let t,r,a;Le(!0),it({status:"loading"}),w.startAuthFlow(new fe.OAuthFlow(e));let n=g.default.get(m.STATE_CODE_KEY),i=e.stateCode;if(n!==i)throw w.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:n??"",returnedStateCode:i??""}}),Le(!1),new F.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,F.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await w.getAccessToken())try{({user:t,oAuthTokens:a}=await w.link()),Ut.current=e.provider;let r=ar(t);t&&r&&ye.emitPrivyEvent(St,"linkAccount","onSuccess",{user:t,linkMethod:Ut.current,linkedAccount:r})}catch(t){throw Le(!1),ye.emitPrivyEvent(St,"linkAccount","onError",t.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:a}=await w.authenticate()),Ut.current=e.provider;let n=ar(t);t&&n&&void 0!==r&&ye.emitPrivyEvent(St,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:Ut.current,loginAccount:n})}catch(e){throw Le(!1),it({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return Te(t),be(r||!1),Pe(!0),Le(!1),it({status:"done"}),a&&t&&ye.emitPrivyEvent(St,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:a,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{let n=new o.EmailFlow({email:e,captchaToken:t,disableSignup:r});w.startAuthFlow(n);try{Ut.current="email",He({status:"sending-code"}),await n.sendCodeEmail({withPrivyUi:a}),He({status:"awaiting-code-input"})}catch(e){throw He({status:"error",error:e}),"login"===Ot.current?ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Ot.current&&ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async(e,t,r)=>{let a=new o.UpdateEmailFlow(e,t,r);w.startAuthFlow(a);try{await a.sendCodeEmail({withPrivyUi:!0})}catch(e){ye.emitPrivyEvent(St,"update","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:Ut.current})}},initUpdatePhone:async(e,t,r)=>{let a=new h.UpdateSmsFlow(e,t,r);w.startAuthFlow(a);try{await a.sendSmsCode({withPrivyUi:!0})}catch(e){ye.emitPrivyEvent(St,"update","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:Ut.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:a})=>{tt({status:"sending-code"});let n=new h.SmsFlow({phoneNumber:e,captchaToken:t,disableSignup:r});w.startAuthFlow(n);try{Ut.current="sms",await n.sendSmsCode({withPrivyUi:a}),tt({status:"awaiting-code-input"})}catch(e){throw tt({status:"error",error:e}),"login"===Ot.current?ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===Ot.current&&ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(w.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(w.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function a(e){w.authFlow instanceof o.EmailFlow?He(e):w.authFlow instanceof h.SmsFlow&&tt(e)}if(a({status:"submitting-code"}),!P){let e=new F.PrivyNotReadyError;throw a({status:"error",error:e}),e}if(w.authFlow instanceof o.EmailFlow)w.authFlow.meta.emailCode=e.trim();else{if(!(w.authFlow instanceof h.SmsFlow)){let e=new F.PrivyClientError("Must initialize a passwordless code flow first");throw a({status:"error",error:e}),e}w.authFlow.meta.smsCode=e.trim()}let n=await et();if("link"===Ot.current)try{({user:t}=await w.link())}catch(e){throw a({status:"error",error:e}),ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:Ut.current}),e}else if("update"===Ot.current)try{({user:t}=await w.link())}catch(e){throw a({status:"error",error:e}),ye.emitPrivyEvent(St,"update","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:Ut.current}),e}else try{({user:t,isNewUser:r}=await w.authenticate())}catch(e){throw a({status:"error",error:e}),ye.emitPrivyEvent(St,"login","onError",e.privyErrorCode||F.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let i=t||_e;Te(i||null),be(r||!1),Pe(!0),a({status:"done"});let s=null;return w.authFlow instanceof o.EmailFlow?s=i?.linkedAccounts.find((({type:e})=>"email"===e))||null:w.authFlow instanceof h.SmsFlow&&(s=i?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:i,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,linkedAccount:s}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{Ot.current="link",Ut.current="siwe",at({status:"generating-message"});let a=await w.generateSiweNonce({address:e,captchaToken:r});return at({status:"awaiting-signature"}),J.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:a})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await w.generateSiweNonce({address:e});return J.prepareSiweMessageWithNonce({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r})=>{let a;a=await w.linkSmartWallet({message:e,signature:t,smartWalletType:r}),Te((a=await lr.refreshSessionAndUser()??a)||_e||null)},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n})=>{let i;Vt("siwe");let o=null;try{at({status:"submitting-signature"}),i=await w.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:a,connectorType:n}),i=await lr.refreshSessionAndUser()??i,at({status:"done"}),(o=ar(i)||null)&&ye.emitPrivyEvent(St,"linkAccount","onSuccess",{user:i,linkMethod:"siwe",linkedAccount:o})}catch(e){throw ye.emitPrivyEvent(St,"linkAccount","onError",e.privyErrorCode||F.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),Ot.current=null,Ut.current=null,at({status:"error",error:e}),e}let s=i||_e;return Te(s||null),Ot.current=null,Ut.current=null,{user:s,linkedAccount:o}},refreshSessionAndUser:async()=>{let e=await w.getAuthenticatedUser();return Pe(!!e),Te(e),e},walletProxy:lt,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>w.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await w.acceptTerms();return Te(e),e},getUsdTokenPrice:e=>w.getUsdTokenPrice(e),getUsdPriceForSol:()=>w.getUsdPriceForSol(),getSplTokenMetadata:e=>w.getSplTokenMetadata(e),recoverPrimaryWallet:async e=>new Promise((async(t,r)=>{let a=E.getPrivyPrimaryWallet(e?.user??_e)||E.getImportedPrivyEthereumWallet(e?.user??_e)||E.getImportedPrivySolanaWallet(e?.user??_e);a||t(!0);let n=await et();if(!n||!lt||!a)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));yt(!0);let{entropyId:i,entropyIdVerifier:o}=E.getEntropyDetailsFromAccount(a);try{await lt.connect({accessToken:n,entropyId:i,entropyIdVerifier:o}),t(!0)}catch(e){D.errorIndicatesRecoveryIsNeeded(e)&&"privy"===a.recoveryMethod?(w.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:a.address}}),(await lt.recover({entropyId:i,entropyIdVerifier:o,accessToken:n})).entropyId||r(Error("Unable to recover wallet")),w.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:a.address}}),t(!0)):D.errorIndicatesRecoveryIsNeeded(e)&&"privy"!==a.recoveryMethod?(wt({recoverWallet:{entropyId:i,entropyIdVerifier:o,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:a.recoveryMethod,action:"recover"}}),Mt(V.embeddedWalletRecoveryScreen(a.recoveryMethod))):r(e)}})),embeddedSolanaWallets:Ne,createEmbeddedSolanaWallet:async e=>{e&&"target"in e&&(e=void 0);let t=await lr.refreshSessionAndUser();if(!t)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before creating a Privy wallet");return(async(e,t,r)=>{let a=E.getPrivyEthereumWallet(e),n=E.getPrivySolanaWallet(e),i=r&&"createAdditional"in r&&r.createAdditional,o=r&&"walletIndex"in r?r.walletIndex:void 0,s=(E.getLatestPrivySolanaWallet(e)?.walletIndex??-1)+1;if(n&&!i&&"number"!=typeof o)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_ALREADY_EXISTS),Error("User already has an embedded wallet.");if("number"==typeof o&&o<0)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.EMBEDDED_WALLET_CREATE_ERROR),Error(`A negative walletIndex (${o}) is invalid.`);let[l,c]=await Promise.all([lr.initializeWalletProxy(t),et()]);if(!l||!c)throw ye.emitPrivyEvent(St,"createWallet","onError",F.PrivyErrorCode.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to connect to wallet proxy");return await Qt({user:e,wp:l,accessToken:c,walletIndex:o??s,ethereumWallet:a})})(t,15e3,e)},exportSolanaWallet:e=>new Promise((async(t,r)=>{if(!Ae||!_e)return void r(Error("User must be authenticated before exporting their Privy wallet"));let a=e?.address??E.getPrivySolanaWallet(_e)?.address;if(!a)return void r(Error("User does not have an HD Solana wallet."));let{signingWallet:n,rootWallet:i}=E.getSolanaSigningAndRootWallet(_e,a);if(!n||!i)return void r(Error("Must have a Privy wallet before exporting"));if(yt(!0),!await et()||!lt)return void r(Error("Must have valid access token to enroll in MFA"));if(!lt)return void r(Error("Must have a Privy wallet before exporting"));let{entropyId:o,entropyIdVerifier:s}=E.getEntropyDetailsFromAccount(i);wt({connectWallet:{entropyId:o,entropyIdVerifier:s,onCompleteNavigateTo:se.ModalScreen.EMBEDDED_WALLET_KEY_EXPORT_SCREEN,onFailure:r,shouldForceMFA:!0},keyExport:{appId:p.appId,appClientId:p.clientId,origin:w.apiUrl,walletToExport:n,primaryWallet:i,onSuccess:t,onFailure:r}}),Mt(se.ModalScreen.EMBEDDED_WALLET_CONNECTING_SCREEN)})),setReadyToTrue:e=>{Ce(!0),Et?.(e)},updateWallets:()=>Yt(),fundWallet:async(e,t)=>{let r=se.ModalScreen.FUNDING_METHOD_SELECTION_SCREEN;wt({funding:me.prepareFundingModalData({address:e,appConfig:dt,fundWalletConfig:t,methodScreen:r})}),Mt(r)},openModal:Mt,requestFarcasterSignerStatus:async e=>{let t=await et(),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(!lt||!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 a=await w.requestFarcasterSignerStatus(e);return"approved"===a.status&&Te(await w.getAuthenticatedUser()||_e||null),a},connectCoinbaseSmartWallet:async()=>{dt.externalWallets.coinbaseWallet.connectionOptions="smartWalletOnly";let e=w.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||w.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),jt(e);await qt("coinbase_wallet","coinbase_smart_wallet")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s})=>{let l=await w.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:a,telegramAuthResult:n,telegramWebAppData:i,farcasterEmbeddedAddress:o,oAuthUserInfo:s});return Te(l),l}};Je=lr.recoverPrimaryWallet,Qe=lr.recoverPrimaryWallet,Ze=lr.solanaSignMessage;let cr=r.useMemo((()=>({wallets:Ie,ready:ft&&kt})),[Ie,ft,kt]),dr=w.authFlow instanceof y.TelegramAuthFlow,ur=!dt.headless&&dt.captchaEnabled&&!Ae&&(P||dr);/*#__PURE__*/return e.jsx(Ee.PrivyContext.Provider,{value:sr,children:/*#__PURE__*/e.jsx(ye.PrivyEventsContext.Provider,{value:St,children:/*#__PURE__*/e.jsx(ve.UseWalletsContext.Provider,{value:cr,children:/*#__PURE__*/e.jsx(he.CaptchaProvider,{...dt,children:/*#__PURE__*/e.jsxs(pe.InternalPrivyContext.Provider,{value:lr,children:[/*#__PURE__*/e.jsx(oe.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(we.ModalProvider,{data:pt,setModalData:wt,setInitialScreen:Me,initialScreen:Re,authenticated:Ae,open:C,children:[p.children,ur&&/*#__PURE__*/e.jsx(_.Captcha,{delayedExecution:!1}),/*#__PURE__*/e.jsx(ce.GlobalStyle,{theme:{...dt.appearance.palette||{}}}),!dt.render.standalone&&/*#__PURE__*/e.jsx(T.LoginModal,{open:C})]})}),ht&&ut?/*#__PURE__*/e.jsx(R.EmbeddedWalletIframe,{appId:p.appId,appClientId:p.clientId,clientAnalyticsId:w.clientAnalyticsId,origin:w.apiUrl,mfaMethods:_e?.mfaMethods,mfaPromise:It,mfaSubmitPromise:Wt,onLoad:ct,onLoadFailed:()=>null}):null,dt.loginConfig.telegramAuthConfiguration&&
2
2
  /*#__PURE__*/e.jsx(le.Hide,{$if:!0,children:/*#__PURE__*/e.jsx(I.TelegramLoginButton,{scriptHost:p.apiUrl||m.DEFAULT_PRIVY_API_URL,botUsername:dt.loginConfig.telegramAuthConfiguration.botName})})]})})})})})};exports.ConnectorManager=xe,exports.Embedded1193Provider=Fe,exports.EmbeddedSolanaProvider=Ve,exports.PrivyClient=He,exports.PrivyProvider=({config:t,...r})=>{var a;if("undefined"!=typeof window&&0>["localhost","127.0.0.1"].indexOf(window.location.hostname)&&"https:"!==window.location.protocol)throw new F.PrivyClientError("Embedded wallet is only available over HTTPS");if("string"!=typeof(a=r.appId)||25!==a.length)throw new F.PrivyClientError("Cannot initialize the Privy provider with an invalid Privy app ID");Ge||(Ge=new He({appId:r.appId,appClientId:r.clientId,apiUrl:r.apiUrl}));let n=Object.assign({},t);/*#__PURE__*/
3
3
  return e.jsx(W.PrivyAppConfigProvider,{client:Ge,clientConfig:n,children:/*#__PURE__*/e.jsx(ne.PrivyPluginProvider,{children:/*#__PURE__*/e.jsx(lt,{...r,client:Ge})})})},exports.getAccessToken=et,exports.getCustomerAccessToken=function(){return Ge?Ge.getCustomerAccessToken():Promise.resolve(g.default.get(m.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.globalRecoverEthereumModal=it,exports.globalRecoverSolanaModal=ot,exports.globalSignMessageModal=tt,exports.globalSignSolanaModal=st,exports.globalSignTransactionModal=at,exports.globalSignTypedDataModal=rt,exports.globalTransactModal=nt;