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