@privy-io/react-auth 3.14.0 → 3.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/{AccountNotFoundScreen-B2BwM9IL.js → AccountNotFoundScreen-C25iBRLm.js} +1 -1
- package/dist/cjs/{Address-CMUXgM3h.js → Address-CHKhHgKJ.js} +1 -1
- package/dist/cjs/{AffirmativeConsentScreen-B7nTfKFs.js → AffirmativeConsentScreen-DT0ojGpw.js} +1 -1
- package/dist/cjs/{AllowlistRejectionScreen-C0ubkz2f.js → AllowlistRejectionScreen-D0I4vTcK.js} +1 -1
- package/dist/cjs/{AuthenticateWithWalletScreen-DHRXcjT5.js → AuthenticateWithWalletScreen-dcVrFqXU.js} +1 -1
- package/dist/cjs/{AwaitingEvmToSolBridgingScreen-D6MB0SW8.js → AwaitingEvmToSolBridgingScreen-20Lokl_2.js} +1 -1
- package/dist/cjs/{AwaitingExternalEthereumTransferScreen-BcnofXQv.js → AwaitingExternalEthereumTransferScreen-B2BOyvEP.js} +1 -1
- package/dist/cjs/{AwaitingPasswordlessCodeScreen-CMMIM_Pj.js → AwaitingPasswordlessCodeScreen-CjeHuBk7.js} +1 -1
- package/dist/cjs/{AwaitingSolToEvmBridgingScreen-C2Op_A4L.js → AwaitingSolToEvmBridgingScreen-NSyS8djM.js} +1 -1
- package/dist/cjs/{BridgeNetworkSelectionView-BU5hxQ4Z.js → BridgeNetworkSelectionView-Cy4dUUah.js} +1 -1
- package/dist/cjs/{CaptchaScreen-TVUbEsJK.js → CaptchaScreen-CchfnELg.js} +1 -1
- package/dist/cjs/{CoinbaseOnrampStatusScreen-_mCdKOIM.js → CoinbaseOnrampStatusScreen-RmmivwEu.js} +1 -1
- package/dist/cjs/{ConnectEmailForm-BgS2Yn3u.js → ConnectEmailForm-BibKRhlR.js} +1 -1
- package/dist/cjs/{ConnectLedgerScreen-DjDvgzxV.js → ConnectLedgerScreen-CB1oTLjq.js} +1 -1
- package/dist/cjs/{ConnectOnlyLandingScreen-CbUMwYrO.js → ConnectOnlyLandingScreen-BI0zDj3o.js} +1 -1
- package/dist/cjs/{ConnectOnlyStatusScreen-DyoV_8V9.js → ConnectOnlyStatusScreen-BAUS-OpP.js} +1 -1
- package/dist/cjs/{ConnectOrCreateScreen-DpR4OmSO.js → ConnectOrCreateScreen-CdoSL34u.js} +1 -1
- package/dist/cjs/{ConnectPhoneForm-CdRNa4Lg.js → ConnectPhoneForm-BPgbe0j3.js} +1 -1
- package/dist/cjs/{ConnectWalletView-Bb4271wb.js → ConnectWalletView-BB2DjcE-.js} +1 -1
- package/dist/cjs/{ConnectionStatusScreen-B8TxWdVC.js → ConnectionStatusScreen-D2pFs10v.js} +1 -1
- package/dist/cjs/{CrossAppAuthScreen-By4i5UqT.js → CrossAppAuthScreen-Dzqgp4fv.js} +1 -1
- package/dist/cjs/{CustomLandingScreenView-C0Vky31_.js → CustomLandingScreenView-Pamy7vPb.js} +1 -1
- package/dist/cjs/{DelegatedActionsConsentScreen-CjUYU339.js → DelegatedActionsConsentScreen-B1RznIyD.js} +1 -1
- package/dist/cjs/{DelegatedActionsRevokeScreen-BGATOJGL.js → DelegatedActionsRevokeScreen-BfYkymoM.js} +1 -1
- package/dist/cjs/{EmbeddedWalletConnectingScreen-GZ8nOvWq.js → EmbeddedWalletConnectingScreen-DaOL3Ico.js} +1 -1
- package/dist/cjs/{EmbeddedWalletCreatedScreen-Be8AYwZh.js → EmbeddedWalletCreatedScreen-B5K1ek4V.js} +1 -1
- package/dist/cjs/{EmbeddedWalletKeyExportScreen-DXa54jFw.js → EmbeddedWalletKeyExportScreen-BJTyn-Lk.js} +1 -1
- package/dist/cjs/{EmbeddedWalletOnAccountCreateScreen-C8-LkEhs.js → EmbeddedWalletOnAccountCreateScreen-BbZKkeLp.js} +1 -1
- package/dist/cjs/{EmbeddedWalletPasswordUpdateScreen-B7N8Noqf.js → EmbeddedWalletPasswordUpdateScreen-DMx4Tn8E.js} +1 -1
- package/dist/cjs/{EmbeddedWalletPasswordUpdateSplashScreen-kiTrvJ2h.js → EmbeddedWalletPasswordUpdateSplashScreen-wUfHEYpF.js} +1 -1
- package/dist/cjs/{EnrollTotp-Bxzun51r.js → EnrollTotp-B1qE1mCx.js} +1 -1
- package/dist/cjs/{ErrorScreen-BsvL8i4R.js → ErrorScreen-BPXQabSS.js} +1 -1
- package/dist/cjs/{FarcasterConnectStatusScreen-DMnzjTAV.js → FarcasterConnectStatusScreen-C_NK2UCS.js} +1 -1
- package/dist/cjs/{FarcasterSignerStatusScreen-Xb4KBH8f.js → FarcasterSignerStatusScreen-D3DUvPPw.js} +1 -1
- package/dist/cjs/{FundSolWalletWithExternalSolanaWallet-BT4nT21N.js → FundSolWalletWithExternalSolanaWallet-BoOhBVX9.js} +1 -1
- package/dist/cjs/{FundWalletMethodHeader-D_l3529h.js → FundWalletMethodHeader-BUHyY_8M.js} +1 -1
- package/dist/cjs/FundWithBankDepositScreen-D_qA2wCk.js +176 -0
- package/dist/cjs/{FundingEditAmountScreen-CBp--May.js → FundingEditAmountScreen-DLWLIjEZ.js} +1 -1
- package/dist/cjs/FundingMethodSelectionScreen-BRz8TLz5.js +1 -0
- package/dist/cjs/{InAppBrowserLoginNotPossible-fTc3VwS8.js → InAppBrowserLoginNotPossible-iLA0OVLk.js} +1 -1
- package/dist/cjs/{InstallWalletScreen-Bm_jzHEL.js → InstallWalletScreen-BS2Bwxvi.js} +1 -1
- package/dist/cjs/{LandingScreen-D6094d73.js → LandingScreen-C4KpTL08.js} +1 -1
- package/dist/cjs/{LinkConflictScreen-Bic4pZUv.js → LinkConflictScreen-CNQSun1F.js} +1 -1
- package/dist/cjs/{LinkEmailScreen-BuuqcFAa.js → LinkEmailScreen-oNzcpVes.js} +1 -1
- package/dist/cjs/{LinkPasskeyScreen-CbuNym_z.js → LinkPasskeyScreen-CjdxFDoA.js} +1 -1
- package/dist/cjs/{LinkPhoneScreen-ZIe5uzPN.js → LinkPhoneScreen-B6OzKZnd.js} +1 -1
- package/dist/cjs/{LoginFailedScreen-JnBtBxi1.js → LoginFailedScreen-Cj3ATfwH.js} +1 -1
- package/dist/cjs/{ManualTransferScreen-B4TkbelL.js → ManualTransferScreen-M26HCQmU.js} +1 -1
- package/dist/cjs/{MfaAuthEnrollmentFlowScreen-CmLIp9Ll.js → MfaAuthEnrollmentFlowScreen-D1zKxqD8.js} +1 -1
- package/dist/cjs/{MfaAuthVerifyFlowScreen-B3ATEO7f.js → MfaAuthVerifyFlowScreen-D3eQj9zt.js} +1 -1
- package/dist/cjs/{MfaEnrollmentFlowScreen-COciRqP3.js → MfaEnrollmentFlowScreen-B2gvvMfX.js} +1 -1
- package/dist/cjs/{MfaVerifyFlowScreen-BuljrcdS.js → MfaVerifyFlowScreen-AyHxACnF.js} +1 -1
- package/dist/cjs/{ModalHeader-C45fdSY0.js → ModalHeader-BCPQgekO.js} +1 -1
- package/dist/cjs/{MoonpayStatusScreen-zWJq589Z.js → MoonpayStatusScreen-BQaJBdWu.js} +1 -1
- package/dist/cjs/{OAuthStatusScreen-ecJqpiHx.js → OAuthStatusScreen-JHIOff6A.js} +1 -1
- package/dist/cjs/{PasskeySelectSignupOrLogin-B-0EIFsW.js → PasskeySelectSignupOrLogin-B9J49RMF.js} +1 -1
- package/dist/cjs/{PasskeyStatusScreen-DzuiIFq2.js → PasskeyStatusScreen-ms-tH4cc.js} +1 -1
- package/dist/cjs/{PasswordRecoveryScreen-DQEy0Nqy.js → PasswordRecoveryScreen-CDHZosNL.js} +1 -1
- package/dist/cjs/{QrCode-BKnLFoFt.js → QrCode-CE12LRBB.js} +1 -1
- package/dist/cjs/{RecoveryOAuthStatusScreen-06xKXwi8.js → RecoveryOAuthStatusScreen-BUxNTtqd.js} +1 -1
- package/dist/cjs/{RecoveryPasswordCreateScreen-yfl_af11.js → RecoveryPasswordCreateScreen-BkFOrb6m.js} +1 -1
- package/dist/cjs/{RecoverySelectionScreen-BdHkBTuB.js → RecoverySelectionScreen-HBLOm2va.js} +1 -1
- package/dist/cjs/{Screen-ChnafgL7.js → Screen-BfKedqka.js} +1 -1
- package/dist/cjs/{ScreenLayout-CpclvUVQ.js → ScreenLayout-CMb-Fua0.js} +1 -1
- package/dist/cjs/{SetAutomaticRecoveryScreen-JwwwXok0.js → SetAutomaticRecoveryScreen-DPjXBMos.js} +1 -1
- package/dist/cjs/{SetWalletPasswordForm-ByGHfNqH.js → SetWalletPasswordForm-BslxSGLC.js} +1 -1
- package/dist/cjs/{SignRequestScreen-Bcr25XmN.js → SignRequestScreen-Cjn1PsqC.js} +1 -1
- package/dist/cjs/{StandardSignAndSendTransactionScreen-D-63yMIJ.js → StandardSignAndSendTransactionScreen-BIh1TSV6.js} +1 -1
- package/dist/cjs/{TelegramAuthScreen-DxZS64fR.js → TelegramAuthScreen-BZpPqkC8.js} +1 -1
- package/dist/cjs/{TransactionDetails-DBFsWnn1.js → TransactionDetails-BY2Ynu2J.js} +1 -1
- package/dist/cjs/{TransactionErrorView-nUOKizXV.js → TransactionErrorView-CueeggTz.js} +1 -1
- package/dist/cjs/{TransferFromWalletScreen-CYPZmSPV.js → TransferFromWalletScreen-BfWPkgYH.js} +1 -1
- package/dist/cjs/{TransferOrBridgeLoadingScreen-DiPwnn60.js → TransferOrBridgeLoadingScreen-CI2oh7CB.js} +1 -1
- package/dist/cjs/{UpdateEmailScreen-Bwxxqz1k.js → UpdateEmailScreen-BHgHi-KQ.js} +1 -1
- package/dist/cjs/{UpdatePhoneScreen-DU7RGenX.js → UpdatePhoneScreen-J83rbDYY.js} +1 -1
- package/dist/cjs/{UserLimitReachedScreen-fuIfecOX.js → UserLimitReachedScreen-CYNd-wAp.js} +1 -1
- package/dist/cjs/{WalletInfoCard-DmD26XB9.js → WalletInfoCard-CHdyZdLe.js} +1 -1
- package/dist/cjs/{WalletInterstitialScreen-Bn8l3kCq.js → WalletInterstitialScreen-CmqF-Oas.js} +1 -1
- package/dist/cjs/{WalletLink-D7Q4z7WW.js → WalletLink-Bs_1C81F.js} +1 -1
- package/dist/cjs/{WalletOverflowButton-fU7XMRV1.js → WalletOverflowButton-BqeWaSEy.js} +1 -1
- package/dist/cjs/abstract-smart-wallets.js +1 -1
- package/dist/cjs/{context-DK3qW12H.js → context-D-ZJYjUg.js} +1 -1
- package/dist/cjs/{ethers-DpiO5t5F.js → ethers-SCb3aakT.js} +1 -1
- package/dist/cjs/extended-chains.js +1 -1
- package/dist/cjs/{get-is-unified-wallet-CMHZpDfE.js → get-is-unified-wallet-UpdjHxOV.js} +1 -1
- package/dist/cjs/{index-DhmrMcn2.js → index-BcyDbfqY.js} +1 -1
- package/dist/cjs/{index-CgsQCH2r.js → index-C8lpxYDX.js} +3 -3
- package/dist/cjs/{index-VgEQ4kaA.js → index-gohEbwKU.js} +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/internal.js +1 -1
- package/dist/cjs/{shared-BTeM_5HJ.js → shared-e1wjsjhc.js} +1 -1
- package/dist/cjs/{shouldProceedtoEmbeddedWalletCreationFlow-eB6IctoD.js → shouldProceedtoEmbeddedWalletCreationFlow-DADJI9f0.js} +1 -1
- package/dist/cjs/{smart-wallets-DPXIV14D.js → smart-wallets-D-oPjsFS.js} +1 -1
- package/dist/cjs/smart-wallets.js +1 -1
- package/dist/cjs/solana.js +1 -1
- package/dist/cjs/{styles-BfCR4pAO.js → styles-DUvzIwf1.js} +1 -1
- package/dist/cjs/{to-ui-error-CQ9FNFg-.js → to-ui-error-BJRhg6yc.js} +1 -1
- package/dist/cjs/ui.js +1 -1
- package/dist/cjs/use-export-wallet-B5ujV5Nk.js +1 -0
- package/dist/cjs/{use-export-wallet-Ddpx0kgg.js → use-export-wallet-Dt1qheK5.js} +1 -1
- package/dist/cjs/{useActiveWallet-BgdIZtS6.js → useActiveWallet-Cn6zOXx5.js} +1 -1
- package/dist/cjs/{useGetTokenPrice-CouzWOSt.js → useGetTokenPrice-761HAiva.js} +1 -1
- package/dist/cjs/{useI18n-DDbtkfuB.js → useI18n-DFGBJl_S.js} +1 -1
- package/dist/cjs/{usePrivy-DUT7RIf5.js → usePrivy-cfS6o4tX.js} +1 -1
- package/dist/cjs/{useSolanaRpcClient-CefJOh8Z.js → useSolanaRpcClient-PnNtmWdo.js} +1 -1
- package/dist/cjs/{useWallets-XTVLGZyz.js → useWallets-CKAypPZB.js} +1 -1
- package/dist/cjs/{useWallets-DXWvKTyb.js → useWallets-DeTGSqF_.js} +1 -1
- package/dist/dts/{events-context-Fks6josE.d.ts → events-context-Bz1yk0zU.d.mts} +1 -1
- package/dist/dts/{events-context-Fks6josE.d.mts → events-context-Bz1yk0zU.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 +4 -4
- package/dist/dts/index.d.ts +4 -4
- 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/{types-CjDYScKX.d.mts → types-CIvz-X6P.d.mts} +21 -5
- package/dist/dts/{types-CjDYScKX.d.ts → types-CIvz-X6P.d.ts} +21 -5
- package/dist/dts/ui.d.mts +1 -1
- package/dist/dts/ui.d.ts +1 -1
- package/dist/esm/{AccountNotFoundScreen-DzQ8Ded6.mjs → AccountNotFoundScreen-C055cesr.mjs} +1 -1
- package/dist/esm/{Address-ClnXOtX_.mjs → Address-BjZb-TIL.mjs} +1 -1
- package/dist/esm/{AffirmativeConsentScreen-CGLpvQm4.mjs → AffirmativeConsentScreen-DXy2kEcy.mjs} +1 -1
- package/dist/esm/{AllowlistRejectionScreen-0T0W1npW.mjs → AllowlistRejectionScreen-BIzWPeoe.mjs} +1 -1
- package/dist/esm/{AuthenticateWithWalletScreen-aIIbB44q.mjs → AuthenticateWithWalletScreen-q3jQKiH6.mjs} +1 -1
- package/dist/esm/{AwaitingEvmToSolBridgingScreen-Bcx6oRJE.mjs → AwaitingEvmToSolBridgingScreen-B4R4PEVm.mjs} +1 -1
- package/dist/esm/{AwaitingExternalEthereumTransferScreen-BlmM5W1W.mjs → AwaitingExternalEthereumTransferScreen-Dwy69FD1.mjs} +1 -1
- package/dist/esm/{AwaitingPasswordlessCodeScreen-DxV44L8v.mjs → AwaitingPasswordlessCodeScreen-Ch_YXDTX.mjs} +1 -1
- package/dist/esm/{AwaitingSolToEvmBridgingScreen-C_VwI_Sw.mjs → AwaitingSolToEvmBridgingScreen-spElnpUE.mjs} +1 -1
- package/dist/esm/{BridgeNetworkSelectionView-F7koQMl8.mjs → BridgeNetworkSelectionView-CaDh-Zck.mjs} +1 -1
- package/dist/esm/{CaptchaScreen-BeoBh2yB.mjs → CaptchaScreen-BZy78GrD.mjs} +1 -1
- package/dist/esm/{CoinbaseOnrampStatusScreen-h359lw0u.mjs → CoinbaseOnrampStatusScreen-CTWZaE1o.mjs} +1 -1
- package/dist/esm/{ConnectEmailForm-D96RP15S.mjs → ConnectEmailForm-0GOHNayM.mjs} +1 -1
- package/dist/esm/{ConnectLedgerScreen-DlzVqbV7.mjs → ConnectLedgerScreen-CIPOaq8e.mjs} +1 -1
- package/dist/esm/{ConnectOnlyLandingScreen-wbu-70B6.mjs → ConnectOnlyLandingScreen-CbLV-cj4.mjs} +1 -1
- package/dist/esm/{ConnectOnlyStatusScreen-CbWmfcm8.mjs → ConnectOnlyStatusScreen-bmx1wwk1.mjs} +1 -1
- package/dist/esm/{ConnectOrCreateScreen-CSKKpNhC.mjs → ConnectOrCreateScreen-DXw5Y8gN.mjs} +1 -1
- package/dist/esm/{ConnectPhoneForm-Cfdo1Hxx.mjs → ConnectPhoneForm-_lOAQG_X.mjs} +1 -1
- package/dist/esm/{ConnectWalletView-D9FJQoQd.mjs → ConnectWalletView-CDqboUej.mjs} +1 -1
- package/dist/esm/{ConnectionStatusScreen-BCZOSVuo.mjs → ConnectionStatusScreen-D-9fLZfA.mjs} +1 -1
- package/dist/esm/{CrossAppAuthScreen-C9Y8UmMT.mjs → CrossAppAuthScreen-Co723kT3.mjs} +1 -1
- package/dist/esm/{CustomLandingScreenView-C9zIdEBy.mjs → CustomLandingScreenView-9mrgsDhT.mjs} +1 -1
- package/dist/esm/{DelegatedActionsConsentScreen-CRlv1sFS.mjs → DelegatedActionsConsentScreen-CyQTJHgT.mjs} +1 -1
- package/dist/esm/{DelegatedActionsRevokeScreen-CfOOZLtD.mjs → DelegatedActionsRevokeScreen-CFm4F3CM.mjs} +1 -1
- package/dist/esm/{EmbeddedWalletConnectingScreen-DuSxBQbx.mjs → EmbeddedWalletConnectingScreen-DmTtzGwq.mjs} +1 -1
- package/dist/esm/{EmbeddedWalletCreatedScreen--ZpH1G0k.mjs → EmbeddedWalletCreatedScreen-Cj1c5KyP.mjs} +1 -1
- package/dist/esm/{EmbeddedWalletKeyExportScreen-CSJq1Sik.mjs → EmbeddedWalletKeyExportScreen-CsWRTEgd.mjs} +1 -1
- package/dist/esm/{EmbeddedWalletOnAccountCreateScreen-DOSya90v.mjs → EmbeddedWalletOnAccountCreateScreen-DBAmWm90.mjs} +1 -1
- package/dist/esm/{EmbeddedWalletPasswordUpdateScreen-C_es2EpS.mjs → EmbeddedWalletPasswordUpdateScreen-B5w6wtgf.mjs} +1 -1
- package/dist/esm/{EmbeddedWalletPasswordUpdateSplashScreen-DhwnqiCK.mjs → EmbeddedWalletPasswordUpdateSplashScreen-BvsscceO.mjs} +1 -1
- package/dist/esm/{EnrollTotp-YxZ_oitd.mjs → EnrollTotp-uSQt9d2Q.mjs} +1 -1
- package/dist/esm/{ErrorScreen-DZ153hPv.mjs → ErrorScreen-DtGc3Chy.mjs} +1 -1
- package/dist/esm/{FarcasterConnectStatusScreen-CwQhh_aC.mjs → FarcasterConnectStatusScreen-DGeCyr6b.mjs} +1 -1
- package/dist/esm/{FarcasterSignerStatusScreen-D1SKEl4x.mjs → FarcasterSignerStatusScreen-DASa1xq2.mjs} +1 -1
- package/dist/esm/{FundSolWalletWithExternalSolanaWallet-CH85fmbL.mjs → FundSolWalletWithExternalSolanaWallet-0jNi_hvn.mjs} +1 -1
- package/dist/esm/{FundWalletMethodHeader-D0DhWPu0.mjs → FundWalletMethodHeader-Cfci4-83.mjs} +1 -1
- package/dist/esm/FundWithBankDepositScreen-D_uu3GEF.mjs +176 -0
- package/dist/esm/{FundingEditAmountScreen-C_YGQD1r.mjs → FundingEditAmountScreen-vQUS-a80.mjs} +1 -1
- package/dist/esm/FundingMethodSelectionScreen-G8gkM1Mk.mjs +1 -0
- package/dist/esm/{InAppBrowserLoginNotPossible-BiwxWFju.mjs → InAppBrowserLoginNotPossible-C8mlSbYe.mjs} +1 -1
- package/dist/esm/{InstallWalletScreen-DHPONpNA.mjs → InstallWalletScreen-D0kdHc5W.mjs} +1 -1
- package/dist/esm/{LandingScreen-DBZbonr_.mjs → LandingScreen-0MlIkV3C.mjs} +1 -1
- package/dist/esm/{LinkConflictScreen-D0TlabXV.mjs → LinkConflictScreen-DW31R5fr.mjs} +1 -1
- package/dist/esm/{LinkEmailScreen-D9zKrb4E.mjs → LinkEmailScreen-B10iXGH8.mjs} +1 -1
- package/dist/esm/{LinkPasskeyScreen-3_thbT6t.mjs → LinkPasskeyScreen-OxaghvUl.mjs} +1 -1
- package/dist/esm/{LinkPhoneScreen-BwBdaLqt.mjs → LinkPhoneScreen-Cdg3eg7w.mjs} +1 -1
- package/dist/esm/{LoginFailedScreen-Dxi-7tx8.mjs → LoginFailedScreen-BVOo2ycm.mjs} +1 -1
- package/dist/esm/{ManualTransferScreen-e347H8JC.mjs → ManualTransferScreen-_04Sq7zU.mjs} +1 -1
- package/dist/esm/{MfaAuthEnrollmentFlowScreen-BUF154dJ.mjs → MfaAuthEnrollmentFlowScreen-DApO6DPY.mjs} +1 -1
- package/dist/esm/{MfaAuthVerifyFlowScreen-BJ4ZNRWe.mjs → MfaAuthVerifyFlowScreen-mdmdgWdO.mjs} +1 -1
- package/dist/esm/{MfaEnrollmentFlowScreen-B5DfdOkM.mjs → MfaEnrollmentFlowScreen-DRZTnt-I.mjs} +1 -1
- package/dist/esm/{MfaVerifyFlowScreen-fjVmi3M8.mjs → MfaVerifyFlowScreen-mrf95cEs.mjs} +1 -1
- package/dist/esm/{ModalHeader-DBfMXKy4.mjs → ModalHeader-D8-mhjp4.mjs} +1 -1
- package/dist/esm/{MoonpayStatusScreen-BeZtoeAo.mjs → MoonpayStatusScreen-DDSK5dda.mjs} +1 -1
- package/dist/esm/{OAuthStatusScreen-BVLexXQC.mjs → OAuthStatusScreen-DSAUQ_YN.mjs} +1 -1
- package/dist/esm/{PasskeySelectSignupOrLogin-CejGrqSb.mjs → PasskeySelectSignupOrLogin-G19VpAdI.mjs} +1 -1
- package/dist/esm/{PasskeyStatusScreen-BrDLZfaA.mjs → PasskeyStatusScreen-TD2nYAnk.mjs} +1 -1
- package/dist/esm/{PasswordRecoveryScreen-Bks4ITku.mjs → PasswordRecoveryScreen-C0oVVZYe.mjs} +1 -1
- package/dist/esm/{QrCode-CKNL79V_.mjs → QrCode-C1tgJtOy.mjs} +1 -1
- package/dist/esm/{RecoveryOAuthStatusScreen-TsrFc2KU.mjs → RecoveryOAuthStatusScreen-Ca9VYOrA.mjs} +1 -1
- package/dist/esm/{RecoveryPasswordCreateScreen--aWRhenB.mjs → RecoveryPasswordCreateScreen-Q1zuy9fu.mjs} +1 -1
- package/dist/esm/{RecoverySelectionScreen-DJ33E1hd.mjs → RecoverySelectionScreen-scmqFA8Y.mjs} +1 -1
- package/dist/esm/{Screen-omroCwTV.mjs → Screen-Bp-TN9gb.mjs} +1 -1
- package/dist/esm/{ScreenLayout-z1I4hafk.mjs → ScreenLayout-DTmQLGPf.mjs} +1 -1
- package/dist/esm/{SetAutomaticRecoveryScreen-DelsQl1S.mjs → SetAutomaticRecoveryScreen-D-__1Pf7.mjs} +1 -1
- package/dist/esm/{SetWalletPasswordForm-DyVubYdV.mjs → SetWalletPasswordForm-0nuoz3XZ.mjs} +1 -1
- package/dist/esm/{SignRequestScreen-C6XvfvXV.mjs → SignRequestScreen-D6HSUOxx.mjs} +1 -1
- package/dist/esm/{StandardSignAndSendTransactionScreen-FQcyAQoq.mjs → StandardSignAndSendTransactionScreen-YlstFfkB.mjs} +1 -1
- package/dist/esm/{TelegramAuthScreen-LB2IdLqW.mjs → TelegramAuthScreen-DHCcieoC.mjs} +1 -1
- package/dist/esm/{TransactionDetails-CLHEcWFe.mjs → TransactionDetails-BurRo8R0.mjs} +1 -1
- package/dist/esm/{TransactionErrorView-D7uZmR_V.mjs → TransactionErrorView-CPFrt0L4.mjs} +1 -1
- package/dist/esm/{TransferFromWalletScreen-BLLYNl1T.mjs → TransferFromWalletScreen-BG5Mj5tz.mjs} +1 -1
- package/dist/esm/{TransferOrBridgeLoadingScreen-DgS9Jr0v.mjs → TransferOrBridgeLoadingScreen-DcCdHB-g.mjs} +1 -1
- package/dist/esm/{UpdateEmailScreen-DGAco54E.mjs → UpdateEmailScreen-ndRi1gY6.mjs} +1 -1
- package/dist/esm/{UpdatePhoneScreen-CLCixHYj.mjs → UpdatePhoneScreen-DoH__glA.mjs} +1 -1
- package/dist/esm/{UserLimitReachedScreen-ClahBH0m.mjs → UserLimitReachedScreen-BLzaOW7F.mjs} +1 -1
- package/dist/esm/{WalletInfoCard-BURM3rIP.mjs → WalletInfoCard-DFt8ndGE.mjs} +1 -1
- package/dist/esm/{WalletInterstitialScreen-CBzg1He2.mjs → WalletInterstitialScreen-BQ-ku50j.mjs} +1 -1
- package/dist/esm/{WalletLink-BXlPbPVx.mjs → WalletLink--05Hzo2b.mjs} +1 -1
- package/dist/esm/{WalletOverflowButton-CWeBF-Wv.mjs → WalletOverflowButton-BlijhJnI.mjs} +1 -1
- package/dist/esm/abstract-smart-wallets.mjs +1 -1
- package/dist/esm/{context-CCRnMB8L.mjs → context-WTldtXS8.mjs} +1 -1
- package/dist/esm/{ethers-B0Y3_-Pp.mjs → ethers-D1WT71Ay.mjs} +1 -1
- package/dist/esm/extended-chains.mjs +1 -1
- package/dist/esm/{get-is-unified-wallet-j2fzd2YE.mjs → get-is-unified-wallet-Boa8DYrQ.mjs} +1 -1
- package/dist/esm/{index-BgGYO9kN.mjs → index-BBRkihRn.mjs} +3 -3
- package/dist/esm/{index-CIjObncO.mjs → index-BH9-XZRZ.mjs} +1 -1
- package/dist/esm/{index-Dk-s5iXx.mjs → index-C9k7EfLZ.mjs} +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/internal.mjs +1 -1
- package/dist/esm/{shared-B_TYFBiH.mjs → shared-CwuyxHmv.mjs} +1 -1
- package/dist/esm/{shouldProceedtoEmbeddedWalletCreationFlow-DjxNSuIS.mjs → shouldProceedtoEmbeddedWalletCreationFlow-BMF_3TVv.mjs} +1 -1
- package/dist/esm/{smart-wallets-DL1EjW8i.mjs → smart-wallets-DOAgnxKI.mjs} +1 -1
- package/dist/esm/smart-wallets.mjs +1 -1
- package/dist/esm/solana.mjs +1 -1
- package/dist/esm/{styles-BeQ5nIO3.mjs → styles-BmZHuqSX.mjs} +1 -1
- package/dist/esm/{to-ui-error-DR840l8Y.mjs → to-ui-error-REESv0kM.mjs} +1 -1
- package/dist/esm/ui.mjs +1 -1
- package/dist/esm/use-export-wallet-CV4p7L0b.mjs +1 -0
- package/dist/esm/{use-export-wallet-AwUSjJIc.mjs → use-export-wallet-DQde4t0V.mjs} +1 -1
- package/dist/esm/{useActiveWallet-Dqi9nNxj.mjs → useActiveWallet-3RHPIBxJ.mjs} +1 -1
- package/dist/esm/{useGetTokenPrice-Djb6UHOW.mjs → useGetTokenPrice-BPBpM07F.mjs} +1 -1
- package/dist/esm/{useI18n-BK0a87xw.mjs → useI18n-BuIe8nUA.mjs} +1 -1
- package/dist/esm/{usePrivy-D9f62ILp.mjs → usePrivy-6nkpbErN.mjs} +1 -1
- package/dist/esm/{useSolanaRpcClient-DizarIU5.mjs → useSolanaRpcClient-BUWOblv_.mjs} +1 -1
- package/dist/esm/{useWallets-BKPOCKnv.mjs → useWallets-CR0z5IIt.mjs} +1 -1
- package/dist/esm/{useWallets-DQOA0__U.mjs → useWallets-C_dCo2_Q.mjs} +1 -1
- package/package.json +6 -6
- package/dist/cjs/FundWithBankDepositScreen-C1BRYtc8.js +0 -175
- package/dist/cjs/FundingMethodSelectionScreen-CL9xLuBR.js +0 -1
- package/dist/cjs/use-export-wallet-BEW54Ynq.js +0 -1
- package/dist/esm/FundWithBankDepositScreen-BJk-wxSq.mjs +0 -175
- package/dist/esm/FundingMethodSelectionScreen-gGZKP4LD.mjs +0 -1
- package/dist/esm/use-export-wallet-Voe8hSb9.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
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-CMHZpDfE.js"),s=require("eventemitter3"),o=require("./useActiveWallet-BgdIZtS6.js"),l=require("./useWallets-XTVLGZyz.js"),c=require("./internal-context-BJv4f_bO.js"),d=require("./use-export-wallet-BEW54Ynq.js"),u=require("@coinbase/wallet-sdk"),h=require("@privy-io/ethereum"),p=require("./context-DK3qW12H.js"),y=require("mipd"),w=require("react-device-detect"),m=require("viem/utils"),g=require("@privy-io/popup"),v=require("./paths-DizMb-lU.js"),f=require("./usePrivy-DUT7RIf5.js"),E=require("@scure/base"),C=require("styled-components"),A=require("./events-context-Di6--rDg.js"),P=require("zustand"),T=require("@headlessui/react"),k=require("@walletconnect/ethereum-provider"),_=require("@privy-io/urls"),S=require("viem"),b=require("./PrivyPluginContext-DsgaS6n9.js"),I=require("./getEmbeddedConnectedWallet-pJd-l936.js"),W=require("./getPublicClient-BsmZyCGX.js"),U=require("ofetch"),x=require("js-cookie"),R=require("./frame-Oz7volks.js"),O=require("@privy-io/routes"),N=require("x402/client"),M=require("@privy-io/api-base"),F=require("@privy-io/are-addresses-equal"),D=require("viem/accounts"),L=require("./use-sign-with-user-signer-Cu_6Bx7m.js");function j(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function q(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)}var z=/*#__PURE__*/j(t),K=/*#__PURE__*/j(r),H=/*#__PURE__*/q(i),B=/*#__PURE__*/j(s),V=/*#__PURE__*/j(x);class Y{static parse(e){try{return new Y(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return H.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=H.decodeJwt(e)}}class G extends Y{static parse(e){try{return new G(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}const $="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PScwIDAgMTAyNCAxMDI0JyBmaWxsPSdub25lJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHN0eWxlPSdoZWlnaHQ6MjhweDt3aWR0aDoyOHB4Jz48cmVjdCB3aWR0aD0nMTAyNCcgaGVpZ2h0PScxMDI0JyBmaWxsPScjMDA1MkZGJyByeD0nMTAwJyByeT0nMTAwJz48L3JlY3Q+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBjbGlwLXJ1bGU9J2V2ZW5vZGQnIGQ9J00xNTIgNTEyQzE1MiA3MTAuODIzIDMxMy4xNzcgODcyIDUxMiA4NzJDNzEwLjgyMyA4NzIgODcyIDcxMC44MjMgODcyIDUxMkM4NzIgMzEzLjE3NyA3MTAuODIzIDE1MiA1MTIgMTUyQzMxMy4xNzcgMTUyIDE1MiAzMTMuMTc3IDE1MiA1MTJaTTQyMCAzOTZDNDA2Ljc0NSAzOTYgMzk2IDQwNi43NDUgMzk2IDQyMFY2MDRDMzk2IDYxNy4yNTUgNDA2Ljc0NSA2MjggNDIwIDYyOEg2MDRDNjE3LjI1NSA2MjggNjI4IDYxNy4yNTUgNjI4IDYwNFY0MjBDNjI4IDQwNi43NDUgNjE3LjI1NSAzOTYgNjA0IDM5Nkg0MjBaJyBmaWxsPSd3aGl0ZSc+PC9wYXRoPjwvc3ZnPg==",J="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAALZJREFUaEPtmjEOhDAMBNc/O14GvOzys3CAKK6eAlmaVGl2Zc+kTOU685vkc9/bnD2prZK5/TZY24z9P+g4F5hNh7/GdoG37WlAA5CATwgCxHENYISwQAMQII5rACOEBRqAAHFcAxghLNAABIjjGsAIYYEGIEAc1wBGCAs0AAHiuAYwQligAQgQxzWAEcICDUCAOK4BjBAWaAACxHENYISwQAMQII6fBjr+VHkW3+u+tfyxMpJaDgYzYxb/ALZVAAAAAElFTkSuQmCC";let Q,X;class Z 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:J,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)))},Q?(this.proxyProvider.setWalletProvider(Q.getProvider()),this.setBaseAccountSdk(Q)):this.importPromise=import("@base-org/account").then((({createBaseAccountSDK:e})=>{Q=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider(Q.getProvider()),this.setBaseAccountSdk(Q)})).catch(console.error)}}let ee=[1,11155111,137,10,8453,84532,42161,7777777,43114,56];class te 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:$,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",X=u.createCoinbaseWalletSDK({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(X.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"),!X){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter((e=>!ee.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(", ")}`),X=u.createCoinbaseWalletSDK(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(X.getProvider())}}const re=({...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 ne 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:re,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 ie(){let e=Dr();return e?e.getAccessToken():Promise.resolve(d.s.get(p.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||d.s.get(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const ae=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];function se(e){return e?{"privy-ui":"t"}:void 0}class oe{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(v.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(v.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=se(r);try{return await this.api.post(v.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 le extends oe{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(v.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}}}class ce{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 de{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(v.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(v.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(v.farcasterInitPath,{token:this.captchaToken});w.isMobile&&!w.isIOS&&e.connect_uri&&f.openHref(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(v.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 ce(this._startChannelOnce.bind(this)),this.pollForReady=new ce(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function ue(){return"undefined"!=typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function he(){if(!ue())return;let e=window.chrome;return e?.runtime?.id}function pe(){if(!ue())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function ye(e){return new Promise(((t,r)=>{pe()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},(async e=>{try{let r=function(){if(!ue())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=he();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 we(e){return crypto.getRandomValues(new Uint8Array(e))}function me(){return i.base64url.encode(we(36))}function ge(){return me()}async function ve(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 fe{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.s.get(p.CODE_VERIFIER_KEY);if(!e)throw new c.PrivyClientError("Authentication error.");return e}();try{let t=await this.api.post(v.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.s.del(p.CODE_VERIFIER_KEY),d.s.del(p.HEADLESS_OAUTH_KEY),d.s.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.s.get(p.CODE_VERIFIER_KEY);if(!e)throw new c.PrivyClientError("Authentication error.");try{let t=await this.api.post(v.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return d.s.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=me();d.s.put(p.CODE_VERIFIER_KEY,e);let t=ge();d.s.put(p.STATE_CODE_KEY,t);let r=await ve(e);this.meta.withPrivyUi||d.s.put(p.HEADLESS_OAUTH_KEY,!0),this.meta.disableSignup?d.s.put(p.OAUTH_DISABLE_SIGNUP_KEY,!0):d.s.del(p.OAUTH_DISABLE_SIGNUP_KEY);let n=se(this.meta.withPrivyUi),i=window.location.href,a=function(){let e=he();if(e)return`https://${e}.chromiumapp.org`}();a&&(i=a);try{return await this.api.post(v.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 Ee(){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.s.get(p.HEADLESS_OAUTH_KEY),popupFlow:null!==window.opener&&i,disableSignup:!!d.s.get(p.OAUTH_DISABLE_SIGNUP_KEY)}}function Ce(){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.s.del(p.STATE_CODE_KEY),window.history.replaceState({},"",e)}class Ae{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(v.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(v.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(v.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=se(e);return await this.api.post(v.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=se(e);return await this.api.post(v.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(v.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 ce(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new ce(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new ce(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t,hints:r}}}const Pe=({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 Te{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=Pe({address:e,chainId:t,nonce:this.nonce}),this.preparedMessage}constructor(e,t,r,n=!1,i){this._meta={disableSignup:!1},this.getNonceOnce=new ce(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 ke{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:E.base64.decode(this.preparedMessage)});e=E.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=E.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=f.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 ce(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 _e{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(v.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(v.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=se(r);try{return await this.api.post(v.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 Se extends _e{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(v.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 be=/*#__PURE__*/t.createContext({enabled:!1,siteKey:"",provider:void 0,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.noop,reset:c.notImplemented,execute:c.notImplemented});class Ie extends c.PrivyError{constructor(e,t,r){super(e||"Captcha failed"),this.type="Captcha",t instanceof Error&&(this.cause=t),this.privyErrorCode=r}}const We=({children:r,appId:n,captchaSiteKey:i,enabledCaptchaProvider:a})=>{let s=t.useRef(null),l=t.useRef(null),[d,u]=t.useState(),[h,p]=t.useState(),[y,w]=t.useState(!1),m=t.useMemo((()=>a?y||d||h?!y||d||h?d&&!h?{status:"success",token:d}:h?{status:"error",error:h}:{status:"ready"}:{status:"loading"}:{status:"ready"}:{status:"disabled"}),[a,d,h,y]),g=t.useMemo((()=>a?"turnstile"===a?{remove:()=>{s.current?.remove(),w(!1),p(void 0),u(void 0)},reset:()=>{s.current?.reset(),w(!1),p(void 0),u(void 0)},execute:()=>{w(!0),s.current?.execute()},waitForResult:async()=>{try{return await o.pollForResult((()=>s.current?.getResponse()),{interval:200,timeout:2e4})}catch(e){throw new Ie("Captcha failed",null,c.PrivyErrorCode.CAPTCHA_TIMEOUT)}}}:{remove:()=>{l.current?.removeCaptcha(),w(!1),p(void 0),u(void 0)},reset:()=>{l.current?.resetCaptcha(),w(!1),p(void 0),u(void 0)},execute:()=>{w(!0),l.current?.execute()},waitForResult:async()=>{try{return await o.pollForResult((()=>{let e=l.current?.getResponse();if(e)return e}),{interval:200,timeout:2e4})}catch(e){throw new Ie("Captcha failed",null,c.PrivyErrorCode.CAPTCHA_TIMEOUT)}}}:null),[a]),v=t.useMemo((()=>{if(!a||!g)return{...m,enabled:!1,siteKey:"",appId:n,setToken:c.notImplemented,setError:c.notImplemented,setExecuting:c.notImplemented,waitForResult:()=>Promise.resolve(void 0),remove:c.noop,reset:c.notImplemented,execute:c.notImplemented,provider:void 0,ref:{current:null}};let e={...m,enabled:!0,appId:n,setToken:u,setError:p,setExecuting:w};return"turnstile"===a?{...e,provider:"turnstile",ref:s,siteKey:i.split("t:")[1]??"",...g}:{...e,provider:"hcaptcha",ref:l,siteKey:i.split("h:")[1]??"",...g}}),[m,a,g,n,i]);/*#__PURE__*/return e.jsx(be.Provider,{value:v,children:r})},Ue=()=>t.useContext(be);async function xe(e){if(e.enabled){if("error"===e.status)throw new Ie(e.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);return"success"===e.status?e.token:(e.execute(),await e.waitForResult())}}class Re{async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(v.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(v.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 Oe(e){return Object.fromEntries(decodeURIComponent(e).split("&").map((e=>e.split("=").map(decodeURIComponent))))}function Ne(){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)}let Me=/*#__PURE__*/t.lazy((()=>Promise.resolve().then((function(){return require("./TurnstileWrapper-qLN0G5m7.js")})))),Fe=/*#__PURE__*/t.lazy((()=>Promise.resolve().then((function(){return require("./HCaptchaWrapper-CxqJE5RH.js")}))));const De=r=>{let n=Ue();return t.useEffect((()=>n.remove),[n.remove]),n.enabled&&n.provider?/*#__PURE__*/e.jsx(t.Suspense,{fallback:null,children:/*#__PURE__*/e.jsxs("div",{className:"hidden h-0 w-0",children:["turnstile"===n.provider&&/*#__PURE__*/e.jsx(Me,{...r,captchaContext:n}),"hcaptcha"===n.provider&&/*#__PURE__*/e.jsx(Fe,{...r,captchaContext:n})]})}):null};var Le=/*#__PURE__*/Object.freeze({__proto__:null,AccountNotFoundScreen:()=>Promise.resolve().then((function(){return require("./AccountNotFoundScreen-B2BwM9IL.js")})),AffirmativeConsentScreen:()=>Promise.resolve().then((function(){return require("./AffirmativeConsentScreen-B7nTfKFs.js")})),AllowlistRejectionScreen:()=>Promise.resolve().then((function(){return require("./AllowlistRejectionScreen-C0ubkz2f.js")})),AuthenticateWithWalletScreen:()=>Promise.resolve().then((function(){return require("./AuthenticateWithWalletScreen-DHRXcjT5.js")})),AwaitingEvmToSolBridgingScreen:()=>Promise.resolve().then((function(){return require("./AwaitingEvmToSolBridgingScreen-D6MB0SW8.js")})),AwaitingExternalEthereumTransferScreen:()=>Promise.resolve().then((function(){return require("./AwaitingExternalEthereumTransferScreen-BcnofXQv.js")})),AwaitingPasswordlessCodeScreen:()=>Promise.resolve().then((function(){return require("./AwaitingPasswordlessCodeScreen-CMMIM_Pj.js")})),AwaitingSolToEvmBridgingScreen:()=>Promise.resolve().then((function(){return require("./AwaitingSolToEvmBridgingScreen-C2Op_A4L.js")})),CaptchaScreen:()=>Promise.resolve().then((function(){return require("./CaptchaScreen-TVUbEsJK.js")})),CoinbaseOnrampStatusScreen:()=>Promise.resolve().then((function(){return require("./CoinbaseOnrampStatusScreen-_mCdKOIM.js")})),ConnectLedgerScreen:()=>Promise.resolve().then((function(){return require("./ConnectLedgerScreen-DjDvgzxV.js")})),ConnectOnlyLandingScreen:()=>Promise.resolve().then((function(){return require("./ConnectOnlyLandingScreen-CbUMwYrO.js")})),ConnectOnlyStatusScreen:()=>Promise.resolve().then((function(){return require("./ConnectOnlyStatusScreen-DyoV_8V9.js")})),ConnectOrCreateScreen:()=>Promise.resolve().then((function(){return require("./ConnectOrCreateScreen-DpR4OmSO.js")})),ConnectionStatusScreen:()=>Promise.resolve().then((function(){return require("./ConnectionStatusScreen-B8TxWdVC.js")})),CrossAppAuthScreen:()=>Promise.resolve().then((function(){return require("./CrossAppAuthScreen-By4i5UqT.js")})),DelegatedActionsConsentScreen:()=>Promise.resolve().then((function(){return require("./DelegatedActionsConsentScreen-CjUYU339.js")})),DelegatedActionsRevokeScreen:()=>Promise.resolve().then((function(){return require("./DelegatedActionsRevokeScreen-BGATOJGL.js")})),EmbeddedWalletConnectingScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletConnectingScreen-GZ8nOvWq.js")})),EmbeddedWalletCreatedScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletCreatedScreen-Be8AYwZh.js")})),EmbeddedWalletKeyExportScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletKeyExportScreen-DXa54jFw.js")})),EmbeddedWalletOnAccountCreateScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletOnAccountCreateScreen-C8-LkEhs.js")})),EmbeddedWalletPasswordCreateScreen:()=>Promise.resolve().then((function(){return require("./RecoveryPasswordCreateScreen-yfl_af11.js")})),EmbeddedWalletPasswordUpdateScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletPasswordUpdateScreen-B7N8Noqf.js")})),EmbeddedWalletPasswordUpdateSplashScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletPasswordUpdateSplashScreen-kiTrvJ2h.js")})),ErrorScreen:()=>Promise.resolve().then((function(){return require("./ErrorScreen-BsvL8i4R.js")})),FarcasterConnectStatusScreen:()=>Promise.resolve().then((function(){return require("./FarcasterConnectStatusScreen-DMnzjTAV.js")})),FarcasterSignerStatusScreen:()=>Promise.resolve().then((function(){return require("./FarcasterSignerStatusScreen-Xb4KBH8f.js")})),FundSolWalletWithExternalSolanaWallet:()=>Promise.resolve().then((function(){return require("./FundSolWalletWithExternalSolanaWallet-BT4nT21N.js")})),FundWithBankDepositScreen:()=>Promise.resolve().then((function(){return require("./FundWithBankDepositScreen-C1BRYtc8.js")})),FundingAmountEditScreen:()=>Promise.resolve().then((function(){return require("./FundingEditAmountScreen-CBp--May.js")})),FundingMethodSelectionScreen:()=>Promise.resolve().then((function(){return require("./FundingMethodSelectionScreen-CL9xLuBR.js")})),InAppBrowserLoginNotPossible:()=>Promise.resolve().then((function(){return require("./InAppBrowserLoginNotPossible-fTc3VwS8.js")})),InstallWalletScreen:()=>Promise.resolve().then((function(){return require("./InstallWalletScreen-Bm_jzHEL.js")})),LandingScreen:()=>Promise.resolve().then((function(){return require("./LandingScreen-D6094d73.js")})),LinkConflictScreen:()=>Promise.resolve().then((function(){return require("./LinkConflictScreen-Bic4pZUv.js")})),LinkEmailScreen:()=>Promise.resolve().then((function(){return require("./LinkEmailScreen-BuuqcFAa.js")})),LinkPasskeyScreen:()=>Promise.resolve().then((function(){return require("./LinkPasskeyScreen-CbuNym_z.js")})),LinkPhoneScreen:()=>Promise.resolve().then((function(){return require("./LinkPhoneScreen-ZIe5uzPN.js")})),LoginFailedScreen:()=>Promise.resolve().then((function(){return require("./LoginFailedScreen-JnBtBxi1.js")})),ManualTransferScreen:()=>Promise.resolve().then((function(){return require("./ManualTransferScreen-B4TkbelL.js")})),MfaAuthEnrollmentFlowScreen:()=>Promise.resolve().then((function(){return require("./MfaAuthEnrollmentFlowScreen-CmLIp9Ll.js")})),MfaAuthVerifyFlowScreen:()=>Promise.resolve().then((function(){return require("./MfaAuthVerifyFlowScreen-B3ATEO7f.js")})),MfaEnrollmentFlowScreen:()=>Promise.resolve().then((function(){return require("./MfaEnrollmentFlowScreen-COciRqP3.js")})),MoonpayStatusScreen:()=>Promise.resolve().then((function(){return require("./MoonpayStatusScreen-zWJq589Z.js")})),OAuthStatusScreen:()=>Promise.resolve().then((function(){return require("./OAuthStatusScreen-ecJqpiHx.js")})),PasskeySelectSignupOrLogin:()=>Promise.resolve().then((function(){return require("./PasskeySelectSignupOrLogin-B-0EIFsW.js")})),PasskeyStatusScreen:()=>Promise.resolve().then((function(){return require("./PasskeyStatusScreen-DzuiIFq2.js")})),PasswordRecoveryScreen:()=>Promise.resolve().then((function(){return require("./PasswordRecoveryScreen-DQEy0Nqy.js")})),RecoveryOAuthScreen:()=>Promise.resolve().then((function(){return require("./RecoveryOAuthStatusScreen-06xKXwi8.js")})),RecoverySelectionScreen:()=>Promise.resolve().then((function(){return require("./RecoverySelectionScreen-BdHkBTuB.js")})),SendTransactionScreen:()=>Promise.resolve().then((function(){return require("./index-DhmrMcn2.js")})),SetAutomaticRecoveryScreen:()=>Promise.resolve().then((function(){return require("./SetAutomaticRecoveryScreen-JwwwXok0.js")})),SignRequestScreen:()=>Promise.resolve().then((function(){return require("./SignRequestScreen-Bcr25XmN.js")})),StandardSignAndSendTransactionScreen:()=>Promise.resolve().then((function(){return require("./StandardSignAndSendTransactionScreen-D-63yMIJ.js")})),TelegramAuthScreen:()=>Promise.resolve().then((function(){return require("./TelegramAuthScreen-DxZS64fR.js")})),TransferFromWalletScreen:()=>Promise.resolve().then((function(){return require("./TransferFromWalletScreen-CYPZmSPV.js")})),UpdateEmailScreen:()=>Promise.resolve().then((function(){return require("./UpdateEmailScreen-Bwxxqz1k.js")})),UpdatePhoneScreen:()=>Promise.resolve().then((function(){return require("./UpdatePhoneScreen-DU7RGenX.js")})),UserLimitReachedScreen:()=>Promise.resolve().then((function(){return require("./UserLimitReachedScreen-fuIfecOX.js")})),WalletInterstitialScreen:()=>Promise.resolve().then((function(){return require("./WalletInterstitialScreen-Bn8l3kCq.js")}))});function je(e){A.usePrivyEventSubscription("configureMfa",e)}const qe=P.create((()=>({inProgressMfaFlow:void 0})));const ze=C.createGlobalStyle`
|
|
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-UpdjHxOV.js"),s=require("eventemitter3"),o=require("./useActiveWallet-Cn6zOXx5.js"),l=require("./useWallets-CKAypPZB.js"),c=require("./internal-context-BJv4f_bO.js"),d=require("./use-export-wallet-B5ujV5Nk.js"),u=require("@coinbase/wallet-sdk"),h=require("@privy-io/ethereum"),p=require("./context-D-ZJYjUg.js"),y=require("mipd"),w=require("react-device-detect"),m=require("viem/utils"),g=require("@privy-io/popup"),v=require("./paths-DizMb-lU.js"),f=require("./usePrivy-cfS6o4tX.js"),E=require("@scure/base"),C=require("styled-components"),A=require("./events-context-Di6--rDg.js"),P=require("zustand"),T=require("@headlessui/react"),k=require("@walletconnect/ethereum-provider"),_=require("@privy-io/urls"),S=require("viem"),b=require("./PrivyPluginContext-DsgaS6n9.js"),I=require("./getEmbeddedConnectedWallet-pJd-l936.js"),W=require("./getPublicClient-BsmZyCGX.js"),U=require("ofetch"),x=require("js-cookie"),R=require("./frame-Oz7volks.js"),O=require("@privy-io/routes"),N=require("x402/client"),M=require("@privy-io/api-base"),F=require("@privy-io/are-addresses-equal"),D=require("viem/accounts"),L=require("./use-sign-with-user-signer-Cu_6Bx7m.js");function j(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function q(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)}var z=/*#__PURE__*/j(t),K=/*#__PURE__*/j(r),H=/*#__PURE__*/q(i),B=/*#__PURE__*/j(s),V=/*#__PURE__*/j(x);class Y{static parse(e){try{return new Y(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return H.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=H.decodeJwt(e)}}class G extends Y{static parse(e){try{return new G(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}const $="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PScwIDAgMTAyNCAxMDI0JyBmaWxsPSdub25lJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHN0eWxlPSdoZWlnaHQ6MjhweDt3aWR0aDoyOHB4Jz48cmVjdCB3aWR0aD0nMTAyNCcgaGVpZ2h0PScxMDI0JyBmaWxsPScjMDA1MkZGJyByeD0nMTAwJyByeT0nMTAwJz48L3JlY3Q+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBjbGlwLXJ1bGU9J2V2ZW5vZGQnIGQ9J00xNTIgNTEyQzE1MiA3MTAuODIzIDMxMy4xNzcgODcyIDUxMiA4NzJDNzEwLjgyMyA4NzIgODcyIDcxMC44MjMgODcyIDUxMkM4NzIgMzEzLjE3NyA3MTAuODIzIDE1MiA1MTIgMTUyQzMxMy4xNzcgMTUyIDE1MiAzMTMuMTc3IDE1MiA1MTJaTTQyMCAzOTZDNDA2Ljc0NSAzOTYgMzk2IDQwNi43NDUgMzk2IDQyMFY2MDRDMzk2IDYxNy4yNTUgNDA2Ljc0NSA2MjggNDIwIDYyOEg2MDRDNjE3LjI1NSA2MjggNjI4IDYxNy4yNTUgNjI4IDYwNFY0MjBDNjI4IDQwNi43NDUgNjE3LjI1NSAzOTYgNjA0IDM5Nkg0MjBaJyBmaWxsPSd3aGl0ZSc+PC9wYXRoPjwvc3ZnPg==",J="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAALZJREFUaEPtmjEOhDAMBNc/O14GvOzys3CAKK6eAlmaVGl2Zc+kTOU685vkc9/bnD2prZK5/TZY24z9P+g4F5hNh7/GdoG37WlAA5CATwgCxHENYISwQAMQII5rACOEBRqAAHFcAxghLNAABIjjGsAIYYEGIEAc1wBGCAs0AAHiuAYwQligAQgQxzWAEcICDUCAOK4BjBAWaAACxHENYISwQAMQII6fBjr+VHkW3+u+tfyxMpJaDgYzYxb/ALZVAAAAAElFTkSuQmCC";let Q,X;class Z 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:J,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)))},Q?(this.proxyProvider.setWalletProvider(Q.getProvider()),this.setBaseAccountSdk(Q)):this.importPromise=import("@base-org/account").then((({createBaseAccountSDK:e})=>{Q=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider(Q.getProvider()),this.setBaseAccountSdk(Q)})).catch(console.error)}}let ee=[1,11155111,137,10,8453,84532,42161,7777777,43114,56];class te 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:$,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",X=u.createCoinbaseWalletSDK({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(X.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"),!X){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter((e=>!ee.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(", ")}`),X=u.createCoinbaseWalletSDK(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(X.getProvider())}}const re=({...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 ne 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:re,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 ie(){let e=Dr();return e?e.getAccessToken():Promise.resolve(d.s.get(p.PRIVY_ACCESS_TOKEN_STORAGE_KEY)||d.s.get(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)}const ae=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];function se(e){return e?{"privy-ui":"t"}:void 0}class oe{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(v.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(v.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=se(r);try{return await this.api.post(v.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 le extends oe{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(v.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}}}class ce{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 de{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(v.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(v.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(v.farcasterInitPath,{token:this.captchaToken});w.isMobile&&!w.isIOS&&e.connect_uri&&f.openHref(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(v.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 ce(this._startChannelOnce.bind(this)),this.pollForReady=new ce(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function ue(){return"undefined"!=typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function he(){if(!ue())return;let e=window.chrome;return e?.runtime?.id}function pe(){if(!ue())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function ye(e){return new Promise(((t,r)=>{pe()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},(async e=>{try{let r=function(){if(!ue())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=he();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 we(e){return crypto.getRandomValues(new Uint8Array(e))}function me(){return i.base64url.encode(we(36))}function ge(){return me()}async function ve(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 fe{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.s.get(p.CODE_VERIFIER_KEY);if(!e)throw new c.PrivyClientError("Authentication error.");return e}();try{let t=await this.api.post(v.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.s.del(p.CODE_VERIFIER_KEY),d.s.del(p.HEADLESS_OAUTH_KEY),d.s.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.s.get(p.CODE_VERIFIER_KEY);if(!e)throw new c.PrivyClientError("Authentication error.");try{let t=await this.api.post(v.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return d.s.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=me();d.s.put(p.CODE_VERIFIER_KEY,e);let t=ge();d.s.put(p.STATE_CODE_KEY,t);let r=await ve(e);this.meta.withPrivyUi||d.s.put(p.HEADLESS_OAUTH_KEY,!0),this.meta.disableSignup?d.s.put(p.OAUTH_DISABLE_SIGNUP_KEY,!0):d.s.del(p.OAUTH_DISABLE_SIGNUP_KEY);let n=se(this.meta.withPrivyUi),i=window.location.href,a=function(){let e=he();if(e)return`https://${e}.chromiumapp.org`}();a&&(i=a);try{return await this.api.post(v.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 Ee(){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.s.get(p.HEADLESS_OAUTH_KEY),popupFlow:null!==window.opener&&i,disableSignup:!!d.s.get(p.OAUTH_DISABLE_SIGNUP_KEY)}}function Ce(){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.s.del(p.STATE_CODE_KEY),window.history.replaceState({},"",e)}class Ae{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(v.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(v.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(v.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=se(e);return await this.api.post(v.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=se(e);return await this.api.post(v.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(v.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 ce(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new ce(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new ce(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t,hints:r}}}const Pe=({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 Te{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=Pe({address:e,chainId:t,nonce:this.nonce}),this.preparedMessage}constructor(e,t,r,n=!1,i){this._meta={disableSignup:!1},this.getNonceOnce=new ce(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 ke{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:E.base64.decode(this.preparedMessage)});e=E.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=E.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=f.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 ce(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 _e{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(v.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(v.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=se(r);try{return await this.api.post(v.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 Se extends _e{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(v.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 be=/*#__PURE__*/t.createContext({enabled:!1,siteKey:"",provider:void 0,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.noop,reset:c.notImplemented,execute:c.notImplemented});class Ie extends c.PrivyError{constructor(e,t,r){super(e||"Captcha failed"),this.type="Captcha",t instanceof Error&&(this.cause=t),this.privyErrorCode=r}}const We=({children:r,appId:n,captchaSiteKey:i,enabledCaptchaProvider:a})=>{let s=t.useRef(null),l=t.useRef(null),[d,u]=t.useState(),[h,p]=t.useState(),[y,w]=t.useState(!1),m=t.useMemo((()=>a?y||d||h?!y||d||h?d&&!h?{status:"success",token:d}:h?{status:"error",error:h}:{status:"ready"}:{status:"loading"}:{status:"ready"}:{status:"disabled"}),[a,d,h,y]),g=t.useMemo((()=>a?"turnstile"===a?{remove:()=>{s.current?.remove(),w(!1),p(void 0),u(void 0)},reset:()=>{s.current?.reset(),w(!1),p(void 0),u(void 0)},execute:()=>{w(!0),s.current?.execute()},waitForResult:async()=>{try{return await o.pollForResult((()=>s.current?.getResponse()),{interval:200,timeout:2e4})}catch(e){throw new Ie("Captcha failed",null,c.PrivyErrorCode.CAPTCHA_TIMEOUT)}}}:{remove:()=>{l.current?.removeCaptcha(),w(!1),p(void 0),u(void 0)},reset:()=>{l.current?.resetCaptcha(),w(!1),p(void 0),u(void 0)},execute:()=>{w(!0),l.current?.execute()},waitForResult:async()=>{try{return await o.pollForResult((()=>{let e=l.current?.getResponse();if(e)return e}),{interval:200,timeout:2e4})}catch(e){throw new Ie("Captcha failed",null,c.PrivyErrorCode.CAPTCHA_TIMEOUT)}}}:null),[a]),v=t.useMemo((()=>{if(!a||!g)return{...m,enabled:!1,siteKey:"",appId:n,setToken:c.notImplemented,setError:c.notImplemented,setExecuting:c.notImplemented,waitForResult:()=>Promise.resolve(void 0),remove:c.noop,reset:c.notImplemented,execute:c.notImplemented,provider:void 0,ref:{current:null}};let e={...m,enabled:!0,appId:n,setToken:u,setError:p,setExecuting:w};return"turnstile"===a?{...e,provider:"turnstile",ref:s,siteKey:i.split("t:")[1]??"",...g}:{...e,provider:"hcaptcha",ref:l,siteKey:i.split("h:")[1]??"",...g}}),[m,a,g,n,i]);/*#__PURE__*/return e.jsx(be.Provider,{value:v,children:r})},Ue=()=>t.useContext(be);async function xe(e){if(e.enabled){if("error"===e.status)throw new Ie(e.error,null,c.PrivyErrorCode.CAPTCHA_FAILURE);return"success"===e.status?e.token:(e.execute(),await e.waitForResult())}}class Re{async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(v.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(v.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 Oe(e){return Object.fromEntries(decodeURIComponent(e).split("&").map((e=>e.split("=").map(decodeURIComponent))))}function Ne(){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)}let Me=/*#__PURE__*/t.lazy((()=>Promise.resolve().then((function(){return require("./TurnstileWrapper-qLN0G5m7.js")})))),Fe=/*#__PURE__*/t.lazy((()=>Promise.resolve().then((function(){return require("./HCaptchaWrapper-CxqJE5RH.js")}))));const De=r=>{let n=Ue();return t.useEffect((()=>n.remove),[n.remove]),n.enabled&&n.provider?/*#__PURE__*/e.jsx(t.Suspense,{fallback:null,children:/*#__PURE__*/e.jsxs("div",{className:"hidden h-0 w-0",children:["turnstile"===n.provider&&/*#__PURE__*/e.jsx(Me,{...r,captchaContext:n}),"hcaptcha"===n.provider&&/*#__PURE__*/e.jsx(Fe,{...r,captchaContext:n})]})}):null};var Le=/*#__PURE__*/Object.freeze({__proto__:null,AccountNotFoundScreen:()=>Promise.resolve().then((function(){return require("./AccountNotFoundScreen-C25iBRLm.js")})),AffirmativeConsentScreen:()=>Promise.resolve().then((function(){return require("./AffirmativeConsentScreen-DT0ojGpw.js")})),AllowlistRejectionScreen:()=>Promise.resolve().then((function(){return require("./AllowlistRejectionScreen-D0I4vTcK.js")})),AuthenticateWithWalletScreen:()=>Promise.resolve().then((function(){return require("./AuthenticateWithWalletScreen-dcVrFqXU.js")})),AwaitingEvmToSolBridgingScreen:()=>Promise.resolve().then((function(){return require("./AwaitingEvmToSolBridgingScreen-20Lokl_2.js")})),AwaitingExternalEthereumTransferScreen:()=>Promise.resolve().then((function(){return require("./AwaitingExternalEthereumTransferScreen-B2BOyvEP.js")})),AwaitingPasswordlessCodeScreen:()=>Promise.resolve().then((function(){return require("./AwaitingPasswordlessCodeScreen-CjeHuBk7.js")})),AwaitingSolToEvmBridgingScreen:()=>Promise.resolve().then((function(){return require("./AwaitingSolToEvmBridgingScreen-NSyS8djM.js")})),CaptchaScreen:()=>Promise.resolve().then((function(){return require("./CaptchaScreen-CchfnELg.js")})),CoinbaseOnrampStatusScreen:()=>Promise.resolve().then((function(){return require("./CoinbaseOnrampStatusScreen-RmmivwEu.js")})),ConnectLedgerScreen:()=>Promise.resolve().then((function(){return require("./ConnectLedgerScreen-CB1oTLjq.js")})),ConnectOnlyLandingScreen:()=>Promise.resolve().then((function(){return require("./ConnectOnlyLandingScreen-BI0zDj3o.js")})),ConnectOnlyStatusScreen:()=>Promise.resolve().then((function(){return require("./ConnectOnlyStatusScreen-BAUS-OpP.js")})),ConnectOrCreateScreen:()=>Promise.resolve().then((function(){return require("./ConnectOrCreateScreen-CdoSL34u.js")})),ConnectionStatusScreen:()=>Promise.resolve().then((function(){return require("./ConnectionStatusScreen-D2pFs10v.js")})),CrossAppAuthScreen:()=>Promise.resolve().then((function(){return require("./CrossAppAuthScreen-Dzqgp4fv.js")})),DelegatedActionsConsentScreen:()=>Promise.resolve().then((function(){return require("./DelegatedActionsConsentScreen-B1RznIyD.js")})),DelegatedActionsRevokeScreen:()=>Promise.resolve().then((function(){return require("./DelegatedActionsRevokeScreen-BfYkymoM.js")})),EmbeddedWalletConnectingScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletConnectingScreen-DaOL3Ico.js")})),EmbeddedWalletCreatedScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletCreatedScreen-B5K1ek4V.js")})),EmbeddedWalletKeyExportScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletKeyExportScreen-BJTyn-Lk.js")})),EmbeddedWalletOnAccountCreateScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletOnAccountCreateScreen-BbZKkeLp.js")})),EmbeddedWalletPasswordCreateScreen:()=>Promise.resolve().then((function(){return require("./RecoveryPasswordCreateScreen-BkFOrb6m.js")})),EmbeddedWalletPasswordUpdateScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletPasswordUpdateScreen-DMx4Tn8E.js")})),EmbeddedWalletPasswordUpdateSplashScreen:()=>Promise.resolve().then((function(){return require("./EmbeddedWalletPasswordUpdateSplashScreen-wUfHEYpF.js")})),ErrorScreen:()=>Promise.resolve().then((function(){return require("./ErrorScreen-BPXQabSS.js")})),FarcasterConnectStatusScreen:()=>Promise.resolve().then((function(){return require("./FarcasterConnectStatusScreen-C_NK2UCS.js")})),FarcasterSignerStatusScreen:()=>Promise.resolve().then((function(){return require("./FarcasterSignerStatusScreen-D3DUvPPw.js")})),FundSolWalletWithExternalSolanaWallet:()=>Promise.resolve().then((function(){return require("./FundSolWalletWithExternalSolanaWallet-BoOhBVX9.js")})),FundWithBankDepositScreen:()=>Promise.resolve().then((function(){return require("./FundWithBankDepositScreen-D_qA2wCk.js")})),FundingAmountEditScreen:()=>Promise.resolve().then((function(){return require("./FundingEditAmountScreen-DLWLIjEZ.js")})),FundingMethodSelectionScreen:()=>Promise.resolve().then((function(){return require("./FundingMethodSelectionScreen-BRz8TLz5.js")})),InAppBrowserLoginNotPossible:()=>Promise.resolve().then((function(){return require("./InAppBrowserLoginNotPossible-iLA0OVLk.js")})),InstallWalletScreen:()=>Promise.resolve().then((function(){return require("./InstallWalletScreen-BS2Bwxvi.js")})),LandingScreen:()=>Promise.resolve().then((function(){return require("./LandingScreen-C4KpTL08.js")})),LinkConflictScreen:()=>Promise.resolve().then((function(){return require("./LinkConflictScreen-CNQSun1F.js")})),LinkEmailScreen:()=>Promise.resolve().then((function(){return require("./LinkEmailScreen-oNzcpVes.js")})),LinkPasskeyScreen:()=>Promise.resolve().then((function(){return require("./LinkPasskeyScreen-CjdxFDoA.js")})),LinkPhoneScreen:()=>Promise.resolve().then((function(){return require("./LinkPhoneScreen-B6OzKZnd.js")})),LoginFailedScreen:()=>Promise.resolve().then((function(){return require("./LoginFailedScreen-Cj3ATfwH.js")})),ManualTransferScreen:()=>Promise.resolve().then((function(){return require("./ManualTransferScreen-M26HCQmU.js")})),MfaAuthEnrollmentFlowScreen:()=>Promise.resolve().then((function(){return require("./MfaAuthEnrollmentFlowScreen-D1zKxqD8.js")})),MfaAuthVerifyFlowScreen:()=>Promise.resolve().then((function(){return require("./MfaAuthVerifyFlowScreen-D3eQj9zt.js")})),MfaEnrollmentFlowScreen:()=>Promise.resolve().then((function(){return require("./MfaEnrollmentFlowScreen-B2gvvMfX.js")})),MoonpayStatusScreen:()=>Promise.resolve().then((function(){return require("./MoonpayStatusScreen-BQaJBdWu.js")})),OAuthStatusScreen:()=>Promise.resolve().then((function(){return require("./OAuthStatusScreen-JHIOff6A.js")})),PasskeySelectSignupOrLogin:()=>Promise.resolve().then((function(){return require("./PasskeySelectSignupOrLogin-B9J49RMF.js")})),PasskeyStatusScreen:()=>Promise.resolve().then((function(){return require("./PasskeyStatusScreen-ms-tH4cc.js")})),PasswordRecoveryScreen:()=>Promise.resolve().then((function(){return require("./PasswordRecoveryScreen-CDHZosNL.js")})),RecoveryOAuthScreen:()=>Promise.resolve().then((function(){return require("./RecoveryOAuthStatusScreen-BUxNTtqd.js")})),RecoverySelectionScreen:()=>Promise.resolve().then((function(){return require("./RecoverySelectionScreen-HBLOm2va.js")})),SendTransactionScreen:()=>Promise.resolve().then((function(){return require("./index-BcyDbfqY.js")})),SetAutomaticRecoveryScreen:()=>Promise.resolve().then((function(){return require("./SetAutomaticRecoveryScreen-DPjXBMos.js")})),SignRequestScreen:()=>Promise.resolve().then((function(){return require("./SignRequestScreen-Cjn1PsqC.js")})),StandardSignAndSendTransactionScreen:()=>Promise.resolve().then((function(){return require("./StandardSignAndSendTransactionScreen-BIh1TSV6.js")})),TelegramAuthScreen:()=>Promise.resolve().then((function(){return require("./TelegramAuthScreen-BZpPqkC8.js")})),TransferFromWalletScreen:()=>Promise.resolve().then((function(){return require("./TransferFromWalletScreen-BfWPkgYH.js")})),UpdateEmailScreen:()=>Promise.resolve().then((function(){return require("./UpdateEmailScreen-BHgHi-KQ.js")})),UpdatePhoneScreen:()=>Promise.resolve().then((function(){return require("./UpdatePhoneScreen-J83rbDYY.js")})),UserLimitReachedScreen:()=>Promise.resolve().then((function(){return require("./UserLimitReachedScreen-CYNd-wAp.js")})),WalletInterstitialScreen:()=>Promise.resolve().then((function(){return require("./WalletInterstitialScreen-CmqF-Oas.js")}))});function je(e){A.usePrivyEventSubscription("configureMfa",e)}const qe=P.create((()=>({inProgressMfaFlow:void 0})));const ze=C.createGlobalStyle`
|
|
2
2
|
:root {
|
|
3
3
|
${e=>Ke(e.palette)}
|
|
4
4
|
};
|
|
@@ -137,7 +137,7 @@
|
|
|
137
137
|
align-items: center;
|
|
138
138
|
justify-content: center;
|
|
139
139
|
height: 100%;
|
|
140
|
-
`;const Je=()=>{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),Le[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 Qe=/*#__PURE__*/t.lazy((()=>Promise.resolve().then((function(){return require("./MfaVerifyFlowScreen-
|
|
140
|
+
`;const Je=()=>{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),Le[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 Qe=/*#__PURE__*/t.lazy((()=>Promise.resolve().then((function(){return require("./MfaVerifyFlowScreen-AyHxACnF.js")})))),Xe=/*#__PURE__*/t.lazy((()=>(e=>Le[e]().then((e=>({default:e.default.component}))))("MfaAuthVerifyFlowScreen"))),Ze=()=>/*#__PURE__*/e.jsx(at,{children:/*#__PURE__*/e.jsx(o.Loader,{})}),et=()=>{let{currentScreen:r}=a.usePrivyModal(),n=qe((e=>e.inProgressMfaFlow)),i=()=>qe.setState({inProgressMfaFlow:void 0}),{component:s,isLoading:l}=Je();return function(){let{isModalOpen:e}=a.usePrivyContext(),{headless:r}=p.useAppConfig(),{currentScreen:n}=a.usePrivyModal(),{status:i,execute:s,reset:o,enabled:l}=Ue(),[c,d]=t.useState(!1);t.useEffect((()=>{!e&&l&&o()}),[e,l,o]),t.useEffect((()=>{n?Le[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(Ze,{}):s?
|
|
141
141
|
/*#__PURE__*/e.jsxs(e.Fragment,{children:[/*#__PURE__*/e.jsx(o.Hide,{$if:!!n,children:/*#__PURE__*/e.jsx(t.Suspense,{children:/*#__PURE__*/e.jsx(s,{})})}),/*#__PURE__*/e.jsxs(t.Suspense,{children:["txn"===n&&/*#__PURE__*/e.jsx(Qe,{onClose:i}),"auth"===n&&/*#__PURE__*/e.jsx(Xe,{})]})]}):null:/*#__PURE__*/e.jsx(t.Suspense,{children:/*#__PURE__*/e.jsx(Qe,{onClose:i})})},tt=()=>{let r=t.useRef(null);/*#__PURE__*/return e.jsx(it,{style:{height:o.useElementHeight(r)},id:"privy-modal-content",children:/*#__PURE__*/e.jsx("div",{ref:r,children:/*#__PURE__*/e.jsx(et,{})})})};const rt=({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=qe((e=>e.inProgressMfaFlow));return je({onMfaRequired:()=>{n.mfa.noPromptOnMfaRequired||qe.setState({inProgressMfaFlow:"txn"})}}),n.render.standalone?/*#__PURE__*/e.jsx(He,{children:/*#__PURE__*/e.jsx(nt,{id:"privy-modal-content",children:/*#__PURE__*/e.jsx(et,{})})}):/*#__PURE__*/e.jsx(Be,{open:!(!r&&!s),id:"privy-dialog","aria-label":"log in or sign up","aria-labelledby":"privy-dialog-title",onClick:()=>i(),children:/*#__PURE__*/e.jsx(He,{children:/*#__PURE__*/e.jsx(tt,{})})})};let nt=C.styled.div`
|
|
142
142
|
display: flex;
|
|
143
143
|
flex-direction: column;
|
|
@@ -171,4 +171,4 @@
|
|
|
171
171
|
padding: 2rem;
|
|
172
172
|
`;function st(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 ot=()=>{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.s.put(p.CONNECTIONS_HISTORY_KEY,t)};return r.connectors?.on("walletsUpdated",t),()=>{r.connectors?.off("walletsUpdated",t)}}),[e,r.connectors]),null};class lt 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,f.deleteWalletConnectDeepLink(),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(),f.removeWalletConnectDeepLink(),!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}=f.buildTargetUrl(e,this.walletEntry);f.openHref(t,"_self"),f.setWalletConnectDeepLink({href:r,name:this.walletEntry.metadata?.shortName||this.walletEntry.name});let n=f.buildUniversalFallbackUrl(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=f.buildUniversalFallbackUrl(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 ct=["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 dt extends Error{constructor(e,t){super(t),this.type=e}}function ut(e){let t=e.type;return"string"==typeof t&&ct.includes(t)}function ht(e){return ut(e)&&"wallet_not_on_device"===e.type}async function pt(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 dt("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 dt("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 dt("mfa_verification_max_attempts_reached","Max MFA verification attempts reached");throw n.current?.reject(e),e}return l}var yt;let wt=(yt=0,()=>"id-"+yt++);function mt(e){return void 0!==e.error}let gt=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={}}},vt=new Map,ft=(e,t)=>"bigint"==typeof t?t.toString():t;function Et(e,t,r,n){let i=r.contentWindow;if(!i)throw Error("iframe not initialized");let a=((e,t)=>`${e}${JSON.stringify(t,ft)}`)(e,t);if("privy:wallet:create"===e||"privy:wallets:add"===e||"privy:solana-wallet:create"===e){let e=vt.get(a);if(e)return e}let s=new Promise(((r,a)=>{let s=wt();gt.enqueue(s,{resolve:r,reject:a}),i.postMessage({id:s,event:e,data:t},n)})).finally((()=>{vt.delete(a)}));return vt.set(a,s),s}function Ct(r){let n=p.useIsServerConfigLoaded(),i=t.useRef(null),a=t.useRef(r.mfaMethods),s=A.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=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data);case"privy:user-signer:sign":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:add":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:set-recovery":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:connect":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:recover":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallets:rpc":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:wallet:create":let r=gt.dequeue(e.event,e.id);return mt(e)?r.reject(new dt(e.error.type,e.error.message)):r.resolve(e.data);case"privy:wallets:import":let n=gt.dequeue(e.event,e.id);return mt(e)?n.reject(new dt(e.error.type,e.error.message)):n.resolve(e.data);case"privy:mfa:verify":let i=gt.dequeue(e.event,e.id);return mt(e)?i.reject(new dt(e.error.type,e.error.message)):i.resolve(e.data);case"privy:mfa:init-enrollment":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:submit-enrollment":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:unenroll":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:mfa:clear":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:auth:unlink-passkey":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:solana-wallet:create":let a=gt.dequeue(e.event,e.id);return mt(e)?a.reject(new dt(e.error.type,e.error.message)):a.resolve(e.data);case"privy:farcaster:init-signer":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:farcaster:sign":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}case"privy:delegated-actions:consent":{let t=gt.dequeue(e.event,e.id);return mt(e)?t.reject(new dt(e.error.type,e.error.message)):t.resolve(e.data)}default:console.warn("Unsupported wallet proxy method:",e)}}(e.data)}let n={signWithUserSigner:t=>pt((n=>Et("privy:user-signer:sign",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),addWallet:t=>pt((n=>Et("privy:wallets:add",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),setRecovery:t=>pt((n=>Et("privy:wallets:set-recovery",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),connect:t=>pt((n=>Et("privy:wallets:connect",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),recover:t=>pt((n=>Et("privy:wallets:recover",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s,!t.recoveryAccessToken&&!t.recoveryPassword&&!t.recoverySecretOverride),rpc:t=>pt((n=>Et("privy:wallets:rpc",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),create:t=>Et("privy:wallet:create",t,e,r.origin),importWallet:t=>Et("privy:wallets:import",t,e,r.origin),createSolana:t=>pt((n=>Et("privy:solana-wallet:create",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),createDelegatedAction:t=>Et("privy:delegated-actions:consent",t,e,r.origin),verifyMfa:t=>pt((n=>Et("privy:mfa:verify",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s,!0),initEnrollMfa:t=>pt((n=>Et("privy:mfa:init-enrollment",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),submitEnrollMfa:t=>pt((n=>Et("privy:mfa:submit-enrollment",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),unenrollMfa:t=>pt((n=>Et("privy:mfa:unenroll",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),clearMfa:t=>Et("privy:mfa:clear",t,e,r.origin),unlinkPasskeyAccount:t=>pt((n=>Et("privy:auth:unlink-passkey",{...t,...n},e,r.origin)),a.current,r.mfaPromise,r.mfaSubmitPromise,s),initFarcasterSigner:t=>Et("privy:farcaster:init-signer",t,e,r.origin),signFarcasterMessage:t=>Et("privy:farcaster:sign",t,e,r.origin)};window.addEventListener("message",t);let c=new AbortController;return o.invokeUntilSettled((()=>Et("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?
|
|
173
173
|
/*#__PURE__*/e.jsx("iframe",{ref:i,width:"0",height:"0",style:{display:"none",height:"0px",width:"0px"},onLoad:()=>c(!0),src:_.constructURL({origin:r.origin,path:`/apps/${r.appId}/embedded-wallets`,query:{caid:r.clientAnalyticsId,client_id:r.appClientId}})}):null}const At=({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}},Pt=({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}},Tt=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"privy"===e.walletClientType&&e.delegated));const kt="popup-privy-oauth",_t="PRIVY_OAUTH_USE_BROADCAST_CHANNEL";class St{async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(v.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:this.meta.codeVerifier,provider:this.meta.provider,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(v.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(e){this.meta=e}}async function bt({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 It=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 bt({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",Wt(n));let u=g.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 Wt=e=>JSON.stringify({content:{request:{request:Ut(e,S.toHex)}},timestamp:Date.now(),callbackUrl:window.origin});const Ut=(e,t)=>"bigint"==typeof e?t(e):Array.isArray(e)?e.map((e=>Ut(e,t))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,r])=>[e,Ut(r,t)]))):e;function xt({isCreatingWallet:e,skipSplashScreen:t}){return e?"EmbeddedWalletPasswordCreateScreen":t?"EmbeddedWalletPasswordUpdateScreen":"EmbeddedWalletPasswordUpdateSplashScreen"}function Rt({walletAction:e,availableRecoveryMethods:t,legacySetWalletPasswordFlow:r,isResettingPassword:n,showAutomaticRecovery:i}){return i?"SetAutomaticRecoveryScreen":r||1===t.length?xt({isCreatingWallet:"create"===e,skipSplashScreen:n}):"RecoverySelectionScreen"}function Ot(e){switch(e){case"user-passcode":return"PasswordRecoveryScreen";case"google-drive":case"icloud":return"RecoveryOAuthScreen";default:throw Error("Recovery method not supported")}}function Nt(e,t){if(e.onComplete)switch(t){case"external":e.fundingResult?e.onComplete({...e.fundingResult,fundingMethod:t}):e.onComplete({status:"cancelled",address:e.address,fundingMethod:t,amount:e.amount});break;case null:e.onComplete({status:"cancelled",address:e.address,fundingMethod:void 0,amount:e.amount});break;default:e.onComplete({status:"completed",address:e.address,fundingMethod:t,amount:e.amount})}}const Mt=new Map([["FundingMethodSelectionScreen",null],["TransferFromWalletScreen","external"],["FundingAmountEditScreen","external"],["ConnectOnlyLandingScreen","external"],["ConnectOnlyStatusScreen","external"],["AwaitingExternalEthereumTransferScreen","external"],["AwaitingEvmToSolBridgingScreen","external"],["AwaitingSolToEvmBridgingScreen","external"],["ManualTransferScreen","manual"],["MoonpayStatusScreen","moonpay"]]);function Ft(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 Lt={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 jt=e=>{if(a.isCustomOAuthProvider(e))return{displayName:e.replace("custom:",""),loginMethod:"custom"};let t=Lt[e];return"wallet"===e||"phone"===e?{displayName:e,loginMethod:t}:{displayName:t,loginMethod:t}};async function qt(e,t,r,n){let i=h.toViemTransactionSerializable(e),{chain:a,...s}=await(async()=>n?await n():await t.prepareTransactionRequest({...i,account:{address:r,type:"json-rpc"}}))();return{...s,type:h.STRING_TO_NUMBER_TXN_TYPE[s.type]}}const zt=()=>{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,migrated:!1};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,migrated:!1};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(!ht(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(!ht(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,migrated:!0}}),[e.embeddedWallets.mode,r,s,n,i])}},Kt=({disabled:e})=>{let{migrate:r}=zt(),{user:n}=a.usePrivyContext(),{walletProxy:i}=c.usePrivyInternal(),s=t.useRef(!1),o=t.useRef(0);return t.useEffect((()=>{e||o.current>2||s.current||!n||!i||(s.current=!0,o.current++,r().catch((e=>{console.debug("Unable to migrate wallets: ",e)})).finally((()=>{s.current=!1})))}),[n,i,e,r]),null},Ht=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}),Bt=P.create((()=>({ethereum:[]}))),Vt=()=>Bt.getState().ethereum,Yt=P.create((()=>({user:null,authenticated:!1}))),Gt=e=>Yt.setState({user:e}),$t=e=>Yt.setState({authenticated:e});class Jt{async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(v.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(v.customJwtAccountLinkPath,{token:this.meta.token})}catch(e){throw c.formatApiError(e)}}constructor(e){this.meta={token:e}}}const Qt=(e,t)=>!a.getPrivyEthereumWallet(e)&&("all-users"===t||"users-without-wallets"===t&&!Xt(e).length);let Xt=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"ethereum"===e.chainType));const Zt=(e,t)=>!a.getPrivySolanaWallet(e)&&("all-users"===t||"users-without-wallets"===t&&!er(e).length);let er=e=>e.linkedAccounts.filter((e=>"wallet"===e.type&&"solana"===e.chainType));const tr=()=>{let{walletProxy:e,recoverEmbeddedWallet:t,setUser:r,refreshSessionAndUser:n,privy:i,client:a}=c.usePrivyInternal(),s=p.useAppConfig();return{create:async({walletIndex:o,chainType:l,latestUser:c,recoveryMethod:d,recoveryPassword:u,recoveryAccessToken:h,idempotencyKey:p})=>{let y=c;y||(y=await n());let w=await a.getAccessToken();if(!y||!w||!e)throw Error("User must be authenticated before creating a Privy wallet");return await f.createWalletAtIndex({appConfig:s,user:y,refreshSessionAndUser:n,privy:i,accessToken:w,proxy:e,recoverEmbeddedWallet:t,setUser:r,walletIndex:o,chainType:l,recoveryMethod:d,recoveryPassword:u,recoveryAccessToken:h,idempotencyKey:p})}}};function rr({subscribe:e,getExternalJwt:r,enabled:n=!0,onAuthenticated:i,onUnauthenticated:a,onError:s}){let{client:o,setAuthenticated:l,setUser:d,setIsNewUser:u}=c.usePrivyInternal(),{logout:h,authenticated:y,ready:w}=f.usePrivy(),{create:m}=tr(),g=p.useAppConfig();if(!o)throw new c.PrivyClientError("`useSyncJwtBasedAuthState` must be used within a `PrivyProvider`");let[v,E]=t.useState({status:"initial"}),C=t.useRef(),A=t.useRef(!1),P=t.useRef(r);t.useEffect((()=>{P.current=r}),[r]);let T=t.useRef(i);t.useEffect((()=>{T.current=i}),[i]);let k=t.useRef(a);t.useEffect((()=>{k.current=a}),[a]);let _=t.useRef(s);t.useEffect((()=>{_.current=s}),[s]);let S=t.useRef(m);t.useEffect((()=>{S.current=m}),[m]);let b=t.useRef(g.embeddedWallets.ethereum.createOnLogin);t.useEffect((()=>{b.current=g.embeddedWallets.ethereum.createOnLogin}),[g.embeddedWallets.ethereum.createOnLogin]);let I=t.useRef(g.embeddedWallets.solana.createOnLogin);t.useEffect((()=>{I.current=g.embeddedWallets.solana.createOnLogin}),[g.embeddedWallets.solana.createOnLogin]);let W=t.useRef(d);t.useEffect((()=>{W.current=d}),[d]);let U=t.useRef(u);t.useEffect((()=>{U.current=u}),[u]);let x=t.useRef(l);return t.useEffect((()=>{x.current=l}),[l]),t.useEffect((()=>{if(!n||!w)return;let t=async()=>{if(!A.current){A.current=!0;try{E({status:"loading"});let e=await P.current();if(void 0!==C.current&&C.current===e)return void E({status:"done"});if(!e)return y&&(await h(),k.current?.()),C.current=e,void E({status:"done"});o.startAuthFlow(new Jt(e));let{user:t,isNewUser:r=!1}=await o.authenticate();if(!t)throw new c.PrivyClientError("Failed to sync with custom auth provider");T.current?.({user:t,isNewUser:r}),W.current(t),U.current(r),x.current(!0);let n=Qt(t,b.current),i=Zt(t,I.current);if(n&&i){let e=await S.current({chainType:"ethereum",walletIndex:0,latestUser:t});await S.current({chainType:"solana",walletIndex:0,latestUser:e.user})}else i?await S.current({chainType:"solana",walletIndex:0,latestUser:t}):n&&await S.current({chainType:"ethereum",walletIndex:0,latestUser:t});C.current=e,E({status:"done"})}catch(e){if(console.warn(e),await h().catch((()=>{})),k.current?.(),e instanceof c.PrivyApiError&&e.privyErrorCode===c.PrivyErrorCode.LINKED_TO_ANOTHER_USER)return E({status:"initial"}),void setTimeout((()=>{t()}),0);_.current?.(e),E({status:"error",error:e})}finally{A.current=!1}}};return t(),e(t)}),[e,o,y,h,n,w]),n?{state:v}:{state:{status:"not-enabled"}}}let nr=P.create((()=>({jwtAuthFlowState:{status:"not-enabled"}})));function ir({customAuth:e}){let{jwtAuthFlowState:r}=function({customAuth:e}){let r=A.useEmitPrivyEvent(),n=t.useRef(),i=t.useCallback((e=>(n.current=e,()=>{n.current=void 0})),[]),a=e?.getCustomAccessToken??(()=>Promise.resolve(void 0)),{state:s}=rr({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((()=>{nr.setState({jwtAuthFlowState:r})}),[r]),null}const ar=/*#__PURE__*/t.createContext(!1);let sr,or,lr,cr,dr;const ur=n=>{let i=n.client,s=n.privy,u=b.usePlugins(),h=p.useAppConfig();o.useExternalWalletListings(o.shouldFetchWcRegistryListings(h?.appearance.walletList??[]));let[E,C]=t.useState(!1),P=qe((e=>e.inProgressMfaFlow)),[T,k]=t.useState(!1),_=Yt((e=>e.user)),S=Bt((e=>e.ethereum)),[U,x]=t.useState(void 0),[R,O]=t.useState(!1),[N,M]=t.useState(null),[F,D]=t.useState(!1),[L,j]=t.useState({status:"disconnected",connectedWallet:null,connectError:null,connector:null,connectRetry:c.notImplemented}),[q,z]=t.useState({status:"initial"}),[K,H]=t.useState({status:"initial"}),[B,V]=t.useState({status:"initial"}),[Y,G]=t.useState({status:"initial"}),[$,J]=t.useState({status:"initial"}),[Q,X]=t.useState({status:"initial"}),[Z,ee]=t.useState(null),te=p.useIsServerConfigLoaded(),[re,ne]=t.useState({}),[ae,se]=t.useState(null),ce=t.useRef(null),[ue,he]=t.useState(!1),we=t.useRef(null),Ce=t.useRef(null),be=t.useRef(A.privyEventsDefault),[Ie,Ue]=t.useState(!1),xe=Yt((e=>e.authenticated)),Me=t.useCallback((e=>{$t(e),!e&&N&&Le[N]().then((e=>{e.default.isUnauthenticatedScreem&&M(null)}))}),[N]);i.onStoreCustomerAccessToken=e=>{e&&A.emitPrivyEvent(be,"accessToken","onAccessTokenGranted",{accessToken:e})},i.onDeleteCustomerAccessToken=()=>{Gt(null),Me(!1),A.emitPrivyEvent(be,"accessToken","onAccessTokenRemoved")};let Fe=t.useRef(null),je=t.useRef(null),Ke=t.useRef(!1),He=({showWalletUIs:e})=>Ke.current?Ke.current:void 0!==e?!e:!h.embeddedWallets.showWalletUIs,Be=e=>{M(e),setTimeout((()=>{C(!0)}),15)};t.useEffect((()=>{if(!_)return void i.connectors?.removeEmbeddedWalletConnectors();let e=a.getPrivyEthereumWallet(_),t=a.getPrivyEthereumHDWallets(_),r=a.getImportedPrivyEthereumWallets(_);e&&t.length||i.connectors?.removeEmbeddedWalletConnectors(),r.length||i.connectors?.removeImportedWalletConnectors(),i.connectors?Z?(e&&i.connectors.addEmbeddedWalletConnectors({walletProxy:Z,user:_,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,_]),t.useEffect((()=>{Z&&ce.current?.(Z)}),[Z]),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&&te&&async function(){let e,t=Ve(),r=Ye(),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:x}),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?Ue(!0):e=setTimeout((()=>{console.debug({message:"Unable to initialize all expected connectors before timeout",initialized:r,expected:t}),Ue(!0)}),1500)})),i.connectors?.initialize().then((()=>{Xe()}));let a=await i.getAuthenticatedUser(),s=!!a;h.legal.requireUsersAcceptTerms&&a&&!a.hasAcceptedTerms?(await i.logout(),wt.setReadyToTrue(!0),A.emitPrivyEvent(be,"logout","onSuccess")):(h.customAuth?.enabled||(Me(!!a),a&&A.emitPrivyEvent(be,"login","onComplete",{user:a,isNewUser:!1,wasAlreadyAuthenticated:!0,loginMethod:null,loginAccount:null}),Gt(a)),t?je.current=s?"link":"login":r&&!s?(je.current="login",ne({telegramAuthModalData:{seamlessAuth:!0}}),Be("TelegramAuthScreen")):wt.setReadyToTrue(!!a))}()}),[i,ae,T,te]),t.useEffect((()=>{if(T){if(!_||!_.linkedAccounts.find((e=>"wallet"===e.type&&"privy"===e.walletClientType)))return void he(!!Z);if([...S].some((e=>"privy"===e.walletClientType)))return void he(!0);he(!!Z)}}),[T,_,S,Z]),t.useEffect((()=>{i.connectors?.setWalletList(h.appearance.walletList)}),[h.appearance.walletList.join()]);let Ve=()=>{let e=Ee();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(kt).postMessage({type:"PRIVY_OAUTH_RESPONSE",stateCode:e.stateCode,authorizationCode:e.authorizationCode}),window.close()),!!e.inProgress&&!!e.withPrivyUi&&(i.startAuthFlow(new fe({...e,customOAuthRedirectUrl:h.customOAuthRedirectUrl})),Be("OAuthStatusScreen"),!0))},Ye=()=>{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())}())?(Ne(),{flowType:"login-url",authData:e}):(e=function(){let e=window.location.hash;if(!e||!e.startsWith("#tgWebAppData"))return;let t=Oe(e.replace("#tgWebAppData=","")),{user:r,auth_date:n,hash:i}=t;return r&&n&&i?t:void 0}())?(Ne(),{flowType:"web-app",authData:e}):void 0}();if(!e||!h.loginMethods.telegram||!h.loginConfig.telegramAuthConfiguration?.seamlessAuthEnabled)return;let t=new Re;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},Ge=async(e,t,r,n)=>{if("solana_adapter"!==e)$e(await(i.connectors?.createEthereumWalletConnector({connectorType:e,walletClientType:t}))||null,t,r,n);else{let e=i.connectors?.findSolanaWalletConnector(t);if(!e)return;$e(e,t,r,n)}};async function $e(e,t,r,n){if(!e)return j({status:"disconnected",connectedWallet:null,connectError:new c.PrivyConnectorError("Unable to connect to wallet."),connector:null,connectRetry:c.notImplemented}),n?.(null,r);j({status:"disconnected",connectedWallet:null,connectError:null,connector:e,connectRetry:c.notImplemented}),e instanceof lt&&t&&await e.resetConnection(t),j({connector:e,status:"connecting",connectedWallet:null,connectError:null,connectRetry:()=>$e(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)){j((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 j((e=>({...e,status:"connected",connectedWallet:t,connectError:null,connectRetry:c.notImplemented}))),t&&A.emitPrivyEvent(be,"connectWallet","onSuccess",{wallet:t}),n?.(t,r)}catch(e){return e instanceof c.PrivyError?(console.warn(e.cause?e.cause:e.message),A.emitPrivyEvent(be,"connectWallet","onError",e.privyErrorCode||c.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR)):(console.warn(e),A.emitPrivyEvent(be,"connectWallet","onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR)),j((t=>({...t,status:"disconnected",connectedWallet:null,connectError:e}))),n?.(null,r)}}let Je=async(e,t,r)=>{if(null===e||!o.isBaseConnectedEthereumWallet(e))return;let n=new Te(i,e,t,r);i.startAuthFlow(n)},Qe=async(e,t,r,n="plain")=>{let a=u(f.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 ke(e,i,t,r,n,a);i.startAuthFlow(s)},Xe=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 Be("LoginFailedScreen");if(!i.connectors)throw new c.PrivyClientError("Connector not initialized");await Be(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),Ge(t,r,void 0,n?void 0:"solana_adapter"===t?Qe:Je)};t.useEffect((()=>{T&&xe&&null===_&&i.getAuthenticatedUser().then(Gt)}),[T,xe,_,i]);let Ze=e=>{if(!xe)throw A.emitPrivyEvent(be,"linkAccount","onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:e}),new c.PrivyClientError("User must be authenticated before linking an account.")},et=e=>{if(!xe||!_)return!1;if("privy"===e.walletClientType)return!0;for(let t of _.linkedAccounts)if("wallet"===t.type&&t.address===e.address&&"privy"!==t.walletClientType)return!0;return!1},tt=()=>{Bt.setState((e=>{let t=i.connectors?.wallets.filter(o.isBaseConnectedEthereumWallet).map((e=>({...e,linked:et(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,j((r=>({...r,connector:t,status:"connected",connectedWallet:e,connectError:null,connectRetry:c.notImplemented}))),h.captcha.enabledProvider&&!xe?(ne({captchaModalData:{callback:t=>o.isBaseConnectedEthereumWallet(e)?Je(e,t):Qe(e,t),userIntentRequired:!1,onSuccessNavigateTo:"ConnectionStatusScreen",onErrorNavigateTo:"ErrorScreen"}}),await Be("CaptchaScreen")):(o.isBaseConnectedEthereumWallet(e)?await Je(e):await Qe(e),await Be("ConnectionStatusScreen"))})(e)},fund:async t=>{await wt.fundWallet(e.address,t)},unlink:async()=>{if(!xe)throw new c.PrivyClientError("User is not authenticated.");if("embedded"===e.connectorType&&"privy"===e.walletClientType)throw new c.PrivyClientError("Cannot unlink an embedded wallet");Gt(await i.unlinkEthereumWallet(e.address))}})))||[];return o.areWalletArraysEqual(e.ethereum,t)?{}:{ethereum:t}}))};t.useEffect((()=>{tt()}),[_?.linkedAccounts,xe,T]),t.useEffect((()=>{if(T){if(!i.connectors)throw new c.PrivyClientError("Connector not initialized");tt(),i.connectors.on("walletsUpdated",tt)}}),[T]),t.useEffect((()=>{[...h.loginMethodsAndOrder?.primary??[],...h.loginMethodsAndOrder?.overflow??[]].filter((e=>e.startsWith("privy:"))).forEach((e=>i.getCrossAppProviderDetails(e.replace("privy:",""))))}),[!!i]);let nt=({transaction:e,sponsor:t,uiOptions:p,fundWalletConfig:y,address:w,signOnly:g})=>new Promise((async(v,f)=>{let{requesterAppId:E}=p||{},C=g?"signTransaction":"sendTransaction",P=w?a.getPrivyWalletWithAddress(_,w):a.getPrivyEthereumWallet(_);if(!P&&w){let r=a.getConnectedWalletWithAddress(Vt(),w);if(r){if(t)throw new c.PrivyClientError("Cannot sponsor transactions for externally connected wallet.");try{let t=await r.getEthereumProvider(),n=e.data,i=u(I.DATA_SUFFIX_PLUGIN_ID);i&&(n=i.appendDataSuffix({data:n}));let a={...e,from:w,chainId:e.chainId||Number(r.chainId.replace("eip155:","")),value:void 0!==e.value?m.toHex(e.value):void 0,data:n},s=await t.request({method:"sendTransaction"===C?"eth_sendTransaction":"eth_signTransaction",params:[a]});return A.emitPrivyEvent(be,C,"onSuccess",{hash:s}),void v({hash:s})}catch(e){return A.emitPrivyEvent(be,C,"onError",c.PrivyErrorCode.TRANSACTION_FAILURE),void f(e??new d.PrivyProviderRpcError("Unable to "+C+e))}}}if(!P)return A.emitPrivyEvent(be,C,"onError",c.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void f(new c.PrivyClientError("No embedded or connected wallet found for address."));if(!xe||!_)return A.emitPrivyEvent(be,C,"onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED),void f(Error("User must be authenticated before signing with a Privy wallet"));let T=P.address,k=P.walletIndex??0,{entropyId:S,entropyIdVerifier:b}=l.getEntropyDetailsForUser(_,P),U=mt.wallets.find((e=>"privy"===e.walletClientType&&m.getAddress(e.address)===m.getAddress(T)));if(!U)return A.emitPrivyEvent(be,C,"onError",c.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void f(Error("Must have a Privy wallet before signing"));let x=await U.getEthereumProvider(),R=await x.request({method:"eth_chainId"}),O=e.chainId?Number(e.chainId):d.extractChainIdFromCAIP2(R);(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)})(O);let N=e.data,M=u(I.DATA_SUFFIX_PLUGIN_ID);M&&(N=M.appendDataSuffix({data:N}));let F={...e,from:e.from??T,chainId:O,data:N},D=await ie();if(!D||!Z)return A.emitPrivyEvent(be,C,"onError",c.PrivyErrorCode.EMBEDDED_WALLET_NOT_FOUND),void f(Error("Must have valid access token and Privy wallet to send transaction"));let L=W.getPublicClient(F.chainId,h.chains,h.rpcConfig,{appId:n.appId}),j=a.getIsUnifiedWallet(P),q=async({transactionRequest:e})=>{try{let n;if(!await wt.recoverEmbeddedWallet({address:T}))throw A.emitPrivyEvent(be,C,"onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),f(Error("Unable to connect to wallet")),Error("Unable to connect to wallet");if(t){let t=await(async({transactionRequest:e})=>{if(!j)throw new c.PrivyClientError("Sponsoring is only supported for wallets on the TEE stack");if(g)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:D,requesterAppId:E,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:P.id});if(n.data&&"hash"in n.data)return n.data.hash;throw new d.PrivyProviderRpcError("Unable to sign transaction")})({transactionRequest:e});return A.emitPrivyEvent(be,"sendTransaction","onSuccess",{hash:t}),t}if(j){let t=e=>null==e?void 0:m.toHex(e),i=await r.rpc(s,(async({message:e})=>await Z.signWithUserSigner({accessToken:D,requesterAppId:E,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:P.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:D,entropyId:S,entropyIdVerifier:b,transactingWalletIndex:k,walletProxy:Z,transactionRequest:e,requesterAppId:E});if(g)return A.emitPrivyEvent(be,"signTransaction","onSuccess",{signature:n}),n;{let e=await L.sendRawTransaction({serializedTransaction:n});return A.emitPrivyEvent(be,"sendTransaction","onSuccess",{hash:e}),e}}catch(e){throw A.emitPrivyEvent(be,C,"onError",c.PrivyErrorCode.TRANSACTION_FAILURE),e}};if(He({showWalletUIs:p?.showWalletUIs})){let e=g||t?F:await qt(F,L,F.from);try{let t=await q({transactionRequest:e});g?A.emitPrivyEvent(be,"signTransaction","onSuccess",{signature:t}):A.emitPrivyEvent(be,"sendTransaction","onSuccess",{hash:t}),v({hash:t})}catch(e){A.emitPrivyEvent(be,C,"onError",c.PrivyErrorCode.TRANSACTION_FAILURE),f(e)}}else{let e={connectingWalletAddress:T,recoveryMethod:P.recoveryMethod,entropyId:S,entropyIdVerifier:b,onCompleteNavigateTo:"SendTransactionScreen",isUnifiedWallet:j,onFailure:e=>{A.emitPrivyEvent(be,C,"onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),f(e)}},r=(e=>!!e.fundingConfig&&d.filterSupportedOptions(e.fundingConfig.options).length>=1)(h)?d.prepareFundingModalData({address:T,appConfig:h,fundWalletConfig:y,methodScreen:"FundingMethodSelectionScreen",chainIdOverride:F.chainId,comingFromSendTransactionScreen:!0}):void 0;ne({connectWallet:e,sendTransaction:{transactionRequest:F,transactingWalletIndex:k,transactingWalletAddress:T,entropyId:S,entropyIdVerifier:b,signOnly:g,scanTransaction:async()=>{let e=await qt(F,L,F.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})=>q({transactionRequest:e}),onSuccess:e=>{g?A.emitPrivyEvent(be,"signTransaction","onSuccess",{signature:e.hash}):A.emitPrivyEvent(be,"sendTransaction","onSuccess",{hash:e.hash}),v(e)},onFailure:e=>{A.emitPrivyEvent(be,C,"onError",c.PrivyErrorCode.TRANSACTION_FAILURE),f(e)},uiOptions:p||{},fundWalletConfig:y,requesterAppId:E},funding:r}),Be("EmbeddedWalletConnectingScreen")}}));function it(){return new Promise((async(e,t)=>{let r=await ie();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 at=e=>e?.linkedAccounts.filter((e=>null!==e.latestVerifiedAt&&!("wallet"===e.type&&"privy"===e.walletClientType))).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0],ct=e=>{let t=_?.linkedAccounts.filter((t=>t.type===e)).length??0,{displayName:r,loginMethod:n}=jt(e);if("passkey"===e&&t>=5||"passkey"!==e&&t>=1)throw A.emitPrivyEvent(be,"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 dt({showAutomaticRecovery:e=!1,legacySetWalletPasswordFlow:t=!1}){M(null);let r=t?"setWalletPassword":"setWalletRecovery";if(!xe||!_)throw A.emitPrivyEvent(be,r,"onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED),Error("User must be authenticated before adding recovery method to Privy wallet");let n=a.getPrivyPrimaryWallet(_);if(!n||!Z)throw A.emitPrivyEvent(be,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 A.emitPrivyEvent(be,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 it()}catch(e){throw A.emitPrivyEvent(be,r,"onError",c.PrivyErrorCode.MISSING_MFA_CREDENTIALS),e}return new Promise(((a,s)=>{let o="user-passcode"===n.recoveryMethod,d=Rt({walletAction:"update",availableRecoveryMethods:h.embeddedWallets.userOwnedRecoveryOptions,legacySetWalletPasswordFlow:t,isResettingPassword:o,showAutomaticRecovery:e}),{entropyId:u,entropyIdVerifier:p}=l.getEntropyDetailsForUser(_),y={recoveryMethod:n.recoveryMethod,connectingWalletAddress:n.address,onCompleteNavigateTo:d,shouldForceMFA:!1,entropyId:u,isUnifiedWallet:i,entropyIdVerifier:p,onFailure:e=>{A.emitPrivyEvent(be,r,"onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),s(e)}};ne({setWalletPassword:{onSuccess:e=>{A.emitPrivyEvent(be,r,"onSuccess",{method:"user-passcode",wallet:e}),a(e)},onFailure:e=>{A.emitPrivyEvent(be,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}}),Be("EmbeddedWalletConnectingScreen")}))}async function ut({appId:e,action:t,disableSignup:r}){let n=await ie();if("link"===t&&!n)throw A.emitPrivyEvent(be,"linkAccount","onError",c.PrivyErrorCode.MUST_BE_AUTHENTICATED,{linkMethod:`privy:${e}`}),new c.PrivyClientError("User must be authenticated before linking an account.");if("login"===t&&n)throw A.emitPrivyEvent(be,"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.");Fe.current=`privy:${e}`,je.current=t;let a=g.trigger();return i.createAnalyticsEvent({eventName:"cross_app_auth_started",payload:{providerAppId:e}}),new Promise((async(n,s)=>{let{name:o,logoUrl:l}=await bt({api:i.api,providerAppId:e,requesterAppId:h.id});ne({crossAppAuth:{appId:e,name:o,logoUrl:l,action:t,popup:a,disableSignup:r,onSuccess:n,onError:s}}),Be("CrossAppAuthScreen")}))}let pt={ready:T,authenticated:xe,user:_,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}}),Be("ConnectOnlyLandingScreen")},linkWallet:e=>(e&&"target"in e&&e&&(e=void 0),Ze("siwe"),Fe.current="siwe",je.current="link",ne({...re,externalConnectWallet:{...re.externalConnectWallet,walletList:e?.walletList,walletChainType:e?.walletChainType,description:e?.description||`Link a wallet to your ${h?.name} account`}}),Be("AuthenticateWithWalletScreen")),startCrossAppAuthFlow:ut,linkEmail:()=>{Ze("email"),ct("email"),Fe.current="email",je.current="link",Be("LinkEmailScreen")},linkPhone:()=>{Ze("sms"),ct("phone"),Fe.current="sms",je.current="link",Be("LinkPhoneScreen")},linkGoogle:async()=>{Ze("google"),ct("google_oauth"),je.current="link",await wt.initLoginWithOAuth("google")},linkTwitter:async()=>{Ze("twitter"),ct("twitter_oauth"),je.current="link",await wt.initLoginWithOAuth("twitter")},linkTwitch:async()=>{Ze("twitch"),ct("twitch_oauth"),je.current="link",await wt.initLoginWithOAuth("twitch")},linkDiscord:async()=>{Ze("discord"),ct("discord_oauth"),je.current="link",await wt.initLoginWithOAuth("discord")},linkGithub:async()=>{Ze("github"),ct("github_oauth"),je.current="link",await wt.initLoginWithOAuth("github")},linkSpotify:async()=>{Ze("spotify"),ct("spotify_oauth"),je.current="link",await wt.initLoginWithOAuth("spotify")},linkInstagram:async()=>{Ze("instagram"),ct("instagram_oauth"),je.current="link",await wt.initLoginWithOAuth("instagram")},linkTiktok:async()=>{Ze("tiktok"),ct("tiktok_oauth"),je.current="link",await wt.initLoginWithOAuth("tiktok")},linkLine:async()=>{Ze("line"),ct("line_oauth"),je.current="link",await wt.initLoginWithOAuth("line")},linkLinkedIn:async()=>{Ze("linkedin"),ct("linkedin_oauth"),je.current="link",await wt.initLoginWithOAuth("linkedin")},linkApple:async()=>{Ze("apple"),ct("apple_oauth"),je.current="link",await wt.initLoginWithOAuth("apple")},linkPasskey:async()=>{Ze("passkey"),ct("passkey"),await wt.initLinkWithPasskey(),Be("LinkPasskeyScreen")},linkTelegram:async e=>{if(Ze("telegram"),ct("telegram"),je.current="link",Fe.current="telegram",e?.launchParams)if(e.launchParams.initDataRaw){let t=new Re;i.startAuthFlow(t),t.meta.telegramAuthResult=void 0,t.meta.telegramWebAppData=Oe(e.launchParams.initDataRaw),ne({telegramAuthModalData:{seamlessAuth:!0}}),Be("TelegramAuthScreen")}else A.emitPrivyEvent(be,"linkAccount","onError",c.PrivyErrorCode.INVALID_DATA,{linkMethod:"telegram"});else await wt.initLoginWithTelegram();Be("TelegramAuthScreen")},linkFarcaster:async()=>{Ze("farcaster"),ct("farcaster"),await wt.initLoginWithFarcaster(),je.current="link",Fe.current="farcaster",Be("FarcasterConnectStatusScreen")},updateEmail:()=>{if(Ze("email"),!_?.email)throw new c.PrivyClientError("User does not have an email linked to their account.");je.current="update",Fe.current="email",Be("UpdateEmailScreen")},updatePhone:()=>{if(Ze("sms"),!_?.phone)throw new c.PrivyClientError("User does not have a phone number linked to their account.");je.current="update",Fe.current="sms",Be("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=>{se((t=>e.bind(t)))}));if(se(null),e)return void console.warn(t)}!_||_.isGuest?(je.current="login",ne({login:e}),Be("LandingScreen")):console.warn(t)},connectOrCreateWallet:async()=>{T||(await new Promise((e=>{se((()=>e))})),se(null)),xe?console.warn("User must be unauthenticated to `connectOrCreateWallet`"):(je.current="connect-or-create",Be("ConnectOrCreateScreen"))},logout:async()=>{if(je.current=null,Fe.current=null,_&&i.clearProviderAcccessTokens(_),M(null),await i.logout(),_&&Z)try{await Z.clearMfa({userId:_.id})}catch(e){}Gt(null),Me(!1),H({status:"initial"}),V({status:"initial"}),z({status:"initial"}),G({status:"initial"}),J({status:"initial"}),X({status:"initial"}),A.emitPrivyEvent(be,"logout","onSuccess"),C(!1),d.s.del(p.CLIENT_ANALYTICS_ID_KEY),d.s.del(p.getGuestCredentialStorageKey(h.id))},getAccessToken:t.useCallback((async()=>{let e=await i.getCustomerAccessToken();return e&&!xe&&Me(!0),e}),[i,xe]),unlinkWallet:async e=>{let t;return Gt(t=e.startsWith("0x")?await i.unlinkEthereumWallet(e):await i.unlinkSolanaWallet(e)),t},unlinkEmail:async e=>{let t=await i.unlinkEmail(e);return Gt(t),t},unlinkPhone:async e=>{let t=await i.unlinkPhone(e);return Gt(t),t},unlinkGoogle:async e=>{let t=await i.unlinkOAuth("google",e);return Gt(t),t},unlinkTwitter:async e=>{let t=await i.unlinkOAuth("twitter",e);return Gt(t),t},unlinkTwitch:async e=>{let t=await i.unlinkOAuth("twitch",e);return Gt(t),t},unlinkDiscord:async e=>{let t=await i.unlinkOAuth("discord",e);return Gt(t),t},unlinkGithub:async e=>{let t=await i.unlinkOAuth("github",e);return Gt(t),t},unlinkSpotify:async e=>{let t=await i.unlinkOAuth("spotify",e);return Gt(t),t},unlinkInstagram:async e=>{let t=await i.unlinkOAuth("instagram",e);return Gt(t),t},unlinkTiktok:async e=>{let t=await i.unlinkOAuth("tiktok",e);return Gt(t),t},unlinkLine:async e=>{let t=await i.unlinkOAuth("line",e);return Gt(t),t},unlinkLinkedIn:async e=>{let t=await i.unlinkOAuth("linkedin",e);return Gt(t),t},unlinkApple:async e=>{let t=await i.unlinkOAuth("apple",e);return Gt(t),t},unlinkFarcaster:async e=>{let t=await i.unlinkFarcaster(e);return Gt(t),t},unlinkTelegram:async e=>{let t=await i.unlinkTelegram(e);return Gt(t),t},unlinkPasskey:async e=>{let t=await ie();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 Gt(n),n},unlinkCrossAppAccount:async({subject:e})=>{let t=_?.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 Gt(r),r},setWalletRecovery:async e=>dt({legacySetWalletPasswordFlow:!1,showAutomaticRecovery:e?.showAutomaticRecovery??!1}),setWalletPassword:async()=>dt({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(_,t.address):a.getPrivyEthereumWallet(_);if(!p&&void 0!==t?.address){let e=a.getConnectedWalletWithAddress(Vt(),t.address);if(e)try{let t=await e.getEthereumProvider(),r=await t.request({method:"personal_sign",params:[h,e.address]});return A.emitPrivyEvent(be,"signMessage","onSuccess",{signature:r}),void n({signature:r})}catch(e){return A.emitPrivyEvent(be,"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(!xe||!_)return A.emitPrivyEvent(be,"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:g,entropyIdVerifier:v}=l.getEntropyDetailsForUser(_,p),f=a.getIsUnifiedWallet(p);if("string"!=typeof h||h.length<1)return A.emitPrivyEvent(be,"signMessage","onError",c.PrivyErrorCode.INVALID_MESSAGE),void o(Error("Message must be a non-empty string"));let E=async()=>{let t;if(!xe)throw Error("User must be authenticated before signing with a Privy wallet");let n=await ie();if(!Z||!n||!await wt.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:g,entropyIdVerifier:v,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(He({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await E();A.emitPrivyEvent(be,"signMessage","onSuccess",{signature:e}),n({signature:e})}catch(e){A.emitPrivyEvent(be,"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=>{A.emitPrivyEvent(be,"signMessage","onSuccess",{signature:e}),n({signature:e})},onFailure:e=>{A.emitPrivyEvent(be,"signMessage","onError",c.PrivyErrorCode.UNABLE_TO_SIGN),o(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:p.recoveryMethod,connectingWalletAddress:y,entropyId:g,entropyIdVerifier:v,onCompleteNavigateTo:"SignRequestScreen",isUnifiedWallet:f,onFailure:e=>{A.emitPrivyEvent(be,"signMessage","onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),o(e)}}}),Be("EmbeddedWalletConnectingScreen")})),signTypedData:(e,t)=>new Promise((async(n,u)=>{let{requesterAppId:h}=t?.uiOptions||{},p=t?.address?a.getPrivyWalletWithAddress(_,t.address):a.getPrivyEthereumWallet(_);if(!p&&t?.address){let r=a.getConnectedWalletWithAddress(Vt(),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 A.emitPrivyEvent(be,"signTypedData","onSuccess",{signature:a}),void n({signature:a})}catch(e){return A.emitPrivyEvent(be,"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(!xe||!_)return A.emitPrivyEvent(be,"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:g}=l.getEntropyDetailsForUser(_,p),v=a.getIsUnifiedWallet(p),f=o.generateTypedDataWithDomainType(e),E=async()=>{let e;if(!xe)throw Error("User must be authenticated before signing with a Privy wallet");let t=await ie();if(!Z||!t||!await wt.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}}),v){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:g,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(He({showWalletUIs:t?.uiOptions?.showWalletUIs}))try{let e=await E();A.emitPrivyEvent(be,"signTypedData","onSuccess",{signature:e}),n({signature:e})}catch(e){A.emitPrivyEvent(be,"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=>{A.emitPrivyEvent(be,"signTypedData","onSuccess",{signature:e}),n({signature:e})},onFailure:e=>{A.emitPrivyEvent(be,"signTypedData","onError",c.PrivyErrorCode.UNABLE_TO_SIGN),u(e)},uiOptions:t?.uiOptions||{}},connectWallet:{recoveryMethod:p.recoveryMethod,connectingWalletAddress:p.address,entropyId:m,isUnifiedWallet:v,entropyIdVerifier:g,onCompleteNavigateTo:"SignRequestScreen",onFailure:e=>{A.emitPrivyEvent(be,"signMessage","onError",c.PrivyErrorCode.UNKNOWN_CONNECT_WALLET_ERROR),u(e)}}}),Be("EmbeddedWalletConnectingScreen")})),sendTransaction:async(e,t)=>await nt({transaction:e,sponsor:t?.sponsor,uiOptions:t?.uiOptions,fundWalletConfig:t?.fundWalletConfig,address:t?.address,signOnly:!1}),signTransaction:async(e,t)=>({signature:(await nt({transaction:e,uiOptions:t?.uiOptions,address:t?.address,signOnly:!0})).hash}),promptMfa:it,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");we.current?.resolve({mfaMethod:e,mfaCode:t,relyingParty:window.origin}),await new Promise(((e,t)=>{Ce.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=Ht(await r.startAuthentication({optionsJSON:t}));we.current?.resolve({mfaMethod:e,mfaCode:n,relyingParty:window.origin}),await new Promise(((e,t)=>{Ce.current={resolve:e,reject:t}}));break;default:throw we.current?.reject(new c.PrivyClientError("Unsupported MFA method")),new c.PrivyClientError(`Unsupported MFA method: ${e}`)}},cancel(){we.current?.reject(new c.PrivyClientError("MFA canceled"))},async initEnrollmentWithSms(e){let t=await ie();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 wt.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}}),Be("MfaEnrollmentFlowScreen")})),async initEnrollmentWithTotp(){let e=await ie();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 ie();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}),Gt(await i.getAuthenticatedUser())},async submitEnrollmentWithTotp(e){let t=await ie();if(!t||!Z)throw Error("Must have valid access token to enroll in MFA");await Z.submitEnrollMfa({method:"totp",accessToken:t,code:e.mfaCode}),Gt(await i.getAuthenticatedUser())},async initEnrollmentWithPasskey(){},async submitEnrollmentWithPasskey({credentialIds:e},t={}){let r=await ie();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}),Gt(await i.getAuthenticatedUser())},async unenroll(e,t={}){let r=await ie();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}),Gt(await i.getAuthenticatedUser())},requestFarcasterSignerFromWarpcast:async()=>{let e=await ie(),t=_?.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(!_?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await wt.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&&Gt(await i.getAuthenticatedUser()||_||null),ne({farcasterSigner:r}),Be("FarcasterSignerStatusScreen")},getFarcasterSignerPublicKey:async()=>{let e,t=await ie(),r=_?.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(!_?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await wt.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!_.farcaster?.signerPublicKey)throw Error("Must have a Farcaster signer public key to sign");return e=_.farcaster.signerPublicKey.slice(2),Uint8Array.from(e.match(/.{1,2}/g).map((e=>parseInt(e,16))))},signFarcasterMessage:async e=>{let t=await ie(),r=_?.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(!_?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");if(!await wt.recoverEmbeddedWallet({address:r.address}))throw Error("Unable to connect to wallet");if(!_.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(_.farcaster.fid),relyingParty:window.origin});return new Uint8Array(n.base64URLStringToBuffer(i.signature))},signMessageWithCrossAppWallet(e,{address:t,chainId:r}){let n=_?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return It({user:_,client:i,address:t,requesterAppId:h.id,request:{method:n?"privy_signSmartWalletMessage":"personal_sign",params:[e,t],chainId:r},reconnect:ut})},signTypedDataWithCrossAppWallet(e,{address:t,chainId:r}){let n=_?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t)))),a=o.generateTypedDataWithDomainType(e);return It({user:_,client:i,address:t,requesterAppId:h.id,request:{method:n?"privy_signSmartWalletTypedData":"eth_signTypedData_v4",params:[t,a],chainId:r},reconnect:ut})},sendTransactionWithCrossAppWallet(e,{address:t}){let r=_?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return It({user:_,client:i,address:t,requesterAppId:h.id,request:{method:r?"privy_sendSmartWalletTx":"eth_sendTransaction",params:[e],chainId:e.chainId},reconnect:ut})},signTransactionWithCrossAppWallet(e,{address:t}){let r=_?.linkedAccounts.some((e=>"cross_app"===e.type&&e.smartWallets.some((e=>e.address===t))));return It({user:_,client:i,address:t,requesterAppId:h.id,request:{method:r?"privy_signSmartWalletTx":"eth_signTransaction",params:[e],chainId:e.chainId},reconnect:ut})},isModalOpen:E||!!P,mfaMethods:h.mfa.methods};sr=pt.signMessage,or=pt.signTypedData,cr=async(e,t)=>await nt({transaction:e,...t,signOnly:!1}),lr=async(e,t)=>({signature:(await nt({transaction:e,...t,signOnly:!0})).hash});let yt=async e=>{let t,r,n;D(!0),J({status:"loading"}),i.startAuthFlow(new fe({...e,customOAuthRedirectUrl:h.customOAuthRedirectUrl}));let a=d.s.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??""}}),D(!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()),Fe.current=e.provider;let r=at(t);t&&r&&A.emitPrivyEvent(be,"linkAccount","onSuccess",{user:t,linkMethod:Fe.current,linkedAccount:r})}catch(t){throw D(!1),A.emitPrivyEvent(be,"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()),Fe.current=e.provider;let a=at(t);t&&a&&void 0!==r&&A.emitPrivyEvent(be,"login","onComplete",{user:t,isNewUser:r,wasAlreadyAuthenticated:!1,loginMethod:Fe.current,loginAccount:a})}catch(e){throw D(!1),J({status:"error",error:e}),A.emitPrivyEvent(be,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}return Gt(t),O(r||!1),Me(!0),D(!1),J({status:"done"}),n&&t&&A.emitPrivyEvent(be,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),t??void 0},wt={privy:s,setAuthenticated:Me,setUser:Gt,setIsNewUser:O,isNewUserThisSession:R,pendingTransaction:null,walletConnectionStatus:L,setWalletConnectionStatus:j,connectors:i.connectors?.walletConnectors??[],rpcConfig:h.rpcConfig,chains:h.chains,appId:n.appId,showFiatPrices:"native-token"!==h.embeddedWallets.priceDisplay.primary,clientAnalyticsId:i.clientAnalyticsId,hideWalletUIs:Ke,isHeadlessSigning:t.useCallback(He,[h.embeddedWallets.showWalletUIs]),emailOtpState:K,setEmailOtpState:H,smsOtpState:B,setSmsOtpState:V,oAuthState:$,setOAuthState:J,telegramAuthState:Q,setTelegramAuthState:X,siweState:Y,setSiweState:G,isHeadlessOAuthLoading:F,baseAccountSdk:U,setBaseAccountSdk:x,nativeTokenSymbolForChainId:e=>h.chains.find((t=>t.id===Number(e)))?.nativeCurrency.symbol,initializeWalletProxy:async e=>{if(Z)return Z;let t=new Promise((e=>{ce.current=e})),r=new Promise((t=>setTimeout((()=>t(null)),e))),n=await Promise.race([t,r]);return ce.current=null,n},getAuthFlow:()=>i.authFlow,getAuthMeta:()=>i.authFlow?.meta,client:i,closePrivyModal:async(e={shouldCallAuthOnSuccess:!0,isSuccess:!1})=>{let t,r=T&&xe&&_;if(r&&Fe.current&&(t=at(_)),"login"===je.current)e.shouldCallAuthOnSuccess&&r&&Fe.current?A.emitPrivyEvent(be,"login","onComplete",{user:_,isNewUser:R,wasAlreadyAuthenticated:!1,loginMethod:Fe.current,loginAccount:t??null}):A.emitPrivyEvent(be,"login","onError",c.PrivyErrorCode.USER_EXITED_AUTH_FLOW);else if("link"===je.current&&t)e.isSuccess&&r&&Fe.current?A.emitPrivyEvent(be,"linkAccount","onSuccess",{user:_,linkMethod:Fe.current,linkedAccount:t}):Fe.current&&A.emitPrivyEvent(be,"linkAccount","onError",c.PrivyErrorCode.USER_EXITED_LINK_FLOW,{linkMethod:Fe.current});else if("update"===je.current&&t)e.isSuccess&&r&&Fe.current?A.emitPrivyEvent(be,"update","onSuccess",{user:_,updateMethod:Fe.current,updatedAccount:t}):Fe.current&&A.emitPrivyEvent(be,"update","onError",c.PrivyErrorCode.USER_EXITED_UPDATE_FLOW,{linkMethod:Fe.current});else if("connect-or-create"===je.current){let e=Vt();e[0]?A.emitPrivyEvent(be,"connectOrCreateWallet","onSuccess",{wallet:e[0]}):A.emitPrivyEvent(be,"connectOrCreateWallet","onError",c.PrivyErrorCode.USER_EXITED_AUTH_FLOW)}let a=N&&Mt.has(N),s="ErrorScreen"===N&&re.errorModalData&&Mt.has(re.errorModalData.previousScreen);if((a||s)&&re.funding){let e,t=Mt.get(N)??null;if(s&&re.funding?.onError){let e=re.errorModalData?.error,t=e?.privyErrorCode||c.PrivyErrorCode.UNKNOWN_FUNDING_ERROR,r=new c.PrivyClientError(e?.message||"Funding failed",e,t);re.funding?.onError?.(r)}if("solana"===re.funding.chainType){let r=h.solanaRpcs[re.funding.chain];if(!r)return console.warn("Unable to load solana rpc, skipping balance"),A.emitPrivyEvent(be,"fundSolanaWallet","onUserExited",{address:re.funding.address,fundingMethod:t,chain:re.funding.chain,balance:e}),C(!1),void Nt(re.funding,t);if(u(f.SOLANA_FUNDING_PLUGIN_ID))try{e=await Dt({rpc:r.rpc,address:re.funding.address})}catch{console.error("Unable to pull wallet balance")}else console.warn("Unable to load solana plugin, skipping balance");A.emitPrivyEvent(be,"fundSolanaWallet","onUserExited",{address:re.funding.address,fundingMethod:t,chain:re.funding.chain,balance:e})}else{let r=W.getPublicClient(re.funding.chain.id,h.chains,h.rpcConfig,{appId:n.appId});try{e=await r.getBalance({address:re.funding.address})}catch{console.error("Unable to pull wallet balance")}A.emitPrivyEvent(be,"fundWallet","onUserExited",{address:re.funding.address,chain:re.funding.chain,fundingMethod:t,balance:e}),Nt(re.funding,t)}}ne((e=>({...e,externalConnectWallet:{}}))),je.current=null,Fe.current=null,O(!1),C(!1),j({status:"disconnected",connectedWallet:null,connector:null,connectError:null,connectRetry:()=>{}}),setTimeout((()=>{i.authFlow=void 0}),200)},openPrivyModal:Be,connectWallet:$e,initLoginWithWallet:async(e,t,r,n)=>{o.isBaseConnectedEthereumWallet(e)?(Fe.current="siwe",Je(e,t,r)):(Fe.current="siws",Qe(e,t,r,n))},loginWithWallet:async()=>{let e,t,r;if(!T)throw new c.PrivyNotReadyError;if(i.authFlow instanceof Te?e="siwe":i.authFlow instanceof ke&&(e="siws"),!e)throw new c.PrivyClientError("Must initialize SIWE/SIWS flow first.");if(null!==await i.getAccessToken())try{({user:t}=await i.link()),Fe.current=e}catch(t){throw A.emitPrivyEvent(be,"linkAccount","onError",t.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}else try{({user:t,isNewUser:r}=await i.authenticate()),Fe.current=e}catch(e){throw A.emitPrivyEvent(be,"login","onError",e.privyErrorCode||c.PrivyErrorCode.GENERIC_CONNECT_WALLET_ERROR),e}Gt(t||_||null),O(r||!1),Me(!0)},delegateWallet:async({address:e,chainType:t,showDelegationUIs:r})=>new Promise((async(n,i)=>{let s=await ie();if(!xe||!_||!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=wt.walletProxy??await wt.initializeWalletProxy(15e3);if(!o)throw new c.PrivyClientError("Wallet proxy not initialized.");if((({address:e,user:t})=>!!Tt(t).find((t=>t.address===e)))({address:e,user:_}))return n();let l=a.getPrivyWalletWithAddress(_,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=At({address:e,user:_}),u=Pt({address:e,user:_}),h=async()=>{await o.createDelegatedAction({accessToken:s,rootWallet:u,delegatedWallets:[d]}),await wt.refreshSessionAndUser()};if(await wt.recoverEmbeddedWallet({address:e}),r)ne({delegatedActions:{consent:{address:e,onDelegate:h,onSuccess:async()=>{n()},onError:async e=>{i(e)}}}}),Be("DelegatedActionsConsentScreen");else try{await h(),n()}catch(e){i(e)}})),revokeDelegatedWallets:async({showDelegationUIs:e})=>new Promise((async(t,r)=>{if(!xe||!_)throw new c.PrivyClientError("User must be authenticated and have an embedded wallet to revoke a delegated wallet.");let n=Tt(_);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 wt.refreshSessionAndUser()};if(e)ne({delegatedActions:{revoke:{onRevoke:s,onSuccess:async()=>{t()},onError:async e=>{r(e)}}}}),Be("DelegatedActionsRevokeScreen");else try{await s(),t()}catch(e){r(e)}})),initLoginWithFarcaster:async(e,t)=>{let r=new de(e,t);i.startAuthFlow(r);try{Fe.current="farcaster",await r.initializeFarcasterConnect()}catch(e){throw"login"===je.current?A.emitPrivyEvent(be,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===je.current&&A.emitPrivyEvent(be,"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 de))throw new c.PrivyClientError("Must initialize Farcaster flow first.");if(null!==await i.getAccessToken())try{({user:e}=await i.link()),Fe.current="farcaster"}catch(e){throw A.emitPrivyEvent(be,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"farcaster"}),e}else try{({user:e,isNewUser:t}=await i.authenticate()),Fe.current="farcaster"}catch(e){throw A.emitPrivyEvent(be,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Gt(e||null),O(t||!1),Me(!0)},async crossAppAuthFlow({appId:e,popup:t,action:r,disableSignup:n}){let a=`privy:${e}`;Fe.current=a;let{url:s,stateCode:o,codeVerifier:l}=await async function({api:e,appId:t}){let r=me(),n=ge(),i=await ve(r);try{let{url:a}=await e.post(v.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(!s)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 d=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===_t&&((n=new BroadcastChannel(kt)).onmessage=o))}window.addEventListener("message",o)}))}({url:s,popup:t,provider:a}),u=d.stateCode,h=d.authorizationCode;if(u!==o)throw i.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:a,storedStateCode:o??"",returnedStateCode:u??""}}),new c.PrivyClientError("Unexpected auth flow. This may be a phishing attempt.",void 0,c.PrivyErrorCode.OAUTH_UNEXPECTED);let p=await async function({appId:e,stateCode:t,codeVerifier:r,authorizationCode:n,action:i,client:a,disableSignup:s}){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 o=new St({authorizationCode:n,stateCode:t,codeVerifier:r,provider:`privy:${e}`,disableSignup:!!s});a.startAuthFlow(o);let l="link"===i?await a.link():await a.authenticate(),c=l.oAuthTokens?.accessToken;return console.debug(),c}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:l,stateCode:u,authorizationCode:h,action:r,client:i,disableSignup:n});p&&i.storeProviderAccessToken(e,p);let y=await wt.refreshSessionAndUser();if(!y)throw new c.PrivyClientError("Unable to update user");return i.createAnalyticsEvent({eventName:"cross_app_auth_completed",payload:{providerAppId:e}}),y}catch(e){throw i.createAnalyticsEvent({eventName:"cross_app_auth_error",payload:{error:e.toString(),provider:a}}),e}},async initLoginWithOAuth(e,t,r){if(Fe.current=e,!d.e())return void Be("InAppBrowserLoginNotPossible");if("google"===e&&!h.allowOAuthInEmbeddedBrowsers&&Ft(window.navigator.userAgent))return void Be("InAppBrowserLoginNotPossible");"twitter"===e&&window.opener&&window.opener.postMessage({type:_t},"*"),d.s.del(p.HEADLESS_OAUTH_KEY),d.s.del(p.OAUTH_DISABLE_SIGNUP_KEY);let n=new fe({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&&pe())try{let{privyOAuthCode:e,privyOAuthState:t}=await ye(a.url);Be("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;Fe.current="telegram";let r=new Re(e,t);i.startAuthFlow(r),X({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"===je.current?A.emitPrivyEvent(be,"linkAccount","onError",c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}):"login"===je.current?A.emitPrivyEvent(be,"login","onError",c.PrivyErrorCode.INVALID_CREDENTIALS):"update"===je.current&&A.emitPrivyEvent(be,"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 Re))throw new c.PrivyClientError("Must initialize Telegram flow before calling loginWithTelegram");i.authFlow.meta.captchaToken||=e?.captchaToken;let n=await ie(),a=e?.intent||je.current;if("login"===a)try{let e=await i.authenticate();t=e.user,r=e.isNewUser,Fe.current="telegram"}catch(e){throw A.emitPrivyEvent(be,"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,Fe.current="telegram"}catch(e){throw A.emitPrivyEvent(be,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"telegram"}),e}}Gt(t),O(r||!1),Me(!0),X({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 fe))throw new c.PrivyClientError("Must initialize OAuth flow before calling loginWithOAuth");let a=d.s.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,Fe.current=e}catch(t){throw A.emitPrivyEvent(be,"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,Fe.current=e}catch(t){throw"login"===je.current?A.emitPrivyEvent(be,"login","onError",t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===je.current&&A.emitPrivyEvent(be,"linkAccount","onError",t.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:e}),t}return Gt(t),O(r||!1),Me(!0),n&&t&&A.emitPrivyEvent(be,"oAuthAuthorization","onOAuthTokenGrant",{oAuthTokens:n,user:t}),n},passkeyAuthState:q,setPasskeyAuthState:z,async initSignupWithPasskey({captchaToken:e,withPrivyUi:t}){let r=new Ae({captchaToken:e,setPasskeyAuthState:z,hints:h.passkeys.registration?.hints});i.startAuthFlow(r),je.current="login";try{Fe.current="passkey",z({status:"generating-challenge"}),await r.initRegisterFlow(t),z({status:"awaiting-passkey"})}catch(e){throw z({status:"error",error:e}),A.emitPrivyEvent(be,"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 Ae))throw new c.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Fe.current){let e=new c.PrivyClientError("Must init login with Passkey flow first.");throw z({status:"error",error:e}),e}let r=await ie();try{Fe.current="passkey",z({status:"awaiting-passkey"}),({user:e,isNewUser:t}=await i.authenticate())}catch(e){throw z({status:"error",error:e}),A.emitPrivyEvent(be,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Gt(e),O(t||!1),Me(!0),z({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 Ae({captchaToken:e,setPasskeyAuthState:z,hints:void 0});i.startAuthFlow(r),je.current="login";try{Fe.current="passkey",z({status:"generating-challenge"}),await r.initAuthenticationFlow(t),z({status:"awaiting-passkey"})}catch(e){throw z({status:"error",error:e}),A.emitPrivyEvent(be,"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 Ae))throw new c.PrivyClientError("Must initialize Passkey flow first.");if(e?.credentialIds&&(i.authFlow.meta.allowedCredentialsIds=e.credentialIds),"passkey"!==Fe.current){let e=new c.PrivyClientError("Must init login with Passkey flow first.");throw z({status:"error",error:e}),e}let n=await ie();try{Fe.current="passkey",z({status:"awaiting-passkey"}),({user:t,isNewUser:r}=await i.authenticate())}catch(e){throw z({status:"error",error:e}),A.emitPrivyEvent(be,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}Gt(t),O(r||!1),Me(!0),z({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 Ae({captchaToken:e,hints:h.passkeys.registration?.hints});i.startAuthFlow(t),je.current="link",Fe.current="passkey",z({status:"generating-challenge"});try{await t.initLinkFlow(),z({status:"awaiting-passkey"})}catch(e){throw A.emitPrivyEvent(be,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),z({status:"error",error:e}),e}},async linkWithPasskey(){let e;if(!T)throw new c.PrivyNotReadyError;if(!(i.authFlow instanceof Ae))throw new c.PrivyClientError("Must initialize Passkey flow first.");if("passkey"!==Fe.current)throw new c.PrivyClientError("Must init login with Passkey flow first.");try{Fe.current="passkey",({user:e}=await i.link())}catch(e){throw A.emitPrivyEvent(be,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"passkey"}),e}return Gt(e||_||null),z({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&&Ft(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 fe({provider:e,withPrivyUi:!1,disableSignup:r??!1,customOAuthRedirectUrl:h.customOAuthRedirectUrl});t&&n.addCaptchaToken(t),J({status:"loading"});let a=await i.startAuthFlow(n).getAuthorizationUrl();if(a?.url)if("chrome-extension:"===window.location.protocol&&pe())try{let{privyOAuthCode:e,privyOAuthState:t}=await ye(a.url);n.meta.stateCode=t,n.meta.authorizationCode=e,await yt(n.meta)}catch(e){throw J({status:"error",error:e}),e}else window.location.assign(a.url)},loginWithHeadlessOAuth:yt,initLoginWithEmail:async({email:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{let a=new oe({email:e,captchaToken:t,disableSignup:r});i.startAuthFlow(a);try{Fe.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"===je.current?A.emitPrivyEvent(be,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===je.current&&A.emitPrivyEvent(be,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"email"}),e}},initUpdateEmail:async({oldAddress:e,newAddress:t,captchaToken:r})=>{let n=new le(e,t,r);i.startAuthFlow(n);try{await n.sendCodeEmail({withPrivyUi:!0})}catch(e){throw A.emitPrivyEvent(be,"update","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:Fe.current}),e}},initUpdatePhone:async(e,t,r)=>{let n=new Se(e,t,r);i.startAuthFlow(n);try{await n.sendSmsCode({withPrivyUi:!0})}catch(e){A.emitPrivyEvent(be,"update","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR,{linkMethod:Fe.current})}},initLoginWithSms:async({phoneNumber:e,captchaToken:t,disableSignup:r,withPrivyUi:n})=>{V({status:"sending-code"});let a=new _e({phoneNumber:e,captchaToken:t,disableSignup:r});i.startAuthFlow(a);try{Fe.current="sms",await a.sendSmsCode({withPrivyUi:n}),V({status:"awaiting-code-input"})}catch(e){throw V({status:"error",error:e}),"login"===je.current?A.emitPrivyEvent(be,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR):"link"===je.current&&A.emitPrivyEvent(be,"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 oe?H(e):i.authFlow instanceof _e&&V(e)}if(n({status:"submitting-code"}),!T){let e=new c.PrivyNotReadyError;throw n({status:"error",error:e}),e}if(i.authFlow instanceof oe)i.authFlow.meta.emailCode=e.trim();else{if(!(i.authFlow instanceof _e)){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 ie();if("link"===je.current)try{({user:t}=await i.link())}catch(e){throw n({status:"error",error:e}),A.emitPrivyEvent(be,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:Fe.current}),e}else if("update"===je.current)try{({user:t}=await i.link())}catch(e){throw n({status:"error",error:e}),A.emitPrivyEvent(be,"update","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_UPDATE_ACCOUNT,{linkMethod:Fe.current}),e}else try{({user:t,isNewUser:r}=await i.authenticate())}catch(e){throw n({status:"error",error:e}),A.emitPrivyEvent(be,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),e}let s=t||_;Gt(s||null),O(r||!1),Me(!0),n({status:"done"});let o=null;return i.authFlow instanceof oe?o=s?.linkedAccounts.find((({type:e})=>"email"===e))||null:i.authFlow instanceof _e&&(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})=>{je.current=xe?"link":"login",Fe.current="siwe",G({status:"generating-message"});let n=await i.generateSiweNonce({address:e,captchaToken:r});return G({status:"awaiting-signature"}),Pe({address:e,chainId:t.replace("eip155:",""),nonce:n})},generateSiweMessageForSmartWallet:async({address:e,chainId:t})=>{let r=await i.generateSiweNonce({address:e});return Pe({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}),Gt((a=await wt.refreshSessionAndUser()??a)||_||null)},loginWithSiwe:async({message:e,signature:t,captchaToken:r,disableSignup:n,walletClientType:a,connectorType:s})=>{let o,l=null;try{if(_)throw Error("User already authenticated");let c=new Te(i,void 0,r,n,{message:e,signature:t,walletClientType:a,connectorType:s});i.startAuthFlow(c),Fe.current="siwe",je.current="login",G({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 A.emitPrivyEvent(be,"login","onError",e.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),G({status:"error",error:e}),e}return Gt(l),O(o||!1),Me(!0),G({status:"done"}),je.current=null,Fe.current=null,{user:l,isNewUser:o||!1}},linkWithSiwe:async({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a})=>{let s;Ze("siwe");let o=null;try{G({status:"submitting-signature"}),s=await i.linkWithSiwe({message:e,signature:t,chainId:r,walletClientType:n,connectorType:a}),s=await wt.refreshSessionAndUser()??s,G({status:"done"}),(o=at(s)||null)&&A.emitPrivyEvent(be,"linkAccount","onSuccess",{user:s,linkMethod:"siwe",linkedAccount:o})}catch(e){throw A.emitPrivyEvent(be,"linkAccount","onError",e.privyErrorCode||c.PrivyErrorCode.FAILED_TO_LINK_ACCOUNT,{linkMethod:"siwe"}),je.current=null,Fe.current=null,G({status:"error",error:e}),e}let l=s||_;return Gt(l||null),je.current=null,Fe.current=null,{user:l,linkedAccount:o}},refreshSessionAndUser:async()=>{let e=await i.getAuthenticatedUser();return Me(!!e),Gt(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 Gt(e),e},getUsdTokenPrice:e=>i.getUsdTokenPrice(e),getUsdPriceForSol:()=>i.getUsdPriceForSol(),getSplTokenMetadata:e=>i.getSplTokenMetadata(e),recoverEmbeddedWallet:async e=>new Promise((async(t,r)=>{if(!_)return void t(!0);let n=e?.address?a.getPrivyWalletWithAddress(_,e.address):a.getPrivyPrimaryWallet(_)||a.getImportedPrivyEthereumWallets(_).at(0)||a.getImportedPrivySolanaWallets(_).at(0);if(!n||a.getIsUnifiedWallet(n))return void t(!0);let s=await ie();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(_,n);try{await Z.connect({accessToken:s,entropyId:o,entropyIdVerifier:c}),t(!0)}catch(e){if(ht(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 ht(e)&&"privy"!==n.recoveryMethod&&"privy-v2"!==n.recoveryMethod?(ne((e=>({...e,recoverWallet:{entropyId:o,entropyIdVerifier:c,onFailure:r,onSuccess:()=>{t(!0)},onCompleteNavigateTo:e.createWallet?"EmbeddedWalletOnAccountCreateScreen":void 0},recoveryOAuthStatus:{provider:n.recoveryMethod,action:"recover",shouldCreateEth:!1,shouldCreateSol:!1,isInAccountCreateFlow:!!e.createWallet}}))),Be(Ot(n.recoveryMethod))):r(e)}})),setReadyToTrue:e=>{k(!0),ae?.(e)},updateWallets:()=>tt(),fundWallet:async(e,t)=>{let r="FundingMethodSelectionScreen";return new Promise(((n,i)=>{ne({funding:{...d.prepareFundingModalData({address:e,appConfig:h,fundWalletConfig:t,methodScreen:r,onComplete:n,onError:i})}}),Be(r)}))},openModal:Be,requestFarcasterSignerStatus:async e=>{let t=await ie(),r=_?.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(!_?.farcaster?.fid)throw Error("Must have Farcaster account to use Farcaster signers");let n=await i.requestFarcasterSignerStatus(e);return"approved"===n.status&&Gt(await i.getAuthenticatedUser()||_||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"),$e(e);await Ge("coinbase_wallet","coinbase_smart_wallet")},connectBaseAccount:async()=>{let e=i.connectors?.findWalletConnector("base_account","base_account");if(e)return $e(e);await Ge("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 Gt(c),c},inProgressAuthFlowRef:je,inProgressLoginOrLinkMethodRef:Fe};dr=wt.recoverEmbeddedWallet,wt.recoverEmbeddedWallet;let mt=t.useMemo((()=>({wallets:S,ready:ue&&Ie})),[S,ue,Ie]),gt=i.authFlow instanceof Re,{siteKey:vt,enabledProvider:ft}=h.captcha,Et=!h.headless&&ft&&!xe&&(T||gt);/*#__PURE__*/return e.jsx(ar.Provider,{value:!0,children:/*#__PURE__*/e.jsx(a.PrivyContext.Provider,{value:pt,children:/*#__PURE__*/e.jsx(A.PrivyEventsContext.Provider,{value:be,children:/*#__PURE__*/e.jsx(l.UseWalletsContext.Provider,{value:mt,children:/*#__PURE__*/e.jsx(We,{appId:h.id,captchaSiteKey:vt,enabledCaptchaProvider:ft,children:/*#__PURE__*/e.jsxs(c.InternalPrivyContext.Provider,{value:wt,children:[/*#__PURE__*/e.jsx(o.RecentlyUsedAccountProvider,{children:/*#__PURE__*/e.jsxs(a.ModalProvider,{data:re,setModalData:ne,setInitialScreen:M,initialScreen:N,authenticated:xe,open:E,children:[n.children,/*#__PURE__*/e.jsx(ir,{customAuth:h.customAuth}),Et&&/*#__PURE__*/e.jsx(De,{delayedExecution:!1}),/*#__PURE__*/e.jsx(ot,{}),/*#__PURE__*/e.jsx(Kt,{disabled:h.embeddedWallets.disableAutomaticMigration}),/*#__PURE__*/e.jsx(ze,{palette:h.appearance.palette||{}}),!h.render.standalone&&/*#__PURE__*/e.jsx(rt,{open:E})]})}),/*#__PURE__*/e.jsx(Ct,{appId:n.appId,appClientId:n.clientId,clientAnalyticsId:i.clientAnalyticsId,origin:i.apiUrl,mfaMethods:_?.mfaMethods,mfaPromise:we,mfaSubmitPromise:Ce,onLoad:ee,onLoadFailed:()=>null}),h.loginConfig.telegramAuthConfiguration&&
|
|
174
|
-
/*#__PURE__*/e.jsx(o.Hide,{$if:!0,children:/*#__PURE__*/e.jsx(st,{scriptHost:n.apiUrl||p.DEFAULT_PRIVY_API_URL,botUsername:h.loginConfig.telegramAuthConfiguration.botName})})]})})})})})})};class hr extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class pr extends B.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new hr(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await ie()||!this.address)throw new hr("Disconnected",4900);let{hash:r}=await((e,t)=>cr(e,t))(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new hr(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await ie()||!this.address)throw new hr("Disconnected",4900);let{signature:r}=await((e,t)=>lr(e,t))(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new hr(`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 hr(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=W.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)=>sr(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)=>or(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=>ae.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await ie();if(await(e=>dr(e))({address:this.address}),!t||!this.address)throw new hr("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 hr("Disconnected",4900)}}}async handleWalletApiRequest(e,t,n){let i=this.privyClient;if(!i)throw new hr("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 hr(`Invalid params for ${e.method}`,4200);return a.data.signature}throw new hr(`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=W.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 yr=({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"})}),wr=({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 mr(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var gr=0;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{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 fr="__private_"+gr+++"__walletBranding";class Er 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 mr(this,fr)[fr]??{name:"Browser Extension",icon:yr,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,fr,{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?mr(this,fr)[fr]={name:"MetaMask",icon:o.Metamask,id:"io.metamask"}:"phantom"===i&&(mr(this,fr)[fr]={name:"Phantom",icon:wr,id:"phantom"})}}class Cr extends vr{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 Ar extends B.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")||o.shouldFetchWcRegistryListings(this.walletList)&&"ethereum-only"!==this.walletChainType,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 ne({provider:new pr({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 ne({provider:new pr({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 lt&&i.resetConnection(t),i;let a=(()=>"injected"!==e?"coinbase_wallet"===e?new te(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new Z(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new lt({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 Cr(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Er(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Er(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Er(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new vr(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 Pr=P.create((()=>({identityToken:null})));let Tr=[v.sessionsRefreshPath,v.sessionsLogoutPath,v.analyticsEventsPath];class kr{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=U.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=Tr.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}})}}const _r=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.s.get(t))return d.s.get(t);{let e=i.base64url.encode(we(32));return d.s.put(t,e),e}}return i.base64url.encode(we(32))}async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(v.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.s.get(e);return"string"==typeof t?Y.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=d.s.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.s.get(p.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return null;{let r=new Y(t);return r.isExpired()?(d.s.del(p.getProviderAccessTokenStorageKey(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=V.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=Y.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.s.put(p.getProviderAccessTokenStorageKey(e),t):d.s.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 oe?"email":e instanceof _e?"sms":e instanceof Te?"siwe":e instanceof Sr?"guest":e instanceof Jt?"custom_auth":e instanceof fe?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(v.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(v.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.s.get(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY);if(d.s.put(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY,e),!this.client?.useServerCookies){let t=Y.parse(e)?.expiration;V.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.s.del(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY),V.default.remove(p.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(d.s.put(p.REFRESH_TOKEN_STORAGE_KEY,e),this.client?.useServerCookies||V.default.set(p.SESSION_COOKIE_KEY,"t",{sameSite:"Strict",secure:br(),expires:30})):(d.s.del(p.REFRESH_TOKEN_STORAGE_KEY),V.default.remove(p.REFRESH_TOKEN_COOKIE_KEY),V.default.remove(p.SESSION_COOKIE_KEY))}storePrivyAccessToken(e){"string"==typeof e?d.s.put(p.PRIVY_ACCESS_TOKEN_STORAGE_KEY,e):d.s.del(p.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}storeIdentityToken(e){if(Pr.setState({identityToken:e}),this.client?.useServerCookies)return;d.s.put(p.IDENTITY_TOKEN_STORAGE_KEY,e);let t=Y.parse(e)?.expiration;V.default.set(p.IDENTITY_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:br(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){d.s.del(p.IDENTITY_TOKEN_STORAGE_KEY),Pr.setState({identityToken:null}),V.default.remove(p.IDENTITY_TOKEN_COOKIE_KEY)}constructor(){this.authenticateOnce=new ce((async e=>this._authenticate(e))),this.linkOnce=new ce((async e=>this._link(e))),this.refreshOnce=new ce(this._refresh.bind(this)),this.destroyOnce=new ce(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 Ar(this.appId,e,t,r,n,i,a,s,o,l,d,c))}generateApi(){let e=new kr({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(v.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw c.formatApiError(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(v.mfaPasskeyInitPath,{});return _r(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(v.acceptTermsPath,{});return a.convertUserResponseToUser(e)}catch(e){throw c.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(v.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(v.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(v.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(v.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(v.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(v.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(v.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(v.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(v.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(v.moonpayPluginOnRampPath,e)}catch(e){throw c.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(v.coinbaseOnRampInitPath,e)}catch(e){throw c.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${v.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)?G.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 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(v.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(v.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(v.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(v.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(v.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(v.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=v.transferEmailPath,d={nonce:e,email:t};break;case"sms":c=v.transferPhonePath,d={nonce:e,phoneNumber:t};break;case"siwe":if(c=v.transferWalletPath,!n)throw Error("Wallet parameters must be defined");d={nonce:e,address:t,...n};break;case"farcaster":c=v.transferFarcasterPath,d={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":c=v.telegramAccountTransferPath,d={nonce:e,telegram_auth_result:i,telegram_web_app_data:s};break;case"siws":c=v.siwsTransferPath,d={nonce:e,address:t,...n};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:c=v.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(v.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(v.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(v.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.s.get(p.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=n.v4();try{return d.s.put(p.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}function Dr(){if(!Rr)throw new c.PrivyClientError("No global PrivyClient instance found. Please ensure you have initialized the PrivyProvider.");return Rr}const Lr=Symbol("cross-tab-user-sync-plugin");let jr=null,qr=null,zr=!1;const Kr=()=>{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}):qe.setState({inProgressMfaFlow:void 0}),a()},onFailure:async e=>{t?await i({shouldCallAuthOnSuccess:!1,isSuccess:!1}):qe.setState({inProgressMfaFlow:void 0}),o(e)},sendSmsCode:async()=>{throw Error("Not enabled")},verifySmsCode:async()=>{throw Error("Not enabled")},verifyTotpCode:async e=>{await n.fetchPrivyRoute(O.MfaAuthTotpVerify,{body:{code:e}})},generateOptions:async()=>_r((await n.fetchPrivyRoute(O.MfaAuthPasskeyInit,{body:{}})).options),verifyPasskey:async e=>{let t=await import("@simplewebauthn/browser"),r=await t.startAuthentication({optionsJSON:e});await n.fetchPrivyRoute(O.MfaAuthPasskeyVerify,{body:{authenticator_response:Ht(r)}})}}}))),void(t?r("MfaAuthVerifyFlowScreen"):qe.setState({inProgressMfaFlow:"auth"}))):o(Error("Must be logged in to verify MFA"))))})),[n,e,r,i])};const Hr=async({wallet:e})=>{let t=await e.getEthereumProvider();return D.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:n})=>{let i;if("string"==typeof n)i=n;else{if("string"!=typeof n.raw)throw new r.PrivyClientError({error:"signMessage only supports string messages or {raw: Hex} format",code:"invalid_input"});i=n.raw}return await t.request({method:"personal_sign",params:[i,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]}),signAuthorization:async n=>{if("privy"!==e.walletClientType)throw new r.PrivyClientError({error:"EIP-7702 authorization signing is not supported by external wallets.",code:"unsupported_wallet_type"});let i={chainId:n.chainId,address:n.contractAddress??n.address,nonce:n.nonce},a=m.hashAuthorization(i),s=S.parseSignature(await t.request({method:"secp256k1_sign",params:[a]}));return{...i,...s}}})};let Br=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 Vr=()=>{let{user:e}=a.usePrivyContext(),t=c.usePrivyInternal(),{signWithUserSigner:n}=L.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=At({address:n,user:e}),i=Pt({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}}}};const Yr=rt;exports.BASE_ACCOUNT_DATA_URI=J,exports.Blobby=re,exports.BrowserExtensionWallet=yr,exports.COINBASE_WALLET_DATA_URI=$,exports.Captcha=De,exports.CaptchaError=Ie,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=Ar,exports.LoginModal=Yr,exports.Phantom=wr,exports.PrivyClient=Mr,exports.PrivyIframeError=dt,exports.PrivyModal=rt,exports.PrivyProvider=({config:r,...n})=>{(()=>{if(t.useContext(ar))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 K.default({appId:n.appId,clientId:n.clientId,storage:d.s,baseUrl:n.apiUrl,sdkVersion:"react-auth:3.14.0"})),[]),a=Dr(),s=Object.assign({},r);/*#__PURE__*/return e.jsx(p.PrivyAppConfigProvider,{client:i,legacyClient:a,appClientId:n.clientId,clientConfig:s,children:/*#__PURE__*/e.jsx(b.PrivyPluginProvider,{configPlugins:r?.plugins,children:/*#__PURE__*/e.jsx(ur,{...n,client:a,privy:i})})})},exports.RunEffectOnce=ce,exports.SiweFlow=Te,exports.SiwsFlow=ke,exports.WalletConnectV2WalletConnector=lt,exports.addFundingResultToModalData=function(e,t,r,n,i,a,s){return{...e,funding:e?.funding?{...e.funding,fundingResult:{status:t,address:e.funding.address,fundingMethod:void 0,transactionHash:r,amount:e.funding.amount,assetType:i?a?.symbol||"ETH":s.nativeCurrency.symbol||"ETH",metadata:{walletClientType:n}}}:void 0,solanaFundingData:e?.solanaFundingData,sendTransaction:e?.sendTransaction}},exports.createCodeVerifier=me,exports.createCrossTabUserSyncPlugin=function(e){if(!e.channelId)throw Error("[Privy] Cross-tab sync plugin requires a channelId.");return"undefined"==typeof BroadcastChannel||jr||((jr=new BroadcastChannel(`PRIVY_CROSS_TAB_CHANNEL:${e.channelId}`)).onmessage=e=>{e.data.eventId!==qr&&(qr=e.data.eventId,zr=!0,Gt(e.data.user),$t(!!e.data.user),zr=!1)},Yt.subscribe(((e,t)=>{if(e.user===t.user||zr)return;let r=n.v4();qr=r,jr?.postMessage({user:e.user,eventId:r})}))),{id:Lr}},exports.createStateCode=ge,exports.deriveCodeChallengeFromCodeVerifier=ve,exports.e=Ft,exports.embeddedWalletRecoveryScreen=Ot,exports.embeddedWalletSetPasswordScreen=xt,exports.errorIndicatesInvalidRecoveryPassword=function(e){return ut(e)&&("invalid_recovery_pin"===e.type||"invalid_request_arguments"===e.type)},exports.errorIndicatesMaxMfaRetries=function(e){return!!ut(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!(!ut(e)||!e.message.includes("code 429"))},exports.errorIndicatesMfaTimeout=function(e){return!!ut(e)&&"mfa_timeout"===e.type},exports.errorIndicatesMfaVerificationFailed=function(e){return!!ut(e)&&"missing_or_invalid_mfa"===e.type},exports.errorIndicatesRecoveryIsNeeded=ht,exports.fetchWalletBalance=Dt,exports.getCustomerAccessToken=function(){let e=Dr();return e?e.getCustomerAccessToken():Promise.resolve(d.s.get(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.getIdentityToken=async function(){return await(Rr?.updateUserAndIdToken()),Rr?.useServerCookies?Pr.getState().identityToken:Promise.resolve(d.s.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 Ie&&(t.retryable=!0,t.detail="Something went wrong. Try again."),t},exports.prepareTransactionRequest=qt,exports.shouldCreateEmbeddedEthWallet=Qt,exports.shouldCreateEmbeddedSolWallet=Zt,exports.stripUrlOAuthParamsAndRemoveStateCode=Ce,exports.toDisplayFromAccountType=jt,exports.toEmbeddedWalletSetRecoveryScreen=Rt,exports.toViemAccount=Hr,exports.useAuthMfa=Kr,exports.useAuthMfaEnrollment=()=>{let e=p.useAppConfig(),{setModalData:r}=a.usePrivyModal(),{verify:n}=Kr(),{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(O.MfaAuthTotpInit,{body:{}}),enrollTotp:async e=>{await s.fetchPrivyRoute(O.MfaAuthTotpEnroll,{body:{code:e}});let t=await l();return d(t),t},unenrollTotp:async()=>{await s.fetchPrivyRoute(O.MfaAuthTotpUnenroll,{body:{}});let e=await l();return d(e),e},enrollPasskey:async e=>{await s.fetchPrivyRoute(O.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}=L.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=Ue,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 A.usePrivyEventSubscription("connectOrCreateWallet",e),{connectOrCreateWallet:t}},exports.useCreateWalletWithoutFallback=tr,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=nr((e=>e.jwtAuthFlowState));return A.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.useFundWalletWithBankDeposit=()=>{let{openModal:e,closePrivyModal:r,privy:n}=c.usePrivyInternal(),{setModalData:i}=a.usePrivyModal();return t.useMemo((()=>({fund:t=>new Promise(((a,s)=>{i({FundWithBankDepositScreen:{onSuccess:async()=>{await r({shouldCallAuthOnSuccess:!1,isSuccess:!0}),a({})},onFailure:async e=>{await r({shouldCallAuthOnSuccess:!1,isSuccess:!1}),s(e)},getCustomer:async({kycRedirectUrl:e})=>{let r={provider:t.provider};return e&&(r.kyc_redirect_url=e),await n.fetchPrivyRoute({path:"/api/v1/fiat/customer",method:"GET"},{query:r})},createOrUpdateCustomer:async({hasAcceptedTerms:e,kycRedirectUrl:r})=>await n.fetchPrivyRoute({path:"/api/v1/fiat/customer",method:"PUT"},{body:{provider:t.provider,has_accepted_terms:e,kyc_redirect_url:r}}),getOrCreateVirtualAccount:async e=>await n.fetchPrivyRoute({path:"/api/v1/fiat/customer/virtual_accounts",method:"PUT"},{body:{...e,provider:t.provider}}),opts:t}}),e("FundWithBankDepositScreen")}))})),[])},exports.useGetAccessTokenForProvider=()=>t.useMemo((()=>({getAccessTokenForProvider:({appId:e})=>{try{let t=d.s.get(p.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return{token:null};{let r=new Y(t);return r.isExpired()?(d.s.del(p.getProviderAccessTokenStorageKey(e)),{token:null}):{token:r.value}}}catch(e){return console.error(e),{token:null}}}})),[]),exports.useGetWalletPrivateKey=function(){let{user:e}=a.usePrivyContext(),{client:r}=c.usePrivyInternal(),n=p.useAppConfig(),i=t.useCallback((async({address:t,recipientPublicKey:i})=>{if(!e)throw new c.PrivyClientError("User must be authenticated before exporting their wallet");let s=await r.getAccessToken();if(!s)throw new c.PrivyClientError("Must have valid access token");let o=a.getPrivyWalletWithAddress(e,t);if(!o)throw new c.PrivyClientError("User does not have a wallet with this address");if(!a.getIsUnifiedWallet(o))throw new c.PrivyClientError("Client export is only supported for unified stack wallets. On-device wallets are not supported.");return function(e,t,r){let n=document.createElement("iframe");return n.style.display="none",n.src=e,document.body.appendChild(n),new Promise(((e,i)=>{let a=null,s=()=>{null!==a&&(clearTimeout(a),a=null),window.removeEventListener("message",o),n.parentNode&&n.parentNode.removeChild(n)},o=t=>{var n;t.origin===r&&"object"==typeof(n=t.data)&&null!==n&&"type"in n&&("CLIENT_EXPORT_RESPONSE"===n.type||"CLIENT_EXPORT_ERROR"===n.type)&&(s(),"CLIENT_EXPORT_ERROR"===t.data.type?i(new c.PrivyClientError(t.data.error)):e({ciphertext:t.data.ciphertext,encapsulatedKey:t.data.encapsulatedKey,chainType:t.data.chainType}))};window.addEventListener("message",o),n.onload=()=>{n.contentWindow?.postMessage({type:"CLIENT_EXPORT_REQUEST",recipientPublicKey:t},r)},a=setTimeout((()=>{s(),i(new c.PrivyClientError("Wallet export timed out"))}),3e4)}))}(_.constructURL({origin:r.apiUrl,path:`/apps/${n.id}/embedded-wallets/export`,query:{v:"1-unified",wallet_id:o.id,client_id:n.appClientId,mode:"client-export"},hash:{token:s}}),i,r.apiUrl)}),[e,r,n.id,n.appClientId]);return t.useMemo((()=>({getWalletPrivateKey:i})),[i])},exports.useGuestAccounts=function(){let e=p.useAppConfig(),t=A.useEmitPrivyEvent(),{client:r,setUser:n,setAuthenticated:i,setIsNewUser:a,initializeWalletProxy:s}=c.usePrivyInternal(),{create:o}=f.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=Qt(d,e.embeddedWallets.ethereum.createOnLogin),r=Zt(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}=Pr();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:g,linkFarcaster:v,linkPasskey:f}=t.useContext(a.PrivyContext);return A.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:v,linkTelegram:g,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 Jt(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=Ue(),{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 Ie(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=Ue(),{client:r,setUser:n,refreshSessionAndUser:i}=c.usePrivyInternal(),{authenticated:a}=f.usePrivy();return{generateSiwsMessage:t.useCallback((async({address:t})=>{let n=await xe(e),i=await r.generateSiwsNonce({address:t,captchaToken:n});return f.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");await xe(e);let c=await r.linkWithSiws({message:s,signature:t,walletClientType:o,connectorType:l,messageType:"plain"}),d=(e=>{if(!e)return;let t=e.linkedAccounts;return t&&0!==t.length?t[t.length-1]:void 0})(c=await i()??c)||null;return n(c||null),{user:c,linkedAccount:d}}),[a,e,r,i,n])}},exports.useLoginWithEmail=e=>{let r=Ue(),{emailOtpState:n,setEmailOtpState:i,initLoginWithEmail:a,loginWithCode:s}=c.usePrivyInternal();return{sendCode:t.useCallback((async({email:t,disableSignup:n})=>{try{if(!t)throw Error("Email required to send OTP code");let e=await xe(r);return 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,r]),loginWithCode:t.useCallback((async({code:t})=>{try{let{user:r,isNewUser:n,wasAlreadyAuthenticated:i,linkedAccount:a}=await s(t);e?.onComplete?.({user:r,isNewUser:n,wasAlreadyAuthenticated:i,loginMethod:"email",loginAccount:a})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[s]),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 R.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 R.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=>{A.usePrivyEventSubscription("login",e);let r=Ue(),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 Ie(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=Ee();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{Ce()}}),[l]);return t.useEffect((()=>{let e=Ee();i&&n&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&w().catch((()=>{}))}),[i,n]),{initOAuth:y,loading:h,state:d}},exports.useLoginWithPasskey=e=>{let r=Ue(),{initLoginWithPasskey:n,loginWithPasskey:i,passkeyAuthState:a,setPasskeyAuthState:s}=c.usePrivyInternal();return{loginWithPasskey:t.useCallback((async t=>{try{let a=await xe(r);await n({captchaToken:a,withPrivyUi:!1});let{user:s,isNewUser:o,wasAlreadyAuthenticated:l,loginAccount:c}=await i(t);e?.onComplete?.({user:s,isNewUser:o,wasAlreadyAuthenticated:l,loginMethod:"passkey",loginAccount:c})}catch(t){throw s({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[i,r]),state:a}},exports.useLoginWithSiwe=e=>{let r=Ue(),{siweState:n,setSiweState:i,client:a,generateSiweMessage:s,loginWithSiwe:o}=c.usePrivyInternal();return{generateSiweNonce:t.useCallback((async t=>{try{let e=await xe(r);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=await xe(r);return 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=await xe(r),{user:c,isNewUser:d}=await o({message:t,signature:n,captchaToken:i,disableSignup:a,walletClientType:s,connectorType:l});return e?.onComplete?.({user:c,isNewUser:d,wasAlreadyAuthenticated:!1,loginMethod:"siwe",loginAccount:null}),c}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[o,r]),state:n}},exports.useLoginWithSiws=()=>{let e=Ue(),{client:r,setAuthenticated:n,setUser:i,setIsNewUser:a}=c.usePrivyInternal(),{authenticated:s}=f.usePrivy();return{generateSiwsMessage:t.useCallback((async({address:t})=>{let n=await xe(e),i=await r.generateSiwsNonce({address:t,captchaToken:n});return f.prepareSiwsMessageWithNonce({address:t,nonce:i})}),[e,r]),loginWithSiws:t.useCallback((async({message:e,signature:t,disableSignup:o,walletClientType:l,connectorType:c})=>{if(s)throw Error("User already authenticated");let{user:d,isNewUser:u}=await r.authenticateWithSiws({message:e,signature:t,walletClientType:l,connectorType:c,mode:o?"no-signup":"login-or-sign-up",messageType:"plain"});if(!d)throw Error("Authentication failed - no user returned");return i(d),a(u||!1),n(!0),d}),[s,r,n,i,a])}},exports.useLoginWithSms=e=>{let r=Ue(),{smsOtpState:n,setSmsOtpState:i,initLoginWithSms:a,loginWithCode:s}=c.usePrivyInternal();return{sendCode:t.useCallback((async({phoneNumber:t,disableSignup:n})=>{try{if(!t)throw Error("SMS required to send OTP code");let e=await xe(r);return 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,r]),loginWithCode:t.useCallback((async({code:t})=>{try{let{user:r,isNewUser:n,wasAlreadyAuthenticated:i,linkedAccount:a}=await s(t);e?.onComplete?.({user:r,isNewUser:n,wasAlreadyAuthenticated:i,loginMethod:"sms",loginAccount:a})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[s]),state:n}},exports.useLoginWithTelegram=e=>{let r=Ue(),{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 Ie(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=zt,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=A.useEmitPrivyEvent();return A.usePrivyEventSubscription("oAuthAuthorization",e),{reauthorize:e=>Br(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 ie();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=je,exports.useSendTransaction=function(e){let{sendTransaction:r}=t.useContext(a.PrivyContext);return A.usePrivyEventSubscription("sendTransaction",e),{sendTransaction:r}},exports.useSessionSigners=()=>{let{addSessionSignersInternal:e,removeSessionSignersInternal:t}=Vr();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 A.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??S.zeroAddress,u=r.find((e=>S.getAddress(e.address)===S.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=S.createWalletClient({account:d,chain:e,transport:S.http(W.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,...S.parseSignature(y)}}),[e,r,n,s])}},exports.useSignMessage=function(e){let{signMessage:r}=t.useContext(a.PrivyContext);return A.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 A.usePrivyEventSubscription("signTypedData",e),{signTypedData:r}},exports.useSigners=()=>{let{addSessionSignersInternal:e,removeSessionSignersInternal:t}=Vr();return{addSigners:async({address:t,signers:r})=>e({address:t,signers:r}),removeSigners:async({address:e})=>t({address:e})}},exports.useSignupWithPasskey=e=>{let r=Ue(),{initSignupWithPasskey:n,signupWithPasskey:i,passkeyAuthState:a,setPasskeyAuthState:s}=c.usePrivyInternal();return{signupWithPasskey:t.useCallback((async()=>{try{let t=await xe(r);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]),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 rr({...n,subscribe:a})},exports.useSyncJwtBasedAuthState=rr,exports.useToken=function(e){let{getAccessToken:r}=t.useContext(a.PrivyContext);return A.usePrivyEventSubscription("accessToken",e),{getAccessToken:r}},exports.useUpdateAccount=function(e){let{updateEmail:r,updatePhone:n}=t.useContext(a.PrivyContext);return A.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 le(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=N.selectPaymentRequirements,config:a})=>{let s=t||e[0]?.address;if(!s)throw new M.InvalidInputError("No wallet available for payment");let o=e.find((e=>F.areAddressesEqual(e.address,s)));if(!o)throw new M.InvalidInputError(`Wallet ${s} not found in connected wallets`);return async(e,t)=>{let s=await r(e,t);if(402!==s.status)return s;if(t?.__is402Retry)throw Error("Payment already attempted for this request");let{x402Version:l,accepts:c}=await s.json(),d=i(c,void 0,"exact");if(BigInt(d.maxAmountRequired)>n)throw new M.InvalidInputError("Payment amount exceeds maximum allowed");let u=await Hr({wallet:o}),h=await N.createPaymentHeader(u,l,d,a),p={...t,headers:{...t?.headers||{},"X-PAYMENT":h,"Access-Control-Expose-Headers":"X-PAYMENT-RESPONSE"},__is402Retry:!0};return await r(e,p)}}})),[e])};
|
|
174
|
+
/*#__PURE__*/e.jsx(o.Hide,{$if:!0,children:/*#__PURE__*/e.jsx(st,{scriptHost:n.apiUrl||p.DEFAULT_PRIVY_API_URL,botUsername:h.loginConfig.telegramAuthConfiguration.botName})})]})})})})})})};class hr extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class pr extends B.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new hr(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await ie()||!this.address)throw new hr("Disconnected",4900);let{hash:r}=await((e,t)=>cr(e,t))(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new hr(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await ie()||!this.address)throw new hr("Disconnected",4900);let{signature:r}=await((e,t)=>lr(e,t))(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new hr(`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 hr(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=W.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)=>sr(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)=>or(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=>ae.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await ie();if(await(e=>dr(e))({address:this.address}),!t||!this.address)throw new hr("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 hr("Disconnected",4900)}}}async handleWalletApiRequest(e,t,n){let i=this.privyClient;if(!i)throw new hr("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 hr(`Invalid params for ${e.method}`,4200);return a.data.signature}throw new hr(`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=W.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 yr=({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"})}),wr=({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 mr(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var gr=0;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{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 fr="__private_"+gr+++"__walletBranding";class Er 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 mr(this,fr)[fr]??{name:"Browser Extension",icon:yr,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,fr,{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?mr(this,fr)[fr]={name:"MetaMask",icon:o.Metamask,id:"io.metamask"}:"phantom"===i&&(mr(this,fr)[fr]={name:"Phantom",icon:wr,id:"phantom"})}}class Cr extends vr{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 Ar extends B.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")||o.shouldFetchWcRegistryListings(this.walletList)&&"ethereum-only"!==this.walletChainType,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 ne({provider:new pr({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 ne({provider:new pr({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 lt&&i.resetConnection(t),i;let a=(()=>"injected"!==e?"coinbase_wallet"===e?new te(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new Z(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new lt({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 Cr(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Er(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Er(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Er(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new vr(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 Pr=P.create((()=>({identityToken:null})));let Tr=[v.sessionsRefreshPath,v.sessionsLogoutPath,v.analyticsEventsPath];class kr{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=U.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=Tr.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}})}}const _r=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.s.get(t))return d.s.get(t);{let e=i.base64url.encode(we(32));return d.s.put(t,e),e}}return i.base64url.encode(we(32))}async authenticate(){if(!this.api)throw new c.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(v.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.s.get(e);return"string"==typeof t?Y.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=d.s.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.s.get(p.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return null;{let r=new Y(t);return r.isExpired()?(d.s.del(p.getProviderAccessTokenStorageKey(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=V.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=Y.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.s.put(p.getProviderAccessTokenStorageKey(e),t):d.s.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 oe?"email":e instanceof _e?"sms":e instanceof Te?"siwe":e instanceof Sr?"guest":e instanceof Jt?"custom_auth":e instanceof fe?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(v.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(v.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.s.get(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY);if(d.s.put(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY,e),!this.client?.useServerCookies){let t=Y.parse(e)?.expiration;V.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.s.del(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY),V.default.remove(p.CUSTOMER_ACCESS_TOKEN_COOKIE_KEY),this.client?.onDeleteCustomerAccessToken?.()}storeRefreshToken(e){"string"==typeof e?(d.s.put(p.REFRESH_TOKEN_STORAGE_KEY,e),this.client?.useServerCookies||V.default.set(p.SESSION_COOKIE_KEY,"t",{sameSite:"Strict",secure:br(),expires:30})):(d.s.del(p.REFRESH_TOKEN_STORAGE_KEY),V.default.remove(p.REFRESH_TOKEN_COOKIE_KEY),V.default.remove(p.SESSION_COOKIE_KEY))}storePrivyAccessToken(e){"string"==typeof e?d.s.put(p.PRIVY_ACCESS_TOKEN_STORAGE_KEY,e):d.s.del(p.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}storeIdentityToken(e){if(Pr.setState({identityToken:e}),this.client?.useServerCookies)return;d.s.put(p.IDENTITY_TOKEN_STORAGE_KEY,e);let t=Y.parse(e)?.expiration;V.default.set(p.IDENTITY_TOKEN_COOKIE_KEY,e,{sameSite:"Strict",secure:br(),expires:t?new Date(1e3*t):void 0})}clearIdentityToken(){d.s.del(p.IDENTITY_TOKEN_STORAGE_KEY),Pr.setState({identityToken:null}),V.default.remove(p.IDENTITY_TOKEN_COOKIE_KEY)}constructor(){this.authenticateOnce=new ce((async e=>this._authenticate(e))),this.linkOnce=new ce((async e=>this._link(e))),this.refreshOnce=new ce(this._refresh.bind(this)),this.destroyOnce=new ce(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 Ar(this.appId,e,t,r,n,i,a,s,o,l,d,c))}generateApi(){let e=new kr({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(v.mfaPasswordlessSmsInitPath,{action:"verify"})}catch(e){throw c.formatApiError(e)}}async initMfaPasskeyVerification(){try{let e=await this.api.post(v.mfaPasskeyInitPath,{});return _r(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(v.acceptTermsPath,{});return a.convertUserResponseToUser(e)}catch(e){throw c.formatPrivyError(e)}}async unlinkEmail(e){try{let t=await this.api.post(v.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(v.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(v.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(v.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(v.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(v.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(v.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(v.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(v.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(v.moonpayPluginOnRampPath,e)}catch(e){throw c.formatPrivyError(e)}}async initCoinbaseOnRamp(e){try{return this.api.post(v.coinbaseOnRampInitPath,e)}catch(e){throw c.formatPrivyError(e)}}async getCoinbaseOnRampStatus({partnerUserId:e}){try{return this.api.get(`${v.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)?G.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 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(v.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(v.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(v.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(v.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(v.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(v.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=v.transferEmailPath,d={nonce:e,email:t};break;case"sms":c=v.transferPhonePath,d={nonce:e,phoneNumber:t};break;case"siwe":if(c=v.transferWalletPath,!n)throw Error("Wallet parameters must be defined");d={nonce:e,address:t,...n};break;case"farcaster":c=v.transferFarcasterPath,d={nonce:e,farcaster_id:t,farcaster_embedded_address:o};break;case"telegram":c=v.telegramAccountTransferPath,d={nonce:e,telegram_auth_result:i,telegram_web_app_data:s};break;case"siws":c=v.siwsTransferPath,d={nonce:e,address:t,...n};break;case"custom":case"guest":case"passkey":throw Error("Invalid transfer account type");default:c=v.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(v.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(v.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(v.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.s.get(p.CLIENT_ANALYTICS_ID_KEY);if("string"==typeof e&&e.length>0)return e}catch(e){}let e=n.v4();try{return d.s.put(p.CLIENT_ANALYTICS_ID_KEY,e),e}catch(t){return e}}function Dr(){if(!Rr)throw new c.PrivyClientError("No global PrivyClient instance found. Please ensure you have initialized the PrivyProvider.");return Rr}const Lr=Symbol("cross-tab-user-sync-plugin");let jr=null,qr=null,zr=!1;const Kr=()=>{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}):qe.setState({inProgressMfaFlow:void 0}),a()},onFailure:async e=>{t?await i({shouldCallAuthOnSuccess:!1,isSuccess:!1}):qe.setState({inProgressMfaFlow:void 0}),o(e)},sendSmsCode:async()=>{throw Error("Not enabled")},verifySmsCode:async()=>{throw Error("Not enabled")},verifyTotpCode:async e=>{await n.fetchPrivyRoute(O.MfaAuthTotpVerify,{body:{code:e}})},generateOptions:async()=>_r((await n.fetchPrivyRoute(O.MfaAuthPasskeyInit,{body:{}})).options),verifyPasskey:async e=>{let t=await import("@simplewebauthn/browser"),r=await t.startAuthentication({optionsJSON:e});await n.fetchPrivyRoute(O.MfaAuthPasskeyVerify,{body:{authenticator_response:Ht(r)}})}}}))),void(t?r("MfaAuthVerifyFlowScreen"):qe.setState({inProgressMfaFlow:"auth"}))):o(Error("Must be logged in to verify MFA"))))})),[n,e,r,i])};const Hr=async({wallet:e})=>{let t=await e.getEthereumProvider();return D.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:n})=>{let i;if("string"==typeof n)i=n;else{if("string"!=typeof n.raw)throw new r.PrivyClientError({error:"signMessage only supports string messages or {raw: Hex} format",code:"invalid_input"});i=n.raw}return await t.request({method:"personal_sign",params:[i,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]}),signAuthorization:async n=>{if("privy"!==e.walletClientType)throw new r.PrivyClientError({error:"EIP-7702 authorization signing is not supported by external wallets.",code:"unsupported_wallet_type"});let i={chainId:n.chainId,address:n.contractAddress??n.address,nonce:n.nonce},a=m.hashAuthorization(i),s=S.parseSignature(await t.request({method:"secp256k1_sign",params:[a]}));return{...i,...s}}})};let Br=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 Vr=()=>{let{user:e}=a.usePrivyContext(),t=c.usePrivyInternal(),{signWithUserSigner:n}=L.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=At({address:n,user:e}),i=Pt({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}}}};const Yr=rt;exports.BASE_ACCOUNT_DATA_URI=J,exports.Blobby=re,exports.BrowserExtensionWallet=yr,exports.COINBASE_WALLET_DATA_URI=$,exports.Captcha=De,exports.CaptchaError=Ie,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=Ar,exports.LoginModal=Yr,exports.Phantom=wr,exports.PrivyClient=Mr,exports.PrivyIframeError=dt,exports.PrivyModal=rt,exports.PrivyProvider=({config:r,...n})=>{(()=>{if(t.useContext(ar))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 K.default({appId:n.appId,clientId:n.clientId,storage:d.s,baseUrl:n.apiUrl,sdkVersion:"react-auth:3.14.1"})),[]),a=Dr(),s=Object.assign({},r);/*#__PURE__*/return e.jsx(p.PrivyAppConfigProvider,{client:i,legacyClient:a,appClientId:n.clientId,clientConfig:s,children:/*#__PURE__*/e.jsx(b.PrivyPluginProvider,{configPlugins:r?.plugins,children:/*#__PURE__*/e.jsx(ur,{...n,client:a,privy:i})})})},exports.RunEffectOnce=ce,exports.SiweFlow=Te,exports.SiwsFlow=ke,exports.WalletConnectV2WalletConnector=lt,exports.addFundingResultToModalData=function(e,t,r,n,i,a,s){return{...e,funding:e?.funding?{...e.funding,fundingResult:{status:t,address:e.funding.address,fundingMethod:void 0,transactionHash:r,amount:e.funding.amount,assetType:i?a?.symbol||"ETH":s.nativeCurrency.symbol||"ETH",metadata:{walletClientType:n}}}:void 0,solanaFundingData:e?.solanaFundingData,sendTransaction:e?.sendTransaction}},exports.createCodeVerifier=me,exports.createCrossTabUserSyncPlugin=function(e){if(!e.channelId)throw Error("[Privy] Cross-tab sync plugin requires a channelId.");return"undefined"==typeof BroadcastChannel||jr||((jr=new BroadcastChannel(`PRIVY_CROSS_TAB_CHANNEL:${e.channelId}`)).onmessage=e=>{e.data.eventId!==qr&&(qr=e.data.eventId,zr=!0,Gt(e.data.user),$t(!!e.data.user),zr=!1)},Yt.subscribe(((e,t)=>{if(e.user===t.user||zr)return;let r=n.v4();qr=r,jr?.postMessage({user:e.user,eventId:r})}))),{id:Lr}},exports.createStateCode=ge,exports.deriveCodeChallengeFromCodeVerifier=ve,exports.e=Ft,exports.embeddedWalletRecoveryScreen=Ot,exports.embeddedWalletSetPasswordScreen=xt,exports.errorIndicatesInvalidRecoveryPassword=function(e){return ut(e)&&("invalid_recovery_pin"===e.type||"invalid_request_arguments"===e.type)},exports.errorIndicatesMaxMfaRetries=function(e){return!!ut(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!(!ut(e)||!e.message.includes("code 429"))},exports.errorIndicatesMfaTimeout=function(e){return!!ut(e)&&"mfa_timeout"===e.type},exports.errorIndicatesMfaVerificationFailed=function(e){return!!ut(e)&&"missing_or_invalid_mfa"===e.type},exports.errorIndicatesRecoveryIsNeeded=ht,exports.fetchWalletBalance=Dt,exports.getCustomerAccessToken=function(){let e=Dr();return e?e.getCustomerAccessToken():Promise.resolve(d.s.get(p.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)||null)},exports.getIdentityToken=async function(){return await(Rr?.updateUserAndIdToken()),Rr?.useServerCookies?Pr.getState().identityToken:Promise.resolve(d.s.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 Ie&&(t.retryable=!0,t.detail="Something went wrong. Try again."),t},exports.prepareTransactionRequest=qt,exports.shouldCreateEmbeddedEthWallet=Qt,exports.shouldCreateEmbeddedSolWallet=Zt,exports.stripUrlOAuthParamsAndRemoveStateCode=Ce,exports.toDisplayFromAccountType=jt,exports.toEmbeddedWalletSetRecoveryScreen=Rt,exports.toViemAccount=Hr,exports.useAuthMfa=Kr,exports.useAuthMfaEnrollment=()=>{let e=p.useAppConfig(),{setModalData:r}=a.usePrivyModal(),{verify:n}=Kr(),{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(O.MfaAuthTotpInit,{body:{}}),enrollTotp:async e=>{await s.fetchPrivyRoute(O.MfaAuthTotpEnroll,{body:{code:e}});let t=await l();return d(t),t},unenrollTotp:async()=>{await s.fetchPrivyRoute(O.MfaAuthTotpUnenroll,{body:{}});let e=await l();return d(e),e},enrollPasskey:async e=>{await s.fetchPrivyRoute(O.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}=L.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=Ue,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 A.usePrivyEventSubscription("connectOrCreateWallet",e),{connectOrCreateWallet:t}},exports.useCreateWalletWithoutFallback=tr,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=nr((e=>e.jwtAuthFlowState));return A.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.useFundWalletWithBankDeposit=()=>{let{openModal:e,closePrivyModal:r,privy:n}=c.usePrivyInternal(),{setModalData:i}=a.usePrivyModal();return t.useMemo((()=>({fund:t=>new Promise(((a,s)=>{i({FundWithBankDepositScreen:{onSuccess:async()=>{await r({shouldCallAuthOnSuccess:!1,isSuccess:!0}),a({})},onFailure:async e=>{await r({shouldCallAuthOnSuccess:!1,isSuccess:!1}),s(e)},getCustomer:async({kycRedirectUrl:e})=>{let r={provider:t.provider};return e&&(r.kyc_redirect_url=e),await n.fetchPrivyRoute({path:"/api/v1/fiat/customer",method:"GET"},{query:r})},createOrUpdateCustomer:async({hasAcceptedTerms:e,kycRedirectUrl:r})=>await n.fetchPrivyRoute({path:"/api/v1/fiat/customer",method:"PUT"},{body:{provider:t.provider,has_accepted_terms:e,kyc_redirect_url:r}}),getOrCreateVirtualAccount:async e=>await n.fetchPrivyRoute({path:"/api/v1/fiat/customer/virtual_accounts",method:"PUT"},{body:e}),opts:t}}),e("FundWithBankDepositScreen")}))})),[])},exports.useGetAccessTokenForProvider=()=>t.useMemo((()=>({getAccessTokenForProvider:({appId:e})=>{try{let t=d.s.get(p.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return{token:null};{let r=new Y(t);return r.isExpired()?(d.s.del(p.getProviderAccessTokenStorageKey(e)),{token:null}):{token:r.value}}}catch(e){return console.error(e),{token:null}}}})),[]),exports.useGetWalletPrivateKey=function(){let{user:e}=a.usePrivyContext(),{client:r}=c.usePrivyInternal(),n=p.useAppConfig(),i=t.useCallback((async({address:t,recipientPublicKey:i})=>{if(!e)throw new c.PrivyClientError("User must be authenticated before exporting their wallet");let s=await r.getAccessToken();if(!s)throw new c.PrivyClientError("Must have valid access token");let o=a.getPrivyWalletWithAddress(e,t);if(!o)throw new c.PrivyClientError("User does not have a wallet with this address");if(!a.getIsUnifiedWallet(o))throw new c.PrivyClientError("Client export is only supported for unified stack wallets. On-device wallets are not supported.");return function(e,t,r){let n=document.createElement("iframe");return n.style.display="none",n.src=e,document.body.appendChild(n),new Promise(((e,i)=>{let a=null,s=()=>{null!==a&&(clearTimeout(a),a=null),window.removeEventListener("message",o),n.parentNode&&n.parentNode.removeChild(n)},o=t=>{var n;t.origin===r&&"object"==typeof(n=t.data)&&null!==n&&"type"in n&&("CLIENT_EXPORT_RESPONSE"===n.type||"CLIENT_EXPORT_ERROR"===n.type)&&(s(),"CLIENT_EXPORT_ERROR"===t.data.type?i(new c.PrivyClientError(t.data.error)):e({ciphertext:t.data.ciphertext,encapsulatedKey:t.data.encapsulatedKey,chainType:t.data.chainType}))};window.addEventListener("message",o),n.onload=()=>{n.contentWindow?.postMessage({type:"CLIENT_EXPORT_REQUEST",recipientPublicKey:t},r)},a=setTimeout((()=>{s(),i(new c.PrivyClientError("Wallet export timed out"))}),3e4)}))}(_.constructURL({origin:r.apiUrl,path:`/apps/${n.id}/embedded-wallets/export`,query:{v:"1-unified",wallet_id:o.id,client_id:n.appClientId,mode:"client-export"},hash:{token:s}}),i,r.apiUrl)}),[e,r,n.id,n.appClientId]);return t.useMemo((()=>({getWalletPrivateKey:i})),[i])},exports.useGuestAccounts=function(){let e=p.useAppConfig(),t=A.useEmitPrivyEvent(),{client:r,setUser:n,setAuthenticated:i,setIsNewUser:a,initializeWalletProxy:s}=c.usePrivyInternal(),{create:o}=f.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=Qt(d,e.embeddedWallets.ethereum.createOnLogin),r=Zt(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}=Pr();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:g,linkFarcaster:v,linkPasskey:f}=t.useContext(a.PrivyContext);return A.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:v,linkTelegram:g,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 Jt(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=Ue(),{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 Ie(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=Ue(),{client:r,setUser:n,refreshSessionAndUser:i}=c.usePrivyInternal(),{authenticated:a}=f.usePrivy();return{generateSiwsMessage:t.useCallback((async({address:t})=>{let n=await xe(e),i=await r.generateSiwsNonce({address:t,captchaToken:n});return f.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");await xe(e);let c=await r.linkWithSiws({message:s,signature:t,walletClientType:o,connectorType:l,messageType:"plain"}),d=(e=>{if(!e)return;let t=e.linkedAccounts;return t&&0!==t.length?t[t.length-1]:void 0})(c=await i()??c)||null;return n(c||null),{user:c,linkedAccount:d}}),[a,e,r,i,n])}},exports.useLoginWithEmail=e=>{let r=Ue(),{emailOtpState:n,setEmailOtpState:i,initLoginWithEmail:a,loginWithCode:s}=c.usePrivyInternal();return{sendCode:t.useCallback((async({email:t,disableSignup:n})=>{try{if(!t)throw Error("Email required to send OTP code");let e=await xe(r);return 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,r]),loginWithCode:t.useCallback((async({code:t})=>{try{let{user:r,isNewUser:n,wasAlreadyAuthenticated:i,linkedAccount:a}=await s(t);e?.onComplete?.({user:r,isNewUser:n,wasAlreadyAuthenticated:i,loginMethod:"email",loginAccount:a})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[s]),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 R.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 R.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=>{A.usePrivyEventSubscription("login",e);let r=Ue(),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 Ie(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=Ee();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{Ce()}}),[l]);return t.useEffect((()=>{let e=Ee();i&&n&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&w().catch((()=>{}))}),[i,n]),{initOAuth:y,loading:h,state:d}},exports.useLoginWithPasskey=e=>{let r=Ue(),{initLoginWithPasskey:n,loginWithPasskey:i,passkeyAuthState:a,setPasskeyAuthState:s}=c.usePrivyInternal();return{loginWithPasskey:t.useCallback((async t=>{try{let a=await xe(r);await n({captchaToken:a,withPrivyUi:!1});let{user:s,isNewUser:o,wasAlreadyAuthenticated:l,loginAccount:c}=await i(t);e?.onComplete?.({user:s,isNewUser:o,wasAlreadyAuthenticated:l,loginMethod:"passkey",loginAccount:c})}catch(t){throw s({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[i,r]),state:a}},exports.useLoginWithSiwe=e=>{let r=Ue(),{siweState:n,setSiweState:i,client:a,generateSiweMessage:s,loginWithSiwe:o}=c.usePrivyInternal();return{generateSiweNonce:t.useCallback((async t=>{try{let e=await xe(r);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=await xe(r);return 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=await xe(r),{user:c,isNewUser:d}=await o({message:t,signature:n,captchaToken:i,disableSignup:a,walletClientType:s,connectorType:l});return e?.onComplete?.({user:c,isNewUser:d,wasAlreadyAuthenticated:!1,loginMethod:"siwe",loginAccount:null}),c}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[o,r]),state:n}},exports.useLoginWithSiws=()=>{let e=Ue(),{client:r,setAuthenticated:n,setUser:i,setIsNewUser:a}=c.usePrivyInternal(),{authenticated:s}=f.usePrivy();return{generateSiwsMessage:t.useCallback((async({address:t})=>{let n=await xe(e),i=await r.generateSiwsNonce({address:t,captchaToken:n});return f.prepareSiwsMessageWithNonce({address:t,nonce:i})}),[e,r]),loginWithSiws:t.useCallback((async({message:e,signature:t,disableSignup:o,walletClientType:l,connectorType:c})=>{if(s)throw Error("User already authenticated");let{user:d,isNewUser:u}=await r.authenticateWithSiws({message:e,signature:t,walletClientType:l,connectorType:c,mode:o?"no-signup":"login-or-sign-up",messageType:"plain"});if(!d)throw Error("Authentication failed - no user returned");return i(d),a(u||!1),n(!0),d}),[s,r,n,i,a])}},exports.useLoginWithSms=e=>{let r=Ue(),{smsOtpState:n,setSmsOtpState:i,initLoginWithSms:a,loginWithCode:s}=c.usePrivyInternal();return{sendCode:t.useCallback((async({phoneNumber:t,disableSignup:n})=>{try{if(!t)throw Error("SMS required to send OTP code");let e=await xe(r);return 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,r]),loginWithCode:t.useCallback((async({code:t})=>{try{let{user:r,isNewUser:n,wasAlreadyAuthenticated:i,linkedAccount:a}=await s(t);e?.onComplete?.({user:r,isNewUser:n,wasAlreadyAuthenticated:i,loginMethod:"sms",loginAccount:a})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||c.PrivyErrorCode.UNKNOWN_AUTH_ERROR),t}}),[s]),state:n}},exports.useLoginWithTelegram=e=>{let r=Ue(),{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 Ie(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=zt,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=A.useEmitPrivyEvent();return A.usePrivyEventSubscription("oAuthAuthorization",e),{reauthorize:e=>Br(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 ie();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=je,exports.useSendTransaction=function(e){let{sendTransaction:r}=t.useContext(a.PrivyContext);return A.usePrivyEventSubscription("sendTransaction",e),{sendTransaction:r}},exports.useSessionSigners=()=>{let{addSessionSignersInternal:e,removeSessionSignersInternal:t}=Vr();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 A.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??S.zeroAddress,u=r.find((e=>S.getAddress(e.address)===S.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=S.createWalletClient({account:d,chain:e,transport:S.http(W.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,...S.parseSignature(y)}}),[e,r,n,s])}},exports.useSignMessage=function(e){let{signMessage:r}=t.useContext(a.PrivyContext);return A.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 A.usePrivyEventSubscription("signTypedData",e),{signTypedData:r}},exports.useSigners=()=>{let{addSessionSignersInternal:e,removeSessionSignersInternal:t}=Vr();return{addSigners:async({address:t,signers:r})=>e({address:t,signers:r}),removeSigners:async({address:e})=>t({address:e})}},exports.useSignupWithPasskey=e=>{let r=Ue(),{initSignupWithPasskey:n,signupWithPasskey:i,passkeyAuthState:a,setPasskeyAuthState:s}=c.usePrivyInternal();return{signupWithPasskey:t.useCallback((async()=>{try{let t=await xe(r);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]),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 rr({...n,subscribe:a})},exports.useSyncJwtBasedAuthState=rr,exports.useToken=function(e){let{getAccessToken:r}=t.useContext(a.PrivyContext);return A.usePrivyEventSubscription("accessToken",e),{getAccessToken:r}},exports.useUpdateAccount=function(e){let{updateEmail:r,updatePhone:n}=t.useContext(a.PrivyContext);return A.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 le(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=N.selectPaymentRequirements,config:a})=>{let s=t||e[0]?.address;if(!s)throw new M.InvalidInputError("No wallet available for payment");let o=e.find((e=>F.areAddressesEqual(e.address,s)));if(!o)throw new M.InvalidInputError(`Wallet ${s} not found in connected wallets`);return async(e,t)=>{let s=await r(e,t);if(402!==s.status)return s;if(t?.__is402Retry)throw Error("Payment already attempted for this request");let{x402Version:l,accepts:c}=await s.json(),d=i(c,void 0,"exact");if(BigInt(d.maxAmountRequired)>n)throw new M.InvalidInputError("Payment amount exceeds maximum allowed");let u=await Hr({wallet:o}),h=await N.createPaymentHeader(u,l,d,a),p={...t,headers:{...t?.headers||{},"X-PAYMENT":h,"Access-Control-Expose-Headers":"X-PAYMENT-RESPONSE"},__is402Retry:!0};return await r(e,p)}}})),[e])};
|