@privy-io/react-auth 2.4.0 → 2.4.1

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