UNPKG

@privy-io/expo

Version:

Expo client for the Privy Auth API

1,418 lines (1,372 loc) • 61.8 kB
import * as Privy from '@privy-io/js-sdk-core'; import Privy__default, { EmbeddedWalletConfig, UnsignedTransactionRequest, OnNeedsRecovery, MfaMethod, PrivyEmbeddedWalletProvider, PrivyEmbeddedSolanaWalletProvider, EmbeddedBitcoinWalletProvider, GenerateAuthorizationSignatureInput, GenerateAuthorizationSignatureOutput, Storage, Chain, OAuthProviderID, Logger } from '@privy-io/js-sdk-core'; export * from '@privy-io/js-sdk-core'; import React from 'react'; import { E as ErrorCallback, A as AuthLinkSuccessCallback, G as GenerateSiweMessage, S as SiweFlowState, a as AuthSuccessCallback, O as OtpLinkHookOptions, b as OtpLinkHookResult, c as OtpLoginHookOptions, d as OtpLoginHookResult, F as FarcasterFlowState, L as LinkFarcasterInput, e as SubmitFarcasterOptions, f as LoginWithFarcasterInput, g as EmbeddedWalletState, h as EmbeddedSolanaWalletState, i as OtpFlowState, j as OAuthFlowState, W as WalletRecoveryCallbacks, k as SolanaWalletRecoveryCallbacks, R as RecoveryFlowState, P as PasskeyFlowState } from './predicates-f4e23818.js'; export { Y as CreateEthereumEmbeddedWalletOpts, X as CreateOrRecoverEmbeddedWalletProps, _ as CreateSolanaEmbeddedWalletOpts, a1 as CustomAuthFlowState, a5 as EmbeddedSolanaWalletActions, a6 as EmbeddedSolanaWalletStatus, p as EmbeddedWallet, a3 as EmbeddedWalletActions, a4 as EmbeddedWalletStatus, n as LinkedAccountWithMetadata, a2 as MfaConfig, M as PrivyAppleOauthAccount, s as PrivyBitcoinSegwitEmbeddedWalletAccount, t as PrivyBitcoinTaprootEmbeddedWalletAccount, V as PrivyCrossAppWalletAccount, N as PrivyCustomJwtAccount, C as PrivyDiscordOauthAccount, v as PrivyEmailAccount, o as PrivyEmbeddedWalletAccount, x as PrivyEthereumAccount, q as PrivyEthereumEmbeddedWalletAccount, Q as PrivyFarcasterAccount, D as PrivyGithubOauthAccount, z as PrivyGoogleOauthAccount, I as PrivyInstagramOauthAccount, m as PrivyLinkedAccount, K as PrivyLinkedInOauthAccount, T as PrivyPasskeyAccount, w as PrivyPhoneAccount, u as PrivySmartWalletAccount, y as PrivySolanaAccount, r as PrivySolanaEmbeddedWalletAccount, H as PrivySpotifyOauthAccount, U as PrivyTelegramAccount, J as PrivyTiktokOauthAccount, B as PrivyTwitterOauthAccount, l as PrivyUser, Z as RecoverEthereumEmbeddedWalletOpts, $ as RecoverSolanaEmbeddedWalletOpts, a0 as SetRecoveryProps, ad as hasError, a7 as isConnected, a9 as isConnecting, ac as isCreating, aa as isDisconnected, ab as isNotCreated, a8 as isReconnecting, ae as needsRecovery } from './predicates-f4e23818.js'; import * as _privy_io_api_types from '@privy-io/api-types'; import { User, AuthenticatedUser } from '@privy-io/api-types'; export { LinkedAccount, LinkedAccountBitcoinSegwitEmbeddedWallet, LinkedAccountBitcoinTaprootEmbeddedWallet, LinkedAccountEmbeddedWallet, LinkedAccountEthereumEmbeddedWallet, LinkedAccountSmartWallet, LinkedAccountSolanaEmbeddedWallet, User } from '@privy-io/api-types'; import { TypedDataDefinition } from 'viem'; import { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/types'; import { EncryptedAuthorizationKeyResponse } from '@privy-io/routes'; import { AppleAuthenticationCredential } from 'expo-apple-authentication'; /** * Privy configuration options. */ type PrivyConfig = { customAuth?: CustomAuthProviderConfig; /** * Multi-factor authentication configuration. */ mfa?: { /** URL origin where your Apple App Site Association or Digital Asset Links are available (e.g. https://example.com) */ relyingParty: string; }; embedded?: { ethereum?: EmbeddedWalletConfig; solana?: EmbeddedWalletConfig; /** * Set to `true` to disable automatic migration, if you are migrating * manually via the `useMigrateWallets` hook. * * @default false */ disableAutomaticMigration?: boolean; }; }; type CustomAuthProviderConfig = { /** * If true, enable custom authentication integration. * This enables a JWT from a custom auth provider to be used to authenticate Privy embedded wallets. * Defaults to true. * * @default true */ enabled?: boolean; /** * A callback that returns the user's custom auth provider's access token as a string. * Can be left blank if using cookies to store and send access tokens * * @example * const {getAccessTokenSilently} = useAuth(); * * <PrivyProvider * {...props} * config={{ * customAuth: { * getCustomAccessToken: getAccessTokenSilently * }, * }} * /> */ getCustomAccessToken: () => Promise<string | undefined>; /** * Custom auth providers loading state * * @example * const {isLoading} = useAuth(); * * <PrivyProvider * {...props} * config={{ * customAuth: { * isLoading, * }, * }} * /> */ isLoading: boolean; }; interface UseLinkWithSiweOptions { onError?: ErrorCallback; onSuccess: AuthLinkSuccessCallback; onGenerateMessage?: (args: string) => void; } interface UseLinkWithSiwe { generateSiweMessage: GenerateSiweMessage; state: SiweFlowState; linkWithSiwe: (opts: { /** Signature generated against standard [Sign-In With Ethereum](https://eips.ethereum.org/EIPS/eip-4361) message */ signature: string; /** * Optional [Sign-In With Ethereum](https://eips.ethereum.org/EIPS/eip-4361) message, only needed if the message differs from the one in memory that was cached in previous call to `generateMessage` */ messageOverride?: string; }) => Promise<User>; } declare const useLinkWithSiwe: (opts?: UseLinkWithSiweOptions) => UseLinkWithSiwe; interface UseLoginWithSiweOptions { onError?: ErrorCallback; onSuccess: AuthSuccessCallback; onGenerateMessage?: (args: string) => void; } interface UseLoginWithSiwe { generateSiweMessage: GenerateSiweMessage; state: SiweFlowState; loginWithSiwe: (opts: { /** Signature generated against standard [Sign-In With Ethereum](https://eips.ethereum.org/EIPS/eip-4361) message */ signature: string; /** * Optional [Sign-In With Ethereum](https://eips.ethereum.org/EIPS/eip-4361) message, only needed if the message differs from the one in memory that was cached in previous call to `generateMessage` */ messageOverride?: string; disableSignup?: boolean; }) => Promise<User>; } declare const useLoginWithSiwe: (opts?: UseLoginWithSiweOptions) => UseLoginWithSiwe; interface UseLinkWithSiwsInterface { generateMessage: (args: { /** * Solana wallet address */ wallet: { address: string; }; from: { /** * [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986) authority that is requesting the signature */ domain: string; /** *[RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986) URI referring to the resource that is the subject of the signature */ uri: string; }; }) => Promise<{ message: string; }>; link: (opts: { /** Signature generated against the SIWS message */ signature: string; /** The SIWS message */ message: string; wallet?: { /** * Metadata for the wallet account */ walletClientType?: string; /** * Metadata for the wallet account */ connectorType?: string; }; }) => Promise<User>; } declare const useLinkWithSiws: () => UseLinkWithSiwsInterface; interface UseLoginWithSiwsInterface { generateMessage: (args: { /** * Solana wallet address */ wallet: { address: string; }; from: { /** * [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986) authority that is requesting the signature */ domain: string; /** *[RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986) URI referring to the resource that is the subject of the signature */ uri: string; }; }) => Promise<{ message: string; }>; login: (opts: { /** Signature generated against the SIWS message */ signature: string; /** The SIWS message */ message: string; wallet?: { /** * Metadata for the wallet account */ walletClientType?: string; /** * Metadata for the wallet account */ connectorType?: string; }; disableSignup?: boolean; }) => Promise<User>; } declare const useLoginWithSiws: () => UseLoginWithSiwsInterface; interface UseUnlinkWalletOptions { onError?: ErrorCallback; onSuccess: AuthSuccessCallback; onGenerateMessage?: (args: string) => void; } interface UseUnlinkWallet { unlinkWallet: (opts: { address: string; }) => Promise<User>; } declare const useUnlinkWallet: (opts?: UseUnlinkWalletOptions) => UseUnlinkWallet; type LinkWithEmailOptions = OtpLinkHookOptions<{ email: string; }>; type LinkWithEmailHookResult = OtpLinkHookResult<{ email: string; }, { code: string; email?: string; }>; declare const useLinkEmail: (opts?: LinkWithEmailOptions) => LinkWithEmailHookResult; interface UseUnlinkEmailOptions { onError?: ErrorCallback; onSuccess: AuthSuccessCallback; } declare const useUnlinkEmail: (opts?: UseUnlinkEmailOptions) => { unlinkEmail: ({ email }: { email: string; }) => Promise<_privy_io_api_types.User>; }; type LoginWithEmailOptions = OtpLoginHookOptions<{ email: string; }>; type LoginWithEmailHookResult = OtpLoginHookResult<{ email: string; }, { code: string; email?: string; disableSignup?: boolean; }>; declare const useLoginWithEmail: (opts?: LoginWithEmailOptions) => LoginWithEmailHookResult; type LinkWithSMSOptions = OtpLinkHookOptions<{ phone: string; }>; type LinkWithSMSHookResult = OtpLinkHookResult<{ phone: string; }, { code: string; phone?: string; }>; declare const useLinkSMS: (opts?: LinkWithSMSOptions) => LinkWithSMSHookResult; type LoginWithSMSOptions = OtpLoginHookOptions<{ phone: string; }>; type LoginWithSMSHookResult = OtpLoginHookResult<{ phone: string; }, { code: string; phone?: string; disableSignup?: boolean; }>; declare const useLoginWithSMS: (opts?: LoginWithSMSOptions) => LoginWithSMSHookResult; interface UseLinkWithFarcasterOptions { onSuccess: AuthLinkSuccessCallback; onError?: ErrorCallback; } interface UseLinkWithFarcaster { state: FarcasterFlowState; linkWithFarcaster: (input: LinkFarcasterInput, opts?: SubmitFarcasterOptions) => Promise<User>; cancel: (_?: void) => void; } declare const useLinkWithFarcaster: (opts?: UseLinkWithFarcasterOptions) => UseLinkWithFarcaster; interface UseUnlinkFarcasterOptions { onSuccess: AuthLinkSuccessCallback; onError?: ErrorCallback; } interface UseUnlinkFarcaster { unlinkFarcaster: (input: { fid: number; }) => Promise<User>; } declare const useUnlinkFarcaster: (opts?: UseUnlinkFarcasterOptions) => UseUnlinkFarcaster; interface UseLoginWithFarcasterOptions { onSuccess: AuthSuccessCallback; onError?: ErrorCallback; } interface UseLoginWithFarcaster { state: FarcasterFlowState; loginWithFarcaster: (input: LoginWithFarcasterInput, opts?: SubmitFarcasterOptions) => Promise<User>; cancel: (_?: void) => void; } declare const useLoginWithFarcaster: (opts?: UseLoginWithFarcasterOptions) => UseLoginWithFarcaster; type FarcasterV2State = { status: 'initial' | 'fetching-nonce' | 'awaiting-signature' | 'submitting-signature' | 'done'; error?: Error; }; type LoginWithFarcasterV2Input = { fid: number; message: string; signature: string; }; interface UseLoginWithFarcasterV2 { init: (_?: Record<string, never>) => Promise<{ nonce: string; expires_at: string; }>; login: (input: LoginWithFarcasterV2Input) => Promise<{ user: User; }>; state: FarcasterV2State; } declare const useLoginWithFarcasterV2: () => UseLoginWithFarcasterV2; interface UseHeadlessDelegatedActionsInterface { /** * Authorizes the an app to transact on behalf of a user within a set of pre-defined permissions. * Users should always be able to decline or revoke delegation. * * @param address {string} address of the wallet to delegate * @param chainType {'solana' | 'ethereum'} chain type for the wallet to delegate */ delegateWallet: ({ address, chainType, }: { address: string; chainType: 'solana' | 'ethereum'; }) => Promise<{ user: User; }>; /** * Revokes the wallet API's ability to transact with a user's delegated wallets. This will revoke * ALL wallets that have been delegated by the user, in case the user has delegated multiple * embedded wallets. * * @returns Promise that resolves if the revocation was successful, with the updated user object, and errors otherwise */ revokeWallets: () => Promise<{ user: User; }>; } /** * A hook to give permission to execute certain transactions to the wallet API. * * This is the *headless* version of the delegated actions hook. Using this hook will not visibly * prompt the user, and the UI should be handled by the app. */ declare const useHeadlessDelegatedActions: () => UseHeadlessDelegatedActionsInterface; interface SessionSigner { signerId: string; policyIds: string[]; } interface AddSessionSignersInput { address: string; signers: SessionSigner[]; } interface AddSessionSignersOutput { user: User; } interface RemoveSessionSignersInput { address: string; } interface RemoveSessionSignersOutput { user: User; } /** * @deprecated in favor of useSigners */ interface UseSessionSignersInterface { /** * @deprecated in favor of addSigners from useSigners * Grants access of the wallet to a specified key quorum. * * @param input.address address of the wallet to add signers to * @param input.signers array of signers to add as session signers to the wallet * @returns Promise that resolves with the updated user if adding signers was successful, and rejects otherwise */ addSessionSigners: (input: AddSessionSignersInput) => Promise<AddSessionSignersOutput>; /** * @deprecated in favor of removeSigners from useSigners * Removes all session signers from a user wallet. * * @param input.address address of the wallet to remove signers from * @returns Promise that resolves with the updated user if the revocation was successful, and rejects otherwise */ removeSessionSigners: (input: RemoveSessionSignersInput) => Promise<RemoveSessionSignersOutput>; } /** * @deprecated in favor of useSigners */ declare const useSessionSigners: () => UseSessionSignersInterface; interface Signer { signerId: string; policyIds: string[]; } interface AddSignersInput { address: string; signers: Signer[]; } interface AddSignersOutput { user: User; } interface RemoveSignersInput { address: string; } interface RemoveSignersOutput { user: User; } interface UseSignersInterface { /** * Adds a signer to a wallet. * * @param input.address address of the wallet to add signers to * @param input.signers array of signers to add to the wallet * @returns Promise that resolves with the updated user if adding signers was successful, and rejects otherwise */ addSigners: (input: AddSignersInput) => Promise<AddSignersOutput>; /** * Removes all signers from a wallet. * * @param input.address address of the wallet to remove signers from * @returns Promise that resolves with the updated user if the revocation was successful, and rejects otherwise */ removeSigners: (input: RemoveSignersInput) => Promise<RemoveSignersOutput>; } declare const useSigners: () => UseSignersInterface; interface SendEmailCodeInput { /** The new email address you wish to update the user to. */ newEmailAddress: string; } interface UpdateEmailInput { /** The new email address you wish to update the user to. */ newEmailAddress: string; /** The one time code received by the user on the new email address. */ code: string; } interface UseUpdateEmailInterface { /** * Prepare an email address update by sending a one time code to a new email address. * * @param input.newEmailAddress The new email address you wish to update the user to. * @returns a promise that resolves if the code was sent successfully, and rejects otherwise * * @see {@link updateEmail} for submitting the one time code to complete the email update. */ sendCode: (input: SendEmailCodeInput) => Promise<void>; /** * Update a user profile with a new email address by submitting a one time code. * * @param input.newEmailAddress The new email address you wish to update the user to. * @param input.code The one time code previously sent to the email address by using {@link sendCode}. * @returns a promise that resolves with the updated user object. * * @see {@link sendCode} for sending the one time code first. */ updateEmail: (input: UpdateEmailInput) => Promise<User>; } /** A hook to update the email account linked to the current user. */ declare const useUpdateEmail: () => UseUpdateEmailInterface; interface SendPhoneCodeInput { /** The new phone number you wish to update the user to. */ newPhoneNumber: string; } interface UpdatePhoneInput { /** The new phone number you wish to update the user to. */ newPhoneNumber: string; /** The one time code received by the user on the new phone number. */ code: string; } interface UseUpdatePhoneInterface { /** * Prepare a phone number update by sending a one time code to a new phone number. * * @param input.newPhoneNumber The new phone number you wish to update the user to. * @returns a promise that resolves if the code was sent successfully, and rejects otherwise * * @see {@link updatePhone} for submitting the one time code to complete the phone update. */ sendCode: (input: SendPhoneCodeInput) => Promise<void>; /** * Update a user profile with a new phone number by submitting a one time code. * * @param input.newPhoneNumber The new phone number you wish to update the user to. * @param input.code The one time code previously sent to the phone number by using {@link sendCode}. * @returns a promise that resolves with the updated user object. * * @see {@link sendCode} for sending the one time code first. */ updatePhone: (input: UpdatePhoneInput) => Promise<User>; } /** A hook to update the phone account linked to the current user. */ declare const useUpdatePhone: () => UseUpdatePhoneInterface; interface LoginWithCrossAppInput { /** The target Privy app ID from which the user should log into another Privy account */ appId: string; /** a URL path used to redirect back to your app after successful authentication */ redirectUri?: string | undefined; } interface LoginWithCrossAppOutput { /** The logged in user object */ user: User; } interface UseLoginWithCrossAppInterface { /** * Prompts the user to login to your app through an account on another Privy app. * * This will open up an in app browser for the user to log in and authorize your app to access their account. */ loginWithCrossApp: (input: LoginWithCrossAppInput) => Promise<LoginWithCrossAppOutput>; } /** * Use this hook to login to your app with an external account on another Privy app. * * @returns loginWithCrossApp - prompts the user to authorize access to their account on another Privy app. */ declare const useLoginWithCrossApp: () => UseLoginWithCrossAppInterface; interface LinkWithCrossAppInput { /** The target Privy app ID from which the user should link another Privy account */ appId: string; /** a URL path used to redirect back to your app after successful authentication */ redirectUri?: string | undefined; } interface LinkWithCrossAppOutput { /** The user object updated with the newly linked account */ user: User; } interface UseLinkWithCrossAppInterface { /** * Prompts the user to link their account from another Privy app to their account * within your app. * * This will open up an in app browser for the user to log in and authorize your app to access their account. */ linkWithCrossApp: (input: LinkWithCrossAppInput) => Promise<LinkWithCrossAppOutput>; } /** * Use this hook to link an external account on another Privy app to the user's account in your app. * * @returns linkWithCrossApp - prompts the user to authorize access to their account on another Privy app. */ declare const useLinkWithCrossApp: () => UseLinkWithCrossAppInterface; interface SignMessageWithCrossAppInput { /** An arbitrary message to be signed */ message: string; /** Wallet address of the cross-app wallet to sign the message with */ address: string; /** a URL path used to redirect back to your app */ redirectUri?: string | undefined; } interface SignMessageWithCrossAppOutput { /** The resulting signature of the provided message */ signature: string; } interface UseSignMessageWithCrossAppInterface { /** * Prompts the user to sign a message with a wallet on another Privy app that they have linked * with. * * This will open up an in app browser for the user to authorize the signature. */ signMessage: (input: SignMessageWithCrossAppInput) => Promise<SignMessageWithCrossAppOutput>; } /** * Use this hook to sign a message with a wallet on another Privy app that the user has linked with. * * @returns signMessage - prompts the user to sign a message with a wallet on another Privy app. */ declare const useSignMessageWithCrossApp: () => UseSignMessageWithCrossAppInterface; interface SignTypedDataWithCrossAppInput { /** A typed data structure to be signed */ typedData: TypedDataDefinition; /** Wallet address of the cross-app wallet to sign the typed data with */ address: string; /** a URL path used to redirect back to your app */ redirectUri?: string | undefined; } interface SignTypedDataWithCrossAppOutput { /** The resulting signature of the provided typed data */ signature: string; } interface UseSignTypedDataWithCrossAppInterface { /** * Prompts the user to sign a typed data structure with a wallet on another Privy app that they * have linked with. * * This will open up an in app browser for the user to authorize the signature. */ signTypedData: (input: SignTypedDataWithCrossAppInput) => Promise<SignTypedDataWithCrossAppOutput>; } /** * Use this hook to sign a typed data structure with a wallet on another Privy app that the user has * linked with. * * @returns signTypedData - prompts the user to sign a typed data structure with a wallet on another Privy app. */ declare const useSignTypedDataWithCrossApp: () => UseSignTypedDataWithCrossAppInterface; interface SendTransactionWithCrossAppInput { /** The transaction to execute */ transaction: UnsignedTransactionRequest; /** Wallet address of the cross-app wallet to make the transaction with */ address: string; /** a URL path used to redirect back to your app */ redirectUri?: string | undefined; } interface SendTransactionWithCrossAppOutput { /** The hash of the resulting transaction */ transactionHash: string; } interface UseSendTransactionWithCrossAppInterface { /** * Prompts the user to send a transaction from a wallet on another Privy app that they have linked * with. * * This will open up an in app browser for the user to authorize the transaction. */ sendTransaction: (input: SendTransactionWithCrossAppInput) => Promise<SendTransactionWithCrossAppOutput>; } /** * Use this hook to send a transaction from a wallet on another Privy app that the user has linked * with. * * @returns sendTransaction - prompts the user to authorize a transaction from a wallet on another Privy app. */ declare const useSendTransactionWithCrossApp: () => UseSendTransactionWithCrossAppInterface; type SetRecoveryParams = { recoveryMethod: 'recovery-encryption-key'; recoveryKey: string; } | { recoveryMethod: 'user-passcode'; password: string; } | { recoveryMethod: 'google-drive'; } | { recoveryMethod: 'icloud'; } | { recoveryMethod: 'privy'; }; interface UseSetEmbeddedWalletRecoveryResult { /** * The user object with the updated recovery method. * Return null if the flow was deferred, such as for Google Drive. */ user: User | null; } interface UseSetEmbeddedWalletRecovery { /** * An async method to update the recovery method of the embedded wallet. * * @param params The parameters with which to update the recovery method. * @returns A promise that resolves when the recovery method has been updated. */ setRecovery: (params: SetRecoveryParams) => Promise<UseSetEmbeddedWalletRecoveryResult>; } /** * Hook to recover an embedded wallet. It uses the primary wallet of the user for a shared source of recovery. * * It only supports the `user-passcode` recovery method. * * @returns An object with a `setRecovery` method that allows you to update the recovery method of the embedded wallet. */ declare const useSetEmbeddedWalletRecovery: () => UseSetEmbeddedWalletRecovery; type RecoverParams = { recoveryMethod: 'recovery-encryption-key'; recoveryKey: string; } | { recoveryMethod: 'user-passcode'; password: string; } | { recoveryMethod: 'google-drive'; } | { recoveryMethod: 'privy'; } | { recoveryMethod: 'icloud'; }; interface UseRecoverEmbeddedWallet { /** * An async method to recover the embedded wallet. * * @param params The parameters with which to recover the embedded wallet. * @returns A promise that resolves when the embedded wallet has been recovered. */ recover: (params: RecoverParams) => Promise<void>; } /** * Hook to recover an embedded wallet. It uses the primary wallet of the user to * recover all of the embedded wallets. * * @returns An object with a `recover` method that allows you to recover the embedded wallets. * Signing with the embedded wallet is done separately, using the `getProvider()` * method after recovery. * * @example * const {recover} = useRecoverEmbeddedWallet(); * const solanaWallet = useEmbeddedSolanaWallet(); * // ... * await recover(...) // This recovers all embedded wallets * await solanaWallet.getProvider() // Connects to the Solana wallet */ declare const useRecoverEmbeddedWallet: () => UseRecoverEmbeddedWallet; /** * A hook to register a global recovery handler. * * The provided callback will be triggered anytime the user's wallet needs to be * recovered (e.g. on a new device or after local state is wiped). * * NOTE: Ensure that `onRecover` is called after the user has successfully completed * the flow. * * @example * useOnNeedsRecovery({ * onNeedsRecovery: async ({recoveryMethod, onRecovered}) => { * await promptRecovery({recoveryMethod}) * onRecovered(); * }, * }) */ declare const useOnNeedsRecovery: (opts: { onNeedsRecovery: OnNeedsRecovery; }) => void; interface UseOnEmbeddedWalletStateChange { onStateChange: (state: EmbeddedWalletState) => void; } /** * Attach callbacks for state changes on embedded wallets * * @example * useEmbeddedWalletStateChange({ * onStateChange: (state) => { * if (state.status === 'not-created') { * return router.replace('/create-wallet'); * } * * if (state.status === 'connected') { * return router.replace('/'); * } * }, * }); */ declare const useEmbeddedWalletStateChange: ({ onStateChange }: UseOnEmbeddedWalletStateChange) => void; declare const useIdentityToken: () => { getIdentityToken: () => Promise<string | null>; }; interface UseCreateGuestAccountOptions { onSuccess: AuthSuccessCallback; onError?: ErrorCallback; } interface UseCreateGuestAccount { create: () => Promise<User>; } declare const useCreateGuestAccount: (opts?: UseCreateGuestAccountOptions) => UseCreateGuestAccount; /** * Use this hook to register your app's logic for prompting users to complete MFA. * When a user is required to complete MFA in order to use their embedded wallet, * Privy will invoke the logic you register here to have the user complete MFA. * This hook should be mounted somewhere towards the root of your application tree * so that it can handle MFA required events from the entire application. * * @param callbacks callbacks to register your logic for prompting users to complete MFA. * @param callbacks.onMfaRequired Privy will invoke this callback * whenever the user is required to complete MFA. Pass in a function that will prompt * your user to complete MFA with Privy (using `useMfa`) and only returns once * MFA has been completed. * * @example * const [mfaMethods, setMfaMethods] = useState([]) * const [isMfaDialogOpen, setIsMfaDialogOpen] = useState(false) * * // Prompt user to select from their enabled MFA methods * useRegisterMfaListener({ * onMfaRequired: async (methods) => { * setMfaMethods(methods) * setIsMfaDialogOpen(true); * }, * }); * * // Within MFA modal allow the user to select an MFA method * <MFAModal * mfaMethods={mfaMethods} * isOpen={isMfaDialogOpen} * setIsOpen={setIsMfaDialogOpen} * /> * * See `useMfa` for how to execute the MFA flow within Privy in your App. */ declare function useRegisterMfaListener({ onMfaRequired, }: { onMfaRequired: (mfaMethods: MfaMethod[]) => void | Promise<void>; }): void; interface UseMfa { init(args: { method: 'sms'; }): Promise<void>; init(args: { method: 'totp'; }): Promise<void>; init(args: { method: 'passkey'; relyingParty?: string; }): Promise<PublicKeyCredentialRequestOptionsJSON>; submit(args: { method: 'sms' | 'totp'; mfaCode: string; relyingParty?: string; }): Promise<void>; submit(args: { method: 'passkey'; mfaCode: PublicKeyCredentialRequestOptionsJSON; relyingParty?: string; }): Promise<void>; prompt(): Promise<void>; cancel(): void; } /** * Use this hook to execute the MFA flow with Privy. * * @returns init - starts the MFA verification flow * @returns submit - completes the MFA verification flow * @returns prompt - programmatically send mfaRequired event if MFA is needed * @returns cancel - cancels the MFA verification flow * * @example * // MFA flow * * const MFAModal = ({ mfaMethods, isOpen, setIsOpen }: Props) => { * const {init, submit, cancel} = useMfa(); * const [selectedMethod, setSelectedMethod] = useState(null) * const [mfaCode, setMfaCode] = useState('') * * const handleClose = () => { * cancel(); * setIsOpen(false); * }; * * return ( * <Modal isOpen={isOpen} onClose={handleClose}> * // Capture the user's MFA code * {selectedMethod && ( * <button * onClick={async () => { * await submit({mfaMethod: selectedMethod, mfaCode}) * setSelectedMethod(null) * setIsOpen(false) * }} * /> * )} * {mfaMethods.map((mfaMethod) => ( * <button * onClick={async () => { * await init({mfaMethod}); * setSelectedMethod(mfaMethod) * }} * > * Choose {mfaMethod} for MFA * </button> * ))} * </Modal> * ) * }; * * @example * // Error handling * * import { * errorIndicatesMfaVerificationFailed, * errorIndicatesMfaTimeout, * errorIndicatesMfaMaxAttempts * } from '@privy-io/expo'; * const {submit} = useMfa(); * const [errorState, setErrorState] = useState<string | null>(null); * * <button * onClick={async () => { * try { * submit('sms', '<user-mfa-code>'); * } * catch (e) { * if (errorIndicatesMfaVerificationFailed(e)) { * setErrorState('Verification failed, resubmit.') * } * else if (errorIndicatesMfaMaxAttempts(e)) { * setErrorState('Max attempts reached, re-initialize MFA.') * } * else if (errorIndicatesMfaTimeout(e)) { * setErrorState('Timeout reached, re-initialize MFA.') * } * }} * > * {errorState ?? 'Verify SMS MFA Code'} * </button> * */ declare function useMfa(): UseMfa; interface UseMfaEnrollment { initMfaEnrollment(args: { method: 'sms'; phoneNumber: string; }): Promise<void>; initMfaEnrollment(args: { method: 'totp'; }): Promise<{ authUrl?: string; secret?: string; }>; initMfaEnrollment(args: { method: 'passkey'; }): Promise<void>; submitMfaEnrollment(args: { method: 'sms'; code: string; phoneNumber: string; }): Promise<void>; submitMfaEnrollment(args: { method: 'totp'; code: string; }): Promise<void>; submitMfaEnrollment(args: { method: 'passkey'; credentialIds: string[]; removeForLogin?: boolean; }): Promise<void>; unenrollMfa(args: { method: 'sms'; }): Promise<void>; unenrollMfa(args: { method: 'totp'; }): Promise<void>; unenrollMfa(args: { method: 'passkey'; removeForLogin?: boolean; }): Promise<void>; } /** * Use this hook to enroll a user in MFA * * @returns initMfaEnrollment - starts the MFA enrollment flow * @returns submitMfaEnrollment - completes the MFA enrollment flow * @returns unenrollMfa - unenrolls the MFA method * * @example * const {unenrollMfa} = useMfaEnrollment(); * * <button * onClick={() => { * unenrollMfa({method: 'sms'}); * }} * > * Unenroll in SMS MFA * </button> * * @example * const {unenrollMfa} = useMfaEnrollment(); * * <button * onClick={() => { * unenrollMfa({method: 'totp'}); * }} * > * Unenroll in TOTP MFA * </button> */ declare function useMfaEnrollment(): { initMfaEnrollment: { (args: { method: "sms"; phoneNumber: string; }): Promise<void>; (args: { method: "totp"; }): Promise<{ authUrl?: string; secret?: string; }>; (args: { method: "passkey"; }): Promise<void>; }; submitMfaEnrollment: { (args: { method: "sms"; code: string; phoneNumber: string; }): Promise<void>; (args: { method: "totp"; code: string; }): Promise<void>; (args: { method: "passkey"; credentialIds: string[]; removeForLogin?: boolean; }): Promise<void>; }; unenrollMfa: { (args: { method: "sms"; }): Promise<void>; (args: { method: "totp"; }): Promise<void>; (args: { method: "passkey"; removeForLogin?: boolean; }): Promise<void>; }; }; type UseEmbeddedWallet = { /** * Callback function triggered when wallet creation is successful. * @param {PrivyEmbeddedWalletProvider} wallet - The created wallet. */ onCreateWalletSuccess?: (wallet: PrivyEmbeddedWalletProvider) => void; /** * Callback function triggered when wallet creation encounters an error. * @param {Error} error - The error encountered during wallet creation. */ onCreateWalletError?: (error: Error) => void; /** * Callback function triggered when wallet recovery is successful. * @param {PrivyEmbeddedWalletProvider} wallet - The recovered wallet. */ onRecoverWalletSuccess?: (wallet: PrivyEmbeddedWalletProvider) => void; /** * Callback function triggered when wallet recovery encounters an error. * @param {Error} error - The error encountered during wallet recovery. */ onRecoverWalletError?: (error: Error) => void; /** * Callback function triggered when wallet recovery upgrade is successful. * @param {PrivyEmbeddedWalletProvider} wallet - The wallet with upgrading recovery. */ onSetWalletRecoverySuccess?: (wallet: PrivyEmbeddedWalletProvider) => void; /** * Callback function triggered when ugradinge wallet recovery encounters an error. * @param {Error} error - The error encountered during wallet recovery upgrade. */ onSetWalletRecoveryError?: (error: Error) => void; }; /** * @deprecated use the `useEmbeddedEthereumWallet` hook instead, in combination with * `useRecoverEmbeddedWallet` and `useSetEmbeddedWalletRecovery` for recovery specific needs. */ declare const useEmbeddedWallet: (props?: UseEmbeddedWallet) => EmbeddedWalletState; type ConnectedEthereumWallet = { /** * Address for this wallet */ address: string; /** * HD wallet index of this wallet */ walletIndex: number; /** * The chain type for this wallet */ chainType: 'ethereum'; /** * A function returning a promise that resolves to a provider to make signature * requests with this wallet. */ getProvider: () => Promise<PrivyEmbeddedWalletProvider>; }; interface UseEmbeddedEthereumWallet { /** * List of embedded ethereum wallets. */ wallets: ConnectedEthereumWallet[]; /** * Creates an Ethereum account. * * @param o input options * @param o.createAdditional whether or not to create an additional account if the user already has one * * @returns an object with the updated user */ create: (opts?: { createAdditional?: boolean; }) => Promise<{ user: User; }>; } /** * Use this hook to interact with the user's embedded ethereum wallets. */ declare const useEmbeddedEthereumWallet: () => UseEmbeddedEthereumWallet; type UseEmbeddedSolanaWallet = { /** * Callback function triggered when wallet creation is successful. * @param {PrivyEmbeddedSolanaWalletProvider} wallet - The created wallet. */ onCreateWalletSuccess?: (wallet: PrivyEmbeddedSolanaWalletProvider) => void; /** * Callback function triggered when wallet creation encounters an error. * @param {Error} error - The error encountered during wallet creation. */ onCreateWalletError?: (error: Error) => void; /** * Callback function triggered when wallet recovery is successful. * @param {PrivyEmbeddedWalletProvider} wallet - The recovered wallet. */ onRecoverWalletSuccess?: (wallet: PrivyEmbeddedSolanaWalletProvider) => void; /** * Callback function triggered when wallet recovery encounters an error. * @param {Error} error - The error encountered during wallet recovery. */ onRecoverWalletError?: (error: Error) => void; }; declare const useEmbeddedSolanaWallet: (props?: UseEmbeddedSolanaWallet) => EmbeddedSolanaWalletState; type ConnectedBitcoinWallet = { /** * Address for this wallet */ address: string; /** * Public key for this wallet, hex encoded. */ publicKey: string; /** * HD wallet index of this wallet */ walletIndex: number; /** * The chain type for this wallet */ chainType: 'bitcoin-segwit' | 'bitcoin-taproot'; /** * A function returning a promise that resolves to a provider to make signature * requests with this wallet. */ getProvider: () => Promise<EmbeddedBitcoinWalletProvider>; }; interface UseEmbeddedBitcoinWallet { /** * List of embedded bitcoin wallets. */ wallets: ConnectedBitcoinWallet[]; /** * Creates a Bitcoin account. * * Currently Bitcoin wallets cannot be created until a user has an existing Ethereum or * Solana wallet. * * @param o input options * @param o.chainType the type of bitcoin wallet to create (e.g. segwit or taproot) * @param o.createAdditional whether or not to create an account if the user already has one * * @returns an object with the updated user and the new embedded wallet provider */ create: (opts: { createAdditional?: boolean; chainType: 'bitcoin-segwit' | 'bitcoin-taproot'; }) => Promise<{ user: User; provider: EmbeddedBitcoinWalletProvider; }>; } /** * Use this hook to interact with the user's embedded bitcoin wallets when * the app is using on-device execution. * * This interface is **not supported for apps using TEE execution**. * Use `useSignRawHash` from `@privy-io/expo/extended-chains` instead for those * applications. * @see {@link https://docs.privy.io/wallets/using-wallets/other-chains#react-native} */ declare const useEmbeddedBitcoinWallet: () => UseEmbeddedBitcoinWallet; declare const usePrivyClient: () => Privy.default; interface UsePrivy { /** * The current authenticated user, or `null` when unauthenticated. */ user: User | null; /** * Whether or not the SDK has initialized and is ready for use. */ isReady: boolean; /** * Any error encountered during SDK initialization. E.g. inability to access * storage for reading/writing tokens. */ error: Error | null; /** * A function that logs the current user out and clears any stored tokens. No-op * if there is no authenticated user. * * @returns a promise that always resolves to void. */ logout: () => Promise<void>; /** * A function that gets the current authenticated user's access token. If the * access token is near its expiration the SDK will attempt to refresh the * token and return the updated token. * * NOTE: this function should be called anytime an access token is needed, at * the time its needed. It is _not recommended_ to cache the response. * * @returns the access token, or `null` */ getAccessToken: () => Promise<string | null>; } /** * Hook that exposes the core state of the Privy SDK, including the current * authenticated user object and whether or not the SDK has initialized. * * @returns the Privy SDK's core state * * @example * const {user, isReady} = usePrivy() */ declare const usePrivy: () => UsePrivy; /** * Hook for accepting the app's terms and conditions and privacy policy on * behalf of the current user. * * Use this in whitelabel integrations where the user has accepted your terms * outside of the Privy UI (e.g. a custom checkbox during signup). * * @example * const {acceptTerms} = useAcceptTerms(); * const {user} = await acceptTerms(); // marks user.has_accepted_terms as true */ declare function useAcceptTerms(): { acceptTerms: () => Promise<{ user: User; }>; }; interface UseAuthorizationSignatureInterface { /** * Generate an authorization signature for an API request with the user's authorization key. * @see {@link https://docs.privy.io/api-reference/authorization-signatures |Authorization signatures} * @param input The request payload to sign. Can be a structured request object (which will be * canonicalized to JSON before signing) or a pre-serialized binary payload (`Uint8Array`) that * will be signed directly. * @returns The user's authorization signature over the API request. */ generateAuthorizationSignature: (input: GenerateAuthorizationSignatureInput | Uint8Array) => Promise<GenerateAuthorizationSignatureOutput>; } /** * Hook to sign an API request with the user's authorization key. * @returns The `generateAuthorizationSignature` method which can be used to sign over an API request. */ declare const useAuthorizationSignature: () => UseAuthorizationSignatureInterface; interface UseGetEncryptedAuthorizationKeyInterface { /** * Fetches an encrypted authorization key by ID using the SDK's internal * Privy access token. Use this instead of calling the endpoint directly * from mobile, where HttpOnly cookies are not available. */ getEncryptedAuthorizationKey: ({ id }: { id: string; }) => Promise<EncryptedAuthorizationKeyResponse>; } /** * Hook to fetch an encrypted authorization key using the SDK's internal Privy access token. * @returns The `getEncryptedAuthorizationKey` method which fetches a key by ID. */ declare const useGetEncryptedAuthorizationKey: () => UseGetEncryptedAuthorizationKeyInterface; type PrivyContext = { client: Privy__default; isReady: boolean; error: Error | null; wallet: EmbeddedWalletState; solanaWallet: EmbeddedSolanaWalletState; otpState: OtpFlowState; setOtpState: React.Dispatch<React.SetStateAction<OtpFlowState>>; oAuthState: OAuthFlowState; setOAuthState: React.Dispatch<React.SetStateAction<OAuthFlowState>>; createWalletCallbacks: React.MutableRefObject<WalletRecoveryCallbacks | undefined>; recoverWalletCallbacks: React.MutableRefObject<WalletRecoveryCallbacks | undefined>; setWalletRecoveryCallbacks: React.MutableRefObject<WalletRecoveryCallbacks | undefined>; createSolanaWalletCallbacks: React.MutableRefObject<SolanaWalletRecoveryCallbacks | undefined>; recoverSolanaWalletCallbacks: React.MutableRefObject<SolanaWalletRecoveryCallbacks | undefined>; recoveryFlowState: RecoveryFlowState; setRecoveryFlowState: React.Dispatch<React.SetStateAction<RecoveryFlowState>>; solanaRecoveryFlowState: RecoveryFlowState; setSolanaRecoveryFlowState: React.Dispatch<React.SetStateAction<RecoveryFlowState>>; siweState: SiweFlowState; setSiweState: React.Dispatch<React.SetStateAction<SiweFlowState>>; passkeyState: PasskeyFlowState; setPasskeyState: React.Dispatch<React.SetStateAction<PasskeyFlowState>>; farcasterState: FarcasterFlowState; setFarcasterState: React.Dispatch<React.SetStateAction<FarcasterFlowState>>; logout: () => Promise<void>; getAccessToken: () => Promise<string | null>; getIdentityToken: () => Promise<string | null>; }; declare const PrivyContext: React.Context<PrivyContext>; interface PrivyProviderProps { children: React.ReactNode; /** * Privy application ID _(can be found in privy developer dashboard)_ */ appId: string; /** * Privy client ID _(can be found in privy developer dashboard, in the clients section for each app)_ */ clientId?: string; /** * By default, the Privy SDK will store any persisted state in SecureStorage. * This behavior can be overridden by defining in a storage prop * that implements the privy `Storage` interface. * * @example * import type {Storage} from '@privy-io/expo'; * * class OtherStorage implements Storage { ... } * * <PrivyProvider appId="<your-app-id>" storage={OtherStorage}> * {children} * </PrivyProvider> */ storage?: Storage; /** * A list of supported chains, used to specify which chains should be used throughout the application. * **Overrides the default list of supported chains.** Calling `sendTransaction` or `switchChain` on * an unsupported network will throw an error. * * For embedded wallets, the wallet will automatically default to the first supplied `supportedChain`. * * Defaults to: * - mainnet * - goerli * - sepolia * - arbitrum * - arbitrumGoerli * - optimism * - optimismGoerli * - polygon * - polygonMumbai * - celo * - celoAlfajores * - filecoin * - filecoinCalibration * - base * - baseGoerli * - linea * - lineaTestnet * - avalanche * - avalancheFuji * - holesky * - redstoneHolesky */ supportedChains?: [Chain, ...Chain[]]; config?: PrivyConfig; /** * A Privy client instance, instantiated and controlled externally. * * @see {@link createPrivyClient} * * @example * // There should only ever be a single global instance of the Privy client * const client = createPrivyClient(opts); * * // Pass the global instance of the Privy client to the provider * <PrivyProvider client={client}>{...}</PrivyProvider> */ client?: Privy__default; } /** * @deprecated Use `client.getAccessToken()` instead. * * Get the access token for the current user, if they are logged in. * This method will refresh the user's access token if is nearing expiration or has expired. * * @returns The access token if the user is logged in, otherwise `null`. */ declare function getAccessToken(o?: { strict?: boolean; }): Promise<string | null>; declare const PrivyProvider: (props: PrivyProviderProps) => React.JSX.Element; interface PrivyAuthGuardProps { loading: React.ReactNode; unauthenticated: React.ReactNode; error?: React.ReactNode | ((error: Error) => React.ReactNode); } /** * This component is used to simplify protecting routes based on the user's * authentication status, and the Privy SDK's readiness. * * @param props.loading Rendered while the SDK is not ready. * @param props.unauthenticated Rendered when the user is not yet authenticated. * @param props.error (Optional) Re