Skip to main content
This package provides React hooks for conveniently accessing embedded wallet functionality. Built on top of @coinbase/cdp-core, it offers a React-friendly interface for end user authentication and embedded wallet operations.

Quickstart

This guide will help you get started with @coinbase/cdp-hooks. You’ll learn how to install the package, set up the provider, and use the hooks in both web and React Native applications.

Installation

Web Applications

For web applications, add the package to your project using your preferred package manager:

React Native Applications

For React Native applications, you’ll need additional crypto polyfills and dependencies:
React Native Setup Code You’ll need to initialize the crypto polyfills before importing your app. Create or update your entry point file (typically index.js or index.ts):
Why these dependencies?
  • react-native-quick-crypto: Provides Web Crypto API compatibility for asymmetric key generation (ECDSA, RSA) required for JWT signing and encryption
  • react-native-get-random-values: Provides secure random number generation via crypto.getRandomValues()
  • @ungap/structured-clone: Polyfills structuredClone for object cloning compatibility
  • @react-native-async-storage/async-storage: Provides persistent storage for auth tokens and secrets

Gather your CDP Project Information

  1. Sign in or create an account on the CDP Portal
  2. On your dashboard, select a project from the dropdown at the at the top, and copy the Project ID

Allowlist your local app

  1. Navigate to the Embedded Wallet Configuration in CDP Portal, and click Add origin to include your local app
  2. Enter the origin of your locally running app - e.g., http://localhost:3000
  3. Click Add origin again to save your changes

Setup Provider

Next, you need to wrap your application with the CDPHooksProvider, which provides the necessary context for hooks to work correctly.

Web Applications

Update your main application file (e.g., main.tsx) to include the provider:

React Native Applications

For React Native, the setup is identical.

Analytics Opt-Out

By default the SDK will emit usage analytics to help us improve the SDK. If you would like to opt-out, you can do so by setting the disableAnalytics configuration option to true.

Smart Account Configuration

You can configure the provider to automatically create Smart Accounts for new users:
  • When ethereum.createOnLogin is set to "smart", new users will automatically get both an EOA and a Smart Account.

Solana Configuration

You can configure the provider to create Solana accounts for new users:
  • When solana.createOnLogin is set to true, new users will automatically get a Solana account instead of EVM accounts.

Deferred Account Creation

You can omit createOnLogin entirely to prevent automatic account creation and instead create accounts manually when needed:
When createOnLogin is omitted, the SDK will:
  1. Not create any accounts automatically upon user login
  2. Require manual account creation using the account creation hooks (see below)
  3. Give you full control over when and what types of accounts to create

Sign In a User

End user authentication proceeds in two steps:
  1. The user inputs their email address to initiate the authentication flow, which will send the user a One Time Password (OTP) and return a flowId
  2. The user submits the six-digit OTP and flowId, after which the user will be authenticated, returning a User object.

Web Applications

Working with Multiple Accounts

Users can have up to 10 accounts per blockchain type (EVM, Solana). The SDK provides both single-account and multi-account hooks to support different use cases.

Single Account Hooks

These hooks return the first account (index 0). They’re ideal for simple applications where most users have one account:
  • useEvmAddress() - Returns first smart account, then first EOA
  • useSolanaAddress() - Returns first Solana account

Multi-Account Hooks (All Accounts with Metadata)

These hooks return all accounts with additional metadata (creation timestamp, owner addresses). Use these when:
  • Users may have multiple accounts
  • You need account metadata (creation date, etc.)
  • You’re building an account selector UI
Available hooks:
  • useEvmAccounts() - All EVM EOA accounts with metadata
  • useSolanaAccounts() - All Solana accounts with metadata
  • useEvmSmartAccounts() - All EVM smart accounts with metadata

When to Use Which?

React Native Applications

For React Native, you’ll use native UI components and handle the sign-in flow similarly:
Once a user is authenticated, you can link additional authentication methods to their account. This allows users to sign in using multiple methods (email, SMS, OAuth providers) with the same embedded wallet. Use the useLinkEmail hook to link an email address to the currently authenticated user:
Use the useLinkSms hook to link a phone number to the currently authenticated user:
Use the useLinkGoogle hook to link a Google account to the currently authenticated user:
Use the useLinkApple hook to link an Apple account to the currently authenticated user:
Use the useLinkOAuth hook to link any supported OAuth provider (Google, Apple) to the currently authenticated user:

Sign In with Custom Authentication

If you’re using a third-party identity provider (Auth0, Firebase, AWS Cognito, or any OIDC-compliant provider), you can authenticate users with JWTs from your provider using the useAuthenticateWithJWT hook.

Prerequisites

Before using custom authentication:
  1. Configure your identity provider in the CDP Portal:
    • Navigate to Embedded Wallet Configuration
    • Click on the Custom auth tab
    • Add your JWKS endpoint URL (e.g., https://your-domain.auth0.com/.well-known/jwks.json)
    • Configure your JWT issuer and audience
  2. Provide a customAuth.getJwt callback in your provider configuration:

Authenticate a User

Multi-Factor Authentication (MFA)

The CDP SDK provides hooks for implementing Multi-Factor Authentication using two methods:
  • TOTP (Time-based One-Time Password): Users enroll using authenticator apps like Google Authenticator or Authy
  • SMS: Users receive verification codes via text message to their phone number
MFA adds an extra layer of security for user accounts and sensitive operations.
Important: Users must be authenticated (signed in) before they can enroll in MFA or perform MFA verification.

Enroll User in TOTP MFA

Use useInitiateMfaEnrollment and useSubmitMfaEnrollment to enroll a user in TOTP MFA:

Enroll User in SMS MFA

Use useInitiateMfaEnrollment and useSubmitMfaEnrollment to enroll a user in SMS MFA:

Verify TOTP MFA for Sensitive Operations

Use useInitiateMfaVerification and useSubmitMfaVerification to verify TOTP MFA for sensitive operations:

Verify SMS MFA for Sensitive Operations

Use useInitiateMfaVerification and useSubmitMfaVerification to verify SMS MFA for sensitive operations:

Check MFA Configuration

Use useGetMfaConfig to check whether MFA is enabled for your project:

Track MFA Enrollment Prompts

Use useRecordMfaEnrollmentPrompted to track when users are shown the MFA enrollment prompt:
Use Cases for Tracking Enrollment Prompts:
  • Track when users skip MFA enrollment to avoid over-prompting
  • Implement smart re-prompting logic based on time intervals
  • Analyze MFA adoption rates across your user base
  • Identify users who need additional education about MFA benefits

View User Information

Once the end user has signed in, you can display their information in your application:

Create Accounts Manually

If you configured your provider without createOnLogin, you can manually create accounts for authenticated users when needed using these hooks.

Create an EOA Account

Use the useCreateEoaAccount hook to create an EOA (Externally Owned Account) for the current user:
Note: This will throw an error if the user already has an EOA account.

Create a Smart Account

Use the useCreateSmartAccount hook to create a Smart Account for the current user:
Note: This will throw an error if the user already has a Smart Account. If the user doesn’t have an EOA, one will be automatically created first to serve as the Smart Account owner.

Create a Solana Account

Use the useCreateSolanaAccount hook to create a Solana account for the current user:
Note: This will throw an error if the user already has a Solana account.

Working with Solana

When your application is configured with solana: { createOnLogin: true }, you can use Solana-specific hooks to interact with Solana accounts.

Access Solana Address

Use the useSolanaAddress hook to get the user’s first Solana address:

Sign a Solana Transaction

Use the useSignSolanaTransaction hook to sign Solana transactions:

Sign a Solana Message

Use the useSignSolanaMessage hook to sign arbitrary messages with Solana accounts:

Send a Solana Transaction

Use the useSendSolanaTransaction hook to sign and send Solana transactions in a single action. This is supported on:
  • Solana Mainnet
  • Solana Devnet

Send a Transaction

We support signing and sending a Blockchain transaction in a single action on the following networks:
  • Base
  • Base Sepolia
  • Ethereum
  • Ethereum Sepolia
  • Avalanche
  • Arbitrum
  • Optimism
  • Polygon
For networks other than those supported by the CDP APIs, your end user must sign the transaction, and then you must broadcast the transaction yourself. This example uses the public client from viem to broadcast the transaction.

Sign Messages and Typed Data

End users can sign EVM messages, hashes, and typed data to generate signatures for various onchain applications.

Export Private Keys

End users can export their private keys from their embedded wallet, allowing them to import them into compatible wallets of their choice. The secure iframe hooks are the recommended way to export private keys. They create a secure iframe that copies the private key directly to the user’s clipboard without ever exposing it to your application’s JavaScript context.
Export EVM Private Key via Iframe
Export Solana Private Key via Iframe

Direct Export (Deprecated)

⚠️ Deprecated: The direct export hooks expose the private key to your application’s JavaScript context and will be removed soon. Use the secure iframe hooks above instead.
Export EVM Private Key (Deprecated)
Export Solana Private Key (Deprecated)
When your application is configured with solana: { createOnLogin: true }, you can export Solana private keys:

Smart Account Operations

Smart Accounts provide advanced account abstraction features with React hooks.

Create Spend Permissions

Spend permissions allow Smart Accounts to delegate spending authority to other accounts within specified limits and time periods. The useCreateSpendPermission hook provides an easy way to create spend permissions with automatic user operation tracking.
The hook automatically:
  • Detects the user’s Smart Account (or allows you to specify evmSmartAccount)
  • Converts periodInDays to seconds
  • Resolves token symbols like “eth” and “usdc” to contract addresses
  • Tracks the user operation status and provides real-time updates

List Spend Permissions

Use the useListSpendPermissions hook to retrieve all spend permissions for a Smart Account. This hook follows a query-style pattern and automatically fetches permissions when enabled.

Revoke Spend Permissions

Use the useRevokeSpendPermission hook to revoke a spend permission. The hook automatically tracks the user operation and provides real-time status updates.

Send User Operations

Send user operations from Smart Accounts with support for multiple calls and paymaster sponsorship. The hook returns a method to execute the user operation and status, data, and error properties to read the result of the user operation:
Transaction Attribution with EIP-8021: You can add attribution data to user operations for tracking app usage and revenue sharing:
The dataSuffix parameter accepts a hex-encoded string following the EIP-8021 standard. This enables onchain attribution for tracking and revenue sharing.

Track User Operation Status

Use the useWaitForUserOperation hook to poll for user operation status and provide real-time updates. This hook immediately fires off a query to get the result of the user operation:

Conditional Polling

You can control when the useWaitForUserOperation hook should start polling using the enabled parameter:

X402 Payment Protocol Support

The SDK includes built-in support for the X402 payment protocol through the useX402 hook. This enables HTTP requests with micropayments, allowing access to paid APIs and services that require payment for each request.

Installation

Ensure you have separately installed the x402-fetch package:

Basic Usage

The useX402 hook provides a wrapped fetch API that automatically handles X402 payment requests:

Advanced Configuration

You can customize the X402 behavior with options:

How It Works

  1. When you make a request to an X402-protected resource, the server responds with a 402 Payment Required status
  2. The wrapped fetch function automatically:
    • Extracts payment details from the server’s response
    • Creates and signs a payment transaction using the user’s wallet
    • Includes the payment proof in a retry request
  3. The server validates the payment and returns the requested resource

Smart Account Support

By default, useX402 will use the user’s Smart Account if available, falling back to their regular EVM account:

Solana Support

Solana support is supported out of the box with useX402. If your end user has both an EVM and Solana account, the EVM account will be used by default. You can pass a Solana address to useX402 to use the Solana account instead.

React Native Support

The useX402 hook works seamlessly in React Native applications: