@privy-io/react-auth 3.7.0 → 3.8.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/AccountNotFoundScreen-jSbfPu_e.js +1 -0
- package/dist/cjs/Address-CZQd_MIA.js +1 -0
- package/dist/cjs/AffirmativeConsentScreen-7a4hl59A.js +1 -0
- package/dist/cjs/AllowlistRejectionScreen-B6roj0JU.js +1 -0
- package/dist/cjs/AuthenticateWithWalletScreen-BcBapHrq.js +1 -0
- package/dist/cjs/AwaitingEvmToSolBridgingScreen-D1Xd83Hp.js +2 -0
- package/dist/cjs/AwaitingExternalEthereumTransferScreen-COL0WYkT.js +2 -0
- package/dist/cjs/AwaitingPasswordlessCodeScreen-Cx5fqGf6.js +1 -0
- package/dist/cjs/AwaitingSolToEvmBridgingScreen-DYS3lDs0.js +2 -0
- package/dist/cjs/BridgeNetworkSelectionView-uivzU_Y9.js +1 -0
- package/dist/cjs/Button-nXApC2Jy.js +2 -0
- package/dist/cjs/CaptchaScreen-025syTLo.js +1 -0
- package/dist/cjs/Checkbox-DXPQZFlQ.js +1 -0
- package/dist/cjs/Chip-ChrHHazc.js +1 -0
- package/dist/cjs/CoinbaseOnrampStatusScreen-ORl8wt4H.js +1 -0
- package/dist/cjs/Column-C2bAbJE0.js +1 -0
- package/dist/cjs/ConnectEmailForm-BEv-7qU9.js +1 -0
- package/dist/cjs/ConnectLedgerScreen-DBYExlWR.js +1 -0
- package/dist/cjs/ConnectOnlyLandingScreen-bOhkl0xJ.js +1 -0
- package/dist/cjs/ConnectOnlyStatusScreen-DvTrLHyY.js +1 -0
- package/dist/cjs/ConnectOrCreateScreen-Dh4EFU5N.js +1 -0
- package/dist/cjs/ConnectPhoneForm-DK-bg2D5.js +1 -0
- package/dist/cjs/ConnectWalletView-4vj7Sq7-.js +1 -0
- package/dist/cjs/ConnectionStatusScreen-Ct-KTCXS.js +1 -0
- package/dist/cjs/CopyToClipboard-fd8Z3kQX.js +1 -0
- package/dist/cjs/CrossAppAuthScreen-B-DtA7IH.js +1 -0
- package/dist/cjs/CustomLandingScreenView-tt_NEfU6.js +2 -0
- package/dist/cjs/DelegatedActionsConsentScreen-B5WlYn7z.js +1 -0
- package/dist/cjs/DelegatedActionsRevokeScreen-2g_ydX-Y.js +1 -0
- package/dist/cjs/EmailInputForm-tjrhBacA.js +1 -0
- package/dist/cjs/EmbeddedWalletConnectingScreen-9seYvsTF.js +1 -0
- package/dist/cjs/EmbeddedWalletCreatedScreen-PycFyIz6.js +1 -0
- package/dist/cjs/EmbeddedWalletKeyExportScreen-BDTDQY1f.js +2 -0
- package/dist/cjs/EmbeddedWalletOnAccountCreateScreen-B0tXEtG9.js +1 -0
- package/dist/cjs/EmbeddedWalletPasswordUpdateScreen-ZfgU86hx.js +1 -0
- package/dist/cjs/EmbeddedWalletPasswordUpdateSplashScreen-tP8rSVUL.js +1 -0
- package/dist/cjs/EnrollTotp-DZ5fIrXr.js +1 -0
- package/dist/cjs/ErrorBanner-CMjaobRI.js +1 -0
- package/dist/cjs/ErrorMessage-f0cRWc29.js +1 -0
- package/dist/cjs/ErrorScreen-Cob9AO30.js +1 -0
- package/dist/cjs/FarcasterConnectStatusScreen-C5FoWA6N.js +2 -0
- package/dist/cjs/FarcasterSignerStatusScreen-CDYkqsxz.js +2 -0
- package/dist/cjs/FundSolWalletWithExternalSolanaWallet-DC_xoE6W.js +2 -0
- package/dist/cjs/FundWalletMethodHeader-zYWhBIiS.js +1 -0
- package/dist/cjs/FundingEditAmountScreen-BB7-k00c.js +1 -0
- package/dist/cjs/FundingMethodSelectionScreen-BrV94GD2.js +1 -0
- package/dist/cjs/InAppBrowserLoginNotPossible-y8g07-kU.js +1 -0
- package/dist/cjs/InfoBanner-CTx1eRnV.js +1 -0
- package/dist/cjs/InjectedWalletIcon-UY3nMvZo.js +1 -0
- package/dist/cjs/InstallWalletScreen-CmGi6mS1.js +1 -0
- package/dist/cjs/JsonTree-xaeo0q6z.js +1 -0
- package/dist/cjs/LabelXs-CYMv6rOZ.js +1 -0
- package/dist/cjs/LandingScreen-B9jb8n_d.js +1 -0
- package/dist/cjs/Layouts-dRL0OSpp.js +1 -0
- package/dist/cjs/Link-DmzPZ_M7.js +1 -0
- package/dist/cjs/LinkConflictScreen-BJXyOu2J.js +1 -0
- package/dist/cjs/LinkEmailScreen-zyJFrvy-.js +1 -0
- package/dist/cjs/LinkPasskeyScreen-Bw7Xs741.js +1 -0
- package/dist/cjs/LinkPhoneScreen-C4JQblY3.js +1 -0
- package/dist/cjs/LoadingSkeleton-DoCrfGnl.js +1 -0
- package/dist/cjs/LoginFailedScreen-CGT-2B2h.js +1 -0
- package/dist/cjs/ManualTransferScreen-DPz98CSt.js +1 -0
- package/dist/cjs/MfaAuthEnrollmentFlowScreen-BBKMKDGR.js +1 -0
- package/dist/cjs/MfaAuthVerifyFlowScreen-3LKUo_xV.js +1 -0
- package/dist/cjs/MfaEnrollmentFlowScreen-B2YgNRCC.js +1 -0
- package/dist/cjs/MfaVerifyFlowScreen-BhVqkM2f.js +1 -0
- package/dist/cjs/ModalHeader-DbV81e3m.js +3 -0
- package/dist/cjs/MoonpayStatusScreen-yghPhz7v.js +1 -0
- package/dist/cjs/NetworkIcon-BZ9Mj6vV.js +1 -0
- package/dist/cjs/OAuthStatusScreen-q9MFItPT.js +1 -0
- package/dist/cjs/OpenLink-BpCUf9iR.js +1 -0
- package/dist/cjs/PasskeySelectSignupOrLogin-BKBH0QxK.js +1 -0
- package/dist/cjs/PasskeyStatusScreen-DVx4lzwq.js +1 -0
- package/dist/cjs/PasswordRecoveryScreen-BmGdXVfh.js +1 -0
- package/dist/cjs/PinInput-DSI6rjOn.js +1 -0
- package/dist/cjs/QrCode-Ua_0cVUP.js +2 -0
- package/dist/cjs/RecoveryOAuthStatusScreen-DUobwBXF.js +1 -0
- package/dist/cjs/RecoveryPasswordCreateScreen-vQG4ErlF.js +1 -0
- package/dist/cjs/RecoverySelectionScreen-E2l_NO8y.js +1 -0
- package/dist/cjs/Row-CxDF-VMy.js +1 -0
- package/dist/cjs/Screen-65eQbiHD.js +9 -0
- package/dist/cjs/ScreenHeader-CyURV6Ti.js +2 -0
- package/dist/cjs/ScreenLayout-B_60rKhZ.js +1 -0
- package/dist/cjs/SetAutomaticRecoveryScreen-DQolobOz.js +1 -0
- package/dist/cjs/SetWalletPasswordForm-8g-lawop.js +2 -0
- package/dist/cjs/SignRequestScreen-BAgmmVVW.js +1 -0
- package/dist/cjs/StackedContainer-ByB6Mdu0.js +1 -0
- package/dist/cjs/StandardSignAndSendTransactionScreen-BUB57iWU.js +1 -0
- package/dist/cjs/Subtitle-Dtmrw8l5.js +1 -0
- package/dist/cjs/TelegramAuthScreen-D5uhx6WN.js +1 -0
- package/dist/cjs/Title-C-tHJvrb.js +1 -0
- package/dist/cjs/TodoList-Cm_a93ef.js +2 -0
- package/dist/cjs/TransactionDetails-BefABtVQ.js +3 -0
- package/dist/cjs/TransactionErrorView-QKWh4urc.js +2 -0
- package/dist/cjs/TransferFromWalletScreen-C_0IpL-A.js +1 -0
- package/dist/cjs/TransferOrBridgeLoadingScreen-C6t1_cTP.js +1 -0
- package/dist/cjs/UpdateEmailScreen-BUAgWudx.js +1 -0
- package/dist/cjs/UpdatePhoneScreen-DefnuTEZ.js +1 -0
- package/dist/cjs/UserLimitReachedScreen-B76r_-LC.js +1 -0
- package/dist/cjs/Value-C-XtZyFa.js +1 -0
- package/dist/cjs/WalletButtonList-bICzXZXM.js +1 -0
- package/dist/cjs/WalletCards-BfpeHH5n.js +1 -0
- package/dist/cjs/WalletInfoCard-CscdnrUV.js +1 -0
- package/dist/cjs/WalletInterstitialScreen-CG1k3EvV.js +1 -0
- package/dist/cjs/WalletLink-DF6dDjkz.js +3 -0
- package/dist/cjs/WarningBanner-B_Gs_15p.js +1 -0
- package/dist/cjs/abstract-smart-wallets.js +1 -1
- package/dist/cjs/analytics-C6C_4JmG.js +1 -0
- package/dist/cjs/capitalizeFirstLetter-D-K8mqBm.js +1 -0
- package/dist/cjs/context-JUEgi5-6.js +1 -0
- package/dist/cjs/copy-BiZ7dtqy.js +1 -0
- package/dist/cjs/ethers-uj8IknV_.js +1 -0
- package/dist/cjs/events-context-Di6--rDg.js +1 -0
- package/dist/cjs/extended-chains.js +1 -1
- package/dist/cjs/farcaster-CWHXGAib.js +1 -0
- package/dist/cjs/farcaster.js +1 -1
- package/dist/cjs/formatErc20TokenAmount-DxwoWe7e.js +1 -0
- package/dist/cjs/frame-bPqBJ8fS.js +1 -0
- package/dist/cjs/get-is-unified-wallet-DmiciSes.js +1 -0
- package/dist/cjs/getChainName-C4rO8-3n.js +1 -0
- package/dist/cjs/getErc20Balance-BZ5-OGfD.js +1 -0
- package/dist/cjs/getErc20TokenInfo-HX7DgcWx.js +1 -0
- package/dist/cjs/getFormattedUsdFromLamports-Mu2fqwL2.js +1 -0
- package/dist/cjs/getPublicClient-EjAv8R2z.js +1 -0
- package/dist/cjs/getUsdcMintAddress-REYZSOb9.js +1 -0
- package/dist/cjs/index-BNNk54gK.js +1 -0
- package/dist/cjs/index-CRFXS9pP.js +1 -0
- package/dist/cjs/index-Cuv6j_Y0.js +1 -0
- package/dist/cjs/index-DvDeCr_m.js +5 -0
- package/dist/cjs/index.js +1 -6
- package/dist/cjs/internal-context-VDPFkIXN.js +1 -0
- package/dist/cjs/internal.js +1 -1
- package/dist/cjs/paths-DizMb-lU.js +1 -0
- package/dist/cjs/prepareFundingModalData-BVlyr8l5.js +1 -0
- package/dist/cjs/reservoir-3I-Vkf2B.js +1 -0
- package/dist/cjs/shared-BPGwTh8c.js +1 -0
- package/dist/cjs/shared-CT5ocsPG.js +1 -0
- package/dist/cjs/shouldProceedtoEmbeddedWalletCreationFlow-DcjqezwI.js +1 -0
- package/dist/cjs/smart-wallets-B7vHjGAW.js +1 -0
- package/dist/cjs/smart-wallets.js +1 -1
- package/dist/cjs/solana.js +1 -1
- package/dist/cjs/styles-Ca_DS00a.js +1 -0
- package/dist/cjs/styles-D4VeJNv1.js +1 -0
- package/dist/cjs/telegram-D3O0_F1a.js +1 -0
- package/dist/cjs/to-ui-error-a-xwbRKZ.js +1 -0
- package/dist/cjs/transaction-DjF5X-by.js +1 -0
- package/dist/cjs/transfer-Cit146vy.js +1 -0
- package/dist/cjs/twitch-BNvhZb2Y.js +1 -0
- package/dist/cjs/twitter-BVVRWkcG.js +1 -0
- package/dist/cjs/ui.js +2 -2
- package/dist/cjs/use-create-wallet-without-fallback-DSOJS4h0.js +1 -0
- package/dist/cjs/use-export-wallet-BRFTskbr.js +1 -0
- package/dist/cjs/{use-sign-with-user-signer-BtJVKMQr.js → use-sign-with-user-signer-On9f1Fag.js} +1 -1
- package/dist/cjs/useActiveWallet-DcxqWAsq.js +1 -0
- package/dist/cjs/useGetSolPrice-eOpcFeNE.js +1 -0
- package/dist/cjs/useGetTokenPrice-EcT0H5rf.js +1 -0
- package/dist/cjs/useI18n-hYSvbQCq.js +1 -0
- package/dist/cjs/usePrivy-CXPeoT5g.js +1 -0
- package/dist/cjs/useSolanaRpcClient-mfV88iJm.js +1 -0
- package/dist/cjs/useWalletBalance-CQAgfkRc.js +1 -0
- package/dist/cjs/useWallets-TxPVNWGS.js +1 -0
- package/dist/cjs/useWallets-h2xCj02C.js +1 -0
- package/dist/dts/{events-context-CCElA92Y.d.mts → events-context-CkFXl3uc.d.mts} +1 -1
- package/dist/dts/{events-context-CCElA92Y.d.ts → events-context-CkFXl3uc.d.ts} +1 -1
- package/dist/dts/extended-chains.d.mts +1 -1
- package/dist/dts/extended-chains.d.ts +1 -1
- package/dist/dts/farcaster.d.mts +1 -1
- package/dist/dts/farcaster.d.ts +1 -1
- package/dist/dts/index.d.mts +11 -9
- package/dist/dts/index.d.ts +11 -9
- package/dist/dts/internal.d.mts +1 -1
- package/dist/dts/internal.d.ts +1 -1
- package/dist/dts/smart-wallets.d.mts +1 -1
- package/dist/dts/smart-wallets.d.ts +1 -1
- package/dist/dts/solana.d.mts +3 -3
- package/dist/dts/solana.d.ts +3 -3
- package/dist/dts/ui.d.mts +1 -1
- package/dist/dts/ui.d.ts +1 -1
- package/dist/esm/AccountNotFoundScreen-CmhSsknC.mjs +1 -0
- package/dist/esm/Address-DtXA0OPS.mjs +1 -0
- package/dist/esm/AffirmativeConsentScreen-C6AcYU94.mjs +1 -0
- package/dist/esm/AllowlistRejectionScreen-BuH5iBJ3.mjs +1 -0
- package/dist/esm/AuthenticateWithWalletScreen-CKJqrLEm.mjs +1 -0
- package/dist/esm/AwaitingEvmToSolBridgingScreen-DuO5iRV2.mjs +2 -0
- package/dist/esm/AwaitingExternalEthereumTransferScreen-C50_Dj-N.mjs +2 -0
- package/dist/esm/AwaitingPasswordlessCodeScreen-Bb0UxW46.mjs +1 -0
- package/dist/esm/AwaitingSolToEvmBridgingScreen-YsM6M4T9.mjs +2 -0
- package/dist/esm/BridgeNetworkSelectionView-Bu0vi9_a.mjs +1 -0
- package/dist/esm/Button-DJ-mtuuD.mjs +2 -0
- package/dist/esm/CaptchaScreen-CWQAXaCK.mjs +1 -0
- package/dist/esm/Checkbox-NmGCZeKL.mjs +1 -0
- package/dist/esm/Chip-Bsgj4Yc-.mjs +1 -0
- package/dist/esm/CoinbaseOnrampStatusScreen-NdySyA5D.mjs +1 -0
- package/dist/esm/Column-DQ5Vw9t1.mjs +1 -0
- package/dist/esm/ConnectEmailForm-DUgOCS2V.mjs +1 -0
- package/dist/esm/ConnectLedgerScreen-3wp1wuP2.mjs +1 -0
- package/dist/esm/ConnectOnlyLandingScreen-BVkcUaO6.mjs +1 -0
- package/dist/esm/ConnectOnlyStatusScreen-CyT_IEgy.mjs +1 -0
- package/dist/esm/ConnectOrCreateScreen-BlIxCxVJ.mjs +1 -0
- package/dist/esm/ConnectPhoneForm-CbuSfwAI.mjs +1 -0
- package/dist/esm/ConnectWalletView-DVDOSzi0.mjs +1 -0
- package/dist/esm/ConnectionStatusScreen-DNdZyKcL.mjs +1 -0
- package/dist/esm/CopyToClipboard-DatKc59_.mjs +1 -0
- package/dist/esm/CrossAppAuthScreen-DEF_slEx.mjs +1 -0
- package/dist/esm/CustomLandingScreenView-DWt9lv8W.mjs +2 -0
- package/dist/esm/DelegatedActionsConsentScreen-DqeBCJkz.mjs +1 -0
- package/dist/esm/DelegatedActionsRevokeScreen-B-xLCB1j.mjs +1 -0
- package/dist/esm/EmailInputForm-B4hjCxRU.mjs +1 -0
- package/dist/esm/EmbeddedWalletConnectingScreen-BCg7qeI6.mjs +1 -0
- package/dist/esm/EmbeddedWalletCreatedScreen-jGepSDyo.mjs +1 -0
- package/dist/esm/EmbeddedWalletKeyExportScreen-DX22sVNh.mjs +2 -0
- package/dist/esm/EmbeddedWalletOnAccountCreateScreen-hkifQ988.mjs +1 -0
- package/dist/esm/EmbeddedWalletPasswordUpdateScreen-CezgHp88.mjs +1 -0
- package/dist/esm/EmbeddedWalletPasswordUpdateSplashScreen-BFamfPb_.mjs +1 -0
- package/dist/esm/EnrollTotp-BzAm1Ya4.mjs +1 -0
- package/dist/esm/ErrorBanner-BdiArMwu.mjs +1 -0
- package/dist/esm/ErrorMessage-Cx8GKGhL.mjs +1 -0
- package/dist/esm/ErrorScreen-DFAo4S7A.mjs +1 -0
- package/dist/esm/FarcasterConnectStatusScreen-Ys1uAk-s.mjs +1 -0
- package/dist/esm/FarcasterSignerStatusScreen-DIfmv7Ft.mjs +1 -0
- package/dist/esm/FundSolWalletWithExternalSolanaWallet-CkEgl8wO.mjs +1 -0
- package/dist/esm/FundWalletMethodHeader-CbTaIDLQ.mjs +1 -0
- package/dist/esm/FundingEditAmountScreen-Cz4tmsMX.mjs +1 -0
- package/dist/esm/FundingMethodSelectionScreen-fBauGI0K.mjs +1 -0
- package/dist/esm/InAppBrowserLoginNotPossible-DBhsoAkw.mjs +1 -0
- package/dist/esm/InfoBanner-D6C6Bt8L.mjs +1 -0
- package/dist/esm/InjectedWalletIcon-DLcYOGDj.mjs +1 -0
- package/dist/esm/InstallWalletScreen-CEcl2LHj.mjs +1 -0
- package/dist/esm/JsonTree-Bvd2C29R.mjs +1 -0
- package/dist/esm/LabelXs-BOisBtqT.mjs +1 -0
- package/dist/esm/LandingScreen-BvRIrtFN.mjs +1 -0
- package/dist/esm/Layouts-Bmf8DxNP.mjs +1 -0
- package/dist/esm/Link-DwjLfHwW.mjs +1 -0
- package/dist/esm/LinkConflictScreen-Bg9QTrJX.mjs +1 -0
- package/dist/esm/LinkEmailScreen-SlCMvM43.mjs +1 -0
- package/dist/esm/LinkPasskeyScreen-CNFL2N09.mjs +1 -0
- package/dist/esm/LinkPhoneScreen-DnPAvact.mjs +1 -0
- package/dist/esm/LoadingSkeleton-CHdaq3pb.mjs +1 -0
- package/dist/esm/LoginFailedScreen-CkxfR75o.mjs +1 -0
- package/dist/esm/ManualTransferScreen-px_MUbVh.mjs +1 -0
- package/dist/esm/MfaAuthEnrollmentFlowScreen-RbHifi_a.mjs +1 -0
- package/dist/esm/MfaAuthVerifyFlowScreen-B3SIiFnH.mjs +1 -0
- package/dist/esm/MfaEnrollmentFlowScreen-LgmZFVEZ.mjs +1 -0
- package/dist/esm/MfaVerifyFlowScreen-DZkVptvz.mjs +1 -0
- package/dist/esm/ModalHeader-D7WajfD8.mjs +3 -0
- package/dist/esm/MoonpayStatusScreen-CBc4DLDR.mjs +1 -0
- package/dist/esm/NetworkIcon-B48ilzF8.mjs +1 -0
- package/dist/esm/OAuthStatusScreen-DvD84FHd.mjs +1 -0
- package/dist/esm/OpenLink-BpeNYBKs.mjs +1 -0
- package/dist/esm/PasskeySelectSignupOrLogin-DZP4Hj5r.mjs +1 -0
- package/dist/esm/PasskeyStatusScreen-bP3yfXNt.mjs +1 -0
- package/dist/esm/PasswordRecoveryScreen-Bt_Cf8-l.mjs +1 -0
- package/dist/esm/PinInput-C3_MNxMt.mjs +1 -0
- package/dist/esm/QrCode-zzqjquVm.mjs +2 -0
- package/dist/esm/RecoveryOAuthStatusScreen-y6_gmb9s.mjs +1 -0
- package/dist/esm/RecoveryPasswordCreateScreen-CloUjFKm.mjs +1 -0
- package/dist/esm/RecoverySelectionScreen-FxCwz-PR.mjs +1 -0
- package/dist/esm/Row-CG0lSY5Z.mjs +1 -0
- package/dist/esm/Screen-dwi2CitY.mjs +8 -0
- package/dist/esm/ScreenHeader-Biz1wq02.mjs +2 -0
- package/dist/esm/ScreenLayout-Dmrhdwtt.mjs +1 -0
- package/dist/esm/SetAutomaticRecoveryScreen-Db5Xg_sQ.mjs +1 -0
- package/dist/esm/SetWalletPasswordForm-ZtRqoZYj.mjs +2 -0
- package/dist/esm/SignRequestScreen-DdAK4SlJ.mjs +1 -0
- package/dist/esm/StackedContainer-BrIQsdas.mjs +1 -0
- package/dist/esm/StandardSignAndSendTransactionScreen-C0IrbkCx.mjs +1 -0
- package/dist/esm/Subtitle-DkvfP2Ev.mjs +1 -0
- package/dist/esm/TelegramAuthScreen-vp2lrJFZ.mjs +1 -0
- package/dist/esm/Title-D0pfZff-.mjs +1 -0
- package/dist/esm/TodoList-Dn0Qu-vv.mjs +2 -0
- package/dist/esm/TransactionDetails-fgHkAnf9.mjs +3 -0
- package/dist/esm/TransactionErrorView-Dgp1KSy5.mjs +2 -0
- package/dist/esm/TransferFromWalletScreen-CTAGaF9C.mjs +1 -0
- package/dist/esm/TransferOrBridgeLoadingScreen-D3vBwM_o.mjs +1 -0
- package/dist/esm/UpdateEmailScreen-BBtChP9Q.mjs +1 -0
- package/dist/esm/UpdatePhoneScreen-Byn7UW7u.mjs +1 -0
- package/dist/esm/UserLimitReachedScreen-DXDqdBpt.mjs +1 -0
- package/dist/esm/Value-B4M62ove.mjs +1 -0
- package/dist/esm/WalletButtonList-CGloXTN0.mjs +1 -0
- package/dist/esm/WalletCards-DH1rqayz.mjs +1 -0
- package/dist/esm/WalletInfoCard-DAv0WFcc.mjs +1 -0
- package/dist/esm/WalletInterstitialScreen-CKiSWjpa.mjs +1 -0
- package/dist/esm/WalletLink-CjuEskpb.mjs +3 -0
- package/dist/esm/WarningBanner-BDp-QC9i.mjs +1 -0
- package/dist/esm/abstract-smart-wallets.mjs +1 -1
- package/dist/esm/analytics-mkkvFRju.mjs +1 -0
- package/dist/esm/capitalizeFirstLetter-DmLYqXsO.mjs +1 -0
- package/dist/esm/{events-context-ClaboIDc.mjs → context-Cb5MFcME.mjs} +1 -1
- package/dist/esm/copy-Bx2Jwc5_.mjs +1 -0
- package/dist/esm/ethers-CpMSCMOg.mjs +1 -0
- package/dist/esm/events-context-CI0iqAXA.mjs +1 -0
- package/dist/esm/extended-chains.mjs +1 -1
- package/dist/esm/farcaster-DPlSjvF5.mjs +1 -0
- package/dist/esm/farcaster.mjs +1 -1
- package/dist/esm/formatErc20TokenAmount-BuPk9xcy.mjs +1 -0
- package/dist/esm/frame-BMa3kyjk.mjs +1 -0
- package/dist/esm/get-is-unified-wallet-DymQMSJy.mjs +1 -0
- package/dist/esm/getChainName-DjpPdUSc.mjs +1 -0
- package/dist/esm/getErc20Balance-Dtau1386.mjs +1 -0
- package/dist/esm/getErc20TokenInfo-CKA_MDcy.mjs +1 -0
- package/dist/esm/getFormattedUsdFromLamports-B6EqSEho.mjs +1 -0
- package/dist/esm/getPublicClient-IxRndou_.mjs +1 -0
- package/dist/esm/getUsdcMintAddress-DFI1hv05.mjs +1 -0
- package/dist/esm/index-B_e8abKi.mjs +1 -0
- package/dist/esm/index-CI666IP9.mjs +5 -0
- package/dist/esm/index-CJMgUOnw.mjs +1 -0
- package/dist/esm/index-DdlRJsoj.mjs +1 -0
- package/dist/esm/index.mjs +1 -5
- package/dist/esm/internal-context-Cvo1WmWN.mjs +1 -0
- package/dist/esm/internal.mjs +1 -1
- package/dist/esm/paths-3HW55qZg.mjs +1 -0
- package/dist/esm/prepareFundingModalData-BUyu5Vhr.mjs +1 -0
- package/dist/esm/reservoir-B0V48m2I.mjs +1 -0
- package/dist/esm/shared-CtYf3O54.mjs +1 -0
- package/dist/esm/shared-DsP7M4P5.mjs +1 -0
- package/dist/esm/shouldProceedtoEmbeddedWalletCreationFlow-CxerhsH3.mjs +1 -0
- package/dist/esm/smart-wallets-Cbhn7qlU.mjs +1 -0
- package/dist/esm/smart-wallets.mjs +1 -1
- package/dist/esm/solana.mjs +1 -1
- package/dist/esm/styles-BxA7nKxI.mjs +1 -0
- package/dist/esm/styles-DY17fuAX.mjs +1 -0
- package/dist/esm/telegram-B-JqnkqZ.mjs +1 -0
- package/dist/esm/to-ui-error-B3m2hl6e.mjs +1 -0
- package/dist/esm/transaction-CnfuREWo.mjs +1 -0
- package/dist/esm/transfer-CMPmjPsM.mjs +1 -0
- package/dist/esm/twitch-5IOe4sIQ.mjs +1 -0
- package/dist/esm/twitter-6jomarO4.mjs +1 -0
- package/dist/esm/ui.mjs +2 -2
- package/dist/esm/use-create-wallet-without-fallback-DodUf3VP.mjs +1 -0
- package/dist/esm/use-export-wallet-CWslDKqf.mjs +1 -0
- package/dist/esm/use-sign-with-user-signer-LJ6ROduD.mjs +1 -0
- package/dist/esm/useActiveWallet-hrZcON-K.mjs +1 -0
- package/dist/esm/useGetSolPrice-Bi0pPiUW.mjs +1 -0
- package/dist/esm/useGetTokenPrice-B4XVfxeD.mjs +1 -0
- package/dist/esm/useI18n-ByKvnaXP.mjs +1 -0
- package/dist/esm/usePrivy-D3OPY7tm.mjs +1 -0
- package/dist/esm/useSolanaRpcClient-DjD2ma5c.mjs +1 -0
- package/dist/esm/useWalletBalance-Xca4-c_r.mjs +1 -0
- package/dist/esm/useWallets-BplPx0Pz.mjs +1 -0
- package/dist/esm/useWallets-CQMJYOF9.mjs +1 -0
- package/package.json +15 -9
- package/dist/cjs/EmbeddedWalletConnectingScreen-JRafXI8d.js +0 -27
- package/dist/cjs/SignRequestScreen-Dy02euV9.js +0 -1
- package/dist/cjs/events-context-7-Gs8c_9.js +0 -1
- package/dist/cjs/frame-B2orQ_lK.js +0 -1
- package/dist/cjs/internal-context-CeWKmK5u.js +0 -1
- package/dist/cjs/smart-wallets-DaqaXBrW.js +0 -1
- package/dist/cjs/use-export-wallet-Cz8MVlvJ.js +0 -2
- package/dist/cjs/useActiveWallet-C5D3a-je.js +0 -1
- package/dist/cjs/usePrivy-BdYU4BZI.js +0 -1
- package/dist/esm/EmbeddedWalletConnectingScreen-D50stmJi.mjs +0 -25
- package/dist/esm/SignRequestScreen-D9o7VhNz.mjs +0 -1
- package/dist/esm/frame-Dj70FEYB.mjs +0 -1
- package/dist/esm/internal-context-eGSwROSk.mjs +0 -1
- package/dist/esm/smart-wallets-BXT3GZwg.mjs +0 -1
- package/dist/esm/use-export-wallet-DTiEdSYz.mjs +0 -1
- package/dist/esm/use-sign-with-user-signer-DaTvrd5T.mjs +0 -1
- package/dist/esm/useActiveWallet-B8DSbnuu.mjs +0 -1
- package/dist/esm/usePrivy-BCcRF869.mjs +0 -1
- package/dist/dts/{types-B6UNnZ2P.d.mts → types-BkkvIRg5.d.mts} +134 -134
- package/dist/dts/{types-B6UNnZ2P.d.ts → types-BkkvIRg5.d.ts} +134 -134
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";var e=require("react/jsx-runtime"),t=require("react"),r=require("@privy-io/js-sdk-core"),n=require("uuid"),i=require("jose"),a=require("./get-is-unified-wallet-DmiciSes.js"),s=require("eventemitter3"),o=require("./useActiveWallet-DcxqWAsq.js"),l=require("./useWallets-h2xCj02C.js"),c=require("./internal-context-VDPFkIXN.js"),d=require("./prepareFundingModalData-BVlyr8l5.js"),u=require("@coinbase/wallet-sdk"),h=require("@privy-io/ethereum"),p=require("./context-JUEgi5-6.js"),y=require("mipd"),w=require("react-device-detect"),m=require("viem/utils"),v=require("@privy-io/popup"),g=require("./paths-DizMb-lU.js"),f=require("@scure/base"),E=require("./usePrivy-CXPeoT5g.js"),C=require("@marsidev/react-turnstile"),A=require("styled-components"),P=require("./events-context-Di6--rDg.js"),T=require("zustand"),_=require("@headlessui/react"),k=require("@walletconnect/ethereum-provider"),S=require("@privy-io/urls"),b=require("viem"),I=require("./getPublicClient-EjAv8R2z.js"),W=require("ofetch"),U=require("js-cookie"),x=require("./frame-bPqBJ8fS.js"),R=require("@privy-io/routes"),O=require("x402/client"),N=require("@privy-io/api-base"),M=require("viem/accounts"),F=require("./use-sign-with-user-signer-On9f1Fag.js");function L(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function D(e){if(e&&"object"==typeof e&&"default"in e)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}require("./getEmbeddedConnectedWallet-6TsVZJkD.js");var j=/*#__PURE__*/L(t),q=/*#__PURE__*/L(r),z=/*#__PURE__*/D(i),H=/*#__PURE__*/L(s),K=/*#__PURE__*/L(U);class B{static parse(e){try{return new B(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return z.decodeJwt(e),e}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){return Date.now()>=1e3*(this.expiration-e)}constructor(e){this.value=e,this._decoded=z.decodeJwt(e)}}class V extends B{static parse(e){try{return new V(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}const Y="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PScwIDAgMTAyNCAxMDI0JyBmaWxsPSdub25lJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHN0eWxlPSdoZWlnaHQ6MjhweDt3aWR0aDoyOHB4Jz48cmVjdCB3aWR0aD0nMTAyNCcgaGVpZ2h0PScxMDI0JyBmaWxsPScjMDA1MkZGJyByeD0nMTAwJyByeT0nMTAwJz48L3JlY3Q+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBjbGlwLXJ1bGU9J2V2ZW5vZGQnIGQ9J00xNTIgNTEyQzE1MiA3MTAuODIzIDMxMy4xNzcgODcyIDUxMiA4NzJDNzEwLjgyMyA4NzIgODcyIDcxMC44MjMgODcyIDUxMkM4NzIgMzEzLjE3NyA3MTAuODIzIDE1MiA1MTIgMTUyQzMxMy4xNzcgMTUyIDE1MiAzMTMuMTc3IDE1MiA1MTJaTTQyMCAzOTZDNDA2Ljc0NSAzOTYgMzk2IDQwNi43NDUgMzk2IDQyMFY2MDRDMzk2IDYxNy4yNTUgNDA2Ljc0NSA2MjggNDIwIDYyOEg2MDRDNjE3LjI1NSA2MjggNjI4IDYxNy4yNTUgNjI4IDYwNFY0MjBDNjI4IDQwNi43NDUgNjE3LjI1NSAzOTYgNjA0IDM5Nkg0MjBaJyBmaWxsPSd3aGl0ZSc+PC9wYXRoPjwvc3ZnPg==",G="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAALZJREFUaEPtmjEOhDAMBNc/O14GvOzys3CAKK6eAlmaVGl2Zc+kTOU685vkc9/bnD2prZK5/TZY24z9P+g4F5hNh7/GdoG37WlAA5CATwgCxHENYISwQAMQII5rACOEBRqAAHFcAxghLNAABIjjGsAIYYEGIEAc1wBGCAs0AAHiuAYwQligAQgQxzWAEcICDUCAOK4BjBAWaAACxHENYISwQAMQII6fBjr+VHkW3+u+tfyxMpJaDgYzYxb/ALZVAAAAAElFTkSuQmCC";let $,J;class Q extends o.EthereumWalletConnector{async initialize(){await this.importPromise,await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:G,id:"com.coinbase.wallet"}}async promptConnection(){try{await this.importPromise;let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new c.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}constructor(e,t,r,n,i){super("base_account",e,t,r),this.connectorType="base_account",this.walletClientType="base_account",this.displayName="Base",this.setBaseAccountSdk=i,this.proxyProvider=new o.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.baseAccountConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},$?(this.proxyProvider.setWalletProvider($.getProvider()),this.setBaseAccountSdk($),console.log("Base Account SDK Initialized")):this.importPromise=import("@base-org/account").then((({createBaseAccountSDK:e})=>{$=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider($.getProvider()),this.setBaseAccountSdk($),console.log("Base Account SDK Initialized")})).catch(console.error)}}let Z=[1,11155111,137,10,8453,84532,42161,7777777,43114,56];class X extends o.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:Y,id:"com.coinbase.wallet"}}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new c.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}updateConnectionPreference(e){this.coinbaseWalletConfig={...this.coinbaseWalletConfig,preference:{...this.coinbaseWalletConfig.preference,options:e}},this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",J=u.createCoinbaseWalletSDK({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(J.getProvider())}constructor(e,t,n,i){if(super("coinbase_wallet",e,t,n),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new o.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.coinbaseWalletConfig={...i,appChainIds:[t.id].concat(e.map((e=>e.id)))},this.walletClientType="smartWalletOnly"===this.coinbaseWalletConfig.preference?.options?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!J){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter((e=>!Z.includes(e))):[];e.length>0&&!e.every((e=>r.DEFAULT_SUPPORTED_CHAIN_IDS.has(e)))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${e.join(", ")}`),J=u.createCoinbaseWalletSDK(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(J.getProvider())}}const ee=({...t})=>/*#__PURE__*/e.jsx("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...t,children:/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M2.37126 11.0323C2.37126 12.696 3.90598 13.4421 5.40654 13.4468C8.91753 13.4468 12.8021 11.2897 12.7819 7.67984C12.7673 5.07728 10.3748 2.86167 7.54357 2.88296C4.8495 2.88296 2.21821 4.6411 2.21803 7.03628C2.21803 7.67951 2.58722 8.30178 3.55231 8.37184C2.74763 9.16826 2.37126 10.1225 2.37126 11.0323ZM7.55283 8.68012C8.11562 8.68012 8.57186 8.13217 8.57186 7.45624C8.57186 6.78032 8.11562 6.23237 7.55283 6.23237C6.99003 6.23237 6.53379 6.78032 6.53379 7.45624C6.53379 8.13217 6.99003 8.68012 7.55283 8.68012ZM10.4747 8.68012C11.0375 8.68012 11.4937 8.13217 11.4937 7.45625C11.4937 6.78032 11.0375 6.23237 10.4747 6.23237C9.91186 6.23237 9.45562 6.78032 9.45562 7.45625C9.45562 8.13217 9.91186 8.68012 10.4747 8.68012Z",fill:t.color||"var(--privy-color-foreground-3)"})});class te extends o.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return await this.isConnected()?(await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[o.toHex(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:ee,id:"io.privy.wallet"}}disconnect(){this.connected=!1}async promptConnection(){}constructor({provider:e,chains:t,defaultChain:r,rpcConfig:n,imported:i,walletIndex:a}){super("privy",t,r,n),this.connectorType="embedded",this.proxyProvider=e,this.walletIndex=a,i&&(this.connectorType="embedded_imported"),this.subscribeListeners()}}async function re(){let e=Lr();return e?e.getAccessToken():Promise.resolve(d.u.get(p.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||d.u.get(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const ne=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];function ie(e){return e?{"privy-ui":"t"}:void 0}class ae{async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new c.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(g.passwordlessAuthenticatePath,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw c.formatApiError(e)}}async link(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new c.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(g.passwordlessLinkPath,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw c.formatApiError(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new c.PrivyClientError("Email must be set when initialzing authentication.");let n=ie(r);try{return await this.api.post(g.passwordlessInitPath,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw c.formatApiError(e)}}constructor({email:e,captchaToken:t,disableSignup:r}){this.meta={email:e,captchaToken:t,disableSignup:r??!1}}}class se extends ae{async link(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new c.PrivyClientError("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(g.updateEmailPath,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw c.formatApiError(e)}}constructor(e,t,r){super({email:t,captchaToken:r}),this.meta={email:t,captchaToken:r,oldAddress:e,disableSignup:!1}}}function oe(e){return{name:e.metadata?.shortName||e.name||"",universalLink:e.mobile.universal,deepLink:e.mobile.native}}function le(e,t){let r=oe(t);if(r.universalLink)return he(r.universalLink,e)}let ce="WALLETCONNECT_DEEPLINK_CHOICE";function de(e){return e.startsWith("http://")||e.startsWith("https://")}function ue(e,t){if(de(e))return he(e,t);let r=e;return r.includes("://")||(r=e.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),{redirect:`${r}wc?uri=${encodeURIComponent(t)}`,href:r}}function he(e,t){if(!de(e))return ue(e,t);let r=e;return r.endsWith("/")||(r=`${r}/`),{redirect:`${r}wc?uri=${encodeURIComponent(t)}`,href:r}}function pe(e,t){window.open(e,t,"noreferrer noopener")}class ye{execute(e){return null===this.promise&&(this.promise=(async()=>{try{return await this.fn(e)}finally{this.promise=null}})()),this.promise}constructor(e){this.promise=null,this.fn=e}}class we{get meta(){return this._meta}async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new c.PrivyClientError("Auth flow must be initialized first");try{let e=await this.api.post(g.farcasterAuthenticatePath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});if(!e)throw new c.PrivyClientError("No response from authentication");return e}catch(e){throw c.formatApiError(e)}}async link(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(g.farcasterLinkPath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(e){throw c.formatApiError(e)}}async _startChannelOnce(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");let e=await this.api.post(g.farcasterInitPath,{token:this.captchaToken});w.isMobile&&!w.isIOS&&e.connect_uri&&pe(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new c.PrivyClientError("Auth flow must be initialized first");let e=await this.api.get(g.farcasterStatusPath,{headers:{"farcaster-channel-token":this.meta.channelToken}});return"completed"===e.state&&(this.message=e.message,this.signature=e.signature,this.fid=e.fid,!0)}constructor(e,t=!1){this._meta={disableSignup:!1},this.captchaToken=e,this.startChannelOnce=new ye(this._startChannelOnce.bind(this)),this.pollForReady=new ye(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function me(){return"undefined"!=typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function ve(){if(!me())return;let e=window.chrome;return e?.runtime?.id}function ge(){if(!me())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function fe(e){return new Promise(((t,r)=>{ge()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},(async e=>{try{let r=function(){if(!me())return;let e=window.chrome;return e?.runtime?.lastError?.message}();if(r||!e){let e=`WebAuthFlow failed: ${r||"Response URI missing"}`;throw Error(e)}let n=new URL(e),i=ve();if(!i)throw Error("Invalid extension context");if("chrome-extension:"===n.protocol){if(n.hostname!==i)throw Error("Invalid responseUri origin")}else{if("https:"!==n.protocol)throw Error("Invalid responseUri protocol");{let e=n.hostname.split(".");if(3!==e.length||"chromiumapp"!==e[1]||"org"!==e[2]||e[0]!==i)throw Error("Invalid responseUri origin")}}let a=n.searchParams.get("privy_oauth_state"),s=n.searchParams.get("privy_oauth_code");if(!a||!s)throw Error("Invalid responseUri - missing required parameters");t({privyOAuthState:a,privyOAuthCode:s})}catch(e){r(e)}})):r(Error("Chrome identity API not available"))}))}function Ee(e){return crypto.getRandomValues(new Uint8Array(e))}function Ce(){return i.base64url.encode(Ee(36))}function Ae(){return Ce()}async function Pe(e,t="S256"){if("S256"!=t)return e;{let t=await async function(e){let t=(new TextEncoder).encode(e);return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}(e);return i.base64url.encode(t)}}class Te{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new c.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new c.PrivyClientError("User denied confirmation during OAuth flow");let e=function(){let e=d.u.get(p.CODE_VERIFIER_KEY);if(!e)throw new c.PrivyClientError("Authentication error.");return e}();try{let t=await this.api.post(g.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});return d.u.del(p.CODE_VERIFIER_KEY),d.u.del(p.HEADLESS_OAUTH_KEY),d.u.del(p.OAUTH_DISABLE_SIGNUP_KEY),t}catch(e){let t=c.formatApiError(e);if(t.privyErrorCode)throw new c.PrivyClientError(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new c.PrivyClientError("Invalid code during oauth flow.",void 0,c.PrivyErrorCode.OAUTH_USER_DENIED);throw new c.PrivyClientError("Invalid code during OAuth flow.",void 0,c.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new c.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new c.PrivyClientError("User denied confirmation during OAuth flow");let e=d.u.get(p.CODE_VERIFIER_KEY);if(!e)throw new c.PrivyClientError("Authentication error.");try{let t=await this.api.post(g.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return d.u.del(p.CODE_VERIFIER_KEY),t}catch(e){throw c.formatApiError(e)}}async getAuthorizationUrl(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.provider)throw new c.PrivyClientError("Provider must be set when initializing OAuth authentication.");let e=Ce();d.u.put(p.CODE_VERIFIER_KEY,e);let t=Ae();d.u.put(p.STATE_CODE_KEY,t);let r=await Pe(e);this.meta.withPrivyUi||d.u.put(p.HEADLESS_OAUTH_KEY,!0),this.meta.disableSignup?d.u.put(p.OAUTH_DISABLE_SIGNUP_KEY,!0):d.u.del(p.OAUTH_DISABLE_SIGNUP_KEY);let n=ie(this.meta.withPrivyUi),i=window.location.href,a=function(){let e=ve();if(e)return`https://${e}.chromiumapp.org`}();a&&(i=a);try{return await this.api.post(g.oAuthInitPath,{provider:this.meta.provider,redirect_to:this.meta.customOAuthRedirectUrl||i,token:this.meta.captchaToken,code_challenge:r,state_code:t},{headers:{...n}})}catch(e){throw c.formatApiError(e)}}constructor(e){this.meta=e}}function _e(){let e=new URLSearchParams(window.location.search),t=e.get("privy_oauth_code"),r=e.get("privy_oauth_state"),n=e.get("privy_oauth_provider");if(!t||!r||!n)return{inProgress:!1};let i=!1;try{i=!!window.opener.location.origin}catch{}return{inProgress:!0,authorizationCode:t,stateCode:r,provider:n,withPrivyUi:!d.u.get(p.HEADLESS_OAUTH_KEY),popupFlow:null!==window.opener&&i,disableSignup:!!d.u.get(p.OAUTH_DISABLE_SIGNUP_KEY)}}function ke(){let e=new URL(window.location.href);e.searchParams.delete("privy_oauth_code"),e.searchParams.delete("privy_oauth_provider"),e.searchParams.delete("privy_oauth_state"),d.u.del(p.STATE_CODE_KEY),window.history.replaceState({},"",e)}class Se{async initRegisterFlow(e){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");this.authenticateForRegistration=!0,this.meta.initRegisterResponse=await this.initRegisterOnce.execute(e)}async initAuthenticationFlow(e){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");this.authenticateForRegistration=!1,this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute(e)}async initLinkFlow(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");this.meta.initLinkResponse=await this.initLinkOnce.execute()}async register(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new c.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initRegisterResponse||(this.meta.initRegisterResponse=await this.initRegisterOnce.execute());try{let t=this.meta.initRegisterResponse.options,r=await e.startRegistration({optionsJSON:this._transformInitLinkOptionsToCamelCase(t)});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(g.passkeyRegisterPath,{relying_party:this.meta.initRegisterResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new c.PrivyClientError("Passkey request timed out or rejected by user.",void 0,c.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw c.formatApiError(e)}}async authenticate(){if(this.authenticateForRegistration)return this.register();let e=await import("@simplewebauthn/browser");if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new c.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initAuthenticateResponse||(this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute());let t=this.meta.allowedCredentialsIds?.map((e=>({type:"public-key",id:e})))??this.meta.initAuthenticateResponse.options.allow_credentials;try{let r=await e.startAuthentication({optionsJSON:this._transformInitAuthenticateOptionsToCamelCase({...this.meta.initAuthenticateResponse.options,allow_credentials:t})});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(g.passkeyAuthenticatePath,{relying_party:this.meta.initAuthenticateResponse.relying_party,challenge:this.meta.initAuthenticateResponse.options.challenge,authenticator_response:this._transformAuthenticationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new c.PrivyClientError("Passkey request timed out or rejected by user.",void 0,c.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw c.formatApiError(e)}}async link(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new c.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initLinkResponse||(this.meta.initLinkResponse=await this.initLinkOnce.execute());try{let t=this.meta.initLinkResponse.options,r=await e.startRegistration({optionsJSON:this._transformInitLinkOptionsToCamelCase(t)});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(g.passkeyLinkPath,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new c.PrivyClientError("Passkey request timed out or rejected by user.",void 0,c.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw c.formatApiError(e)}}async _initRegisterOnce(e){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");let t=ie(e);return await this.api.post(g.passkeyInitRegisterPath,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");let t=ie(e);return await this.api.post(g.passkeyInitAuthenticatePath,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");return await this.api.post(g.passkeyInitLinkPath,{})}_transformInitLinkOptionsToCamelCase(e){return{rp:e.rp,user:{id:e.user.id,name:e.user.name,displayName:e.user.display_name},challenge:e.challenge,pubKeyCredParams:e.pub_key_cred_params.map((e=>({type:e.type,alg:e.alg}))),timeout:e.timeout,excludeCredentials:e.exclude_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports}))),authenticatorSelection:{authenticatorAttachment:e.authenticator_selection?.authenticator_attachment,requireResidentKey:e.authenticator_selection?.require_resident_key,residentKey:e.authenticator_selection?.resident_key,userVerification:e.authenticator_selection?.user_verification},attestation:e.attestation,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props?.rk,hmacCreateSecret:e.extensions?.hmac_create_secret},hints:this.meta.hints}}_transformRegistrationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,attestation_object:e.response.attestationObject,authenticator_data:e.response.authenticatorData},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}_transformInitAuthenticateOptionsToCamelCase(e){return{rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}}_transformAuthenticationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}constructor({captchaToken:e,setPasskeyAuthState:t,hints:r}){this.authenticateForRegistration=!1,this.initRegisterOnce=new ye(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new ye(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new ye(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t,hints:r}}}const be=({address:e,chainId:t,nonce:r})=>`${window.location.host} wants you to sign in with your Ethereum account:\n${e}\n\nBy signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.\n\nURI: ${window.location.origin}\nVersion: 1\nChain ID: ${t}\nNonce: ${r}\nIssued At: ${(new Date).toISOString()}\nResources:\n- https://privy.io`;class Ie{get meta(){return{connectorType:this.wallet?.connectorType,walletClientType:this.wallet?.walletClientType,chainId:this.wallet?.chainId,address:this.wallet?.address,disableSignup:this._meta.disableSignup}}async authenticate(){if(!this.client)throw new c.PrivyClientError("SiweFlow has no client instance");try{if(this.preparedMessage&&this.signature)return await this.client.authenticateWithSiweInternal({message:this.preparedMessage,signature:this.signature,chainId:this.wallet?.chainId,walletClientType:this.walletClientType??this.wallet?.walletClientType,connectorType:this.connectorType??this.wallet?.connectorType,mode:this._meta.disableSignup?"no-signup":"login-or-sign-up"});if(!this.wallet)throw new c.PrivyClientError("SiweFlow has no wallet instance");let{message:e,signature:t}=await this.sign();return await this.client.authenticateWithSiweInternal({message:e,signature:t,chainId:this.wallet.chainId,walletClientType:this.wallet.walletClientType,connectorType:this.wallet.connectorType,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw c.formatApiError(e)}}async link(){if(!this.client)throw new c.PrivyClientError("SiweFlow has no client instance");try{if(!this.wallet)throw new c.PrivyClientError("SiweFlow has no wallet instance");let{message:e,signature:t}=await this.sign();return await this.client.linkWithSiweInternal({message:e,signature:t,chainId:this.wallet.chainId,walletClientType:this.wallet.walletClientType,connectorType:this.wallet.connectorType})}catch(e){throw c.formatApiError(e)}}async sign(){if(!this.client)throw new c.PrivyClientError("SiweFlow has no client instance");if(await this.buildMessage(),!this.preparedMessage)throw new c.PrivyClientError("Could not prepare SIWE message");if(!this.wallet)throw new c.PrivyClientError("SiweFlow has no wallet instance");let e=await this.wallet.sign(this.preparedMessage);return{message:this.preparedMessage,signature:e}}async _getNonceOnce(){if(!this.client)throw new c.PrivyClientError("SiweFlow has no client instance");if(!this.wallet)throw new c.PrivyClientError("UI SiweFlow has no wallet instance");return await this.client.generateSiweNonce({address:this.wallet.address,captchaToken:this.captchaToken})}async buildMessage(){if(!this.client)throw new c.PrivyClientError("SiweFlow has no client instance");if(!this.wallet)throw new c.PrivyClientError("SiweFlow has no wallet instance");let e=this.wallet.address,t=this.wallet.chainId.replace("eip155:","");return this.nonce||(this.nonce=await this.getNonceOnce.execute()),this.preparedMessage=be({address:e,chainId:t,nonce:this.nonce}),this.preparedMessage}constructor(e,t,r,n=!1,i){this._meta={disableSignup:!1},this.getNonceOnce=new ye(this._getNonceOnce.bind(this)),this.wallet=t,this.captchaToken=r,this.client=e,this._meta.disableSignup=n,this.preparedMessage=i?.message,this.signature=i?.signature,this.walletClientType=i?.walletClientType,this.connectorType=i?.connectorType}}class We{get meta(){return{connectorType:this.wallet.connectorType,walletClientType:this.wallet.walletClientType,disableSignup:this._meta.disableSignup,messageType:this._meta.messageType,address:this.wallet?.address}}set messageType(e){this._meta.messageType=e}async authenticate(){if(!this.client)throw new c.PrivyClientError("SiwsFlow has no client instance");try{let{message:e,signature:t}=await this.sign();return await this.client.authenticateWithSiwsInternal({message:e,signature:t,walletClientType:this.wallet.walletClientType,connectorType:this.wallet.connectorType,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up",messageType:this.meta.messageType})}catch(e){throw c.formatApiError(e)}}async link(){if(!this.client)throw new c.PrivyClientError("SiwsFlow has no client instance");try{let{message:e,signature:t}=await this.sign();return await this.client.linkWithSiwsInternal({message:e,signature:t,walletClientType:this.wallet.walletClientType,connectorType:this.wallet.connectorType,messageType:this.meta.messageType})}catch(e){throw c.formatApiError(e)}}async sign(){let e,t;if(!this.client)throw new c.PrivyClientError("SiwsFlow has no client instance");await this.buildMessage();let r="transaction"===this.meta.messageType;if(!this.preparedMessage)throw new c.PrivyClientError("Could not prepare SIWS message");if(!r&&!this.wallet.provider.signMessage||r&&!this.wallet.provider.signTransaction)throw new c.PrivyClientError("Wallet does not support the necessary signing methods");if(r&&this._plugin){let r=await this.wallet.provider.signTransaction({transaction:f.base64.decode(this.preparedMessage)});e=f.base64.encode(r.signedTransaction),t=this._plugin.getSignatureFromTransaction(r.signedTransaction,this.wallet.address)}else{e=this.preparedMessage;let r=await this.wallet.provider.signMessage({message:(new TextEncoder).encode(this.preparedMessage)});t=f.base64.encode(r.signature)}return{message:e,signature:t}}async _getNonceOnce(){if(!this.client)throw new c.PrivyClientError("SiwsFlow has no client instance");return await this.client.generateSiwsNonce({address:this.wallet.address,captchaToken:this.captchaToken})}async buildMessage(){if(!this.client)throw new c.PrivyClientError("SiwsFlow has no client instance");let e=this.wallet.address;return this.nonce||(this.nonce=await this.getNonceOnce.execute()),"transaction"===this.meta.messageType&&this._plugin?this.preparedMessage=this._plugin.createSiwsMemoTransaction({address:e,nonce:this.nonce}):this.preparedMessage=E.prepareSiwsMessageWithNonce({address:e,nonce:this.nonce}),this.preparedMessage}constructor(e,t,r,n=!1,i="plain",a){this._meta={disableSignup:!1,messageType:"plain"},this.getNonceOnce=new ye(this._getNonceOnce.bind(this)),this.wallet=e,this.captchaToken=r,this.client=t,this._meta.disableSignup=n,this._meta.messageType=i,this._plugin=a}}class Ue{async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new c.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(g.passwordlessSmsAuthenticatePath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw c.formatApiError(e)}}async link(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new c.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(g.passwordlessSmsLinkPath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw c.formatApiError(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new c.PrivyClientError("phone nNumber must be set when initialzing authentication.");let n=ie(r);try{return await this.api.post(g.passwordlessSmsInitPath,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw c.formatApiError(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:r}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:r??!1}}}class xe extends Ue{async link(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new c.PrivyClientError("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(g.updatePhonePath,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw c.formatApiError(e)}}constructor(e,t,r){super({phoneNumber:t,captchaToken:r}),this.meta={phoneNumber:t,captchaToken:r,oldPhoneNumber:e,disableSignup:!1}}}const Re=/*#__PURE__*/t.createContext({siteKey:"",enabled:!1,appId:void 0,token:void 0,error:void 0,status:"disabled",setToken:c.notImplemented,setError:c.notImplemented,setExecuting:c.notImplemented,waitForResult:()=>Promise.resolve(""),ref:{current:null},remove:c.notImplemented,reset:c.notImplemented,execute:c.notImplemented});class Oe extends c.PrivyError{constructor(e,t,r){super(e||"Captcha failed"),this.type="Captcha",t instanceof Error&&(this.cause=t),this.privyErrorCode=r}}const Ne=({children:r,id:n,captchaSiteKey:i,captchaEnabled:a})=>{let s=t.useRef(null),[l,d]=t.useState(),[u,h]=t.useState(),[p,y]=t.useState(!1),w=t.useMemo((()=>a?p||l||u?!p||l||u?l&&!u?{status:"success",token:l}:u?{status:"error",error:u}:{status:"ready"}:{status:"loading"}:{status:"ready"}:{status:"disabled"}),[a,l,u,p]);/*#__PURE__*/return e.jsx(Re.Provider,{value:{...w,ref:s,enabled:a,siteKey:i,appId:n,setToken:d,setError:h,setExecuting:y,remove(){a&&(s.current?.remove(),y(!1),h(void 0),d(void 0))},reset(){a&&(s.current?.reset(),y(!1),h(void 0),d(void 0))},execute(){a&&(y(!0),s.current?.execute())},async waitForResult(){if(!a)return"";try{return await o.pollForResult((()=>s.current?.getResponse()),{interval:200,timeout:2e4})}catch(e){throw new Oe("Captcha failed",null,c.PrivyErrorCode.CAPTCHA_TIMEOUT)}}},children:r})},Me=()=>t.useContext(Re);class Fe{async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(g.telegramAccountAuthenticatePath,{captcha_token:this.meta.captchaToken,telegram_auth_result:this.meta.telegramAuthResult,telegram_web_app_data:this.meta.telegramWebAppData,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw c.formatApiError(e)}}async link(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(g.telegramAccountLinkPath,{telegram_auth_result:this.meta.telegramAuthResult,telegram_web_app_data:this.meta.telegramWebAppData})}catch(e){throw c.formatApiError(e)}}constructor(e,t=!1){this.meta={disableSignup:!1},this.meta={captchaToken:e,disableSignup:!1},this.meta.disableSignup=t}}function Le(e){return Object.fromEntries(decodeURIComponent(e).split("&").map((e=>e.split("=").map(decodeURIComponent))))}function De(){let e=new URL(window.location.href);e.searchParams.delete("id"),e.searchParams.delete("hash"),e.searchParams.delete("auth_date"),e.searchParams.delete("first_name"),e.searchParams.delete("last_name"),e.searchParams.delete("username"),e.searchParams.delete("photo_url"),e.hash="",window.history.replaceState({},"",e)}const je=({delayedExecution:r,...n})=>{let{enabled:i,siteKey:a,appId:s,setError:o,setToken:l,setExecuting:c,ref:d}=Me(),[,u]=t.useMemo((()=>a?.split("t:")||[]),[a]);if(t.useEffect((()=>d.current?.remove),[]),!i)return null;if(!u)throw Error("Unsupported captcha site key");/*#__PURE__*/return e.jsx("div",{className:"hidden h-0 w-0",children:/*#__PURE__*/e.jsx(C.Turnstile,{...n,ref:d,siteKey:u,options:{action:s,size:"invisible",...r?{appearance:"execute",execution:"execute"}:{appearance:"always",execution:"render"}},onUnsupported:()=>{n.onUnsupported?.(),console.warn("Browser does not support Turnstile.")},onError:e=>{n.onError?.(e),o("Captcha failed"),c(!1)},onSuccess:e=>{n.onSuccess?.(e),l(e),c(!1)},onExpire:e=>{n.onExpire?.(e);try{d.current?.reset(),o(void 0),l(void 0)}catch(e){o("expired_and_failed_reset")}}})})};var qe=/*#__PURE__*/Object.freeze({__proto__:null,AccountNotFoundScreen:()=>Promise.resolve().then((function(){return require("./AccountNotFoundScreen-jSbfPu_e.js")})),AffirmativeConsentScreen:()=>Promise.resolve().then((function(){return require("./AffirmativeConsentScreen-7a4hl59A.js")})),AllowlistRejectionScreen:()=>Promise.resolve().then((function(){return require("./AllowlistRejectionScreen-B6roj0JU.js")})),AuthenticateWithWalletScreen:()=>Promise.resolve().then((function(){return require("./AuthenticateWithWalletScreen-BcBapHrq.js")})),AwaitingEvmToSolBridgingScreen:()=>Promise.resolve().then((function(){return require("./AwaitingEvmToSolBridgingScreen-D1Xd83Hp.js")})),AwaitingExternalEthereumTransferScreen:()=>Promise.resolve().then((function(){return require("./AwaitingExternalEthereumTransferScreen-COL0WYkT.js")})),AwaitingPasswordlessCodeScreen:()=>Promise.resolve().then((function(){return require("./AwaitingPasswordlessCodeScreen-Cx5fqGf6.js")})),AwaitingSolToEvmBridgingScreen:()=>Promise.resolve().then((function(){return require("./AwaitingSolToEvmBridgingScreen-DYS3lDs0.js")})),CaptchaScreen:()=>Promise.resolve().then((function(){return require("./CaptchaScreen-025syTLo.js")})),CoinbaseOnrampStatusScreen:()=>Promise.resolve().then((function(){return require("./CoinbaseOnrampStatusScreen-ORl8wt4H.js")})),ConnectLedgerScreen:()=>Promise.resolve().then((function(){return require("./ConnectLedgerScreen-DBYExlWR.js")})),ConnectOnlyLandingScreen:()=>Promise.resolve().then((function(){return require("./ConnectOnlyLandingScreen-bOhkl0xJ.js")})),ConnectOnlyStatusScreen:()=>Promise.resolve().then((function(){return require("./ConnectOnlyStatusScreen-DvTrLHyY.js")})),ConnectOrCreateScreen:()=>Promise.resolve().then((function(){return require("./ConnectOrCreateScreen-Dh4EFU5N.js")})),ConnectionStatusScreen:()=>Promise.resolve().then((function(){return require("./ConnectionStatusScreen-Ct-KTCXS.js")})),CrossAppAuthScreen:()=>Promise.resolve().then((function(){return require("./CrossAppAuthScreen-B-DtA7IH.js")})),DelegatedActionsConsentScreen:()=>Promise.resolve().then((function(){return require("./DelegatedActionsConsentScreen-B5WlYn7z.js")})),DelegatedActionsRevokeScreen:()=>Promise.resolve().then((function(){return require("./DelegatedActionsRevokeScreen-2g_ydX-Y.js")})),EmbeddedWalletConnectingScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletConnectingScreen-9seYvsTF.js")})),EmbeddedWalletCreatedScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletCreatedScreen-PycFyIz6.js")})),EmbeddedWalletKeyExportScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletKeyExportScreen-BDTDQY1f.js")})),EmbeddedWalletOnAccountCreateScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletOnAccountCreateScreen-B0tXEtG9.js")})),EmbeddedWalletPasswordCreateScreen:()=>Promise.resolve().then((function(){return require("./RecoveryPasswordCreateScreen-vQG4ErlF.js")})),EmbeddedWalletPasswordUpdateScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletPasswordUpdateScreen-ZfgU86hx.js")})),EmbeddedWalletPasswordUpdateSplashScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletPasswordUpdateSplashScreen-tP8rSVUL.js")})),ErrorScreen:()=>Promise.resolve().then((function(){return require("./ErrorScreen-Cob9AO30.js")})),FarcasterConnectStatusScreen:()=>Promise.resolve().then((function(){return require("./FarcasterConnectStatusScreen-C5FoWA6N.js")})),FarcasterSignerStatusScreen:()=>Promise.resolve().then((function(){return require("./FarcasterSignerStatusScreen-CDYkqsxz.js")})),FundSolWalletWithExternalSolanaWallet:()=>Promise.resolve().then((function(){return require("./FundSolWalletWithExternalSolanaWallet-DC_xoE6W.js")})),FundingAmountEditScreen:()=>Promise.resolve().then((function(){return require("./FundingEditAmountScreen-BB7-k00c.js")})),FundingMethodSelectionScreen:()=>Promise.resolve().then((function(){return require("./FundingMethodSelectionScreen-BrV94GD2.js")})),InAppBrowserLoginNotPossible:()=>Promise.resolve().then((function(){return require("./InAppBrowserLoginNotPossible-y8g07-kU.js")})),InstallWalletScreen:()=>Promise.resolve().then((function(){return require("./InstallWalletScreen-CmGi6mS1.js")})),LandingScreen:()=>Promise.resolve().then((function(){return require("./LandingScreen-B9jb8n_d.js")})),LinkConflictScreen:()=>Promise.resolve().then((function(){return require("./LinkConflictScreen-BJXyOu2J.js")})),LinkEmailScreen:()=>Promise.resolve().then((function(){return require("./LinkEmailScreen-zyJFrvy-.js")})),LinkPasskeyScreen:()=>Promise.resolve().then((function(){return require("./LinkPasskeyScreen-Bw7Xs741.js")})),LinkPhoneScreen:()=>Promise.resolve().then((function(){return require("./LinkPhoneScreen-C4JQblY3.js")})),LoginFailedScreen:()=>Promise.resolve().then((function(){return require("./LoginFailedScreen-CGT-2B2h.js")})),ManualTransferScreen:()=>Promise.resolve().then((function(){return require("./ManualTransferScreen-DPz98CSt.js")})),MfaAuthEnrollmentFlowScreen:()=>Promise.resolve().then((function(){return require("./MfaAuthEnrollmentFlowScreen-BBKMKDGR.js")})),MfaAuthVerifyFlowScreen:()=>Promise.resolve().then((function(){return require("./MfaAuthVerifyFlowScreen-3LKUo_xV.js")})),MfaEnrollmentFlowScreen:()=>Promise.resolve().then((function(){return require("./MfaEnrollmentFlowScreen-B2YgNRCC.js")})),MoonpayStatusScreen:()=>Promise.resolve().then((function(){return require("./MoonpayStatusScreen-yghPhz7v.js")})),OAuthStatusScreen:()=>Promise.resolve().then((function(){return require("./OAuthStatusScreen-q9MFItPT.js")})),PasskeySelectSignupOrLogin:()=>Promise.resolve().then((function(){return require("./PasskeySelectSignupOrLogin-BKBH0QxK.js")})),PasskeyStatusScreen:()=>Promise.resolve().then((function(){return require("./PasskeyStatusScreen-DVx4lzwq.js")})),PasswordRecoveryScreen:()=>Promise.resolve().then((function(){return require("./PasswordRecoveryScreen-BmGdXVfh.js")})),RecoveryOAuthScreen:()=>Promise.resolve().then((function(){return require("./RecoveryOAuthStatusScreen-DUobwBXF.js")})),RecoverySelectionScreen:()=>Promise.resolve().then((function(){return require("./RecoverySelectionScreen-E2l_NO8y.js")})),SendTransactionScreen:()=>Promise.resolve().then((function(){return require("./index-BNNk54gK.js")})),SetAutomaticRecoveryScreen:()=>Promise.resolve().then((function(){return require("./SetAutomaticRecoveryScreen-DQolobOz.js")})),SignRequestScreen:()=>Promise.resolve().then((function(){return require("./SignRequestScreen-BAgmmVVW.js")})),StandardSignAndSendTransactionScreen:()=>Promise.resolve().then((function(){return require("./StandardSignAndSendTransactionScreen-BUB57iWU.js")})),TelegramAuthScreen:()=>Promise.resolve().then((function(){return require("./TelegramAuthScreen-D5uhx6WN.js")})),TransferFromWalletScreen:()=>Promise.resolve().then((function(){return require("./TransferFromWalletScreen-C_0IpL-A.js")})),UpdateEmailScreen:()=>Promise.resolve().then((function(){return require("./UpdateEmailScreen-BUAgWudx.js")})),UpdatePhoneScreen:()=>Promise.resolve().then((function(){return require("./UpdatePhoneScreen-DefnuTEZ.js")})),UserLimitReachedScreen:()=>Promise.resolve().then((function(){return require("./UserLimitReachedScreen-B76r_-LC.js")})),WalletInterstitialScreen:()=>Promise.resolve().then((function(){return require("./WalletInterstitialScreen-CG1k3EvV.js")}))});function ze(e){P.usePrivyEventSubscription("configureMfa",e)}const He=T.create((()=>({inProgressMfaFlow:void 0})));const Ke=/*#__PURE__*/A.createGlobalStyle([":root{","};"],(e=>Be(e.palette)));const Be=e=>
|
|
2
|
+
/*#__PURE__*/A.css(["",""],Object.entries(function(e){return{"--privy-color-background":e.background,"--privy-color-background-2":e.background2,"--privy-color-background-3":e.background3,"--privy-color-foreground":e.foreground,"--privy-color-foreground-2":e.foreground2,"--privy-color-foreground-3":e.foreground3,"--privy-color-foreground-4":e.foreground4,"--privy-color-foreground-accent":e.foregroundAccent,"--privy-color-accent":e.accent,"--privy-color-accent-light":e.accentLight,"--privy-color-accent-hover":e.accentHover,"--privy-color-accent-dark":e.accentDark,"--privy-color-accent-darkest":e.accentDarkest,"--privy-color-success":e.success,"--privy-color-success-dark":e.successDark,"--privy-color-success-light":e.successLight,"--privy-color-success-bg":e.successBg,"--privy-color-error":e.error,"--privy-color-error-light":e.errorLight,"--privy-color-error-bg":e.errorBg,"--privy-color-error-bg-hover":e.errorBgHover,"--privy-color-warn":e.warn,"--privy-color-warn-light":e.warnLight,"--privy-color-warn-bg":e.warnBg,"--privy-color-warning-dark":e.warningDark,"--privy-color-error-dark":e.errorDark,"--privy-color-info-bg":e.infoBg,"--privy-color-info-bg-hover":e.infoBgHover,"--privy-color-border-default":e.borderDefault,"--privy-color-border-hover":e.borderHover,"--privy-color-border-focus":e.borderFocus,"--privy-color-border-error":e.borderError,"--privy-color-border-success":e.borderSuccess,"--privy-color-border-warning":e.borderWarning,"--privy-color-border-info":e.borderInfo,"--privy-color-border-interactive":e.borderInteractive,"--privy-color-border-interactive-hover":e.borderInteractiveHover,"--privy-color-background-hover":e.backgroundHover,"--privy-color-background-clicked":e.backgroundClicked,"--privy-color-background-disabled":e.backgroundDisabled,"--privy-color-background-interactive":e.backgroundInteractive,"--privy-color-background-interactive-hover":e.backgroundInteractiveHover,"--privy-color-background-interactive-clicked":e.backgroundInteractiveClicked,"--privy-color-background-interactive-disabled":e.backgroundInteractiveDisabled,"--privy-color-foreground-hover":e.foregroundHover,"--privy-color-foreground-clicked":e.foregroundClicked,"--privy-color-foreground-disabled":e.foregroundDisabled,"--privy-color-foreground-interactive":e.foregroundInteractive,"--privy-color-foreground-interactive-hover":e.foregroundInteractiveHover,"--privy-link-navigation-color":e.linkNavigationColor,"--privy-link-navigation-decoration":e.linkNavigationDecoration,"--privy-accent-has-good-contrast":e.accentHasGoodContrast,"--privy-color-icon-default":e.iconDefault,"--privy-color-icon-muted":e.iconMuted,"--privy-color-icon-subtle":e.iconSubtle,"--privy-color-icon-inverse":e.iconInverse,"--privy-color-icon-success":e.iconSuccess,"--privy-color-icon-warning":e.iconWarning,"--privy-color-icon-error":e.iconError,"--privy-color-icon-interactive":e.iconInteractive,"--privy-color-icon-default-hover":e.iconDefaultHover,"--privy-color-icon-muted-hover":e.iconMutedHover,"--privy-color-icon-subtle-hover":e.iconSubtleHover,"--privy-color-icon-default-clicked":e.iconDefaultClicked,"--privy-color-icon-muted-clicked":e.iconMutedClicked,"--privy-color-icon-subtle-clicked":e.iconSubtleClicked,"--privy-color-icon-default-disabled":e.iconDefaultDisabled,"--privy-color-icon-muted-disabled":e.iconMutedDisabled,"--privy-color-icon-subtle-disabled":e.iconSubtleDisabled,"--privy-color-icon-error-hover":e.iconErrorHover,"--privy-color-icon-interactive-hover":e.iconInteractiveHover,"--privy-color-icon-error-clicked":e.iconErrorClicked,"--privy-color-icon-interactive-clicked":e.iconInteractiveClicked,"--privy-color-icon-muted-disabled-alt":e.iconMutedDisabledAlt,"--privy-color-icon-subtle-disabled-alt":e.iconSubtleDisabledAlt,"--privy-border-radius-xs":"6px","--privy-border-radius-sm":"8px","--privy-border-radius-md":"12px","--privy-border-radius-mdlg":"16px","--privy-border-radius-lg":"24px","--privy-border-radius-full":"9999px","--privy-height-modal-full":"620px","--privy-height-modal-compact":"480px"}}(e)).map((([e,t])=>`${e}: ${t};`)).join("\n")),Ve=/*#__PURE__*/A.styled.div.withConfig({displayName:"StylesWrapper",componentId:"sc-188229e4-0"})([""," color:var(--privy-color-foreground-2);h3{font-size:16px;line-height:24px;font-weight:500;color:var(--privy-color-foreground-2);}h4{font-size:14px;line-height:20px;font-weight:500;color:var(--privy-color-foreground);}p{font-size:13px;line-height:20px;color:var(--privy-color-foreground-2);}button:focus,input:focus,optgroup:focus,select:focus,textarea:focus{outline:none;border-color:var(--privy-color-accent-light);box-shadow:0 0 0 3px var(--privy-color-border-focus);}.mobile-only{@media (min-width:441px){display:none;}}@keyframes fadein{0%{opacity:0;}100%{opacity:1;}}"],"\n *,\n ::before,\n ::after {\n box-sizing: border-box;\n border-width: 0;\n border-style: solid;\n }\n\n line-height: 1.15;\n -webkit-text-size-adjust: 100%;\n -moz-tab-size: 4;\n tab-size: 4;\n font-feature-settings: normal;\n\n margin: 0;\n font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif,\n 'Apple Color Emoji', 'Segoe UI Emoji';\n\n hr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n }\n\n abbr:where([title]) {\n text-decoration: underline dotted;\n }\n\n h1,\n h2,\n h3,\n h4,\n h5,\n h6 {\n font-size: inherit;\n font-weight: inherit;\n font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif,\n 'Apple Color Emoji', 'Segoe UI Emoji';\n display: inline;\n }\n\n a {\n color: inherit;\n text-decoration: inherit;\n }\n\n b,\n strong {\n font-weight: bolder;\n }\n\n code,\n kbd,\n samp,\n pre {\n font-family: ui-monospace, SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 1em;\n }\n\n small {\n font-size: 80%;\n }\n\n sub,\n sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n }\n\n sub {\n bottom: -0.25em;\n }\n\n sup {\n top: -0.5em;\n }\n\n table {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n }\n\n button,\n input,\n optgroup,\n select,\n textarea {\n font-family: inherit;\n font-size: 100%;\n font-weight: inherit;\n line-height: inherit;\n color: inherit;\n margin: 0;\n padding: 0;\n }\n\n button,\n select {\n text-transform: none;\n }\n\n button,\n [type='button'],\n [type='reset'],\n [type='submit'] {\n -webkit-appearance: button;\n background-color: transparent;\n background-image: none;\n }\n\n ::-moz-focus-inner {\n border-style: none;\n padding: 0;\n }\n\n :-moz-focusring {\n outline: 1px dotted ButtonText;\n }\n\n :-moz-ui-invalid {\n box-shadow: none;\n }\n\n legend {\n padding: 0;\n }\n\n progress {\n vertical-align: baseline;\n }\n\n ::-webkit-inner-spin-button,\n ::-webkit-outer-spin-button {\n height: auto;\n }\n\n [type='search'] {\n -webkit-appearance: textfield;\n outline-offset: -2px;\n }\n\n ::-webkit-search-decoration {\n -webkit-appearance: none;\n }\n\n ::-webkit-file-upload-button {\n -webkit-appearance: button;\n font: inherit;\n }\n\n summary {\n display: list-item;\n }\n\n blockquote,\n dl,\n dd,\n h1,\n h2,\n h3,\n h4,\n h5,\n h6,\n hr,\n figure,\n p,\n pre {\n margin: 0;\n }\n\n fieldset {\n margin: 0;\n padding: 0;\n }\n\n legend {\n padding: 0;\n }\n\n ol,\n ul,\n menu {\n list-style: none;\n margin: 0;\n padding: 0;\n }\n\n textarea {\n resize: vertical;\n }\n\n input::placeholder,\n textarea::placeholder {\n opacity: 1;\n color: #9ca3af;\n }\n\n button,\n [role='button'] {\n cursor: pointer;\n }\n\n :disabled {\n cursor: default;\n }\n\n img,\n svg,\n video,\n canvas,\n audio,\n iframe,\n embed,\n object {\n display: block;\n }\n\n img,\n video {\n max-width: 100%;\n height: auto;\n }\n\n [hidden] {\n display: none;\n }\n"),Ye=({children:t,open:r,onClick:n,...i})=>/*#__PURE__*/e.jsx(_.Transition,{show:r,as:j.default.Fragment,children:/*#__PURE__*/e.jsxs(_.Dialog,{onClose:n,...i,as:$e,children:[/*#__PURE__*/e.jsx(_.TransitionChild,{as:j.default.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/e.jsx(Ge,{id:"privy-dialog-backdrop","aria-hidden":"true"})}),/*#__PURE__*/e.jsx(Je,{children:/*#__PURE__*/e.jsx(_.TransitionChild,{as:j.default.Fragment,enterFrom:"entering",leaveTo:"leaving",children:/*#__PURE__*/e.jsx(_.DialogPanel,{as:Qe,children:t})})})]})});let Ge=/*#__PURE__*/A.styled.div.withConfig({displayName:"Backdrop",componentId:"sc-3cfde0b5-0"})(["position:fixed;inset:0;transition:backdrop-filter 100ms ease;backdrop-filter:blur(3px);-webkit-backdrop-filter:blur(3px);&.entering,&.leaving{backdrop-filter:unset;-webkit-backdrop-filter:unset;}"]),$e=/*#__PURE__*/A.styled.div.withConfig({displayName:"DialogWrapper",componentId:"sc-3cfde0b5-1"})(["position:relative;z-index:999999;"]),Je=/*#__PURE__*/A.styled.div.withConfig({displayName:"DialogContainer",componentId:"sc-3cfde0b5-2"})(["position:fixed;inset:0;display:flex;align-items:center;justify-content:center;width:100vw;min-height:100vh;"]);const Qe=/*#__PURE__*/A.styled.div.withConfig({displayName:"Panel",componentId:"sc-3cfde0b5-3"})(["padding:0;background:transparent;border:none;width:100%;pointer-events:auto;outline:none;display:block;@media (max-width:440px){opacity:1;transform:translate3d(0,0,0);transition:transform 200ms ease-in;position:fixed;bottom:0;&.entering,&.leaving{opacity:0;transform:translate3d(0,100%,0);transition:transform 150ms ease-in 0ms,opacity 0ms ease 150ms;}}@media (min-width:441px){opacity:1;transition:opacity 100ms ease-in;&.entering,&.leaving{opacity:0;transition-delay:5ms;}margin:auto;width:360px;box-shadow:0px 8px 36px rgba(55,65,81,0.15);border-radius:var(--privy-border-radius-lg);}"]);const Ze=()=>{let{ready:e}=a.usePrivyContext(),{currentScreen:r}=a.usePrivyModal(),[n,i]=t.useState(null),[s,o]=t.useState(!1),l=function(e){let[r,n]=t.useState(!1),i=t.useRef(null),a=t.useRef(null),s=t.useRef(null);return t.useEffect((()=>{if(i.current&&(clearTimeout(i.current),i.current=null),a.current&&(clearTimeout(a.current),a.current=null),e)s.current=Date.now(),i.current=setTimeout((()=>{n(!0)}),150);else if(null!==s.current){let e=Date.now()-s.current;if(e>=150){let t=Math.max(0,400-(e-150));a.current=setTimeout((()=>{n(!1),s.current=null}),t)}else i.current&&(clearTimeout(i.current),i.current=null),n(!1),s.current=null}return()=>{i.current&&clearTimeout(i.current),a.current&&clearTimeout(a.current)}}),[e]),r}(s);return t.useEffect((()=>{if(!r)return i(null),void o(!1);o(!0),qe[r]().then((t=>{(!r||e||t.default.isShownBeforeReady)&&(i((()=>t.default.component)),o(!1))})).catch((()=>{i(null),o(!1)}))}),[r,e]),{component:n,isLoading:l}};let Xe=/*#__PURE__*/t.lazy((()=>Promise.resolve().then((function(){return require("./MfaVerifyFlowScreen-BhVqkM2f.js")})))),et=/*#__PURE__*/t.lazy((()=>(e=>qe[e]().then((e=>({default:e.default.component}))))("MfaAuthVerifyFlowScreen"))),tt=()=>/*#__PURE__*/e.jsx(ot,{children:/*#__PURE__*/e.jsx(o.Loader,{})}),rt=()=>{let{currentScreen:r}=a.usePrivyModal(),n=He((e=>e.inProgressMfaFlow)),i=()=>He.setState({inProgressMfaFlow:void 0}),{component:s,isLoading:l}=Ze();return function(){let{isModalOpen:e}=a.usePrivyContext(),{headless:r}=p.useAppConfig(),{currentScreen:n}=a.usePrivyModal(),{status:i,execute:s,reset:o,enabled:l}=Me(),[c,d]=t.useState(!1);t.useEffect((()=>{!e&&l&&o()}),[e,l,o]),t.useEffect((()=>{n?qe[n]().then((e=>{d(!!e.default.isCaptchaRequired)})).catch((()=>{d(!1)})):d(!1)}),[n]),t.useEffect((()=>{e&&c&&!r&&"ready"===i&&l&&s()}),[e,c,r,i,l,s])}(),r||"txn"!==n?l?/*#__PURE__*/e.jsx(tt,{}):s?
|
|
3
|
+
/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.Hide,{$if:!!n,children:/*#__PURE__*/e.jsx(s,{})}),/*#__PURE__*/e.jsxs(t.Suspense,{children:["txn"===n&&/*#__PURE__*/e.jsx(Xe,{onClose:i}),"auth"===n&&/*#__PURE__*/e.jsx(et,{})]})]}):null:/*#__PURE__*/e.jsx(Xe,{onClose:i})},nt=()=>{let r=t.useRef(null);/*#__PURE__*/return e.jsx(st,{style:{height:o.useElementHeight(r)},id:"privy-modal-content",children:/*#__PURE__*/e.jsx("div",{ref:r,children:/*#__PURE__*/e.jsx(rt,{})})})};const it=({open:r})=>{let n=p.useAppConfig(),{gracefulClosePrivyModal:i}=(()=>{let{closePrivyModal:e}=c.usePrivyInternal(),{onUserCloseViaDialogOrKeybindRef:r}=a.usePrivyModal();return{gracefulClosePrivyModal:t.useCallback((()=>{if(!r?.current)return e({shouldCallAuthOnSuccess:!1});r.current()}),[e])}})(),s=He((e=>e.inProgressMfaFlow));return ze({onMfaRequired:()=>{n.mfa.noPromptOnMfaRequired||He.setState({inProgressMfaFlow:"txn"})}}),n.render.standalone?/*#__PURE__*/e.jsx(Ve,{children:/*#__PURE__*/e.jsx(at,{id:"privy-modal-content",children:/*#__PURE__*/e.jsx(rt,{})})}):/*#__PURE__*/e.jsx(Ye,{open:!(!r&&!s),id:"privy-dialog","aria-label":"log in or sign up","aria-labelledby":"privy-dialog-title",onClick:()=>i(),children:/*#__PURE__*/e.jsx(Ve,{children:/*#__PURE__*/e.jsx(nt,{})})})};let at=/*#__PURE__*/A.styled.div.withConfig({displayName:"ContentWrapper",componentId:"sc-4759f1d5-0"})(["display:flex;flex-direction:column;text-align:center;font-size:14px;line-height:20px;width:100%;background:var(--privy-color-background);padding:0 16px;"]),st=/*#__PURE__*/A.styled(at).withConfig({displayName:"BaseModal",componentId:"sc-4759f1d5-1"})(["transition:height 150ms ease-out;overflow-x:hidden;overflow-y:auto;scrollbar-width:none;max-height:calc(100svh - 32px);border-radius:var(--privy-border-radius-lg) var(--privy-border-radius-lg) 0 0;box-shadow:0px 0px 36px rgba(55,65,81,0.15);@media (min-width:441px){box-shadow:0px 8px 36px rgba(55,65,81,0.15);border-radius:var(--privy-border-radius-lg);}"]),ot=/*#__PURE__*/A.styled.div.withConfig({displayName:"LoadingScreenContainer",componentId:"sc-4759f1d5-2"})(["display:flex;align-items:center;justify-content:center;min-height:300px;padding:2rem;"]);function lt(r){let n=t.useRef(null),i=t.useRef();return t.useEffect((()=>{i.current?.remove(),i.current=function({botUsername:e,scriptHost:t}){let r=document.createElement("script"),{origin:n}=new URL(t);return r.async=!0,r.src=`${n}/js/telegram-login.js`,r.setAttribute("data-telegram-login",e),r.setAttribute("data-request-access","write"),r.setAttribute("data-lang","en"),r}(r),n.current?.after(i.current)}),[r]),/*#__PURE__*/e.jsx("div",{ref:n,hidden:!0})}const ct=()=>{let{ready:e}=l.useWallets(),{client:r}=c.usePrivyInternal();return t.useEffect((()=>{let t=()=>{if(!r.connectors||!e)return;let t=r.connectors.wallets.map((e=>({address:e.address,connectorType:e.connectorType,walletClientType:e.walletClientType,connectedAt:e.connectedAt,id:e.meta.id})));d.u.put(p.CONNECTIONS_HISTORY_KEY,t)};return r.connectors?.on("walletsUpdated",t),()=>{r.connectors?.off("walletsUpdated",t)}}),[e,r.connectors]),null};class dt extends o.EthereumWalletConnector{async initialize(){let e=await this.createProvider();this.provider=e,this.proxyProvider.setWalletProvider(e),this.subscribeListeners(),e.session&&(this.walletProvider?.session?.peer.metadata.url&&(this.walletEntry=o.getExternalWalletDataByUrl(this.walletProvider?.session?.peer.metadata.url),this.walletClientType=this.walletEntry?.slug||"unknown"),this.connected=!0,await this.syncAccounts()),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),this.getConnectedWallet()}async isConnected(){return!!this.walletProvider?.connected}get walletBranding(){let e=this.walletProvider?.session?.peer.metadata.icons?.[0];return{name:o.stripEmoji(this.walletProvider?.session?.peer.metadata.name||"")||"WalletConnect",icon:"string"==typeof e?e:d.WALLET_CONNECT_LOGO_DATA_URI,id:this.walletProvider?.session?.peer.metadata.name.toLowerCase()||"wallet_connect_v2"}}async resetConnection(e){this.walletProvider&&this.walletProvider.connected&&(await this.walletProvider.disconnect(),this.walletProvider.signer.session=void 0,this.walletClientType=e,this.redirectUri=void 0,this.fallbackUniversalRedirectUri=void 0,function(){try{localStorage.removeItem(ce)}catch{}}(),this.onDisconnect())}async promptConnection(){if(this.provider)return new Promise(((e,t)=>{(async()=>{let t="",r=await Promise.race([this.walletProvider?.enable(),this.proxyProvider.walletTimeout()]);if(r?.length&&(t=r[0]),!t||""===t)throw new c.PrivyConnectorError("Unable to retrieve address");this.walletProvider?.session?.peer.metadata.url&&(this.walletEntry=o.getExternalWalletDataByUrl(this.walletProvider?.session?.peer.metadata.url),this.walletClientType=this.walletEntry?.slug||"unknown",this.proxyProvider.rpcTimeoutDuration=o.getRpcTimeout(this.rpcConfig,this.walletClientType)),this.connected=!0,await this.syncAccounts(r),e()})().catch((e=>{t(e?d.formatConnectorError(e):new c.PrivyConnectorError("Unknown error during connection"))}))}))}disconnect(){this.walletProvider?.disconnect().then((()=>this.onDisconnect())).catch((()=>console.warn("Unable to disconnect WalletConnect provider")))}get walletProvider(){return this.proxyProvider.walletProvider}setWalletProvider(e){this.proxyProvider.setWalletProvider(e)}async createProvider(){let e={};for(let t of this.chains){let r=o.getJsonRpcEndpoint(t.id,this.chains,this.rpcConfig,this.privyAppId);r&&(e[t.id]=r)}let t=this.shouldEnforceDefaultChainOnConnect?[this.defaultChain.id]:[],r=this.chains.map((e=>e.id)),n=await k.EthereumProvider.init({projectId:this.walletConnectCloudProjectId,chains:t,optionalChains:r,optionalEvents:k.OPTIONAL_EVENTS,optionalMethods:k.OPTIONAL_METHODS,rpcMap:e,showQrModal:!1,metadata:{description:this.privyAppName,name:this.privyAppName,url:window.location.origin,icons:[]}});return n.on("display_uri",(e=>{if(n.signer.abortPairingAttempt(),function(){try{localStorage.removeItem(ce)}catch{}}(),!this.showPrivyQrModal)throw new c.PrivyConnectorError("WalletConnect modal not available - Privy handles wallet connections through its own UI");if(w.isMobile&&this.walletEntry){let{redirect:t,href:r}=function(e,t){let r=oe(t);if(r.deepLink)return ue(r.deepLink,e);if(r.universalLink)return he(r.universalLink,e);throw new c.PrivyClientError(`Unsupported wallet ${t.id}`)}(e,this.walletEntry);pe(t,"_self"),function({href:e,name:t}){try{localStorage.setItem(ce,JSON.stringify({href:e,name:t}))}catch{}}({href:r,name:this.walletEntry.metadata?.shortName||this.walletEntry.name});let n=le(e,this.walletEntry);return this.redirectUri=t,this.fallbackUniversalRedirectUri=n?.redirect,this.showPrivyQrModal({native:t,universal:t})}if(this.redirectUri=void 0,this.walletEntry){let t=le(e,this.walletEntry);this.fallbackUniversalRedirectUri=t?.redirect}this.showPrivyQrModal({native:e,universal:void 0})})),n.on("connect",(()=>{n.session?.peer.metadata.url&&(this.walletEntry=o.getExternalWalletDataByUrl(n.session?.peer.metadata.url),this.walletClientType=this.walletEntry?.slug||"unknown")})),n}async enableProvider(){return this.walletProvider?.connected?Promise.resolve(this.walletProvider.accounts):await(this.walletProvider?.enable())}setWalletEntry(e,t){this.walletEntry=e,this.showPrivyQrModal=t}constructor({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:n,shouldEnforceDefaultChainOnConnect:i,privyAppId:a,privyAppName:s,walletClientType:l}){super(l||"unknown",r,n,t),this.connectorType="wallet_connect_v2",this.privyAppId=a,this.privyAppName=s,this.walletConnectCloudProjectId=e,this.rpcConfig=t,this.shouldEnforceDefaultChainOnConnect=i,this.proxyProvider=new o.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),l&&(this.walletEntry=o.getExternalWalletData(l),this.walletClientType=l)}}const ut=["error","invalid_request_arguments","wallet_not_on_device","invalid_recovery_pin","insufficient_funds","missing_or_invalid_mfa","mfa_verification_max_attempts_reached","mfa_timeout","twilio_verification_failed"];class ht extends Error{constructor(e,t){super(t),this.type=e}}function pt(e){let t=e.type;return"string"==typeof t&&ut.includes(t)}function yt(e){return pt(e)&&"wallet_not_on_device"===e.type}async function wt(e,t,r,n,i,a=!1){let s=a,o=async o=>{if(s&&t&&t.length>0){o===(a?0:1)?i("configureMfa","onMfaRequired",{mfaMethods:t}):n.current?.reject(new ht("missing_or_invalid_mfa","MFA verification failed, retry."));let s=await new Promise(((e,t)=>{r.current={resolve:e,reject:t},setTimeout((()=>{let e=new ht("mfa_timeout","Timed out waiting for MFA code");n.current?.reject(e),t(e)}),3e5)}));return await e(s)}return await e()},l=null;for(let e=0;e<4;e++)try{l=await o(e),n.current?.resolve(void 0);break}catch(e){if("missing_or_invalid_mfa"!==e.type)throw n.current?.resolve(void 0),e;s=!0}if(null===l){let e=new ht("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw n.current?.reject(e),e}return l}var mt;let vt=(mt=0,()=>"id-"+mt++);function gt(e){return void 0!==e.error}let ft=new class{enqueue(e,t){this.callbacks[e]=t}dequeue(e,t){let r=this.callbacks[t];if(!r)throw Error(`cannot dequeue ${e} event: no event found for id ${t}`);switch(delete this.callbacks[t],e){case"privy:iframe:ready":case"privy:user-signer:sign":case"privy:wallets:add":case"privy:wallets:import":case"privy:wallets:set-recovery":case"privy:wallets:connect":case"privy:wallets:recover":case"privy:wallets:rpc":case"privy:wallet:create":case"privy:mfa:verify":case"privy:mfa:init-enrollment":case"privy:mfa:submit-enrollment":case"privy:mfa:unenroll":case"privy:mfa:clear":case"privy:auth:unlink-passkey":case"privy:farcaster:init-signer":case"privy:farcaster:sign":case"privy:solana-wallet:create":case"privy:delegated-actions:consent":return r;default:throw Error(`invalid wallet event type ${e}`)}}constructor(){this.callbacks={}}},Et=new Map,Ct=(e,t)=>"bigint"==typeof t?t.toString():t;function At(e,t,r,n){let i=r.contentWindow;if(!i)throw Error("iframe not initialized");let a=((e,t)=>`${e}${JSON.stringify(t,Ct)}`)(e,t);if("privy:wallet:create"===e){let e=Et.get(a);if(e)return e}let s=new Promise(((r,a)=>{let s=vt();ft.enqueue(s,{resolve:r,reject:a}),i.postMessage({id:s,event:e,data:t},n)})).finally((()=>{Et.delete(a)}));return Et.set(a,s),s}function Pt(r){let n=p.useIsServerConfigLoaded(),i=t.useRef(null),a=t.useRef(r.mfaMethods),s=P.useEmitPrivyEvent(),[l,c]=t.useState(!1);return t.useEffect((()=>{a.current=r.mfaMethods}),[r.mfaMethods]),t.useEffect((()=>{if(!l)return;let e=i.current;if(!e)return;function t(e){var t;e&&e.origin===r.origin&&"string"==typeof(t=e.data).event&&/^privy:.+/.test(t.event)&&function(e){switch(e.event){case"privy:iframe:ready":let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data);case"privy:user-signer:sign":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:add":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:set-recovery":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:connect":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:recover":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:rpc":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallet:create":let r=ft.dequeue(e.event,e.id);return gt(e)?r.reject(new ht(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallets:import":let n=ft.dequeue(e.event,e.id);return gt(e)?n.reject(new ht(e.error.type,e.error.message)):n.resolve(e.data);case"privy:mfa:verify":let i=ft.dequeue(e.event,e.id);return gt(e)?i.reject(new ht(e.error.type,e.error.message)):i.resolve(e.data);case"privy:mfa:init-enrollment":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:submit-enrollment":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:unenroll":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:clear":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:auth:unlink-passkey":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:solana-wallet:create":let a=ft.dequeue(e.event,e.id);return gt(e)?a.reject(new ht(e.error.type,e.error.message)):a.resolve(e.data);case"privy:farcaster:init-signer":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:sign":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:delegated-actions:consent":{let t=ft.dequeue(e.event,e.id);return gt(e)?t.reject(new ht(e.error.type,e.error.message)):t.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}(e.data)}let n={signWithUserSigner:t=>wt((n=>At("privy:user-signer:sign",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),addWallet:t=>wt((n=>At("privy:wallets:add",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),setRecovery:t=>wt((n=>At("privy:wallets:set-recovery",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),connect:t=>wt((n=>At("privy:wallets:connect",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),recover:t=>wt((n=>At("privy:wallets:recover",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s,!t.recoveryAccessToken&&!t.recoveryPassword&&!t.recoverySecretOverride),rpc:t=>wt((n=>At("privy:wallets:rpc",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),create:t=>At("privy:wallet:create",t,e,r.origin),importWallet:t=>At("privy:wallets:import",t,e,r.origin),createSolana:t=>wt((n=>At("privy:solana-wallet:create",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),createDelegatedAction:t=>At("privy:delegated-actions:consent",t,e,r.origin),verifyMfa:t=>wt((n=>At("privy:mfa:verify",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s,!0),initEnrollMfa:t=>wt((n=>At("privy:mfa:init-enrollment",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),submitEnrollMfa:t=>wt((n=>At("privy:mfa:submit-enrollment",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),unenrollMfa:t=>wt((n=>At("privy:mfa:unenroll",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),clearMfa:t=>At("privy:mfa:clear",t,e,r.origin),unlinkPasskeyAccount:t=>wt((n=>At("privy:auth:unlink-passkey",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),initFarcasterSigner:t=>At("privy:farcaster:init-signer",t,e,r.origin),signFarcasterMessage:t=>At("privy:farcaster:sign",t,e,r.origin)};window.addEventListener("message",t);let c=new AbortController;return o.invokeUntilSettled((()=>At("privy:iframe:ready",{},e,r.origin)),{abortSignal:c.signal}).then((()=>r.onLoad(n)),((...e)=>{console.warn("Privy iframe failed to load: ",...e),r.onLoadFailed()})),()=>{window.removeEventListener("message",t),c.abort()}}),[l]),n?
|
|
4
|
+
/*#__PURE__*/e.jsx("iframe",{ref:i,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>c(!0),src:S.constructURL({origin:r.origin,path:`/apps/${r.appId}/embedded-wallets`,query:{caid:r.clientAnalyticsId,client_id:r.appClientId}})}):null}const Tt=({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new c.PrivyClientError("Address to delegate is not associated with current user.");if(!d.isFirstClassChainWallet(r))throw new c.PrivyClientError(`useDelegatedActions is not supported for ${r.chainType} wallets. Use the useSessionSigners hook to provision server side access on behalf of your users.`);return{address:r.address,chainType:r.chainType,walletIndex:r.walletIndex??0}},_t=({address:e,user:t})=>{let r=t.linkedAccounts.find((t=>"wallet"===t.type&&"privy"===t.walletClientType&&t.address===e));if(!r)throw new c.PrivyClientError("Address to delegate is not associated with current user.");let n=r.imported?r:a.getPrivyPrimaryWallet(t);if(!n)throw new c.PrivyClientError("Unable to determine root address for delegated address.");if(!d.isFirstClassChainWallet(n))throw new c.PrivyClientError(`useDelegatedActions is not supported for ${n.chainType} wallets. Use the useSessionSigners hook to provision server side access on behalf of your users.`);return{address:n.address,chainType:n.chainType,imported:n.imported}},kt=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&e.delegated));const St="popup-privy-oauth",bt="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";class It{async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(g.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw c.formatApiError(e)}}async link(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(g.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider})}catch(e){throw c.formatApiError(e)}}constructor({authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}){this.meta={authorizationCode:e,stateCode:t,codeVerifier:r,provider:n}}}async function Wt({api:e,requesterAppId:t,providerAppId:r}){let n=(await e.get(`/api/v1/apps/${t}/cross-app/connections`)).connections.find((e=>e.provider_app_id===r));if(!n)throw new c.PrivyClientError("Invalid connected app");return{name:n.provider_app_name,logoUrl:n.provider_app_icon_url||void 0,apiUrl:n.provider_app_custom_api_url,readOnly:n.read_only,customAuthAuthorizeUrl:n.provider_app_custom_auth_authorize_url,customAuthTransactUrl:n.provider_app_custom_auth_transact_url}}const Ut=async({user:e,address:t,client:r,request:n,requesterAppId:i,reconnect:a})=>{r.createAnalyticsEvent({eventName:"cross_app_request_started",payload:{address:t,method:n.method}});let s=e?.linkedAccounts.find((e=>"cross_app"===e.type&&(e.embeddedWallets.some((e=>e.address===t))||e.smartWallets.some((e=>e.address===t)))));if(!e||!s)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Cannot request a signature with this wallet address",address:t}}),new c.PrivyClientError("Cannot request a signature with this wallet address");let o=r.getProviderAccessToken(s.providerApp.id),l=await Wt({api:r.api,requesterAppId:i,providerAppId:s.providerApp.id});if(!o){if(l.readOnly)throw console.error("cannot transact against a read-only provider app"),new c.PrivyClientError("Cannot transact against a read-only provider app");await a({appId:s.providerApp.id,action:"link"})&&(o=r.getProviderAccessToken(s.providerApp.id))}if(!o)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Transactions require a valid token",address:t}}),new c.PrivyClientError("Transactions require a valid token");let d=new URL(l.customAuthTransactUrl||`${l.apiUrl}/oauth/transact`);d.searchParams.set("token",o||""),d.searchParams.set("request",xt(n));let u=v.trigger({location:d.href});if(!u)throw r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Missing token",address:t}}),new c.PrivyClientError("Failed to initialize signature request");return new Promise(((e,i)=>{let a=setTimeout((()=>{d(),i(new c.PrivyClientError("Request timeout")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"Request timeout",address:t}})}),12e4),o=setInterval((()=>{u.closed&&(d(),i(new c.PrivyClientError("User rejected request")),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:"User rejected request",address:t}}))}),300),l=a=>{a.data&&("set"===a.data.token?.action&&void 0!==a.data.token?.value?r.storeProviderAccessToken(s.providerApp.id,a.data.token.value):"clear"===a.data.token?.action&&r.storeProviderAccessToken(s.providerApp.id,null),"PRIVY_CROSS_APP_ACTION_RESPONSE"===a.data.type&&a.data.result&&(d(),e(a.data.result),r.createAnalyticsEvent({eventName:"cross_app_request_success",payload:{address:t,method:n.method}})),"PRIVY_CROSS_APP_ACTION_ERROR"===a.data.type&&a.data.error&&(d(),i(a.data.error),r.createAnalyticsEvent({eventName:"cross_app_request_error",payload:{error:a.data.error,address:t}})))};window.addEventListener("message",l);let d=()=>{u.close(),clearInterval(o),clearTimeout(a),window.removeEventListener("message",l)}}))};let xt=e=>JSON.stringify({content:{request:{request:Rt(e,b.toHex)}},timestamp:Date.now(),callbackUrl:window.origin});const Rt=(e,t)=>"bigint"==typeof e?t(e):Array.isArray(e)?e.map((e=>Rt(e,t))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,r])=>[e,Rt(r,t)]))):e;function Ot({isCreatingWallet:e,skipSplashScreen:t}){return e?"EmbeddedWalletPasswordCreateScreen":t?"EmbeddedWalletPasswordUpdateScreen":"EmbeddedWalletPasswordUpdateSplashScreen"}function Nt({walletAction:e,availableRecoveryMethods:t,legacySetWalletPasswordFlow:r,isResettingPassword:n,showAutomaticRecovery:i}){return i?"SetAutomaticRecoveryScreen":r||1===t.length?Ot({isCreatingWallet:"create"===e,skipSplashScreen:n}):"RecoverySelectionScreen"}function Mt(e){switch(e){case"user-passcode":return"PasswordRecoveryScreen";case"google-drive":case"icloud":return"RecoveryOAuthScreen";default:throw Error("Recovery method not supported")}}const Ft=new Map([["FundingMethodSelectionScreen",null],["TransferFromWalletScreen","external"],["AwaitingExternalEthereumTransferScreen","external"],["AwaitingEvmToSolBridgingScreen","external"],["AwaitingSolToEvmBridgingScreen","external"],["ManualTransferScreen","manual"],["MoonpayStatusScreen","moonpay"]]);function Lt(e){let t=e.toLowerCase();return!!window?.webkit?.messageHandlers?.ReactNativeWebView||!!window?.ReactNativeWebView||["fbav","fban","instagram","snapchat","linkedinapp"].some((e=>t.includes(e)))}async function Dt({rpc:e,address:t}){return(await e.getBalance(t,{commitment:"confirmed"}).send()).value??0n}let jt={apple_oauth:"apple",custom_auth:"custom",discord_oauth:"discord",email:"email",farcaster:"farcaster",github_oauth:"github",google_oauth:"google",instagram_oauth:"instagram",linkedin_oauth:"linkedin",passkey:"passkey",phone:"sms",spotify_oauth:"spotify",telegram:"telegram",tiktok_oauth:"tiktok",line_oauth:"line",twitch_oauth:"twitch",twitter_oauth:"twitter",wallet:"siwe",smart_wallet:"siwe",cross_app:"privy:"};const qt=e=>{if(a.isCustomOAuthProvider(e))return{displayName:e.replace("custom:",""),loginMethod:"custom"};let t=jt[e];return"wallet"===e||"phone"===e?{displayName:e,loginMethod:t}:{displayName:t,loginMethod:t}},zt=(e,t)=>!a.getPrivyEthereumWallet(e)&&("all-users"===t||"users-without-wallets"===t&&!Ht(e).length);let Ht=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"ethereum"===e.chainType));const Kt=(e,t)=>!a.getPrivySolanaWallet(e)&&("all-users"===t||"users-without-wallets"===t&&!Bt(e).length);let Bt=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"solana"===e.chainType));async function Vt(e,t,r,n){let i=h.toViemTransactionSerializable(e),a=await(async()=>n?await n():await t.prepareTransactionRequest({...i,account:{address:r,type:"json-rpc"}}))();return{...a,type:h.STRING_TO_NUMBER_TXN_TYPE[a.type]}}const Yt=()=>{let e=p.useAppConfig(),{user:r}=a.usePrivyContext(),{client:n,refreshSessionAndUser:i,walletProxy:s}=c.usePrivyInternal();return{migrate:t.useCallback((async()=>{if("legacy-embedded-wallets-only"===e.embeddedWallets.mode)return{success:!0};if(!r)throw new c.PrivyClientError("User must be authenticated before migrating wallets",c.PrivyErrorCode.MUST_BE_AUTHENTICATED);if(!s)throw new c.PrivyClientError("Cannot connect to wallet proxy");let t=await n.getAccessToken();if(!t)throw new c.PrivyClientError("User must be authenticated before migrating wallets",c.PrivyErrorCode.MUST_BE_AUTHENTICATED);let o=r.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&d.isFirstClassChainWallet(e)&&!a.getIsUnifiedWallet(e)));if(0===o.length)return{success:!0};let u=o.filter((e=>e.imported)),h=o.filter((e=>!e.imported));if(h.length>0){let e=h.find((e=>"ethereum"===e.chainType&&0===e.walletIndex))??h.find((e=>"solana"===e.chainType&&0===e.walletIndex))??null;if(!e)throw new c.PrivyClientError("Primary wallet not found");let{entropyId:r,entropyIdVerifier:n}=l.toEntropyDetailsFromAccount(e);try{await s.connect({accessToken:t,entropyId:r,entropyIdVerifier:n})}catch(i){if(!yt(i)||"privy"!==e.recoveryMethod)throw i;await s.recover({accessToken:t,entropyId:r,entropyIdVerifier:n})}await s.createDelegatedAction({accessToken:t,rootWallet:{address:e.address,chainType:e.chainType,imported:!1},delegatedWallets:h.map((e=>({address:e.address,chainType:e.chainType,walletIndex:e.walletIndex??0})))})}for(let e of u){let{entropyId:r,entropyIdVerifier:n}=l.toEntropyDetailsFromAccount(e);try{await s.connect({accessToken:t,entropyId:r,entropyIdVerifier:n})}catch(u){if(!yt(u)||"privy"!==e.recoveryMethod)throw u;await s.recover({accessToken:t,entropyId:r,entropyIdVerifier:n})}await s.createDelegatedAction({accessToken:t,rootWallet:{address:e.address,chainType:e.chainType,imported:!0},delegatedWallets:[{address:e.address,chainType:e.chainType,walletIndex:e.walletIndex??0}]})}return await i(),{success:!0}}),[e.embeddedWallets.mode,r,s,n,i])}},Gt=({disabled:e})=>{let{migrate:r}=Yt(),{user:n}=a.usePrivyContext(),{walletProxy:i}=c.usePrivyInternal();return t.useEffect((()=>{!e&&n&&i&&r().catch((e=>{console.debug("Unable to migrate wallets: ",e)}))}),[n,i,e,r]),null},$t=e=>({id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}),Jt=T.create((()=>({ethereum:[]}))),Qt=()=>Jt.getState().ethereum;class Zt{async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(g.customJwtAccountAuthenticatePath,{token:this.meta.token})}catch(e){throw c.formatApiError(e)}}async link(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(g.customJwtAccountLinkPath,{token:this.meta.token})}catch(e){throw c.formatApiError(e)}}constructor(e){this.meta={token:e}}}function Xt({subscribe:e,getExternalJwt:r,enabled:n=!0,onAuthenticated:i,onUnauthenticated:a,onError:s}){let{client:o,onCustomAuthAuthenticated:l}=c.usePrivyInternal(),{logout:d,authenticated:u,ready:h}=E.usePrivy();if(!o)throw new c.PrivyClientError("`useSyncJwtBasedAuthState` must be used within a `PrivyProvider`");let[p,y]=t.useState({status:"initial"}),w=t.useRef(),m=t.useRef(!1),v=t.useRef(r);t.useEffect((()=>{v.current=r}),[r]);let g=t.useRef(i);t.useEffect((()=>{g.current=i}),[i]);let f=t.useRef(a);t.useEffect((()=>{f.current=a}),[a]);let C=t.useRef(s);return t.useEffect((()=>{C.current=s}),[s]),t.useEffect((()=>{if(!n||!h)return;let t=async()=>{if(!m.current){m.current=!0;try{y({status:"loading"});let e=await v.current();if(void 0!==w.current&&w.current===e)return void y({status:"done"});if(!e)return u&&(await d(),f.current?.()),w.current=e,void y({status:"done"});o.startAuthFlow(new Zt(e));let{user:t,isNewUser:r=!1}=await o.authenticate();if(!t)throw new c.PrivyClientError("Failed to sync with custom auth provider");g.current?.({user:t,isNewUser:r}),l(t,r),w.current=e,y({status:"done"})}catch(e){if(console.warn(e),await d().catch((()=>{})),f.current?.(),e instanceof c.PrivyApiError&&e.privyErrorCode===c.PrivyErrorCode.LINKED_TO_ANOTHER_USER)return y({status:"initial"}),void setTimeout((()=>{t()}),0);C.current?.(e),y({status:"error",error:e})}finally{m.current=!1}}};return t(),e(t)}),[e,o,l,u,d,n,h]),n?{state:p}:{state:{status:"not-enabled"}}}let er=T.create((()=>({jwtAuthFlowState:{status:"not-enabled"}})));function tr({customAuth:e}){let{jwtAuthFlowState:r}=function({customAuth:e}){let r=P.useEmitPrivyEvent(),n=t.useRef(),i=t.useCallback((e=>(n.current=e,()=>{n.current=void 0})),[]),a=e?.getCustomAccessToken??(()=>Promise.resolve(void 0)),{state:s}=Xt({enabled:!0===e?.enabled,subscribe:i,getExternalJwt:a,onAuthenticated:({user:e,isNewUser:t})=>{r("login","onComplete",{user:e,isNewUser:t,wasAlreadyAuthenticated:!1,loginMethod:"custom",loginAccount:null}),r("customAuth","onAuthenticated",{user:e})},onUnauthenticated:()=>{r("customAuth","onUnauthenticated")},onError:e=>{r("login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}});return t.useEffect((()=>{(async()=>{e&&!e.isLoading&&n.current?.()})()}),[e?.enabled,e?.getCustomAccessToken,e?.isLoading]),{jwtAuthFlowState:s}}({customAuth:e});return t.useEffect((()=>{er.setState({jwtAuthFlowState:r})}),[r]),null}const rr=/*#__PURE__*/t.createContext(!1);let nr,ir,ar,sr,or;const lr=n=>{let i=n.client,s=n.privy,u=E.usePlugins(),h=p.useAppConfig();o.useExternalWalletListings(o.shouldFetchWcRegistryListings(h?.appearance.walletList??[]));let[f,C]=t.useState(!1),A=He((e=>e.inProgressMfaFlow)),[T,_]=t.useState(!1),[k,S]=t.useState(null),b=Jt((e=>e.ethereum)),[W,U]=t.useState(void 0),[x,R]=t.useState(!1),[O,N]=t.useState(null),[M,F]=t.useState(!1),[L,D]=t.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:c.notImplemented}),[j,q]=t.useState({status:"initial"}),[z,H]=t.useState({status:"initial"}),[K,B]=t.useState({status:"initial"}),[V,Y]=t.useState({status:"initial"}),[G,$]=t.useState({status:"initial"}),[J,Q]=t.useState({status:"initial"}),[Z,X]=t.useState(null),ee=p.useIsServerConfigLoaded(),[te,ne]=t.useState({}),[ie,oe]=t.useState(null),le=t.useRef(null),[ce,de]=t.useState(!1),[ue,he]=t.useState(!1),pe=t.useRef(null),ye=t.useRef(null),me=t.useRef(P.privyEventsDefault),[ve,Ee]=t.useState(!1),[ke,Re]=t.useState(!1),Oe=t.useCallback((e=>{Re(e),!e&&O&&qe[O]().then((e=>{e.default.isUnauthenticatedScreem&&N(null)}))}),[O]);i.onStoreCustomerAccessToken=e=>{e&&P.emitPrivyEvent(me,"accessToken","onAccessTokenGranted",{accessToken:e})},i.onDeleteCustomerAccessToken=()=>{S(null),Oe(!1),P.emitPrivyEvent(me,"accessToken","onAccessTokenRemoved")};let Me=t.useRef(null),ze=t.useRef(null),Be=t.useRef(!1),Ve=({showWalletUIs:e})=>Be.current?Be.current:void 0!==e?!e:!h.embeddedWallets.showWalletUIs,Ye=e=>{N(e),setTimeout((()=>{C(!0)}),15)};t.useEffect((()=>{if(!k)return void i.connectors?.removeEmbeddedWalletConnectors();let e=a.getPrivyEthereumWallet(k),t=a.getPrivyEthereumHDWallets(k),r=a.getImportedPrivyEthereumWallets(k);e&&t.length||i.connectors?.removeEmbeddedWalletConnectors(),r.length||i.connectors?.removeImportedWalletConnectors(),i.connectors?Z?(e&&i.connectors.addEmbeddedWalletConnectors({walletProxy:Z,user:k,embeddedWallets:t,defaultChain:h.defaultChain,appId:n.appId,privyClient:s}),r.forEach((e=>i.connectors?.addImportedWalletConnector(Z,e.address,h.defaultChain,n.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")}),[Z,k]),t.useEffect((()=>{Z&&le.current?.(Z)}),[Z]);let Ge=t.useCallback(((e,t)=>{S(e),R(t),Oe(!0),he(!0)}),[]);t.useEffect((()=>{ue&&Z&&k&&(async()=>{let e=zt(k,h.embeddedWallets.ethereum.createOnLogin),t=Kt(k,h.embeddedWallets.solana.createOnLogin),r=await re();if(r){if(e&&t){let e=await Z.create({accessToken:r});return await Z.createSolana({accessToken:r,ethereumAddress:e?.address}),void he(!1)}if(t)return await Z.createSolana({accessToken:r,ethereumAddress:a.getPrivyEthereumWallet(k)?.address}),await vt.refreshSessionAndUser(),void he(!1);if(e)return await Z.create({accessToken:r}),void he(!1)}})().catch(console.error)}),[ue&&Z&&k]),t.useEffect((()=>{if(h.externalWallets.solana.connectors)return h.externalWallets.solana.connectors.onMount(),()=>h.externalWallets.solana.connectors?.onUnmount()}),[h.externalWallets.solana.connectors]),t.useEffect((()=>{!T&&ee&&async function(){let e,t=$e(),r=Je(),n=y.createStore();i.initializeConnectorManager({walletConnectCloudProjectId:h.walletConnectCloudProjectId,rpcConfig:h.rpcConfig,chains:h.chains,defaultChain:h.defaultChain,store:n,walletList:h.appearance.walletList,shouldEnforceDefaultChainOnConnect:h.shouldEnforceDefaultChainOnConnect,externalWalletConfig:h.externalWallets,appName:h.name??"Privy",walletChainType:h.appearance.walletChainType,setBaseAccountSdk:U}),i.connectors?.on("connectorInitialized",(()=>{e&&clearTimeout(e);let t=i.connectors.walletConnectors.length,r=i.connectors.walletConnectors.reduce(((e,t)=>e+(t.initialized?1:0)),0);r===t?Ee(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),Ee(!0)}),1500)})),i.connectors?.initialize().then((()=>{tt()}));let a=await i.getAuthenticatedUser(),s=!!a;h.legal.requireUsersAcceptTerms&&a&&!a.hasAcceptedTerms?(await i.logout(),vt.setReadyToTrue(!0),P.emitPrivyEvent(me,"logout","onSuccess")):(h.customAuth?.enabled||(Oe(!!a),a&&P.emitPrivyEvent(me,"login","onComplete",{user:a,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),S(a)),t?ze.current=s?"link":"login":r&&!s?(ze.current="login",ne({telegramAuthModalData:{seamlessAuth:!0}}),Ye("TelegramAuthScreen")):vt.setReadyToTrue(!!a))}()}),[i,ie,T,ee]),t.useEffect((()=>{if(T){if(!k||!k.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void de(!!Z);if([...b].some((e=>"privy"===e.walletClientType)))return void de(!0);de(!!Z)}}),[T,k,b,Z]),t.useEffect((()=>{i.connectors?.setWalletList(h.appearance.walletList)}),[h.appearance.walletList.join()]);let $e=()=>{let e=_e();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&&e.provider.startsWith("privy:")&&!e.popupFlow&&(new BroadcastChannel(St).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(i.startAuthFlow(new Te({...e,customOAuthRedirectUrl:h.customOAuthRedirectUrl})),Ye("OAuthStatusScreen"),!0))},Je=()=>{let e=function(){let e;return(e=function(){let e=new URLSearchParams(window.location.search),t=Number(e.get("id")||""),r=e.get("hash"),n=Number(e.get("auth_date")||""),i=e.get("first_name");if(t&&i&&n&&r)return Object.fromEntries(e.entries())}())?(De(),{flowType:"login-url",authData:e}):(e=function(){let e=window.location.hash;if(!e||!e.startsWith("#tgWebAppData"))return;let t=Le(e.replace("#tgWebAppData=","")),{user:r,auth_date:n,hash:i}=t;return r&&n&&i?t:void 0}())?(De(),{flowType:"web-app",authData:e}):void 0}();if(!e||!h.loginMethods.telegram||!h.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new Fe;return i.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},Qe=async(e,t,r,n)=>{if("solana_adapter"!==e)Ze(await(i.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,n);else{let e=i.connectors?.findSolanaWalletConnector(t);if(!e)return;Ze(e,t,r,n)}};async function Ze(e,t,r,n){if(!e)return D({status:"disconnected",connectedWallet:null,connectError:new c.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:c.notImplemented}),n?.(null,r);D({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:c.notImplemented}),e instanceof dt&&t&&await e.resetConnection(t),D({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>Ze(e,t,r,n)});try{let t=await e.connect({showPrompt:!0});if((!t||o.isBaseConnectedEthereumWallet(t))&&h.shouldEnforceDefaultChainOnConnect&&!h.chains.find((e=>e.id===Number(t?.chainId.replace("eip155:",""))))&&("wallet_connect_v2"!==t?.connectorType||"metamask"!==t?.walletClientType)){D((t=>({...t,connector:e,status:"switching_to_supported_chain",connectedWallet:null,connectError:null,connectRetry:c.notImplemented})));try{await(t?.switchChain(h.defaultChain.id)),t&&(t.chainId=o.formatChainIdToCAIP2(m.toHex(h.defaultChain.id)))}catch{console.warn(`Unable to switch to default chain: ${h.defaultChain.id}`)}}return D((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:c.notImplemented}))),t&&P.emitPrivyEvent(me,"connectWallet","onSuccess",{wallet:t}),n?.(t,r)}catch(e){return e instanceof c.PrivyError?(console.warn(e.cause?e.cause:e.message),P.emitPrivyEvent(me,"connectWallet","onError",e.privyErrorCode||c.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),P.emitPrivyEvent(me,"connectWallet","onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),D((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Xe=async(e,t,r)=>{if(null===e||!o.isBaseConnectedEthereumWallet(e))return;let n=new Ie(i,e,t,r);i.startAuthFlow(n)},et=async(e,t,r,n="plain")=>{let a=u(E.SOLANA_LEDGER_PLUGIN_ID);if("transaction"===n&&!a)throw new c.PrivyClientError("useSolanaLedger plugin hook must be mounted");if(null===e||!o.isBaseConnectedSolanaWallet(e))return;let s=new We(e,i,t,r,n,a);i.startAuthFlow(s)},tt=async()=>{let e=new URLSearchParams(window.location.search),t=e.get("privy_connector"),r=e.get("privy_wallet_client"),n="true"===e.get("privy_connect_only");if(!t||!r)return;let a=o.getWalletConfigForConnector({connectorType:t,walletClientType:r});if(!a||!a.isInstalled)return Ye("LoginFailedScreen");if(!i.connectors)throw new c.PrivyClientError("Connector not initialized");await Ye(n?"ConnectOnlyStatusScreen":"ConnectionStatusScreen");let s=new URL(window.location.href);s.searchParams.delete("privy_connector"),s.searchParams.delete("privy_wallet_client"),s.searchParams.delete("privy_connect_only"),window.history.pushState({},"",s),Qe(t,r,void 0,n?void 0:"solana_adapter"===t?et:Xe)};t.useEffect((()=>{T&&ke&&null===k&&i.getAuthenticatedUser().then(S)}),[T,ke,k,i]);let rt=e=>{if(!ke)throw P.emitPrivyEvent(me,"linkAccount","onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new c.PrivyClientError("User must be authenticated before linking an account.")},nt=e=>{if(!ke||!k)return!1;if("privy"===e.walletClientType)return!0;for(let t of k.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},at=()=>{Jt.setState((e=>{let t=i.connectors?.wallets.filter(o.isBaseConnectedEthereumWallet).map((e=>({...e,linked:nt(e),loginOrLink:async()=>{if(!await e.isConnected())throw new c.PrivyClientError("Wallet is not connected");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new c.PrivyClientError("Cannot link or login with embedded wallet");(async e=>{let t;if(!i.connectors)throw new c.PrivyClientError("Connector not initialized");t="ethereum"===e.type?i.connectors.findWalletConnector(e.connectorType,e.walletClientType)||null:i.connectors.findSolanaWalletConnector(e.walletClientType)||null,D((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:c.notImplemented}))),h.captchaEnabled&&!ke?(ne({captchaModalData:{callback:t=>o.isBaseConnectedEthereumWallet(e)?Xe(e,t):et(e,t),userIntentRequired:!1,onSuccessNavigateTo:"ConnectionStatusScreen",onErrorNavigateTo:"ErrorScreen"}}),await Ye("CaptchaScreen")):(o.isBaseConnectedEthereumWallet(e)?await Xe(e):await et(e),await Ye("ConnectionStatusScreen"))})(e)},fund:async t=>{await vt.fundWallet(e.address,t)},unlink:async()=>{if(!ke)throw new c.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new c.PrivyClientError("Cannot unlink an embedded wallet");S(await i.unlinkEthereumWallet(e.address))}})))||[];return o.areWalletArraysEqual(e.ethereum,t)?{}:{ethereum:t}}))};t.useEffect((()=>{at()}),[k?.linkedAccounts,ke,T]),t.useEffect((()=>{if(T){if(!i.connectors)throw new c.PrivyClientError("Connector not initialized");at(),i.connectors.on("walletsUpdated",at)}}),[T]),t.useEffect((()=>{[...h.loginMethodsAndOrder?.primary??[],...h.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>i.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!i]);let st=({transaction:e,sponsor:t,uiOptions:u,fundWalletConfig:p,address:y,signOnly:w})=>new Promise((async(v,g)=>{let{requesterAppId:f}=u||{},E=w?"signTransaction":"sendTransaction",C=y?a.getPrivyWalletWithAddress(k,y):a.getPrivyEthereumWallet(k);if(!C&&y){let r=a.getConnectedWalletWithAddress(Qt(),y);if(r){if(t)throw new c.PrivyClientError("Cannot sponsor transactions for externally connected wallet.");try{let t=await r.getEthereumProvider(),n={...e,from:y,chainId:e.chainId||Number(r.chainId.replace("eip155:","")),value:void 0!==e.value?m.toHex(e.value):void 0},i=await t.request({method:"sendTransaction"===E?"eth_sendTransaction":"eth_signTransaction",params:[n]});return P.emitPrivyEvent(me,E,"onSuccess",{hash:i}),void v({hash:i})}catch(e){return P.emitPrivyEvent(me,E,"onError",c.PrivyErrorCode.TRANSACTION_FAILURE),void g(e??new d.PrivyProviderRpcError("Unable to "+E+e))}}}if(!C)return P.emitPrivyEvent(me,E,"onError",c.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void g(new c.PrivyClientError("No embedded or connected wallet found for address."));if(!ke||!k)return P.emitPrivyEvent(me,E,"onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED),void g(Error("User must be authenticated before signing with a Privy wallet"));let A=C.address,T=C.walletIndex??0,{entropyId:_,entropyIdVerifier:S}=l.getEntropyDetailsForUser(k,C),b=gt.wallets.find((e=>"privy"===e.walletClientType&&m.getAddress(e.address)===m.getAddress(A)));if(!b)return P.emitPrivyEvent(me,E,"onError",c.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void g(Error("Must have a Privy wallet before signing"));let W=await b.getEthereumProvider(),U=await W.request({method:"eth_chainId"}),x=e.chainId?Number(e.chainId):d.extractChainIdFromCAIP2(U);(e=>{if(!h.chains.map((e=>e.id)).includes(e))throw new c.PrivyConnectorError(`Chain ID ${e} is not supported. It must be added to the config.supportedChains property of the PrivyProvider.`,c.PrivyErrorCode.UNSUPPORTED_CHAIN_ID)})(x);let R={...e,from:e.from??A,chainId:x},O=await re();if(!O||!Z)return P.emitPrivyEvent(me,E,"onError",c.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void g(Error("Must have valid access token and Privy wallet to send transaction"));let N=I.getPublicClient(R.chainId,h.chains,h.rpcConfig,{appId:n.appId}),M=a.getIsUnifiedWallet(C),F=async({transactionRequest:e})=>{try{let n;if(!await vt.recoverEmbeddedWallet({address:A}))throw P.emitPrivyEvent(me,E,"onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),g(Error("Unable to connect to wallet")),Error("Unable to connect to wallet");if(t){let t=await(async({transactionRequest:e})=>{if(!M)throw new c.PrivyClientError("Sponsoring is only supported for wallets on the TEE stack");if(w)throw new c.PrivyClientError("Cannot sponsor a sign transaction request");let t=e=>null==e?void 0:m.toHex(e),n=await r.rpc(s,(async({message:e})=>await Z.signWithUserSigner({accessToken:O,requesterAppId:f,message:e})),{chain_type:"ethereum",method:"eth_sendTransaction",caip2:o.formatChainIdToCAIP2(m.toHex(e.chainId)),sponsor:!0,params:{transaction:{from:e.from,to:e.to,chain_id:t(e.chainId),data:m.isHex(e.data)?e.data?e.data:m.toHex(Uint8Array.from(e.data)):void 0,value:t(e.value)}},wallet_id:C.id});if(n.data&&"hash"in n.data)return n.data.hash;throw new d.PrivyProviderRpcError("Unable to sign transaction")})({transactionRequest:e});return P.emitPrivyEvent(me,"sendTransaction","onSuccess",{hash:t}),t}if(M){let t=e=>null==e?void 0:m.toHex(e),i=await r.rpc(s,(async({message:e})=>await Z.signWithUserSigner({accessToken:O,requesterAppId:f,message:e})),{chain_type:"ethereum",method:"eth_signTransaction",params:{transaction:{from:e.from,to:e.to,nonce:t(e.nonce),chain_id:t(e.chainId),data:m.isHex(e.data)?e.data?e.data:m.toHex(Uint8Array.from(e.data)):void 0,value:t(e.value),type:e.type,gas_limit:t(e.gasLimit??e.gas),gas_price:t(e.gasPrice??e.gas),max_fee_per_gas:t(e.maxFeePerGas),max_priority_fee_per_gas:t(e.maxPriorityFeePerGas)}},wallet_id:C.id});if(!i.data||!("signed_transaction"in i.data))throw new d.PrivyProviderRpcError("Unable to sign transaction");n=i.data.signed_transaction}else n=await async function({accessToken:e,entropyId:t,entropyIdVerifier:r,transactingWalletIndex:n,walletProxy:i,transactionRequest:a,requesterAppId:s}){return(await i.rpc({entropyId:t,entropyIdVerifier:r,hdWalletIndex:n??0,chainType:"ethereum",accessToken:e,requesterAppId:s,request:{method:"eth_signTransaction",params:[a]}})).response.data}({accessToken:O,entropyId:_,entropyIdVerifier:S,transactingWalletIndex:T,walletProxy:Z,transactionRequest:e,requesterAppId:f});if(w)return P.emitPrivyEvent(me,"signTransaction","onSuccess",{signature:n}),n;{let e=await N.sendRawTransaction({serializedTransaction:n});return P.emitPrivyEvent(me,"sendTransaction","onSuccess",{hash:e}),e}}catch(e){throw P.emitPrivyEvent(me,E,"onError",c.PrivyErrorCode.TRANSACTION_FAILURE),e}};if(Ve({showWalletUIs:u?.showWalletUIs})){let e=w||t?R:await Vt(R,N,R.from);try{let t=await F({transactionRequest:e});w?P.emitPrivyEvent(me,"signTransaction","onSuccess",{signature:t}):P.emitPrivyEvent(me,"sendTransaction","onSuccess",{hash:t}),v({hash:t})}catch(e){P.emitPrivyEvent(me,E,"onError",c.PrivyErrorCode.TRANSACTION_FAILURE),g(e)}}else{let e={connectingWalletAddress:A,recoveryMethod:C.recoveryMethod,entropyId:_,entropyIdVerifier:S,onCompleteNavigateTo:"SendTransactionScreen",isUnifiedWallet:M,onFailure:e=>{P.emitPrivyEvent(me,E,"onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),g(e)}},r=(e=>!!e.fundingConfig&&d.filterSupportedOptions(e.fundingConfig.options).length>=1)(h)?d.prepareFundingModalData({address:A,appConfig:h,fundWalletConfig:p,methodScreen:"FundingMethodSelectionScreen",chainIdOverride:R.chainId,comingFromSendTransactionScreen:!0}):void 0;ne({connectWallet:e,sendTransaction:{transactionRequest:R,transactingWalletIndex:T,transactingWalletAddress:A,entropyId:_,entropyIdVerifier:S,signOnly:w,scanTransaction:async()=>{let e=await Vt(R,N,R.from);return await i.scanTransaction({metadata:{domain:h.embeddedWallets.transactionScanning.domain},chain_id:e.chainId.toString(),request:{method:"eth_sendTransaction",params:[{from:e.from,to:e.to,value:e.value?.toString(),gas:e.gas?.toString(),gasPrice:e.gasPrice?.toString(),nonce:e.nonce?.toString(),data:e.data}]}})},getIsSponsored:async()=>!!t,onConfirm:({transactionRequest:e})=>F({transactionRequest:e}),onSuccess:e=>{w?P.emitPrivyEvent(me,"signTransaction","onSuccess",{signature:e.hash}):P.emitPrivyEvent(me,"sendTransaction","onSuccess",{hash:e.hash}),v(e)},onFailure:e=>{P.emitPrivyEvent(me,E,"onError",c.PrivyErrorCode.TRANSACTION_FAILURE),g(e)},uiOptions:u||{},fundWalletConfig:p,requesterAppId:f},funding:r}),Ye("EmbeddedWalletConnectingScreen")}}));function ot(){return new Promise((async(e,t)=>{let r=await re();if(!r||!Z)throw Error("Must have valid access token to enroll in MFA");try{await Z.verifyMfa({accessToken:r}),e()}catch(e){t(e)}}))}let ut=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],ht=e=>{let t=k?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=qt(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw P.emitPrivyEvent(me,"linkAccount","onError",c.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE,{linkMethod:n}),new c.PrivyClientError(`User already has an account of type ${r} linked.`)};async function pt({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){N(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!ke||!k)throw P.emitPrivyEvent(me,r,"onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=a.getPrivyPrimaryWallet(k);if(!n||!Z)throw P.emitPrivyEvent(me,r,"onError",c.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),Error("Must have a Privy wallet to add a recovery method");let i=a.getIsUnifiedWallet(n);if(i)throw P.emitPrivyEvent(me,r,"onError",c.PrivyErrorCode.UNSUPPORTED_WALLET_TYPE),new c.PrivyClientError("User owned wallet recovery is only supported for on-device execution and this app uses TEE execution. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");try{await ot()}catch(e){throw P.emitPrivyEvent(me,r,"onError",c.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((a,s)=>{let o="user-passcode"===n.recoveryMethod,d=Nt({walletAction:"update",availableRecoveryMethods:h.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:o,showAutomaticRecovery:e}),{entropyId:u,entropyIdVerifier:p}=l.getEntropyDetailsForUser(k),y={recoveryMethod:n.recoveryMethod,connectingWalletAddress:n.address,onCompleteNavigateTo:d,shouldForceMFA:!1,entropyId:u,isUnifiedWallet:i,entropyIdVerifier:p,onFailure:e=>{P.emitPrivyEvent(me,r,"onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}};ne({setWalletPassword:{onSuccess:e=>{P.emitPrivyEvent(me,r,"onSuccess",{method:"user-passcode",wallet:e}),a(e)},onFailure:e=>{P.emitPrivyEvent(me,r,"onError",c.PrivyErrorCode.USER_EXITED_SET_PASSWORD_FLOW),s(e)},callAuthOnSuccessOnClose:!1},recoverWallet:{entropyId:u,entropyIdVerifier:p,onFailure:s},connectWallet:y,recoverySelection:{isInAccountCreateFlow:!1,isResettingPassword:o,shouldCreateEth:!1,shouldCreateSol:!1}}),Ye("EmbeddedWalletConnectingScreen")}))}async function wt({appId:e,action:t}){let r=await re();if("link"===t&&!r)throw P.emitPrivyEvent(me,"linkAccount","onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new c.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&r)throw P.emitPrivyEvent(me,"login","onError",c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),new c.PrivyClientError("Attempted to log in, but user is already logged in. Use a `link` helper instead.");Me.current=`privy:${e}`,ze.current=t;let n=v.trigger();return i.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(r,a)=>{let{name:s,logoUrl:o}=await Wt({api:i.api,providerAppId:e,requesterAppId:h.id});ne({crossAppAuth:{appId:e,name:s,logoUrl:o,action:t,popup:n,onSuccess:r,onError:a}}),Ye("CrossAppAuthScreen")}))}let mt={ready:T,authenticated:ke,user:k,walletConnectors:i.connectors||null,connectWallet:e=>{e&&"target"in e&&e&&(e=void 0),ne({externalConnectWallet:{walletList:e?.walletList&&e?.walletList.length>0?e.walletList:void 0,walletChainType:e?.walletChainType,description:e?.description,hideHeader:e?.hideHeader}}),Ye("ConnectOnlyLandingScreen")},linkWallet:e=>(e&&"target"in e&&e&&(e=void 0),rt("siwe"),Me.current="siwe",ze.current="link",ne({...te,externalConnectWallet:{...te.externalConnectWallet,walletList:e?.walletList,walletChainType:e?.walletChainType,description:e?.description||`Link a wallet to your ${h?.name} account`}}),Ye("AuthenticateWithWalletScreen")),startCrossAppAuthFlow:wt,linkEmail:()=>{rt("email"),ht("email"),Me.current="email",ze.current="link",Ye("LinkEmailScreen")},linkPhone:()=>{rt("sms"),ht("phone"),Me.current="sms",ze.current="link",Ye("LinkPhoneScreen")},linkGoogle:async()=>{rt("google"),ht("google_oauth"),ze.current="link",await vt.initLoginWithOAuth("google")},linkTwitter:async()=>{rt("twitter"),ht("twitter_oauth"),ze.current="link",await vt.initLoginWithOAuth("twitter")},linkTwitch:async()=>{rt("twitch"),ht("twitch_oauth"),ze.current="link",await vt.initLoginWithOAuth("twitch")},linkDiscord:async()=>{rt("discord"),ht("discord_oauth"),ze.current="link",await vt.initLoginWithOAuth("discord")},linkGithub:async()=>{rt("github"),ht("github_oauth"),ze.current="link",await vt.initLoginWithOAuth("github")},linkSpotify:async()=>{rt("spotify"),ht("spotify_oauth"),ze.current="link",await vt.initLoginWithOAuth("spotify")},linkInstagram:async()=>{rt("instagram"),ht("instagram_oauth"),ze.current="link",await vt.initLoginWithOAuth("instagram")},linkTiktok:async()=>{rt("tiktok"),ht("tiktok_oauth"),ze.current="link",await vt.initLoginWithOAuth("tiktok")},linkLine:async()=>{rt("line"),ht("line_oauth"),ze.current="link",await vt.initLoginWithOAuth("line")},linkLinkedIn:async()=>{rt("linkedin"),ht("linkedin_oauth"),ze.current="link",await vt.initLoginWithOAuth("linkedin")},linkApple:async()=>{rt("apple"),ht("apple_oauth"),ze.current="link",await vt.initLoginWithOAuth("apple")},linkPasskey:async()=>{rt("passkey"),ht("passkey"),await vt.initLinkWithPasskey(),Ye("LinkPasskeyScreen")},linkTelegram:async e=>{if(rt("telegram"),ht("telegram"),ze.current="link",Me.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new Fe;i.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=Le(e.launchParams.initDataRaw),ne({telegramAuthModalData:{seamlessAuth:!0}}),Ye("TelegramAuthScreen")}else P.emitPrivyEvent(me,"linkAccount","onError",c.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await vt.initLoginWithTelegram();Ye("TelegramAuthScreen")},linkFarcaster:async()=>{rt("farcaster"),ht("farcaster"),await vt.initLoginWithFarcaster(),ze.current="link",Me.current="farcaster",Ye("FarcasterConnectStatusScreen")},updateEmail:()=>{if(rt("email"),!k?.email)throw new c.PrivyClientError("User does not have an email linked to their account.");ze.current="update",Me.current="email",Ye("UpdateEmailScreen")},updatePhone:()=>{if(rt("sms"),!k?.phone)throw new c.PrivyClientError("User does not have a phone number linked to their account.");ze.current="update",Me.current="sms",Ye("UpdatePhoneScreen")},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(!T){let e=await new Promise((e=>{oe((t=>e.bind(t)))}));if(oe(null),e)return void console.warn(t)}!k||k.isGuest?(ze.current="login",ne({login:e}),Ye("LandingScreen")):console.warn(t)},connectOrCreateWallet:async()=>{T||(await new Promise((e=>{oe((()=>e))})),oe(null)),ke?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(ze.current="connect-or-create",Ye("ConnectOrCreateScreen"))},logout:async()=>{if(ze.current=null,Me.current=null,k&&i.clearProviderAcccessTokens(k),N(null),await i.logout(),k&&Z)try{await Z.clearMfa({userId:k.id})}catch(e){}S(null),Oe(!1),H({status:"initial"}),B({status:"initial"}),q({status:"initial"}),Y({status:"initial"}),$({status:"initial"}),Q({status:"initial"}),P.emitPrivyEvent(me,"logout","onSuccess"),C(!1),d.u.del(p.CLIENT_ANALYTICS_ID_KEY),d.u.del(p.getGuestCredentialStorageKey(h.id))},getAccessToken:t.useCallback((async()=>{let e=await i.getCustomerAccessToken();return e&&!ke&&Oe(!0),e}),[i,ke]),unlinkWallet:async e=>{let t;return S(t=e.startsWith("0x")?await i.unlinkEthereumWallet(e):await i.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await i.unlinkEmail(e);return S(t),t},unlinkPhone:async e=>{let t=await i.unlinkPhone(e);return S(t),t},unlinkGoogle:async e=>{let t=await i.unlinkOAuth("google",e);return S(t),t},unlinkTwitter:async e=>{let t=await i.unlinkOAuth("twitter",e);return S(t),t},unlinkTwitch:async e=>{let t=await i.unlinkOAuth("twitch",e);return S(t),t},unlinkDiscord:async e=>{let t=await i.unlinkOAuth("discord",e);return S(t),t},unlinkGithub:async e=>{let t=await i.unlinkOAuth("github",e);return S(t),t},unlinkSpotify:async e=>{let t=await i.unlinkOAuth("spotify",e);return S(t),t},unlinkInstagram:async e=>{let t=await i.unlinkOAuth("instagram",e);return S(t),t},unlinkTiktok:async e=>{let t=await i.unlinkOAuth("tiktok",e);return S(t),t},unlinkLine:async e=>{let t=await i.unlinkOAuth("line",e);return S(t),t},unlinkLinkedIn:async e=>{let t=await i.unlinkOAuth("linkedin",e);return S(t),t},unlinkApple:async e=>{let t=await i.unlinkOAuth("apple",e);return S(t),t},unlinkFarcaster:async e=>{let t=await i.unlinkFarcaster(e);return S(t),t},unlinkTelegram:async e=>{let t=await i.unlinkTelegram(e);return S(t),t},unlinkPasskey:async e=>{let t=await re();if(!t)throw Error("Must have valid access token to enroll in MFA");if(!Z)throw Error("Wallet proxy not initialized.");let r=h.passkeys.shouldUnenrollMfaOnUnlink;await Z.unlinkPasskeyAccount({credentialId:e,accessToken:t,removeAsMfa:r});let n=await i.getAuthenticatedUser();return S(n),n},unlinkCrossAppAccount:async({subject:e})=>{let t=k?.linkedAccounts.find((t=>"cross_app"===t.type&&t.subject===e))?.providerApp;if(!t)throw new c.PrivyClientError("Invalid subject");i.storeProviderAccessToken(t.id,null);let r=await i.unlinkOAuth(`privy:${t.id}`,e);return S(r),r},setWalletRecovery:async e=>pt({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>pt({legacySetWalletPasswordFlow:!0,showAutomaticRecovery:!1}),signMessage:(e,t)=>new Promise((async(n,o)=>{let{requesterAppId:u}=t?.uiOptions||{},h=e.message,p=t?.address?a.getPrivyWalletWithAddress(k,t.address):a.getPrivyEthereumWallet(k);if(!p&&void 0!==t?.address){let e=a.getConnectedWalletWithAddress(Qt(),t.address);if(e)try{let t=await e.getEthereumProvider(),r=await t.request({method:"personal_sign",params:[h,e.address]});return P.emitPrivyEvent(me,"signMessage","onSuccess",{signature:r}),void n({signature:r})}catch(e){return P.emitPrivyEvent(me,"signMessage","onError",c.PrivyErrorCode.UNABLE_TO_SIGN),void o(e??new d.PrivyProviderRpcError("Unable to sign message"))}}if(!p)throw new c.PrivyClientError("No embedded or connected wallet found for address.");if(!ke||!k)return P.emitPrivyEvent(me,"signMessage","onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED),void o(Error("User must be authenticated before signing with a Privy wallet"));let y=p.address,w=p.walletIndex??0,{entropyId:v,entropyIdVerifier:g}=l.getEntropyDetailsForUser(k,p),f=a.getIsUnifiedWallet(p);if("string"!=typeof h||h.length<1)return P.emitPrivyEvent(me,"signMessage","onError",c.PrivyErrorCode.INVALID_MESSAGE),void o(Error("Message must be a non-empty string"));let E=async()=>{let t;if(!ke)throw Error("User must be authenticated before signing with a Privy wallet");let n=await re();if(!Z||!n||!await vt.recoverEmbeddedWallet({address:y}))throw Error("Unable to connect to wallet");if(i.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_started",payload:{walletAddress:y,requesterAppId:u}}),f){let i=m.isHex(e.message,{strict:!0}),a=await r.rpc(s,(async({message:e})=>await Z.signWithUserSigner({accessToken:n,requesterAppId:u,message:e})),{chain_type:"ethereum",method:"personal_sign",params:i?{message:h.slice(2),encoding:"hex"}:{message:h,encoding:"utf-8"},wallet_id:p.id});if(!a.data||!("signature"in a.data))throw new d.PrivyProviderRpcError("Unable to sign message");t=a.data.signature}else{let{response:e}=await Z.rpc({accessToken:n,entropyId:v,entropyIdVerifier:g,chainType:"ethereum",hdWalletIndex:w,requesterAppId:u,request:{method:"personal_sign",params:[h,y]}});t=e.data}return i.createAnalyticsEvent({eventName:"embedded_wallet_sign_message_completed",payload:{walletAddress:y,requesterAppId:u}}),t};if(Ve({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await E();P.emitPrivyEvent(me,"signMessage","onSuccess",{signature:e}),n({signature:e})}catch(e){P.emitPrivyEvent(me,"signMessage","onError",c.PrivyErrorCode.UNABLE_TO_SIGN),o(e??new d.PrivyProviderRpcError("Unable to sign message"))}else ne({signMessage:{method:"personal_sign",data:h,confirmAndSign:E,onSuccess:e=>{P.emitPrivyEvent(me,"signMessage","onSuccess",{signature:e}),n({signature:e})},onFailure:e=>{P.emitPrivyEvent(me,"signMessage","onError",c.PrivyErrorCode.UNABLE_TO_SIGN),o(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:p.recoveryMethod,connectingWalletAddress:y,entropyId:v,entropyIdVerifier:g,onCompleteNavigateTo:"SignRequestScreen",isUnifiedWallet:f,onFailure:e=>{P.emitPrivyEvent(me,"signMessage","onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),o(e)}}}),Ye("EmbeddedWalletConnectingScreen")})),signTypedData:(e,t)=>new Promise((async(n,u)=>{let{requesterAppId:h}=t?.uiOptions||{},p=t?.address?a.getPrivyWalletWithAddress(k,t.address):a.getPrivyEthereumWallet(k);if(!p&&t?.address){let r=a.getConnectedWalletWithAddress(Qt(),t.address);if(r)try{let t=await r.getEthereumProvider(),i=o.generateTypedDataWithDomainType(e),a=await t.request({method:"eth_signTypedData_v4",params:[r.address,i]});return P.emitPrivyEvent(me,"signTypedData","onSuccess",{signature:a}),void n({signature:a})}catch(e){return P.emitPrivyEvent(me,"signTypedData","onError",c.PrivyErrorCode.UNABLE_TO_SIGN),void u(e??new d.PrivyProviderRpcError("Unable to sign typed data "+e))}}if(!p)throw new c.PrivyClientError("No embedded or connected wallet found for address.");if(!ke||!k)return P.emitPrivyEvent(me,"signTypedData","onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED),void u(Error("User must be authenticated before signing with a Privy wallet"));let y=p.address,w=p.walletIndex??0,{entropyId:m,entropyIdVerifier:v}=l.getEntropyDetailsForUser(k,p),g=a.getIsUnifiedWallet(p),f=o.generateTypedDataWithDomainType(e),E=async()=>{let e;if(!ke)throw Error("User must be authenticated before signing with a Privy wallet");let t=await re();if(!Z||!t||!await vt.recoverEmbeddedWallet({address:y}))throw Error("Unable to connect to wallet");if(i.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_started",payload:{walletAddress:y,requesterAppId:h}}),g){let{domain:n,types:i,primaryType:a,message:o}=f,l=await r.rpc(s,(async({message:e})=>await Z.signWithUserSigner({accessToken:t,requesterAppId:h,message:e})),{chain_type:"ethereum",method:"eth_signTypedData_v4",params:{typed_data:{domain:n,types:i,primary_type:a,message:o}},wallet_id:p.id});if(!l.data||!("signature"in l.data))throw new d.PrivyProviderRpcError("Unable to sign message");e=l.data.signature}else{let{response:r}=await Z.rpc({accessToken:t,entropyId:m,entropyIdVerifier:v,chainType:"ethereum",hdWalletIndex:w,requesterAppId:h,request:{method:"eth_signTypedData_v4",params:[y,f]}});e=r.data}return i.createAnalyticsEvent({eventName:"embedded_wallet_sign_typed_data_completed",payload:{walletAddress:y,requesterAppId:h}}),e};if(Ve({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await E();P.emitPrivyEvent(me,"signTypedData","onSuccess",{signature:e}),n({signature:e})}catch(e){P.emitPrivyEvent(me,"signTypedData","onError",c.PrivyErrorCode.UNABLE_TO_SIGN),u(e??new d.PrivyProviderRpcError("Unable to sign message"))}else ne({signMessage:{method:"eth_signTypedData_v4",data:f,confirmAndSign:E,onSuccess:e=>{P.emitPrivyEvent(me,"signTypedData","onSuccess",{signature:e}),n({signature:e})},onFailure:e=>{P.emitPrivyEvent(me,"signTypedData","onError",c.PrivyErrorCode.UNABLE_TO_SIGN),u(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:p.recoveryMethod,connectingWalletAddress:p.address,entropyId:m,isUnifiedWallet:g,entropyIdVerifier:v,onCompleteNavigateTo:"SignRequestScreen",onFailure:e=>{P.emitPrivyEvent(me,"signMessage","onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),u(e)}}}),Ye("EmbeddedWalletConnectingScreen")})),sendTransaction:async(e,t)=>await st({transaction:e,sponsor:t?.sponsor,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await st({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),exportWallet:e=>new Promise((async(t,r)=>{if(!ke||!k)return void r(Error("User must be authenticated before exporting their Privy wallet"));e&&"target"in e&&e&&(e=void 0);let s=e?.address?a.getPrivyWalletWithAddress(k,e.address):a.getPrivyEthereumWallet(k);if(!s)return void r(new c.PrivyClientError("User must have an embedded wallet."));let o=s.address,{entropyId:u,entropyIdVerifier:h}=l.getEntropyDetailsForUser(k,s),p=a.getIsUnifiedWallet(s);if(!o)return void r(Error("User does not have an HD Ethereum wallet. To export an imported wallet, pass the `address` of the wallet to `exportWallet`."));if(!m.isAddress(o))return void r(Error("Must provide a valid Ethereum address."));let y={recoveryMethod:s.recoveryMethod,connectingWalletAddress:s.address,isUnifiedWallet:p,entropyId:u,entropyIdVerifier:h,onCompleteNavigateTo:"EmbeddedWalletKeyExportScreen",onFailure:r,shouldForceMFA:!0};ne(te),await re()&&Z?Z?d.isFirstClassChainWallet(s)?(ne({keyExport:{appId:n.appId,appClientId:n.clientId,origin:i.apiUrl,address:s.address,entropyId:u,entropyIdVerifier:h,hdWalletIndex:s.walletIndex,chainType:s.chainType,walletId:s.id,isUnifiedWallet:p,imported:s.imported,onSuccess:t,onFailure:r},connectWallet:y}),Ye("EmbeddedWalletConnectingScreen")):r(Error(`Export is not supported for ${s.chainType} wallets`)):r(Error("Must have a Privy wallet before exporting")):r(Error("Must have valid access token to enroll in MFA"))})),promptMfa:ot,async init(e){switch(e){case"sms":return void await i.initMfaSmsVerification();case"passkey":return await i.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 c.PrivyClientError("Invalid MFA code");pe.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{ye.current={resolve:e,reject:t}}));break;case"passkey":if("string"==typeof t)throw new c.PrivyClientError("Invalid authenticator response");let r=await import("@simplewebauthn/browser"),n=$t(await r.startAuthentication({optionsJSON:t}));pe.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{ye.current={resolve:e,reject:t}}));break;default:throw pe.current?.reject(new c.PrivyClientError("Unsupported MFA method")),new c.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){pe.current?.reject(new c.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await re();if(!t||!Z)throw Error("Must have valid access token to enroll in MFA");await Z.initEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber})},enrollInMfa:e=>new Promise(((t,r)=>{if(!e)return vt.closePrivyModal(),void t();h.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."),ne({mfaEnrollmentFlow:{mfaMethods:h.mfa.methods,shouldUnlinkOnUnenrollMfa:h.passkeys.shouldUnlinkOnUnenrollMfa,onSuccess:t,onFailure:r}}),Ye("MfaEnrollmentFlowScreen")})),async initEnrollmentWithTotp(){let e=await re();if(!e||!Z)throw Error("Must have valid access token to enroll in MFA");let t=await Z.initEnrollMfa({method:"totp",accessToken:e});return{secret:t.secret,authUrl:t.authUrl}},async submitEnrollmentWithSms(e){let t=await re();if(!t||!Z)throw Error("Must have valid access token to enroll in MFA");await Z.submitEnrollMfa({method:"sms",accessToken:t,phoneNumber:e.phoneNumber,code:e.mfaCode}),S(await i.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await re();if(!t||!Z)throw Error("Must have valid access token to enroll in MFA");await Z.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),S(await i.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await re();if(!r||!Z)throw Error("Must have valid access token to enroll in MFA");await Z.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:e,removeForLogin:t.removeForLogin}),S(await i.getAuthenticatedUser())},async unenroll(e,t={}){let r=await re();if(!r||!Z)throw Error("Must have valid access token to remove MFA");"passkey"===e?await Z.submitEnrollMfa({method:"passkey",accessToken:r,credentialIds:[],removeForLogin:t.removeForLogin}):await Z.unenrollMfa({method:e,accessToken:r}),S(await i.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await re(),t=k?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!e)throw Error("Must have valid access token to connect with Farcaster");if(!Z||!t)throw Error("Must have an embedded wallet to use Farcaster signers");if(a.getIsUnifiedWallet(t))throw new c.PrivyClientError("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!k?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await vt.recoverEmbeddedWallet({address:t.address}))throw Error("Unable to connect to wallet");let r=await Z.initFarcasterSigner({address:t.address,hdWalletIndex:null,accessToken:e,mfaCode:null,mfaMethod:null,relyingParty:window.origin});"approved"===r.status&&S(await i.getAuthenticatedUser()||k||null),ne({farcasterSigner:r}),Ye("FarcasterSignerStatusScreen")},getFarcasterSignerPublicKey:async()=>{let e,t=await re(),r=k?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Z||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(a.getIsUnifiedWallet(r))throw new c.PrivyClientError("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!k?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await vt.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!k.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=k.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await re(),r=k?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Z||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(a.getIsUnifiedWallet(r))throw new c.PrivyClientError("Farcaster signers are only supported for on-device execution and this app uses TEE execution. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");if(!k?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await vt.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!k.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");let n=await import("@simplewebauthn/browser"),i=await Z.signFarcasterMessage({address:r.address,hdWalletIndex:null,accessToken:t,mfaCode:null,mfaMethod:null,payload:{hash:n.bufferToBase64URLString(e)},fid:BigInt(k.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(i.signature))},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let n=k?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Ut({user:k,client:i,address:t,requesterAppId:h.id,request:{method:n?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:wt})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let n=k?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),a=o.generateTypedDataWithDomainType(e);return Ut({user:k,client:i,address:t,requesterAppId:h.id,request:{method:n?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,a],chainId:r},reconnect:wt})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=k?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Ut({user:k,client:i,address:t,requesterAppId:h.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:wt})},signTransactionWithCrossAppWallet(e,{address:t}){let r=k?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return Ut({user:k,client:i,address:t,requesterAppId:h.id,request:{method:r?"privy_signSmartWalletTx":"eth_signTransaction",params:[e],chainId:e.chainId},reconnect:wt})},isModalOpen:f||!!A,mfaMethods:h.mfa.methods};nr=mt.signMessage,ir=mt.signTypedData,sr=async(e,t)=>await st({transaction:e,...t,signOnly:!1}),ar=async(e,t)=>({signature:(await st({transaction:e,...t,signOnly:!0})).hash});let vt={privy:s,setAuthenticated:Oe,setUser:S,setIsNewUser:R,isNewUserThisSession:x,pendingTransaction:null,walletConnectionStatus:L,setWalletConnectionStatus:D,connectors:i.connectors?.walletConnectors??[],rpcConfig:h.rpcConfig,chains:h.chains,appId:n.appId,showFiatPrices:"native-token"!==h.embeddedWallets.priceDisplay.primary,clientAnalyticsId:i.clientAnalyticsId,onCustomAuthAuthenticated:Ge,hideWalletUIs:Be,isHeadlessSigning:t.useCallback(Ve,[h.embeddedWallets.showWalletUIs]),emailOtpState:z,setEmailOtpState:H,smsOtpState:K,setSmsOtpState:B,oAuthState:G,setOAuthState:$,telegramAuthState:J,setTelegramAuthState:Q,siweState:V,setSiweState:Y,isHeadlessOAuthLoading:M,baseAccountSdk:W,setBaseAccountSdk:U,nativeTokenSymbolForChainId:e=>h.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(Z)return Z;let t=new Promise((e=>{le.current=e})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return le.current=null,n},getAuthFlow:()=>i.authFlow,getAuthMeta:()=>i.authFlow?.meta,client:i,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=T&&ke&&k;if(r&&Me.current&&(t=ut(k)),"login"===ze.current)e.shouldCallAuthOnSuccess&&r&&Me.current?P.emitPrivyEvent(me,"login","onComplete",{user:k,isNewUser:x,wasAlreadyAuthenticated:!1,loginMethod:Me.current,loginAccount:t??null}):P.emitPrivyEvent(me,"login","onError",c.PrivyErrorCode.USER_EXITED_AUTH_FLOW);else if("link"===ze.current&&t)e.isSuccess&&r&&Me.current?P.emitPrivyEvent(me,"linkAccount","onSuccess",{user:k,linkMethod:Me.current,linkedAccount:t}):Me.current&&P.emitPrivyEvent(me,"linkAccount","onError",c.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:Me.current});else if("update"===ze.current&&t)e.isSuccess&&r&&Me.current?P.emitPrivyEvent(me,"update","onSuccess",{user:k,updateMethod:Me.current,updatedAccount:t}):Me.current&&P.emitPrivyEvent(me,"update","onError",c.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:Me.current});else if("connect-or-create"===ze.current){let e=Qt();e[0]?P.emitPrivyEvent(me,"connectOrCreateWallet","onSuccess",{wallet:e[0]}):P.emitPrivyEvent(me,"connectOrCreateWallet","onError",c.PrivyErrorCode.USER_EXITED_AUTH_FLOW)}let a=O&&Ft.has(O),s="ErrorScreen"===O&&te.errorModalData&&Ft.has(te.errorModalData.previousScreen);if((a||s)&&te.funding){let e,t=Ft.get(O)??null;if("solana"===te.funding.chainType){let r=h.solanaRpcs[te.funding.chain];if(!r)return void console.warn("Unable to load solana rpc, skipping balance");if(u(E.SOLANA_FUNDING_PLUGIN_ID))try{e=await Dt({rpc:r.rpc,address:te.funding.address})}catch{console.error("Unable to pull wallet balance")}else console.warn("Unable to load solana plugin, skipping balance");P.emitPrivyEvent(me,"fundSolanaWallet","onUserExited",{address:te.funding.address,fundingMethod:t,chain:te.funding.chain,balance:e})}else{let r=I.getPublicClient(te.funding.chain.id,h.chains,h.rpcConfig,{appId:n.appId});try{e=await r.getBalance({address:te.funding.address})}catch{console.error("Unable to pull wallet balance")}P.emitPrivyEvent(me,"fundWallet","onUserExited",{address:te.funding.address,chain:te.funding.chain,fundingMethod:t,balance:e})}}ne((e=>({...e,externalConnectWallet:{}}))),ze.current=null,Me.current=null,R(!1),C(!1),D({status:"disconnected",connectedWallet:null,connector:null,connectError:null,connectRetry:()=>{}}),setTimeout((()=>{i.authFlow=void 0}),200)},openPrivyModal:Ye,connectWallet:Ze,initLoginWithWallet:async(e,t,r,n)=>{o.isBaseConnectedEthereumWallet(e)?(Me.current="siwe",Xe(e,t,r)):(Me.current="siws",et(e,t,r,n))},loginWithWallet:async()=>{let e,t,r;if(!T)throw new c.PrivyNotReadyError;if(i.authFlow instanceof Ie?e="siwe":i.authFlow instanceof We&&(e="siws"),!e)throw new c.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await i.getAccessToken())try{({user:t}=await i.link()),Me.current=e}catch(t){throw P.emitPrivyEvent(me,"linkAccount","onError",t.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await i.authenticate()),Me.current=e}catch(e){throw P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}S(t||k||null),R(r||!1),Oe(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(n,i)=>{let s=await re();if(!ke||!k||!s)throw new c.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if("solana"!==t&&"ethereum"!==t)throw new c.PrivyClientError("Only Solana and Ethereum embedded wallets are supported for delegation and revocation.");let o=vt.walletProxy??await vt.initializeWalletProxy(15e3);if(!o)throw new c.PrivyClientError("Wallet proxy not initialized.");if((({address:e,user:t})=>!!kt(t).find((t=>t.address===e)))({address:e,user:k}))return n();let l=a.getPrivyWalletWithAddress(k,e);if(!l)throw new c.PrivyClientError("Address to delegate is not associated with current user.");if(a.getIsUnifiedWallet(l))throw new c.PrivyClientError("useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");let d=Tt({address:e,user:k}),u=_t({address:e,user:k}),h=async()=>{await o.createDelegatedAction({accessToken:s,rootWallet:u,delegatedWallets:[d]}),await vt.refreshSessionAndUser()};if(await vt.recoverEmbeddedWallet({address:e}),r)ne({delegatedActions:{consent:{address:e,onDelegate:h,onSuccess:async()=>{n()},onError:async e=>{i(e)}}}}),Ye("DelegatedActionsConsentScreen");else try{await h(),n()}catch(e){i(e)}})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!ke||!k)throw new c.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");let n=kt(k);if(0===n.length)throw new c.PrivyClientError("User has no delegated wallets to revoke.");if(n.some(a.getIsUnifiedWallet))throw new c.PrivyClientError("useDelegatedActions is only supported for on-device execution and this app uses TEE execution. Use the useSessionSigners hook to provision server side access on behalf of your users. Learn more at https://docs.privy.io/recipes/tee-wallet-migration-guide");let s=async()=>{await i.revokeDelegatedWallet(),await vt.refreshSessionAndUser()};if(e)ne({delegatedActions:{revoke:{onRevoke:s,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),Ye("DelegatedActionsRevokeScreen");else try{await s(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new we(e,t);i.startAuthFlow(r);try{Me.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===ze.current?P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ze.current&&P.emitPrivyEvent(me,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"farcaster"}),e}},loginWithFarcaster:async()=>{let e,t;if(!T)throw new c.PrivyNotReadyError;if(!(i.authFlow instanceof we))throw new c.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await i.getAccessToken())try{({user:e}=await i.link()),Me.current="farcaster"}catch(e){throw P.emitPrivyEvent(me,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await i.authenticate()),Me.current="farcaster"}catch(e){throw P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}S(e||null),R(t||!1),Oe(!0)},async crossAppAuthFlow({appId:e,popup:t,action:r}){let n=`privy:${e}`;Me.current=n;let{url:a,stateCode:s,codeVerifier:o}=await async function({api:e,appId:t}){let r=Ce(),n=Ae(),i=await Pe(r);try{let{url:a}=await e.post(g.oAuthInitPath,{provider:`privy:${t}`,redirect_to:window.location.href,code_challenge:i,state_code:n});return{url:a,stateCode:n,codeVerifier:r}}catch(e){throw c.formatApiError(e)}}({api:i.api,appId:e});if(!a)throw i.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:"Unable to open cross-app auth popup",appId:e}}),new c.PrivyClientError("No authorization URL returned for cross-app auth.");try{let l=await async function({url:e,popup:t}){return t.location=e,new Promise(((e,r)=>{let n,i=setTimeout((()=>{r(new c.PrivyClientError("Authorization request timed out after 2 minutes.")),a()}),12e4);function a(){t?.close(),window.removeEventListener("message",o)}let s=setInterval((()=>{t?.closed&&!n&&(a(),clearInterval(s),clearTimeout(i),r(new c.PrivyClientError("User rejected request")))}),300);function o(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(clearTimeout(i),e(t.data),a()),"PRIVY_OAUTH_ERROR"===t.data.type&&(clearTimeout(i),r(new c.PrivyClientError(t.data.error)),a()),t.data.type===bt&&((n=new BroadcastChannel(St)).onmessage=o))}window.addEventListener("message",o)}))}({url:a,popup:t,provider:n}),d=l.stateCode,u=l.authorizationCode;if(d!==s)throw i.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:n,storedStateCode:s??"",returnedStateCode:d??""}}),new c.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,c.PrivyErrorCode.OAUTH_UNEXPECTED);let h=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:i,client:a}){if(!n||!t)throw new c.PrivyClientError("[Cross-App AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===n)throw new c.PrivyClientError("User denied confirmation during cross-app auth flow");try{let s=new It({authorizationCode:n,stateCode:t,codeVerifier:r,provider:`privy:${e}`});a.startAuthFlow(s);let o="link"===i?await a.link():await a.authenticate(),l=o.oAuthTokens?.accessToken;return console.debug(),l}catch(e){let t=c.formatApiError(e);if(t.privyErrorCode===c.PrivyErrorCode.ACCOUNT_TRANSFER_REQUIRED)throw t;if(t.privyErrorCode)throw new c.PrivyClientError(t.message||"Invalid code during cross-app auth flow.",void 0,t.privyErrorCode);if("User denied confirmation during cross-app auth flow"===t.message)throw new c.PrivyClientError("Invalid code during cross-app auth flow.",void 0,c.PrivyErrorCode.OAUTH_USER_DENIED);throw new c.PrivyClientError("Invalid code during cross-app auth flow.",void 0,c.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}({appId:e,codeVerifier:o,stateCode:d,authorizationCode:u,action:r,client:i});h&&i.storeProviderAccessToken(e,h);let p=await vt.refreshSessionAndUser();if(!p)throw new c.PrivyClientError("Unable to update user");return i.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),p}catch(e){throw i.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:n}}),e}},async initLoginWithOAuth(e,t,r){if(Me.current=e,!d.e())return void Ye("InAppBrowserLoginNotPossible");if("google"===e&&!h.allowOAuthInEmbeddedBrowsers&&Lt(window.navigator.userAgent))return void Ye("InAppBrowserLoginNotPossible");"twitter"===e&&window.opener&&window.opener.postMessage({type:bt},"*"),d.u.del(p.HEADLESS_OAUTH_KEY),d.u.del(p.OAUTH_DISABLE_SIGNUP_KEY);let n=new Te({provider:e,disableSignup:!!r,withPrivyUi:!0,customOAuthRedirectUrl:h.customOAuthRedirectUrl});t&&n.addCaptchaToken(t),i.startAuthFlow(n);let a=await i.authFlow.getAuthorizationUrl();if(a&&a.url)if("twitter"===e&&w.isAndroid&&(a.url=a.url.replace("x.com","twitter.com")),"chrome-extension:"===window.location.protocol&&ge())try{let{privyOAuthCode:e,privyOAuthState:t}=await fe(a.url);Ye("OAuthStatusScreen"),n.meta.stateCode=t,n.meta.authorizationCode=e}catch(e){throw console.error("OAuth in chrome extension flow failed:",e),e}else window.location.assign(a.url)},async initLoginWithTelegram(e,t){if(!T)throw new c.PrivyNotReadyError;Me.current="telegram";let r=new Fe(e,t);i.startAuthFlow(r),Q({status:"loading"}),r.meta.telegramWebAppData=void 0,r.meta.telegramAuthResult=await new Promise(((e,t)=>h.loginConfig.telegramAuthConfiguration?window.Telegram?void window.Telegram.Login.auth({bot_id:h.loginConfig.telegramAuthConfiguration.botId,request_access:!0},(r=>r?e(r):("link"===ze.current?P.emitPrivyEvent(me,"linkAccount","onError",c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}):"login"===ze.current?P.emitPrivyEvent(me,"login","onError",c.PrivyErrorCode.INVALID_CREDENTIALS):"update"===ze.current&&P.emitPrivyEvent(me,"login","onError",c.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT),t(new c.PrivyClientError("Telegram auth failed or was canceled by the client"))))):t(new c.PrivyClientError("Telegram was not initialized")):t(new c.PrivyClientError("Telegram Auth configuration is not loaded"))))},async loginWithTelegram(e){let t,r;if(!(i.authFlow instanceof Fe))throw new c.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");i.authFlow.meta.captchaToken||=e?.captchaToken;let n=await re(),a=e?.intent||ze.current;if("login"===a)try{let e=await i.authenticate();t=e.user,r=e.isNewUser,Me.current="telegram"}catch(e){throw P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}else{if("link"!==a)throw new c.PrivyClientError("Unknown auth intent");try{t=(await i.link()).user,Me.current="telegram"}catch(e){throw P.emitPrivyEvent(me,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}S(t),R(r||!1),Oe(!0),Q({status:"done"});let s=t?.linkedAccounts.find((({type:e})=>"telegram"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,loginAccount:s}},async loginWithOAuth(e){let t,r,n;if(!(i.authFlow instanceof Te))throw new c.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let a=d.u.get(p.STATE_CODE_KEY),s=i.authFlow.meta.stateCode;if(a!==s)throw i.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e,storedStateCode:a??"",returnedStateCode:s??""}}),new c.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,c.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await i.getAccessToken())try{let r=await i.link();t=r.user,n=r.oAuthTokens,Me.current=e}catch(t){throw P.emitPrivyEvent(me,"linkAccount","onError",t.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{let a=await i.authenticate();t=a.user,r=a.isNewUser,n=a.oAuthTokens,Me.current=e}catch(t){throw"login"===ze.current?P.emitPrivyEvent(me,"login","onError",t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ze.current&&P.emitPrivyEvent(me,"linkAccount","onError",t.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return S(t),R(r||!1),Oe(!0),n&&t&&P.emitPrivyEvent(me,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),n},passkeyAuthState:j,setPasskeyAuthState:q,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new Se({captchaToken:e,setPasskeyAuthState:q,hints:h.passkeys.registration?.hints});i.startAuthFlow(r),ze.current="login";try{Me.current="passkey",q({status:"generating-challenge"}),await r.initRegisterFlow(t),q({status:"awaiting-passkey"})}catch(e){throw q({status:"error",error:e}),P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async signupWithPasskey(){let e,t;if(!T)throw new c.PrivyNotReadyError;if(!(i.authFlow instanceof Se))throw new c.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Me.current){let e=new c.PrivyClientError("Must init login with Passkey flow first.");throw q({status:"error",error:e}),e}let r=await re();try{Me.current="passkey",q({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await i.authenticate())}catch(e){throw q({status:"error",error:e}),P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}S(e),R(t||!1),Oe(!0),q({status:"done"});let n=e?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:e,isNewUser:t||!1,wasAlreadyAuthenticated:!!r,loginAccount:n}},async initLoginWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new Se({captchaToken:e,setPasskeyAuthState:q,hints:void 0});i.startAuthFlow(r),ze.current="login";try{Me.current="passkey",q({status:"generating-challenge"}),await r.initAuthenticationFlow(t),q({status:"awaiting-passkey"})}catch(e){throw q({status:"error",error:e}),P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}},async loginWithPasskey(e){let t,r;if(!T)throw new c.PrivyNotReadyError;if(!(i.authFlow instanceof Se))throw new c.PrivyClientError("Must initialize Passkey flow first.");if(e?.credentialIds&&(i.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==Me.current){let e=new c.PrivyClientError("Must init login with Passkey flow first.");throw q({status:"error",error:e}),e}let n=await re();try{Me.current="passkey",q({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await i.authenticate())}catch(e){throw q({status:"error",error:e}),P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}S(t),R(r||!1),Oe(!0),q({status:"done"});let a=t?.linkedAccounts.find((({type:e})=>"passkey"===e))||null;return{user:t,isNewUser:r||!1,wasAlreadyAuthenticated:!!n,loginAccount:a}},async initLinkWithPasskey(e){let t=new Se({captchaToken:e,hints:h.passkeys.registration?.hints});i.startAuthFlow(t),ze.current="link",Me.current="passkey",q({status:"generating-challenge"});try{await t.initLinkFlow(),q({status:"awaiting-passkey"})}catch(e){throw P.emitPrivyEvent(me,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),q({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!T)throw new c.PrivyNotReadyError;if(!(i.authFlow instanceof Se))throw new c.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Me.current)throw new c.PrivyClientError("Must init login with Passkey flow first.");try{Me.current="passkey",({user:e}=await i.link())}catch(e){throw P.emitPrivyEvent(me,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return S(e||k||null),q({status:"done"}),e},async initLoginWithHeadlessOAuth(e,t,r){if(!d.e())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&&!h.allowOAuthInEmbeddedBrowsers&&Lt(window.navigator.userAgent))throw Error("It looks like you're using an in-app browser. To log in, please try again using an external browser.");let n=new Te({provider:e,withPrivyUi:!1,disableSignup:r??!1,customOAuthRedirectUrl:h.customOAuthRedirectUrl});t&&n.addCaptchaToken(t),$({status:"loading"});let a=await i.startAuthFlow(n).getAuthorizationUrl();if(a?.url)if("chrome-extension:"===window.location.protocol&&ge())try{let{privyOAuthCode:e,privyOAuthState:t}=await fe(a.url);n.meta.stateCode=t,n.meta.authorizationCode=e,await this.loginWithHeadlessOAuth(n.meta)}catch(e){throw $({status:"error",error:e}),e}else window.location.assign(a.url)},async loginWithHeadlessOAuth(e){let t,r,n;F(!0),$({status:"loading"}),i.startAuthFlow(new Te({...e,customOAuthRedirectUrl:h.customOAuthRedirectUrl}));let a=d.u.get(p.STATE_CODE_KEY),s=e.stateCode;if(a!==s)throw i.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:e.provider,storedStateCode:a??"",returnedStateCode:s??""}}),F(!1),new c.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,c.PrivyErrorCode.OAUTH_UNEXPECTED);if(null!==await i.getAccessToken())try{({user:t,oAuthTokens:n}=await i.link()),Me.current=e.provider;let r=ut(t);t&&r&&P.emitPrivyEvent(me,"linkAccount","onSuccess",{user:t,linkMethod:Me.current,linkedAccount:r})}catch(t){throw F(!1),P.emitPrivyEvent(me,"linkAccount","onError",t.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e.provider}),t}else try{({user:t,isNewUser:r,oAuthTokens:n}=await i.authenticate()),Me.current=e.provider;let a=ut(t);t&&a&&void 0!==r&&P.emitPrivyEvent(me,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:Me.current,loginAccount:a})}catch(e){throw F(!1),$({status:"error",error:e}),P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return S(t),R(r||!1),Oe(!0),F(!1),$({status:"done"}),n&&t&&P.emitPrivyEvent(me,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),t??void 0},initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{let a=new ae({email:e,captchaToken:t,disableSignup:r});i.startAuthFlow(a);try{Me.current="email",H({status:"sending-code"});let e=await a.sendCodeEmail({withPrivyUi:n});if(e?.ssoRedirectUrl)return window.location.href=e.ssoRedirectUrl,void await o.sleep(1e4);H({status:"awaiting-code-input"})}catch(e){throw H({status:"error",error:e}),"login"===ze.current?P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ze.current&&P.emitPrivyEvent(me,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async({oldAddress:e,newAddress:t,captchaToken:r})=>{let n=new se(e,t,r);i.startAuthFlow(n);try{await n.sendCodeEmail({withPrivyUi:!0})}catch(e){throw P.emitPrivyEvent(me,"update","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:Me.current}),e}},initUpdatePhone:async(e,t,r)=>{let n=new xe(e,t,r);i.startAuthFlow(n);try{await n.sendSmsCode({withPrivyUi:!0})}catch(e){P.emitPrivyEvent(me,"update","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:Me.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{B({status:"sending-code"});let a=new Ue({phoneNumber:e,captchaToken:t,disableSignup:r});i.startAuthFlow(a);try{Me.current="sms",await a.sendSmsCode({withPrivyUi:n}),B({status:"awaiting-code-input"})}catch(e){throw B({status:"error",error:e}),"login"===ze.current?P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===ze.current&&P.emitPrivyEvent(me,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"sms"}),e}},resendEmailCode:async()=>{await(i.authFlow?.sendCodeEmail({withPrivyUi:!0}))},resendSmsCode:async()=>{await(i.authFlow?.sendSmsCode({withPrivyUi:!0}))},loginWithCode:async e=>{let t,r;function n(e){i.authFlow instanceof ae?H(e):i.authFlow instanceof Ue&&B(e)}if(n({status:"submitting-code"}),!T){let e=new c.PrivyNotReadyError;throw n({status:"error",error:e}),e}if(i.authFlow instanceof ae)i.authFlow.meta.emailCode=e.trim();else{if(!(i.authFlow instanceof Ue)){let e=new c.PrivyClientError("Must initialize a passwordless code flow first");throw n({status:"error",error:e}),e}i.authFlow.meta.smsCode=e.trim()}let a=await re();if("link"===ze.current)try{({user:t}=await i.link())}catch(e){throw n({status:"error",error:e}),P.emitPrivyEvent(me,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:Me.current}),e}else if("update"===ze.current)try{({user:t}=await i.link())}catch(e){throw n({status:"error",error:e}),P.emitPrivyEvent(me,"update","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:Me.current}),e}else try{({user:t,isNewUser:r}=await i.authenticate())}catch(e){throw n({status:"error",error:e}),P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let s=t||k;S(s||null),R(r||!1),Oe(!0),n({status:"done"});let o=null;return i.authFlow instanceof ae?o=s?.linkedAccounts.find((({type:e})=>"email"===e))||null:i.authFlow instanceof Ue&&(o=s?.linkedAccounts.find((({type:e})=>"phone"===e))||null),{user:s,isNewUser:r||!1,wasAlreadyAuthenticated:!!a,linkedAccount:o}},generateSiweMessage:async({address:e,chainId:t,captchaToken:r})=>{ze.current=ke?"link":"login",Me.current="siwe",Y({status:"generating-message"});let n=await i.generateSiweNonce({address:e,captchaToken:r});return Y({status:"awaiting-signature"}),be({address:e,chainId:t.replace("eip155:",""),nonce:n})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await i.generateSiweNonce({address:e});return be({address:e,chainId:t.replace("eip155:",""),nonce:r})},linkSmartWallet:async({message:e,signature:t,smartWalletType:r,smartWalletVersion:n})=>{let a;a=await i.linkSmartWallet({message:e,signature:t,smartWalletType:r,smartWalletVersion:n}),S((a=await vt.refreshSessionAndUser()??a)||k||null)},loginWithSiwe:async({message:e,signature:t,captchaToken:r,disableSignup:n,walletClientType:a,connectorType:s})=>{let o,l=null;try{if(k)throw Error("User already authenticated");let c=new Ie(i,void 0,r,n,{message:e,signature:t,walletClientType:a,connectorType:s});i.startAuthFlow(c),Me.current="siwe",ze.current="login",Y({status:"submitting-signature"});let d=await i.authenticate();if(({user:l,isNewUser:o}=d),!l)throw Error("Authentication failed - no user returned")}catch(e){throw P.emitPrivyEvent(me,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),Y({status:"error",error:e}),e}return S(l),R(o||!1),Oe(!0),Y({status:"done"}),ze.current=null,Me.current=null,{user:l,isNewUser:o||!1}},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a})=>{let s;rt("siwe");let o=null;try{Y({status:"submitting-signature"}),s=await i.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}),s=await vt.refreshSessionAndUser()??s,Y({status:"done"}),(o=ut(s)||null)&&P.emitPrivyEvent(me,"linkAccount","onSuccess",{user:s,linkMethod:"siwe",linkedAccount:o})}catch(e){throw P.emitPrivyEvent(me,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),ze.current=null,Me.current=null,Y({status:"error",error:e}),e}let l=s||k;return S(l||null),ze.current=null,Me.current=null,{user:l,linkedAccount:o}},refreshSessionAndUser:async()=>{let e=await i.getAuthenticatedUser();return Oe(!!e),S(e),e},walletProxy:Z,createAnalyticsEvent:({eventName:e,payload:t,timestamp:r})=>i.createAnalyticsEvent({eventName:e,payload:t,timestamp:r}),acceptTerms:async()=>{let e=await i.acceptTerms();return S(e),e},getUsdTokenPrice:e=>i.getUsdTokenPrice(e),getUsdPriceForSol:()=>i.getUsdPriceForSol(),getSplTokenMetadata:e=>i.getSplTokenMetadata(e),recoverEmbeddedWallet:async e=>new Promise((async(t,r)=>{if(!k)return void t(!0);let n=e?.address?a.getPrivyWalletWithAddress(k,e.address):a.getPrivyPrimaryWallet(k)||a.getImportedPrivyEthereumWallets(k).at(0)||a.getImportedPrivySolanaWallets(k).at(0);if(!n||a.getIsUnifiedWallet(n))return void t(!0);let s=await re();if(!s||!Z||!n)return void r(Error("Must have valid access token and Privy wallet to recover wallet"));let{entropyId:o,entropyIdVerifier:c}=l.getEntropyDetailsForUser(k,n);try{await Z.connect({accessToken:s,entropyId:o,entropyIdVerifier:c}),t(!0)}catch(e){if(yt(e)&&"privy"===n.recoveryMethod){let e;i.createAnalyticsEvent({eventName:"embedded_wallet_pinless_recovery_started",payload:{walletAddress:n.address}});try{e=await Z.recover({entropyId:o,entropyIdVerifier:c,accessToken:s})}catch(e){return void r(e)}e.entropyId||r(Error("Unable to recover wallet")),i.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:n.address}}),t(!0)}else yt(e)&&"privy"!==n.recoveryMethod&&"privy-v2"!==n.recoveryMethod?(ne({recoverWallet:{entropyId:o,entropyIdVerifier:c,onFailure:r,onSuccess:()=>t(!0)},recoveryOAuthStatus:{provider:n.recoveryMethod,action:"recover",shouldCreateEth:!1,shouldCreateSol:!1}}),Ye(Mt(n.recoveryMethod))):r(e)}})),setReadyToTrue:e=>{_(!0),ie?.(e)},updateWallets:()=>at(),fundWallet:async(e,t)=>{let r="FundingMethodSelectionScreen";ne({funding:d.prepareFundingModalData({address:e,appConfig:h,fundWalletConfig:t,methodScreen:r})}),Ye(r)},openModal:Ye,requestFarcasterSignerStatus:async e=>{let t=await re(),r=k?.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType));if(!t)throw Error("Must have valid access token to connect with Farcaster");if(!Z||!r)throw Error("Must have an embedded wallet to use Farcaster signers");if(!k?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let n=await i.requestFarcasterSignerStatus(e);return"approved"===n.status&&S(await i.getAuthenticatedUser()||k||null),n},connectCoinbaseSmartWallet:async()=>{h.externalWallets.coinbaseWallet.config.preference={...h.externalWallets.coinbaseWallet.config.preference,options:"smartWalletOnly"};let e=i.connectors?.findWalletConnector("coinbase_wallet","coinbase_smart_wallet")||i.connectors?.findWalletConnector("coinbase_wallet","coinbase_wallet");if(e)return e.updateConnectionPreference("smartWalletOnly"),Ze(e);await Qe("coinbase_wallet","coinbase_smart_wallet")},connectBaseAccount:async()=>{let e=i.connectors?.findWalletConnector("base_account","base_account");if(e)return Ze(e);await Qe("base_account","base_account")},initiateAccountTransfer:async({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:a,telegramWebAppData:s,farcasterEmbeddedAddress:o,oAuthUserInfo:l})=>{let c=await i.sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:a,telegramWebAppData:s,farcasterEmbeddedAddress:o,oAuthUserInfo:l});return S(c),c},inProgressAuthFlowRef:ze,inProgressLoginOrLinkMethodRef:Me};or=vt.recoverEmbeddedWallet,vt.recoverEmbeddedWallet;let gt=t.useMemo((()=>({wallets:b,ready:ce&&ve})),[b,ce,ve]),ft=i.authFlow instanceof Fe,Et=!h.headless&&h.captchaEnabled&&!ke&&(T||ft);/*#__PURE__*/return e.jsx(rr.Provider,{value:!0,children:/*#__PURE__*/e.jsx(a.PrivyContext.Provider,{value:mt,children:/*#__PURE__*/e.jsx(P.PrivyEventsContext.Provider,{value:me,children:/*#__PURE__*/e.jsx(l.UseWalletsContext.Provider,{value:gt,children:/*#__PURE__*/e.jsx(Ne,{...h,children:/*#__PURE__*/e.jsxs(c.InternalPrivyContext.Provider,{value:vt,children:[/*#__PURE__*/e.jsx(o.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(a.ModalProvider,{data:te,setModalData:ne,setInitialScreen:N,initialScreen:O,authenticated:ke,open:f,children:[n.children,/*#__PURE__*/e.jsx(tr,{customAuth:h.customAuth}),Et&&/*#__PURE__*/e.jsx(je,{delayedExecution:!1}),/*#__PURE__*/e.jsx(ct,{}),/*#__PURE__*/e.jsx(Gt,{disabled:h.embeddedWallets.disableAutomaticMigration}),/*#__PURE__*/e.jsx(Ke,{palette:h.appearance.palette||{}}),!h.render.standalone&&/*#__PURE__*/e.jsx(it,{open:f})]})}),/*#__PURE__*/e.jsx(Pt,{appId:n.appId,appClientId:n.clientId,clientAnalyticsId:i.clientAnalyticsId,origin:i.apiUrl,mfaMethods:k?.mfaMethods,mfaPromise:pe,mfaSubmitPromise:ye,onLoad:X,onLoadFailed:()=>null}),h.loginConfig.telegramAuthConfiguration&&
|
|
5
|
+
/*#__PURE__*/e.jsx(o.Hide,{$if:!0,children:/*#__PURE__*/e.jsx(lt,{scriptHost:n.apiUrl||p.DEFAULT_PRIVY_API_URL,botUsername:h.loginConfig.telegramAuthConfiguration.botName})})]})})})})})})};class cr extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class dr extends H.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new cr(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await re()||!this.address)throw new cr("Disconnected",4900);let{hash:r}=await((e,t)=>sr(e,t))(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new cr(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await re()||!this.address)throw new cr("Disconnected",4900);let{signature:r}=await((e,t)=>ar(e,t))(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new cr(`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 cr(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=I.getPublicClient(this.chainId,this.chains,this.rpcConfig,{appId:this.appId}),this.emit("chainChanged",t)}async handlePersonalSign(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for personal_sign");let t=e.params[0],r=e.params[1],{signature:n}=await((e,t)=>nr(e,t))({message:t},{address:r});return n}async handleSignedTypedData(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_signTypedData_v4");let t=e.params[0],r="string"==typeof e.params[1]?JSON.parse(e.params[1]):e.params[1],{signature:n}=await((e,t)=>ir(e,t))(o.generateTypedDataWithDomainType(r),{address:t});return n}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_estimateGas");delete e.params[0].gasPrice,delete e.params[0].maxFeePerGas,delete e.params[0].maxPriorityFeePerGas;let t={...e.params[0],chainId:o.toHex(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...h.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 o.toHex(this.chainId);case"eth_estimateGas":return this.handleEstimateGas(e);case"eth_sendTransaction":return this.handleSendTransaction(e);case"eth_signTransaction":return this.handleSignTransaction(e);case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(e);case"personal_sign":return this.handlePersonalSign(e);case"eth_signTypedData_v4":return this.handleSignedTypedData(e)}if(!(e=>ne.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await re();if(await(e=>or(e))({address:this.address}),!t||!this.address)throw new cr("Disconnected",4900);try{let r={method:e.method,params:e.params},n=this.walletAccount;return n&&a.getIsUnifiedWallet(n)?this.handleWalletApiRequest(r,n,t):(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:r})).response.data}catch(e){throw console.error(e),new cr("Disconnected",4900)}}}async handleWalletApiRequest(e,t,n){let i=this.privyClient;if(!i)throw new cr("Disconnected",4900);if("secp256k1_sign"===e.method){let a=await r.rpc(i,(async({message:e})=>this.walletProxy.signWithUserSigner({accessToken:n,message:e})),{chain_type:"ethereum",method:"secp256k1_sign",wallet_id:t.id,params:{hash:e.params[0]}});if("secp256k1_sign"!==a.method)throw new cr(`Invalid params for ${e.method}`,4200);return a.data.signature}throw new cr(`Method not supported: ${e.method}`,4200)}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:n,rpcConfig:i,chains:a,appId:s,chainId:l=1,walletIndex:c,privyClient:d,walletAccount:u}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=n,this.chainId=l,this.rpcConfig=i,this.chains=a,this.publicClient=I.getPublicClient(l,this.chains,i,{appId:s}),this.rpcTimeoutDuration=o.getRpcTimeout(i,"privy"),this.appId=s,this.walletIndex=c,this.privyClient=d,this.walletAccount=u}}const ur=({style:t,...r})=>/*#__PURE__*/e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",stroke:"currentColor",strokeWidth:1.5,viewBox:"0 0 24 24",style:{...t},...r,children:/*#__PURE__*/e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25m18 0A2.25 2.25 0 0018.75 3H5.25A2.25 2.25 0 003 5.25m18 0V12a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 12V5.25"})}),hr=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"108",height:"108",viewBox:"0 0 108 108",fill:"none",style:{height:"28px",width:"28px",...t},...r,children:[/*#__PURE__*/e.jsx("rect",{width:"108",height:"108",rx:"23",fill:"#AB9FF2"}),/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M46.5267 69.9229C42.0054 76.8509 34.4292 85.6182 24.348 85.6182C19.5824 85.6182 15 83.6563 15 75.1342C15 53.4305 44.6326 19.8327 72.1268 19.8327C87.768 19.8327 94 30.6846 94 43.0079C94 58.8258 83.7355 76.9122 73.5321 76.9122C70.2939 76.9122 68.7053 75.1342 68.7053 72.314C68.7053 71.5783 68.8275 70.7812 69.0719 69.9229C65.5893 75.8699 58.8685 81.3878 52.5754 81.3878C47.993 81.3878 45.6713 78.5063 45.6713 74.4598C45.6713 72.9884 45.9768 71.4556 46.5267 69.9229ZM83.6761 42.5794C83.6761 46.1704 81.5575 47.9658 79.1875 47.9658C76.7816 47.9658 74.6989 46.1704 74.6989 42.5794C74.6989 38.9885 76.7816 37.1931 79.1875 37.1931C81.5575 37.1931 83.6761 38.9885 83.6761 42.5794ZM70.2103 42.5795C70.2103 46.1704 68.0916 47.9658 65.7216 47.9658C63.3157 47.9658 61.233 46.1704 61.233 42.5795C61.233 38.9885 63.3157 37.1931 65.7216 37.1931C68.0916 37.1931 70.2103 38.9885 70.2103 42.5795Z",fill:"#FFFDF8"})]});function pr(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var yr=0;class wr extends o.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return{name:this.providerDetail.info.name,icon:this.providerDetail.info.icon,id:this.providerDetail.info.rdns}}disconnect(){console.warn(`Programmatic disconnect with ${this.providerDetail.info.name} is not yet supported.`)}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new c.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}constructor(e,t,r,n,i){super(i||"unknown",e,t,r),this.connectorType="injected",this.proxyProvider=new o.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=n;let a=n.provider;this.proxyProvider.setWalletProvider(a)}}var mr="__private_"+yr+++"__walletBranding";class vr extends o.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return pr(this,mr)[mr]??{name:"Browser Extension",icon:ur,id:"extension"}}disconnect(){console.warn("Programmatic disconnect with browser wallets is not yet supported.")}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new c.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}constructor(e,t,r,n,i){super(i??"unknown",e,t,r),Object.defineProperty(this,mr,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new o.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(n),"metamask"===i?pr(this,mr)[mr]={name:"MetaMask",icon:o.Metamask,id:"io.metamask"}:"phantom"===i&&(pr(this,mr)[mr]={name:"Phantom",icon:hr,id:"phantom"})}}class gr extends wr{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){try{w.isMobile||await this.proxyProvider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new c.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw d.formatConnectorError(e)}}}class fr extends H.default{get wallets(){let e=new Set;return this.walletConnectors.flatMap((e=>e.wallets)).sort(((e,t)=>e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0)).filter((t=>{let r=`${t.address}${t.walletClientType}${t.connectorType}${t.meta.id}`;return!e.has(r)&&(e.add(r),!0)}))}async initialize(e){if(this.initialized&&!e||(e&&this.removeAllConnectors(),this.externalWalletConfig.disableAllExternalWallets))return;let t=o.detectInjectedConnectors({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:r})=>{this.createEthereumWalletConnector({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:r}})}))}));for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),this.walletList.includes("base_account")&&this.createEthereumWalletConnector({connectorType:"base_account",walletClientType:"base_account"}),Object.values(o.mobileWalletsConfig)))!e.isInstalled&&this.walletList.includes(e.client)&&(["ethereum-only","ethereum-and-solana"].includes(this.walletChainType)&&e.chainTypes.includes("ethereum")&&this.createEthereumWalletConnector({connectorType:"null",walletClientType:e.client,walletConfig:e}),["ethereum-and-solana","solana-only"].includes(this.walletChainType)&&e.chainTypes.includes("solana")&&this.addSolanaWalletConnector(new o.SolanaNullConnector({id:e.client,name:e.name})));this.externalWalletConfig.walletConnect.enabled&&(this.walletList.includes("wallet_connect_qr")||o.shouldFetchWcRegistryListings(this.walletList))&&"solana-only"!==this.walletChainType&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"unknown"});let r=this.walletList.includes("wallet_connect_qr_solana"),n=this.externalWalletConfig.solana.connectors?.get()||[],i=async e=>{if(!r)return;let t=e.find((e=>"walletconnect_solana"===e.walletBranding?.id));t&&t.wallet&&await t.wallet.initialize({walletConnectCloudProjectId:this.walletConnectCloudProjectId,privyAppName:this.privyAppName})};i(n),n.filter((e=>r||"walletconnect_solana"!==e.walletBranding?.id)).forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{i(e),e?.filter((e=>r||"walletconnect_solana"!==e.walletBranding?.id)).forEach(this.addSolanaWalletConnector)})),await t,this.initialized=!0}findWalletConnector(e,t,r){return"wallet_connect_v2"===e?this.walletConnectors.filter(o.isEthereumWalletConnector).find((t=>t.connectorType===e&&(!r||t.wallets.some((e=>e.address===r)))))??null:this.walletConnectors.filter(o.isEthereumWalletConnector).find((n=>n.connectorType===e&&n.walletClientType===t&&(!r||n.wallets.some((e=>e.address===r)))))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(o.isSolanaWalletConnector).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}findImportedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded_imported"===e.connectorType))}onInitialized(e){e.wallets.forEach((e=>{let t=this.storedConnections.find((t=>t.address===e.address&&t.connectorType===e.connectorType&&("solana"===e.type&&"unknown"===t.walletClientType&&"unknown"===e.walletClientType?e.meta.id===t.id:t.walletClientType===e.walletClientType)));t&&(e.connectedAt=t.connectedAt)})),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&this.emit("walletsUpdated")}addEmbeddedWalletConnectors({walletProxy:e,user:t,embeddedWallets:r,defaultChain:n,appId:i,privyClient:a}){let{entropyId:s,entropyIdVerifier:c}=l.getEntropyDetailsForUser(t);for(let t of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===t.walletIndex));if(r&&o.isEthereumWalletConnector(r))r.proxyProvider.walletProxy=e;else{let r=new te({provider:new dr({walletProxy:e,address:t.address,entropyId:s,entropyIdVerifier:c,rpcConfig:this.rpcConfig,chains:this.chains,appId:i,chainId:n.id,walletIndex:t.walletIndex,privyClient:a,walletAccount:t}),chains:this.chains,defaultChain:n,rpcConfig:this.rpcConfig,imported:!1,walletIndex:t.walletIndex});this.addWalletConnector(r)}}}addImportedWalletConnector(e,t,r,n){let i=this.findWalletConnector("embedded_imported","privy",t);if(i&&o.isEthereumWalletConnector(i))i.proxyProvider.walletProxy=e;else{let i=new te({provider:new dr({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(i)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.storedConnections=d.loadConnectionHistory(),this.emit("walletsUpdated")}removeImportedWalletConnectors(){let e=this.findImportedWalletConnectors();e.length&&(e.forEach((e=>{let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1)})),this.storedConnections=d.loadConnectionHistory(),this.emit("walletsUpdated"))}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:n}){let i=this.findWalletConnector(e,t);if(i&&o.isEthereumWalletConnector(i))return i instanceof dt&&i.resetConnection(t),i;let a=(()=>"injected"!==e?"coinbase_wallet"===e?new X(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new Q(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new dt({walletConnectCloudProjectId:this.walletConnectCloudProjectId,rpcConfig:this.rpcConfig,chains:this.chains,defaultChain:this.defaultChain,shouldEnforceDefaultChainOnConnect:this.shouldEnforceDefaultChainOnConnect,privyAppId:this.privyAppId,privyAppName:this.privyAppName,walletClientType:t}):n?new o.EthereumNullConnector({id:n.client,name:n.name,defaultChain:this.defaultChain,walletClientType:n.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new gr(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new vr(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new vr(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new vr(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new wr(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,t):void 0)();return a&&this.addWalletConnector(a),a||null}addWalletConnector(e){this.walletConnectors.push(e),e.on("initialized",(()=>this.onInitialized(e))),e.on("walletsUpdated",(()=>this.onWalletsUpdated(e))),e.initialize().catch((e=>{console.debug("Failed to initialize connector",e)}))}setWalletList(e){this.walletList=e,this.initialized&&this.initialize(!0).catch(console.error)}removeAllConnectors(){for(let e of this.walletConnectors)e.removeAllListeners();this.walletConnectors=[]}constructor(e,t,r,n,i,a,s,o,l,c,u,h){super(),this.addSolanaWalletConnector=async e=>{let t=this.findSolanaWalletConnector(e.walletClientType);if(!t||"null"===t.connectorType){if("null"===t?.connectorType){let e=this.walletConnectors.indexOf(t);this.walletConnectors.splice(e,1)}this.addWalletConnector(e)}},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=n,this.defaultChain=i,this.walletConnectors=[],this.initialized=!1,this.store=a,this.walletList=s,this.shouldEnforceDefaultChainOnConnect=o,this.externalWalletConfig=l,this.privyAppName=c,this.walletChainType=h||"ethereum-only",this.setBaseAccountSdk=u,this.storedConnections=d.loadConnectionHistory()}}const Er=T.create((()=>({identityToken:null})));let Cr=[g.sessionsRefreshPath,g.sessionsLogoutPath,g.analyticsEventsPath];class Ar{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw c.formatApiError(e)}}async post(e,t,r){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...r})}catch(e){throw c.formatApiError(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw c.formatApiError(e)}}constructor({appId:e,appClientId:t,client:r,defaults:n}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=r.clientAnalyticsId,this.sdkVersion=p.VERSION,this.client=r,this.defaults=n,this.fallbackApiUrl=r.fallbackApiUrl,this.baseFetch=W.ofetch.create({baseURL:this.defaults.baseURL,timeout:this.defaults.timeout,retry:3,retryDelay:500,retryStatusCodes:[408,409,425,500,502,503,504],credentials:"include",onRequest:async({request:e,options:t})=>{let r=new Headers(t.headers);r.set("privy-app-id",this.appId),this.appClientId&&r.set("privy-client-id",this.appClientId),r.set("privy-ca-id",this.clientAnalyticsId||""),r.set("privy-client",`react-auth:${this.sdkVersion}`);let n=Cr.includes(e.toString());if(!r.has("authorization")){let e=await this.client.getAccessToken({disableAutoRefresh:n});null!==e&&r.set("authorization",`Bearer ${e}`)}t.headers=r,t.retryDelay&&"number"==typeof t.retryDelay&&(t.retryDelay=3*t.retryDelay)},onRequestError:({error:e})=>{if(e instanceof DOMException&&"AbortError"===e.name)throw new c.PrivyTimeoutError}})}}let Pr=/paymaster\.biconomy\.io\/api/i,Tr={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const _r=(e,t)=>e&&Pr.test(e)?Tr:t&&t.policy_id?{policyId:t.policy_id}:void 0,kr=e=>({rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification});class Sr{getOrCreateGuestCredential(e){let t=p.getGuestCredentialStorageKey(e);if(d.e()){if(d.u.get(t))return d.u.get(t);{let e=i.base64url.encode(Ee(32));return d.u.put(t,e),e}}return i.base64url.encode(Ee(32))}async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(g.guestAccountAuthenticatePath,{guest_credential:this.meta.guestCredential})}catch(e){throw c.formatApiError(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}function br(){return!(w.isSafari&&window.location.origin.startsWith("http://localhost"))}var Ir,Wr=((Ir={}).PRIVY="privy_access_token",Ir.CUSTOMER="customer_access_token",Ir);class Ur{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)}get privyAccessToken(){return this._getToken(p.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}_getToken(e){try{let t=d.u.get(e);return"string"==typeof t?B.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=d.u.get(p.REFRESH_TOKEN_STORAGE_KEY);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=d.u.get(p.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return null;{let r=new B(t);return r.isExpired()?(d.u.del(p.getProviderAccessTokenStorageKey(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=K.default.get(p.SESSION_COOKIE_KEY);return void 0!==e&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(e="privy_access_token"){let t="string"==typeof this.getToken(e),r="string"==typeof this.refreshToken&&this.refreshToken!==p.DEPRECATED_REFRESH_TOKEN;return this.mightHaveServerCookies||t&&r}hasActiveAccessToken(e){let t=B.parse(this.getToken(e));return null!==t&&!t.isExpired(30)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}destroy(){return this.destroyOnce.execute()}storeProviderAccessToken(e,t){"string"==typeof t?d.u.put(p.getProviderAccessTokenStorageKey(e),t):d.u.del(p.getProviderAccessTokenStorageKey(e))}updateIdentityToken(e){"string"==typeof e?this.storeIdentityToken(e):this.clearIdentityToken()}async _authenticate(e){try{let t=await e.authenticate(),{user:r,is_new_user:n,oauth_tokens:i}=t;this.handleTokenResponse(t);let s=i?{provider:i.provider,accessToken:i.access_token,accessTokenExpiresInSeconds:i.access_token_expires_in_seconds,refreshToken:i.refresh_token,refreshTokenExpiresInSeconds:i.refresh_token_expires_in_seconds,scopes:i.scopes}:void 0;return this._trackAuthenticateEvents(e,n),{user:a.convertUserResponseToUser(r),isNewUser:n,oAuthTokens:s}}catch(e){throw console.warn("Error authenticating session"),c.formatPrivyError(e)}}_trackAuthenticateEvents(e,t){let r=function(e){return e instanceof ae?"email":e instanceof Ue?"sms":e instanceof Ie?"siwe":e instanceof Sr?"guest":e instanceof Zt?"custom_auth":e instanceof Te?e.meta.provider:null}(e);r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:r,isNewUser:t}}),"siwe"===r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate_siwe",payload:{connectorType:e.meta.connectorType,walletClientType:e.meta.walletClientType}})}async _link(e){try{let t=await e.link(),r=t.oauth_tokens,n=r?{provider:r.provider,accessToken:r.access_token,accessTokenExpiresInSeconds:r.access_token_expires_in_seconds,refreshToken:r.refresh_token,refreshTokenExpiresInSeconds:r.refresh_token_expires_in_seconds,scopes:r.scopes}:void 0;return{user:a.convertUserResponseToUser(t),oAuthTokens:n}}catch(e){throw console.warn("Error linking account"),c.formatPrivyError(e)}}async _refresh(){if(!this.api)throw new c.PrivyClientError("Session has no API instance");if(!this.client)throw new c.PrivyClientError("Session has no PrivyClient instance");await this.client.getAccessToken({disableAutoRefresh:!0});let e=this.token,t=this.refreshToken;if(this.client.useServerCookies&&!this.mightHaveServerCookies&&this.token&&window.location.origin===this.client.apiUrl)return this.destroyLocalState(),null;try{let r;if(!(e&&t||this.mightHaveServerCookies))return null;{let n={};e&&(n.authorization=`Bearer ${e}`),r=await this.api.post(g.sessionsRefreshPath,t?{refresh_token:t}:{},{headers:n})}return this.handleTokenResponse(r),a.convertUserResponseToUser(r.user)}catch(e){if(e instanceof c.PrivyApiError&&e.privyErrorCode===c.PrivyErrorCode.MISSING_OR_INVALID_TOKEN)return console.warn("Unable to refresh tokens - token is missing or no longer valid"),this.destroyLocalState(),null;throw c.formatPrivyError(e)}}handleTokenResponse(e){e.session_update_action&&"set"!==e.session_update_action?"clear"===e.session_update_action?this.destroyLocalState():"ignore"===e.session_update_action&&(e.token&&(this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token)),e.identity_token&&this.storeIdentityToken(e.identity_token)):this._storeAllTokens(e)}_storeAllTokens(e){this.storeRefreshToken(e.refresh_token),this.storeCustomerAccessToken(e.token),this.storePrivyAccessToken(e.privy_access_token),e.identity_token&&this.storeIdentityToken(e.identity_token)}async _destroy(){try{await(this.api?.post(g.sessionsLogoutPath,{refresh_token:this.refreshToken}))}catch(e){console.warn("Error destroying session")}this.destroyLocalState()}destroyLocalState(){this.storeRefreshToken(null),this.storeCustomerAccessToken(null),this.storePrivyAccessToken(null),this.clearIdentityToken()}storeCustomerAccessToken(e){if("string"==typeof e){let t=d.u.get(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY);if(d.u.put(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY,e),!this.client?.useServerCookies){let t=B.parse(e)?.expiration;K.default.set(p.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:br(),expires:t?new Date(1e3*t):void 0})}t!==e&&this.client?.onStoreCustomerAccessToken?.(e)}else d.u.del(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY),K.default.remove(p.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(d.u.put(p.REFRESH_TOKEN_STORAGE_KEY,e),this.client?.useServerCookies||K.default.set(p.SESSION_COOKIE_KEY,"t",{sameSite:"Strict",secure:br(),expires:30})):(d.u.del(p.REFRESH_TOKEN_STORAGE_KEY),K.default.remove(p.REFRESH_TOKEN_COOKIE_KEY),K.default.remove(p.SESSION_COOKIE_KEY))}storePrivyAccessToken(e){"string"==typeof e?d.u.put(p.PRIVY_ACCESS_TOKEN_STORAGE_KEY,e):d.u.del(p.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}storeIdentityToken(e){if(Er.setState({identityToken:e}),this.client?.useServerCookies)return;d.u.put(p.IDENTITY_TOKEN_STORAGE_KEY,e);let t=B.parse(e)?.expiration;K.default.set(p.IDENTITY_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:br(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){d.u.del(p.IDENTITY_TOKEN_STORAGE_KEY),Er.setState({identityToken:null}),K.default.remove(p.IDENTITY_TOKEN_COOKIE_KEY)}constructor(){this.authenticateOnce=new ye((async e=>this._authenticate(e))),this.linkOnce=new ye((async e=>this._link(e))),this.refreshOnce=new ye(this._refresh.bind(this)),this.destroyOnce=new ye(this._destroy.bind(this))}}let xr,Rr;var Or=0,Nr="__private_"+Or+++"__getOrGenerateClientAnalyticsId";class Mr{getAppId(){return this.appId}initializeConnectorManager({walletConnectCloudProjectId:e,rpcConfig:t,chains:r,defaultChain:n,store:i,walletList:a,shouldEnforceDefaultChainOnConnect:s,externalWalletConfig:o,appName:l,walletChainType:c,setBaseAccountSdk:d}){this.connectors||(this.connectors=new fr(this.appId,e,t,r,n,i,a,s,o,l,d,c))}generateApi(){let e=new Ar({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 c.PrivyClientError("No auth flow in progress.");return this.session.authenticate(this.authFlow)}async link(){if(!this.authFlow)throw new c.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(g.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw c.formatApiError(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(g.mfaPasskeyInitPath,{});return kr(e.options)}catch(e){throw c.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(g.acceptTermsPath,{});return a.convertUserResponseToUser(e)}catch(e){throw c.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(g.unlinkEmailPath,{address:e});return await this.getAuthenticatedUser()??a.convertUserResponseToUser(t)}catch(e){throw c.formatPrivyError(e)}}async unlinkPhone(e){try{let t=await this.api.post(g.unlinkPhonePath,{phoneNumber:e});return await this.getAuthenticatedUser()??a.convertUserResponseToUser(t)}catch(e){throw c.formatPrivyError(e)}}async unlinkEthereumWallet(e){try{let t=await this.api.post(g.unlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??a.convertUserResponseToUser(t)}catch(e){throw c.formatPrivyError(e)}}async unlinkSolanaWallet(e){try{let t=await this.api.post(g.siwsUnlinkWalletPath,{address:e});return await this.getAuthenticatedUser()??a.convertUserResponseToUser(t)}catch(e){throw c.formatPrivyError(e)}}async unlinkOAuth(e,t){try{let r=await this.api.post(g.unlinkOAuthPath,{provider:e,subject:t});return await this.getAuthenticatedUser()??a.convertUserResponseToUser(r)}catch(e){throw c.formatPrivyError(e)}}async unlinkFarcaster(e){try{let t=await this.api.post(g.unlinkFarcasterPath,{fid:e});return await this.getAuthenticatedUser()??a.convertUserResponseToUser(t)}catch(e){throw c.formatPrivyError(e)}}async unlinkTelegram(e){try{let t=await this.api.post(g.telegramAccountUnlinkPath,{telegram_user_id:e});return await this.getAuthenticatedUser()??a.convertUserResponseToUser(t)}catch(e){throw c.formatPrivyError(e)}}async revokeDelegatedWallet(){try{await this.api.post(g.delegatedActionsRevokePath,{})}catch(e){throw c.formatPrivyError(e)}}async createAnalyticsEvent({eventName:e,payload:t,timestamp:r,options:n}){if("undefined"!=typeof window)try{this.clientAnalyticsId||console.warn("No client analytics id set, refusing to send analytics event"),await this.api.post(g.analyticsEventsPath,{event_name:e,client_id:this.clientAnalyticsId,payload:{...t||{},clientTimestamp:r?r.toISOString():(new Date).toISOString()}},{retry:-1,keepalive:n?.keepAlive??!1})}catch(e){console.log("Unable to submit event. This is not an issue.")}}async signMoonpayOnRampUrl(e){try{return this.api.post(g.moonpayPluginOnRampPath,e)}catch(e){throw c.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(g.coinbaseOnRampInitPath,e)}catch(e){throw c.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${g.coinbaseOnRampStatusPath}?partnerUserId=${e}`)}catch(e){throw c.formatPrivyError(e)}}async getAuthenticatedUser(){return this.session.hasRefreshCredentials()?this.session.refresh():null}async getAccessToken(e){return await this.getPrivyAccessToken(e)||await this.getCustomerAccessToken(e)}async getCustomerAccessToken(e){return await this._getToken(Wr.CUSTOMER,e)}async getPrivyAccessToken(e){return await this._getToken(Wr.PRIVY,e)}async _getToken(e,t){return this.session.getToken(e)?this.session.hasActiveAccessToken(e)?this.session.hasRefreshCredentials(e)?V.parse(this.session.getToken(e))?.appId!==this.appId?(await this.logout(),null):this.session.getToken(e):(this.session.destroyLocalState(),null):!t?.disableAutoRefresh&&this.session.hasRefreshCredentials(e)?(await this.session.refresh(),this.session.getToken(e)):null:null}async getSmartWalletsConfig(){try{let e={},t=this.session.token;t&&(e.authorization=`Bearer ${t}`);let r=await this.api.get(`/api/v1/apps/${this.appId}/smart_wallets`,{baseURL:this.fallbackApiUrl,headers:e});return r.enabled?{enabled:r.enabled,smartWalletVersion:r.smart_wallet_version,smartWalletType:r.smart_wallet_type,configuredNetworks:r.configured_networks.map((e=>({chainId:e.chain_id,bundlerUrl:e.bundler_url,paymasterUrl:e.paymaster_url,paymasterContext:_r(e.paymaster_url,e.paymaster_context)})))}:{enabled:r.enabled}}catch(e){throw c.formatPrivyError(e)}}async getUsdTokenPrice(e){try{return(await this.api.get(`/api/v1/token_price?chainId=${e.id}&tokenSymbol=${e.nativeCurrency.symbol}`)).usd}catch(t){return void console.error(`Unable to fetch token price for chain with id ${e.id}`)}}async getUsdPriceForSol(){try{return(await this.api.get("/api/v1/token_price?chainId=0&tokenSymbol=SOL")).usd}catch(e){return void console.error("Unable to fetch token price for SOL")}}async getSplTokenMetadata({mintAddress:e,cluster:t}){try{return await this.api.get(`/api/v1/spl_token_info?mint_address=${e}&cluster=${t}`)}catch(r){return void console.error(`Unable to fetch token metadata for ${t}:${e}`)}}async requestFarcasterSignerStatus(e){try{return await this.api.post("/api/v1/farcaster/signer/status",{ed25519_public_key:e})}catch(e){throw console.error("Unable to fetch Farcaster signer status"),e}}async generateSiweNonce({address:e,captchaToken:t}){try{return(await this.api.post(g.siweInitPath,{address:e,token:t})).nonce}catch(e){throw c.formatPrivyError(e)}}async authenticateWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i,mode:a}){return await this.api.post(g.siweAuthenticatePath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:i,mode:a})}async linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}){return await this.api.post(g.siweLinkPath,{message:e,signature:t,chainId:r,walletClientType:n,connectorType:i})}async linkSmartWallet({message:e,signature:t,smartWalletType:r,smartWalletVersion:n}){try{let i=await this.api.post(g.smartWalletLinkPath,{message:e,signature:t,smart_wallet_type:r,smart_wallet_version:n});return a.convertUserResponseToUser(i)}catch(e){throw c.formatPrivyError(e)}}async linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i}){try{let s=await this.linkWithSiweInternal({message:e,signature:t,chainId:r,walletClientType:n,connectorType:i});return a.convertUserResponseToUser(s)}catch(e){throw c.formatPrivyError(e)}}async generateSiwsNonce({address:e,captchaToken:t}){try{return(await this.api.post(g.siwsInitPath,{address:e,token:t})).nonce}catch(e){throw c.formatPrivyError(e)}}async authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:i,messageType:a="plain"}){return await this.api.post(g.siwsAuthenticatePath,{message:e,signature:t,walletClientType:r,connectorType:n,mode:i,message_type:a})}async authenticateWithSiws({message:e,signature:t,walletClientType:r,connectorType:n,mode:i,messageType:s="plain"}){let o=await this.authenticateWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,mode:i,messageType:s});this.session.handleTokenResponse(o);let l=a.convertUserResponseToUser(o.user);if(!l)throw Error("Authentication failed - no user returned");return{user:l,isNewUser:o.is_new_user||!1}}async sendAccountTransferRequest({nonce:e,account:t,accountType:r,externalWalletMetadata:n,telegramAuthResult:i,telegramWebAppData:s,farcasterEmbeddedAddress:o,oAuthUserInfo:l}){try{let c,d;switch(r){case"email":c=g.transferEmailPath,d={nonce:e,email:t};break;case"sms":c=g.transferPhonePath,d={nonce:e,phoneNumber:t};break;case"siwe":if(c=g.transferWalletPath,!n)throw Error("Wallet parameters must be defined");d={nonce:e,address:t,...n};break;case"farcaster":c=g.transferFarcasterPath,d={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":c=g.telegramAccountTransferPath,d={nonce:e,telegram_auth_result:i,telegram_web_app_data:s};break;case"siws":c=g.siwsTransferPath,d={nonce:e,address:t,...n};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:c=g.transferOAuthPath,d={nonce:e,userInfo:l}}let u=await this.api.post(c,d);return await this.getAuthenticatedUser()??a.convertUserResponseToUser(u)}catch(e){throw c.formatPrivyError(e)}}async linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,messageType:i="plain"}){return await this.api.post(g.siwsLinkPath,{message:e,signature:t,walletClientType:r,connectorType:n,message_type:i})}async linkWithSiws({message:e,signature:t,walletClientType:r,connectorType:n,messageType:i="plain"}){try{let s=await this.linkWithSiwsInternal({message:e,signature:t,walletClientType:r,connectorType:n,messageType:i});return a.convertUserResponseToUser(s)}catch(e){throw c.formatPrivyError(e)}}async updateUserAndIdToken(){try{let e=await this.api.get(g.usersMePath);return this.session.updateIdentityToken(e.identity_token),a.convertUserResponseToUser(e.user)}catch(e){throw c.formatPrivyError(e)}}async scanTransaction(e){try{return await this.api.post(g.transactionScanningPath,e)}catch(e){throw c.formatPrivyError(e)}}constructor({apiUrl:e=p.DEFAULT_PRIVY_API_URL,appId:t,appClientId:r,timeout:n=p.DEFAULT_API_TIMEOUT_MS}){Object.defineProperty(this,Nr,{value:Fr}),this._cachedProviderAppDetails={},this.apiUrl=e,this.fallbackApiUrl=this.apiUrl,this.useServerCookies=e!==p.DEFAULT_PRIVY_API_URL&&e.startsWith("https://privy."),this.timeout=n,this.appId=t,this.appClientId=r,this.clientAnalyticsId=function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}(this,Nr)[Nr](),xr||(xr=new Ur),this.session=xr,this.api=this.generateApi(),this.session.client=this}}function Fr(){if("undefined"==typeof window)return null;try{let e=d.u.get(p.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=n.v4();try{return d.u.put(p.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}function Lr(){if(!Rr)throw new c.PrivyClientError("No global PrivyClient instance found. Please ensure you have initialized the PrivyProvider.");return Rr}const Dr=()=>{let{setModalData:e}=a.usePrivyModal(),{openModal:r,privy:n,closePrivyModal:i}=c.usePrivyInternal(),{user:s}=a.usePrivyContext();return t.useMemo((()=>({verify:async({standalone:t=!0}={standalone:!0})=>new Promise(((a,o)=>s?0===s.mfaMethods.length?a():(e((e=>({...e,mfaVerify:{onSuccess:async()=>{t?await i({shouldCallAuthOnSuccess:!1,isSuccess:!0}):He.setState({inProgressMfaFlow:void 0}),a()},onFailure:async e=>{t?await i({shouldCallAuthOnSuccess:!1,isSuccess:!1}):He.setState({inProgressMfaFlow:void 0}),o(e)},sendSmsCode:async()=>{throw Error("Not enabled")},verifySmsCode:async()=>{throw Error("Not enabled")},verifyTotpCode:async e=>{await n.fetchPrivyRoute(R.MfaAuthTotpVerify,{body:{code:e}})},generateOptions:async()=>kr((await n.fetchPrivyRoute(R.MfaAuthPasskeyInit,{body:{}})).options),verifyPasskey:async e=>{let t=await import("@simplewebauthn/browser"),r=await t.startAuthentication({optionsJSON:e});await n.fetchPrivyRoute(R.MfaAuthPasskeyVerify,{body:{authenticator_response:$t(r)}})}}}))),void(t?r("MfaAuthVerifyFlowScreen"):He.setState({inProgressMfaFlow:"auth"}))):o(Error("Must be logged in to verify MFA"))))})),[n,e,r,i])};const jr=async({wallet:e})=>{let t=await e.getEthereumProvider();return M.toAccount({address:e.address,sign:async({hash:n})=>{if("privy"!==e.walletClientType)throw new r.PrivyClientError({error:"Unprefixed signing is not supported by external wallets.",code:"unsupported_wallet_type"});return await t.request({method:"secp256k1_sign",params:[n]})},signMessage:async({message:r})=>await t.request({method:"personal_sign",params:[r,e.address]}),signTypedData:async r=>await t.request({method:"eth_signTypedData_v4",params:[e.address,r]}),signTransaction:async e=>await t.request({method:"eth_signTransaction",params:[e]})})};let qr=async(e,t,r,n,i)=>{if(!e)throw n("linkAccount","onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:i}),new c.PrivyClientError("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(i))))throw new c.PrivyClientError(`OAuth account of type ${i} not linked to the account.`);await r(i)};const zr=it;exports.BASE_ACCOUNT_DATA_URI=G,exports.Blobby=ee,exports.BrowserExtensionWallet=ur,exports.COINBASE_WALLET_DATA_URI=Y,exports.Captcha=je,exports.CaptchaError=Oe,exports.CoinbaseWallet=({style:t,...r})=>/*#__PURE__*/e.jsxs("svg",{viewBox:"0 0 1024 1024",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{height:"28px",width:"28px",...t},...r,children:[/*#__PURE__*/e.jsx("rect",{width:"1024",height:"1024",fill:"#0052FF",rx:100,ry:100}),/*#__PURE__*/e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z",fill:"white"})]}),exports.ConnectorManager=fr,exports.LoginModal=zr,exports.Phantom=hr,exports.PrivyClient=Mr,exports.PrivyIframeError=ht,exports.PrivyModal=it,exports.PrivyProvider=({config:r,...n})=>{(()=>{if(t.useContext(rr))throw new c.PrivyClientError("Multiple PrivyProvider instances found","Found multiple instances of PrivyProvider, ensure there is only one mounted in your application tree.")})(),function(){if("undefined"==typeof window)return;let e=["localhost","127.0.0.1"].includes(window.location.hostname),t="https:"===window.location.protocol||"chrome-extension:"===window.location.protocol;if(!e&&!t)throw new c.PrivyClientError("Embedded wallet is only available over HTTPS")}(),function(e){if("string"!=typeof e||25!==e.length)throw new c.PrivyClientError("Cannot initialize the Privy provider with an invalid Privy app ID")}(n.appId),function(e){Rr||(Rr=new Mr({appId:e.appId,appClientId:e.clientId,apiUrl:e.apiUrl}))}(n);let i=t.useMemo((()=>new q.default({appId:n.appId,clientId:n.clientId,storage:d.u,baseUrl:n.apiUrl,sdkVersion:"react-auth:3.8.0"})),[]),a=Lr(),s=Object.assign({},r);/*#__PURE__*/return e.jsx(p.PrivyAppConfigProvider,{client:i,legacyClient:a,appClientId:n.clientId,clientConfig:s,children:/*#__PURE__*/e.jsx(E.PrivyPluginProvider,{children:/*#__PURE__*/e.jsx(lr,{...n,client:a,privy:i})})})},exports.RunEffectOnce=ye,exports.SiweFlow=Ie,exports.SiwsFlow=We,exports.WalletConnectV2WalletConnector=dt,exports.createCodeVerifier=Ce,exports.createStateCode=Ae,exports.deriveCodeChallengeFromCodeVerifier=Pe,exports.e=Lt,exports.embeddedWalletRecoveryScreen=Mt,exports.embeddedWalletSetPasswordScreen=Ot,exports.errorIndicatesInvalidRecoveryPassword=function(e){return pt(e)&&("invalid_recovery_pin"===e.type||"invalid_request_arguments"===e.type)},exports.errorIndicatesMaxMfaRetries=function(e){return!!pt(e)&&"mfa_verification_max_attempts_reached"===e.type},exports.errorIndicatesMfaCanceled=function(e){return!!function(e){let t=e.type;return"string"==typeof t&&"client_error"===t}(e)&&"MFA canceled"===e.message},exports.errorIndicatesMfaRateLimit=function(e){return!(!pt(e)||!e.message.includes("code 429"))},exports.errorIndicatesMfaTimeout=function(e){return!!pt(e)&&"mfa_timeout"===e.type},exports.errorIndicatesMfaVerificationFailed=function(e){return!!pt(e)&&"missing_or_invalid_mfa"===e.type},exports.errorIndicatesRecoveryIsNeeded=yt,exports.fetchWalletBalance=Dt,exports.getCustomerAccessToken=function(){let e=Lr();return e?e.getCustomerAccessToken():Promise.resolve(d.u.get(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.getIdentityToken=async function(){return await(Rr?.updateUserAndIdToken()),Rr?.useServerCookies?Er.getState().identityToken:Promise.resolve(d.u.get(p.IDENTITY_TOKEN_STORAGE_KEY)||null)},exports.getTelegramAuthErrorMessage=function(e){let t={detail:"",retryable:!1};return e?.privyErrorCode===c.PrivyErrorCode.LINKED_TO_ANOTHER_USER&&(t.detail="This account has already been linked to another user."),e?.privyErrorCode===c.PrivyErrorCode.DISALLOWED_LOGIN_METHOD&&(t.detail="Login with Telegram not allowed."),e?.privyErrorCode===c.PrivyErrorCode.INVALID_DATA&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode===c.PrivyErrorCode.CANNOT_LINK_MORE_OF_TYPE&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode===c.PrivyErrorCode.INVALID_CREDENTIALS&&(t.retryable=!0,t.detail="Something went wrong. Try again."),e?.privyErrorCode===c.PrivyErrorCode.TOO_MANY_REQUESTS&&(t.detail="Too many requests. Please wait before trying again."),e?.privyErrorCode===c.PrivyErrorCode.TOO_MANY_REQUESTS&&e.message.includes("rate limit")&&(t.detail="Request limit reached for Telegram. Please wait a moment and try again."),e instanceof Oe&&(t.retryable=!0,t.detail="Something went wrong. Try again."),t},exports.prepareTransactionRequest=Vt,exports.shouldCreateEmbeddedEthWallet=zt,exports.shouldCreateEmbeddedSolWallet=Kt,exports.stripUrlOAuthParamsAndRemoveStateCode=ke,exports.toDisplayFromAccountType=qt,exports.toEmbeddedWalletSetRecoveryScreen=Nt,exports.toViemAccount=jr,exports.useAuthMfa=Dr,exports.useAuthMfaEnrollment=()=>{let e=p.useAppConfig(),{setModalData:r}=a.usePrivyModal(),{verify:n}=Dr(),{openModal:i,privy:s,closePrivyModal:o,refreshSessionAndUser:l,setUser:d}=c.usePrivyInternal();return t.useMemo((()=>({enroll:async t=>new Promise(((a,c)=>{r({mfaEnroll:{onSuccess:async e=>{await o({shouldCallAuthOnSuccess:!1,isSuccess:!0}),a(e)},onFailure:async e=>{await o({shouldCallAuthOnSuccess:!1,isSuccess:!1}),c(e)},onBack:t?.onBack?async()=>{await o({shouldCallAuthOnSuccess:!1,isSuccess:!1}),c(Error("User canceled MFA enrollment flow.")),t.onBack?.()}:void 0,verify:()=>n({standalone:!1}),shouldUnlinkOnUnenrollMfa:!0,mfaMethods:e.mfa.methods,sendSmsCode:async()=>{throw Error("Not enabled")},enrollSms:async()=>{throw Error("Not enabled")},unenrollSms:async()=>{throw Error("Not enabled")},generateTotpSecret:async()=>await s.fetchPrivyRoute(R.MfaAuthTotpInit,{body:{}}),enrollTotp:async e=>{await s.fetchPrivyRoute(R.MfaAuthTotpEnroll,{body:{code:e}});let t=await l();return d(t),t},unenrollTotp:async()=>{await s.fetchPrivyRoute(R.MfaAuthTotpUnenroll,{body:{}});let e=await l();return d(e),e},enrollPasskey:async e=>{await s.fetchPrivyRoute(R.MfaAuthPasskeyEnrollment,{body:{credential_ids:e,remove_for_login:!0}});let t=await l();return d(t),t}}}),i("MfaAuthEnrollmentFlowScreen")}))})),[s,r,i,o])},exports.useAuthorizationSignature=()=>{let{signWithUserSigner:e}=F.useSignWithUserSigner();return t.useMemo((()=>({async generateAuthorizationSignature(t){let{targetAppId:n,...i}=t,{signature:a}=await r.generateAuthorizationSignature((async({message:t})=>e({message:t,targetAppId:n})),i);return{signature:a}}})),[e])},exports.useBaseAccountSdk=()=>{let{baseAccountSdk:e}=c.usePrivyInternal();return{baseAccountSdk:e}},exports.useCaptcha=Me,exports.useConnectBaseAccount=()=>{let{connectBaseAccount:e}=c.usePrivyInternal();return{connectBaseAccount:e}},exports.useConnectCoinbaseSmartWallet=()=>{let{connectCoinbaseSmartWallet:e}=c.usePrivyInternal();return{connectCoinbaseSmartWallet:e}},exports.useConnectOrCreateWallet=e=>{let{connectOrCreateWallet:t}=a.usePrivyContext();return P.usePrivyEventSubscription("connectOrCreateWallet",e),{connectOrCreateWallet:t}},exports.useCrossAppAccounts=()=>{let{startCrossAppAuthFlow:e,unlinkCrossAppAccount:t,signMessageWithCrossAppWallet:r,signTypedDataWithCrossAppWallet:n,sendTransactionWithCrossAppWallet:i,signTransactionWithCrossAppWallet:s}=a.usePrivyContext();return{loginWithCrossAppAccount:({appId:t})=>e({appId:t,action:"login"}),linkCrossAppAccount:({appId:t})=>e({appId:t,action:"link"}),unlinkCrossAppAccount:t,signMessage:r,signTypedData:n,sendTransaction:i,signTransaction:s}},exports.useCustomAuth=e=>{let t=er((e=>e.jwtAuthFlowState));return P.usePrivyEventSubscription("customAuth",e),{status:t}},exports.useDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=c.usePrivyInternal();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},exports.useFarcasterSigner=function(){let{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}=a.usePrivyContext();return{getFarcasterSignerPublicKey:e,signFarcasterMessage:t,requestFarcasterSignerFromWarpcast:r}},exports.useGetAccessTokenForProvider=()=>t.useMemo((()=>({getAccessTokenForProvider:({appId:e})=>{try{let t=d.u.get(p.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return{token:null};{let r=new B(t);return r.isExpired()?(d.u.del(p.getProviderAccessTokenStorageKey(e)),{token:null}):{token:r.value}}}catch(e){return console.error(e),{token:null}}}})),[]),exports.useGuestAccounts=function(){let e=p.useAppConfig(),t=P.useEmitPrivyEvent(),{client:r,setUser:n,setAuthenticated:i,setIsNewUser:a,initializeWalletProxy:s}=c.usePrivyInternal(),{create:o}=E.useCreateWalletInternal();return{createGuestAccount:async()=>{if(!e.id||!r)throw Error("SDK not yet ready");r.startAuthFlow(new Sr(e.id));try{let l=await r.authenticate(),d=l.user,u=l.isNewUser??!1;if(!d)throw new c.PrivyClientError("Unable to authenticate guest account");let h=await r.getAccessToken(),y=await s(p.WALLET_PROXY_TIMEOUT);if(h&&y)try{let t=zt(d,e.embeddedWallets.ethereum.createOnLogin),r=Kt(d,e.embeddedWallets.solana.createOnLogin);t&&r?(d=(await o({chainType:"ethereum",latestUser:d})).user,d=(await o({chainType:"solana",latestUser:d})).user):r?d=(await o({chainType:"solana",latestUser:d})).user:t?d=(await o({chainType:"ethereum",latestUser:d})).user:n(d)}catch(e){n(d),console.warn("Unable to create embedded wallet for guest account")}return a(u),i(!0),t("login","onComplete",{user:d,isNewUser:u,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),d}catch(e){throw t("login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}}}},exports.useHeadlessDelegatedActions=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=c.usePrivyInternal();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}},exports.useIdentityToken=function(){let{identityToken:e}=Er();return{identityToken:e}},exports.useLinkAccount=function(e){let{linkEmail:r,linkPhone:n,linkWallet:i,linkGoogle:s,linkApple:o,linkTwitter:l,linkTwitch:c,linkDiscord:d,linkGithub:u,linkLinkedIn:h,linkTiktok:p,linkLine:y,linkSpotify:w,linkInstagram:m,linkTelegram:v,linkFarcaster:g,linkPasskey:f}=t.useContext(a.PrivyContext);return P.usePrivyEventSubscription("linkAccount",e),{linkEmail:r,linkPhone:n,linkWallet:i,linkGoogle:s,linkApple:o,linkTwitter:l,linkTwitch:c,linkDiscord:d,linkGithub:u,linkLinkedIn:h,linkTiktok:p,linkLine:y,linkSpotify:w,linkInstagram:m,linkFarcaster:g,linkTelegram:v,linkPasskey:f}},exports.useLinkJwtAccount=function(e){let{client:r}=c.usePrivyInternal(),[n,i]=t.useState({status:"initial"});return{linkWithCustomJwt:t.useCallback((async t=>{try{i({status:"initial"}),r.startAuthFlow(new Zt(t)),i({status:"loading"});let{user:n}=await r.link();if(!n)throw Error("Error, user not found");let a=n.linkedAccounts.filter((e=>"custom_auth"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime())).at(0);return i({status:"done"}),e?.onSuccess?.({user:n,linkMethod:"custom",linkedAccount:a}),{user:n}}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"custom"}),t}}),[r.startAuthFlow,r.link]),state:n}},exports.useLinkWithPasskey=e=>{let{initLinkWithPasskey:r,linkWithPasskey:n,passkeyAuthState:i,setPasskeyAuthState:a}=c.usePrivyInternal();return{linkWithPasskey:t.useCallback((async()=>{try{await r();let t=await n();if(!t)throw Error("Error, user not found");let i=t.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:t,linkMethod:"passkey",linkedAccount:i})}catch(t){throw a({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[n]),state:i}},exports.useLinkWithSiwe=e=>{let r=Me(),{siweState:n,setSiweState:i,linkWithSiwe:a,generateSiweMessage:s}=c.usePrivyInternal();return{generateSiweMessage:t.useCallback((async({address:t,chainId:r})=>{try{if(!t||!r)throw Error("wallet address and chainId required to generate nonce");return await s({address:t,chainId:r}).then((e=>e))}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[s]),linkWithSiwe:t.useCallback((async({signature:t,message:n,chainId:s,walletClientType:o,connectorType:l})=>{try{if(r.enabled&&"success"!==r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);let{user:i,linkedAccount:d}=await a({message:n,signature:t,chainId:s,walletClientType:o,connectorType:l});d&&e?.onSuccess?.({user:i,linkMethod:"siwe",linkedAccount:d})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[a,r.status]),state:n}},exports.useLinkWithSiws=()=>{let e=Me(),{client:r,setUser:n,refreshSessionAndUser:i}=c.usePrivyInternal(),{authenticated:a}=E.usePrivy();return{generateSiwsMessage:t.useCallback((async({address:t})=>{let n;if(e.enabled&&"error"===e.status)throw new Oe(e.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),n=await e.waitForResult());let i=await r.generateSiwsNonce({address:t,captchaToken:n});return E.prepareSiwsMessageWithNonce({address:t,nonce:i})}),[e,r]),linkWithSiws:t.useCallback((async({signature:t,message:s,walletClientType:o,connectorType:l})=>{if(!a)throw Error("User must be authenticated before linking");if(e.enabled&&"error"===e.status)throw new Oe(e.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);let d=await r.linkWithSiws({message:s,signature:t,walletClientType:o,connectorType:l,messageType:"plain"}),u=(e=>{if(!e)return;let t=e.linkedAccounts;return t&&0!==t.length?t[t.length-1]:void 0})(d=await i()??d)||null;return n(d||null),{user:d,linkedAccount:u}}),[a,e,r,i,n])}},exports.useLoginWithEmail=e=>{let r=Me(),{emailOtpState:n,setEmailOtpState:i,initLoginWithEmail:a,loginWithCode:s}=c.usePrivyInternal();return{sendCode:t.useCallback((async({email:t,disableSignup:n})=>{try{let e;if(!t)throw Error("Email required to send OTP code");if(r.enabled&&"error"===r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);return r.enabled&&"success"!==r.status&&(r.execute(),e=await r.waitForResult()),await a({email:t,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[a]),loginWithCode:t.useCallback((async({code:t})=>{try{if(r.enabled&&"error"===r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:o}=await s(t);e?.onComplete?.({user:n,isNewUser:i,wasAlreadyAuthenticated:a,loginMethod:"email",loginAccount:o})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[s,r.status]),state:n}},exports.useLoginWithFarcasterV2=()=>{let{client:e,setAuthenticated:r,setUser:n}=c.usePrivyInternal();return t.useMemo((()=>({init:async()=>{if(!e)throw new c.PrivyClientError("Must initialize Privy client first.");let t=new x.FarcasterFramesFlow;return e.startAuthFlow(t),await t.init()},login:async({fid:t,message:i,signature:a})=>{if(!e)throw new c.PrivyClientError("Must initialize Privy client first.");if(!(e.authFlow instanceof x.FarcasterFramesFlow))throw new c.PrivyClientError("Must initialize Farcaster Mini App flow first.");e.authFlow.setAuthData({message:i,signature:a,fid:t});let{user:s}=await e.authenticate();if(!s)throw new c.PrivyClientError("Failed to login with Farcaster V2");return n(s),r(!0),{user:s}}})),[e,n,r])},exports.useLoginWithOAuth=e=>{P.usePrivyEventSubscription("login",e);let r=Me(),n=p.useIsServerConfigLoaded(),{ready:i,user:s}=a.usePrivyContext(),{initLoginWithHeadlessOAuth:o,loginWithHeadlessOAuth:l,oAuthState:d,setOAuthState:u,isHeadlessOAuthLoading:h}=c.usePrivyInternal(),y=t.useCallback((async e=>{try{if(r.enabled&&"success"!==r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);return await o(e.provider,r.token,e.disableSignup)}catch(e){throw u({status:"error",error:e}),e}}),[o,r]),w=t.useCallback((async()=>{let e=_e();try{if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");let t=e.provider;if(a.isCustomOAuthProvider(t)){if(s&&s.linkedAccounts.some((e=>e.type===t)))return console.warn("User is already logged in with this OAuth provider"),s}else if(s&&t in s&&s[t])return console.warn("User is already logged in with this OAuth provider"),s;if(e.popupFlow)return}catch(e){throw u({status:"error",error:e}),e}try{return await l(e)}catch(e){throw u({status:"error",error:e}),e}finally{ke()}}),[l]);return t.useEffect((()=>{let e=_e();i&&n&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&w().catch((()=>{}))}),[i,n]),{initOAuth:y,loading:h,state:d}},exports.useLoginWithPasskey=e=>{let r=Me(),{initLoginWithPasskey:n,loginWithPasskey:i,passkeyAuthState:a,setPasskeyAuthState:s}=c.usePrivyInternal();return{loginWithPasskey:t.useCallback((async t=>{try{let a;if(r.enabled&&"error"===r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);r.enabled&&"success"!==r.status&&(r.execute(),a=await r.waitForResult()),await n({captchaToken:a,withPrivyUi:!1});let{user:s,isNewUser:o,wasAlreadyAuthenticated:l,loginAccount:d}=await i(t);e?.onComplete?.({user:s,isNewUser:o,wasAlreadyAuthenticated:l,loginMethod:"passkey",loginAccount:d})}catch(t){throw s({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[i,r.status]),state:a}},exports.useLoginWithSiwe=e=>{let r=Me(),{siweState:n,setSiweState:i,client:a,generateSiweMessage:s,loginWithSiwe:o}=c.usePrivyInternal();return{generateSiweNonce:t.useCallback((async t=>{try{let e;if(r.enabled&&"error"===r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);r.enabled&&"success"!==r.status&&(r.execute(),e=await r.waitForResult()),i({status:"generating-message"});let n=await a.generateSiweNonce({address:t?.address,captchaToken:e});return i({status:"awaiting-signature"}),n}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[a,r]),generateSiweMessage:t.useCallback((async({address:t,chainId:n})=>{try{let e;if(r.enabled&&"error"===r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);return r.enabled&&"success"!==r.status&&(r.execute(),e=await r.waitForResult()),await s({address:t,chainId:n,captchaToken:e})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[s,r]),loginWithSiwe:t.useCallback((async({message:t,signature:n,disableSignup:a,walletClientType:s,connectorType:l})=>{try{let i;if(r.enabled&&"error"===r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);r.enabled&&"success"!==r.status&&(r.execute(),i=await r.waitForResult());let{user:d,isNewUser:u}=await o({message:t,signature:n,captchaToken:i,disableSignup:a,walletClientType:s,connectorType:l});return e?.onComplete?.({user:d,isNewUser:u,wasAlreadyAuthenticated:!1,loginMethod:"siwe",loginAccount:null}),d}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[o,r.status]),state:n}},exports.useLoginWithSiws=()=>{let e=Me(),{client:r,setAuthenticated:n,setUser:i,setIsNewUser:a}=c.usePrivyInternal(),{authenticated:s}=E.usePrivy();return{generateSiwsMessage:t.useCallback((async({address:t})=>{let n;if(e.enabled&&"error"===e.status)throw new Oe(e.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),n=await e.waitForResult());let i=await r.generateSiwsNonce({address:t,captchaToken:n});return E.prepareSiwsMessageWithNonce({address:t,nonce:i})}),[e,r]),loginWithSiws:t.useCallback((async({message:t,signature:o,disableSignup:l,walletClientType:d,connectorType:u})=>{if(s)throw Error("User already authenticated");if(e.enabled&&"error"===e.status)throw new Oe(e.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);e.enabled&&"success"!==e.status&&(e.execute(),await e.waitForResult());let{user:h,isNewUser:p}=await r.authenticateWithSiws({message:t,signature:o,walletClientType:d,connectorType:u,mode:l?"no-signup":"login-or-sign-up",messageType:"plain"});if(!h)throw Error("Authentication failed - no user returned");return i(h),a(p||!1),n(!0),h}),[s,e,r,n,i,a])}},exports.useLoginWithSms=e=>{let r=Me(),{smsOtpState:n,setSmsOtpState:i,initLoginWithSms:a,loginWithCode:s}=c.usePrivyInternal();return{sendCode:t.useCallback((async({phoneNumber:t,disableSignup:n})=>{try{let e;if(!t)throw Error("SMS required to send OTP code");if(r.enabled&&"error"===r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);return r.enabled&&"success"!==r.status&&(r.execute(),e=await r.waitForResult()),await a({phoneNumber:t,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[a]),loginWithCode:t.useCallback((async({code:t})=>{try{if(r.enabled&&"error"===r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);let{user:n,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:o}=await s(t);e?.onComplete?.({user:n,isNewUser:i,wasAlreadyAuthenticated:a,loginMethod:"sms",loginAccount:o})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[s,r.status]),state:n}},exports.useLoginWithTelegram=e=>{let r=Me(),{initLoginWithTelegram:n,loginWithTelegram:i,telegramAuthState:a,setTelegramAuthState:s}=c.usePrivyInternal();return{login:t.useCallback((async t=>{try{if(r.enabled&&"success"!==r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);await n(r.token,t?.disableSignup);let{user:a,isNewUser:s,loginAccount:o,wasAlreadyAuthenticated:l}=await i({intent:"login"});e?.onComplete?.({user:a,isNewUser:s,wasAlreadyAuthenticated:l,loginMethod:"telegram",loginAccount:o})}catch(t){throw s({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[n,i,r]),state:a}},exports.useMfa=function(){let{promptMfa:e,init:r,submit:n,cancel:i,mfaMethods:s}=t.useContext(a.PrivyContext);return{promptMfa:e,init:r,submit:n,cancel:i,mfaMethods:s}},exports.useMfaEnrollment=function(){let{initEnrollmentWithSms:e,initEnrollmentWithTotp:r,initEnrollmentWithPasskey:n,submitEnrollmentWithSms:i,submitEnrollmentWithTotp:s,submitEnrollmentWithPasskey:o,unenroll:l,enrollInMfa:c}=t.useContext(a.PrivyContext);return{initEnrollmentWithSms:e,initEnrollmentWithTotp:r,initEnrollmentWithPasskey:n,submitEnrollmentWithSms:i,submitEnrollmentWithTotp:s,submitEnrollmentWithPasskey:o,unenrollWithSms:()=>l("sms"),unenrollWithTotp:()=>l("totp"),unenrollWithPasskey:e=>l("passkey",e),showMfaEnrollmentModal:()=>c(!0),closeMfaEnrollmentModal:()=>c(!1)}},exports.useMigrateWallets=Yt,exports.useModalStatus=()=>{let{isModalOpen:e}=t.useContext(a.PrivyContext);return{isOpen:e}},exports.useOAuthTokens=function(e){let{authenticated:t,user:r}=a.usePrivyContext(),{initLoginWithOAuth:n}=c.usePrivyInternal(),i=P.useEmitPrivyEvent();return P.usePrivyEventSubscription("oAuthAuthorization",e),{reauthorize:e=>qr(t,r,n,i,e.provider)}},exports.useRecoverEmbeddedWallet=()=>{let{user:e}=a.usePrivyContext(),{walletProxy:r}=c.usePrivyInternal();return{recover:t.useCallback((async t=>{if(!r)throw Error("Wallet proxy is not ready");let n=await re();if(!e||!n)throw new c.PrivyClientError("User must be logged in before attempting to modify the recovery method.");let{entropyId:i,entropyIdVerifier:a}=l.getEntropyDetailsForUser(e);try{await r.recover({entropyId:i,entropyIdVerifier:a,accessToken:n,...t})}catch{throw new c.PrivyClientError("Unable to recover wallets")}}),[r,e])}},exports.useRegisterMfaListener=ze,exports.useSendTransaction=function(e){let{sendTransaction:r}=t.useContext(a.PrivyContext);return P.usePrivyEventSubscription("sendTransaction",e),{sendTransaction:r}},exports.useSessionSigners=()=>{let{addSessionSignersInternal:e,removeSessionSignersInternal:t}=(()=>{let{user:e}=a.usePrivyContext(),t=c.usePrivyInternal(),{signWithUserSigner:n}=F.useSignWithUserSigner(),i=async({wallet:i,additional_signers:a})=>{let s=await t.client.getAccessToken();if(!e||!s)throw new c.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if(!i.id)throw new c.PrivyClientError("Wallet to add signers to must have ID on server");if(!t.walletProxy)throw new c.PrivyClientError("Wallet proxy not initialized.");await r.updateWallet(t.privy,{wallet_id:i.id},n,{additional_signers:a})};return{addSessionSignersInternal:async({address:n,signers:s})=>{let l=await t.client.getAccessToken();if(!e||!l)throw new c.PrivyClientError("User must be authenticated and have an embedded wallet to add a session signer.");let d=t.walletProxy??await t.initializeWalletProxy(15e3);if(!d)throw new c.PrivyClientError("Wallet proxy not initialized.");let u=a.getPrivyWalletWithAddress(e,n);if(!u)throw new c.PrivyClientError("Address to add signers too is not associated with current user.");if(a.getIsUnifiedWallet(u)){if(0===s.length)throw new c.PrivyClientError("Must specify at least one signer to add.");let e=[...(await r.getWallet(t.privy,{wallet_id:u.id})).additional_signers,...o.parseAdditionalSigners(s)];await i({wallet:u,additional_signers:e})}else{if(u.delegated)return{user:e};if(s.length>0)throw new c.PrivyClientError("Specifying signers in addSessionSigners is only supported for TEE execution and this app uses On-device execution. Pass an empty array for signers instead. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let r=Tt({address:n,user:e}),i=_t({address:n,user:e});await t.recoverEmbeddedWallet({address:n}),await d.createDelegatedAction({accessToken:l,rootWallet:i,delegatedWallets:[r]})}let h=await t.refreshSessionAndUser();if(!h)throw Error("Could not refresh user");return{user:h}},removeSessionSignersInternal:async({address:r})=>{let n=await t.client.getAccessToken();if(!e||!n)throw new c.PrivyClientError("User must be authenticated and have an embedded wallet to delegate actions.");if(!(t.walletProxy??await t.initializeWalletProxy(15e3)))throw new c.PrivyClientError("Wallet proxy not initialized.");let s=a.getPrivyWalletWithAddress(e,r);if(!s)throw new c.PrivyClientError("Address to remove signers from is not associated with current user.");a.getIsUnifiedWallet(s)?await i({wallet:s,additional_signers:[]}):await t.client.revokeDelegatedWallet();let o=await t.refreshSessionAndUser();if(!o)throw Error("Could not refresh user");return{user:o}}}})();return{addSessionSigners:async({address:t,signers:r})=>e({address:t,signers:r}),removeSessionSigners:async({address:e})=>t({address:e})}},exports.useSetWalletRecovery=function(e){let{setWalletRecovery:r}=t.useContext(a.PrivyContext);return P.usePrivyEventSubscription("setWalletRecovery",e),{setWalletRecovery:r}},exports.useSign7702Authorization=()=>{let{ready:e,wallets:r}=l.useWallets(),{user:n}=a.usePrivyContext(),{rpcConfig:i,chains:s,appId:o}=c.usePrivyInternal();return{signAuthorization:t.useCallback((async(t,l)=>{let c;if(!n)throw Error("User must be authenticated before signing with a Privy wallet");if(!e)throw Error("Wallets are not ready");let d=l?.address??a.getPrivyEthereumWallet(n)?.address??b.zeroAddress,u=r.find((e=>b.getAddress(e.address)===b.getAddress(d)));if(!u)throw Error("Signing wallet not found.");let h=t.chainId??Number(u.chainId.split(":")[1]);if(0===h)c={chainId:0,address:t.contractAddress,nonce:t.nonce??0};else{let e=s.find((e=>e.id===h));if(!e)throw Error("Error, chain not configured in PrivyProvider config");let r=b.createWalletClient({account:d,chain:e,transport:b.http(I.getJsonRpcEndpointFromChain(e,i,o))});c=await r.prepareAuthorization({...t})}let p=await u.getEthereumProvider(),y=await p.request({method:"secp256k1_sign",params:[m.hashAuthorization(c)]});return{...c,...b.parseSignature(y)}}),[e,r,n,s])}},exports.useSignMessage=function(e){let{signMessage:r}=t.useContext(a.PrivyContext);return P.usePrivyEventSubscription("signMessage",e),{signMessage:r}},exports.useSignTransaction=function(){let{signTransaction:e}=t.useContext(a.PrivyContext);return{signTransaction:e}},exports.useSignTypedData=function(e){let{signTypedData:r}=t.useContext(a.PrivyContext);return P.usePrivyEventSubscription("signTypedData",e),{signTypedData:r}},exports.useSignupWithPasskey=e=>{let r=Me(),{initSignupWithPasskey:n,signupWithPasskey:i,passkeyAuthState:a,setPasskeyAuthState:s}=c.usePrivyInternal();return{signupWithPasskey:t.useCallback((async()=>{try{let t;if(r.enabled&&"error"===r.status)throw new Oe(r.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);r.enabled&&"success"!==r.status&&(r.execute(),t=await r.waitForResult()),await n({captchaToken:t,withPrivyUi:!1});let{user:a,isNewUser:s,wasAlreadyAuthenticated:o,loginAccount:l}=await i();e?.onComplete?.({user:a,isNewUser:s,wasAlreadyAuthenticated:o,loginMethod:"passkey",loginAccount:l})}catch(t){throw s({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[i,r.status]),state:a}},exports.useSubscribeToJwtAuthWithFlag=function({isAuthenticated:e,isLoading:r,...n}){let i=t.useRef();t.useEffect((()=>{r||i.current?.()}),[e,r]);let a=t.useCallback((e=>(i.current=e,()=>{i.current=void 0})),[]);return Xt({...n,subscribe:a})},exports.useSyncJwtBasedAuthState=Xt,exports.useToken=function(e){let{getAccessToken:r}=t.useContext(a.PrivyContext);return P.usePrivyEventSubscription("accessToken",e),{getAccessToken:r}},exports.useUpdateAccount=function(e){let{updateEmail:r,updatePhone:n}=t.useContext(a.PrivyContext);return P.usePrivyEventSubscription("update",e),{updateEmail:r,updatePhone:n}},exports.useUpdateEmail=e=>{let{user:r}=a.usePrivyContext(),{loginWithCode:n,emailOtpState:i,setEmailOtpState:s,client:o,inProgressAuthFlowRef:l,inProgressLoginOrLinkMethodRef:d}=c.usePrivyInternal();return{state:i,sendCode:t.useCallback((async({newEmailAddress:t})=>{try{if(!r?.email)throw Error("User is required to have an email address to update it.");let e=new se(r.email.address,t);o.startAuthFlow(e),await e.sendCodeEmail({withPrivyUi:!1})}catch(t){s({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[r?.email]),verifyCode:t.useCallback((async({code:t})=>{try{if(!r?.email)throw Error("User is required to have an email address to update it.");l.current="update",d.current="email";let{user:i,linkedAccount:a}=await n(t);return e?.onSuccess?.({user:i,updateMethod:"email",updatedAccount:a}),{user:i}}catch(t){s({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"email"})}}),[r?.email])}},exports.useUser=()=>{let{setUser:e,client:r}=t.useContext(c.InternalPrivyContext),{user:n}=t.useContext(a.PrivyContext);return{user:n,refreshUser:t.useCallback((async()=>{let t=await(r?.updateUserAndIdToken());return e(t??null),t}),[r,e])}},exports.useX402Fetch=()=>{let{wallets:e}=l.useWallets();return t.useMemo((()=>({wrapFetchWithPayment:({walletAddress:t,fetch:r,maxValue:n=BigInt(1e5),paymentRequirementsSelector:i=O.selectPaymentRequirements,config:s})=>{let o=t||e[0]?.address;if(!o)throw new N.InvalidInputError("No wallet available for payment");let l=e.find((e=>a.areAddressesEqual(e.address,o)));if(!l)throw new N.InvalidInputError(`Wallet ${o} not found in connected wallets`);return async(e,t)=>{let a=await r(e,t);if(402!==a.status)return a;if(t?.__is402Retry)throw Error("Payment already attempted for this request");let{x402Version:o,accepts:c}=await a.json(),d=i(c,void 0,"exact");if(BigInt(d.maxAmountRequired)>n)throw new N.InvalidInputError("Payment amount exceeds maximum allowed");let u=await jr({wallet:l}),h=await O.createPaymentHeader(u,o,d,s),p={...t,headers:{...t?.headers||{},"X-PAYMENT":h,"Access-Control-Expose-Headers":"X-PAYMENT-RESPONSE"},__is402Retry:!0};return await r(e,p)}}})),[e])};
|