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