Embedded Wallets provides components that work with Coinbase’s Onramp API to enable developers to move money from fiat to onchain economies. A user can fund their wallet with their Coinbase account or through guest checkout with a debit card.This guide shows how to get started with the FundModal component.
Coinbase Onramp is enabled by default in trial mode for every CDP project. In trial mode, there are limitations to how much you can purchase.
To begin, add your domain to the list of allowed domains in CDP Portal.
1
Access CDP Portal
Navigate to the Domains Configuration in CDP Portal, and click Add domain to include your local app.
2
Add your domain
Use http://localhost:3000 (the port your demo app will run locally).
Do not do this in your CDP project intended for production use. Malicious apps running locally could impersonate your frontend and abuse your project credentials.
3
Save your changes
Click Add domain again to save your changes.
You should see your local app URL listed in the CDP Portal dashboard. The allowlist will take effect immediately upon saving.
Navigate to the API Keys tab of the CDP Portal. Create your API key by entering an API key nickname (restrictions are optional).
Secure your private/public key pair in a safe location. You will use these in step 3 when configuring your demo app.
Optional API Key File DownloadFor enhanced security, API key files are no longer automatically downloaded. If you need to reference your API key via file path in your code, click the Download API key button in the modal to save the key file. Otherwise, you can copy the key details directly from the modal and use them as environment variables (recommended for better security).
2
Copy your Project ID
Navigate to CDP Portal and select your project from the top-left dropdown. Clicking the gear icon will take you to your project details:
Copy the Project ID value. You will use this in the next step when configuring your demo app.
3
Create a new demo app
Use the latest version of create-cdp-app to create a new demo app using your package manager:
Report incorrect code
Copy
Ask AI
npm create @coinbase/cdp-app@latest
4
Configure your app
Follow the prompts to configure your app. Name your project, select the Next.js Full Stack App template, and paste your project ID from CDP Portal.
The Next.js Full Stack App template must be selected because Onramp requires server-side code!
You can choose between EVM EOA (Regular Accounts), EVM Smart Accounts, or Solana Accounts, and you should enable Onramp.
For this demo app, we will choose EVM EOA (Regular Accounts).To complete configuration, enter the API Key ID and API Key Secret key pair you created in the previous step and confirm that you have added your domain.
Report incorrect code
Copy
Ask AI
✔ Project name: … cdp-app-nextjs✔ Template: › Next.js Full Stack App✔ CDP Project ID: … 8c21e60b-c8af-4286-a0d3-111111111111✔ Account Type: › EVM EOA (Regular Accounts)✔ Enable Coinbase Onramp?: … yes✔ CDP API Key ID: … 9b12d52e-d2be-5516-bd90-111111111111✔ CDP API Key Secret: … *****************************************✔ Confirm you have whitelisted 'http://localhost:3000' … yes
5
Run your app
Navigate to your project and start the development server:
Congrats! Your new embedded wallet has been created, authenticated, and is ready to use on the Base network.
What is Base?
Base is a fast, low-cost blockchain built by Coinbase.
From the demo app, you can copy-and-paste your wallet address from the top-right corner. You can also fund your wallet and monitor your balance. You should see similar to the following:
Click the Deposit ETH button to start funding your new wallet.
5
Enter deposit details
This opens the funding modal where you can specify how much you want to deposit. Choose a preset amount or enter your own, select your preferred payment method, and click Deposit to proceed to the Coinbase Onramp widget.
6
Complete your purchase
The Coinbase Onramp widget opens for you to review the transaction details. Here, you can verify the payment method, destination address, and total cost before finalizing the purchase.
Click Confirm & Purchase to complete the transaction.
7
View your confirmation
Once the transaction is successful, you’ll see a confirmation message. The funds are now being sent to your wallet onchain, and your balance will update shortly.
You can also find record of your wallet and its transaction on Base explorer using the URL: https://basescan.org/address/YOUR-WALLET-ADDRESS.
What is a transaction?
A blockchain transaction transfers cryptocurrency between wallets. Unlike bank transfers, they’re:
Optional API Key File DownloadFor enhanced security, API key files are no longer automatically downloaded. If you need to reference your API key via file path in your code, click the Download API key button in the modal to save the key file. Otherwise, you can copy the key details directly from the modal and use them as environment variables (recommended for better security).
Navigate to the API Keys tab of the CDP Portal. Create your API key by entering an API key nickname (restrictions are optional).
Secure your private/public key pair in a safe location.
2
Update .env
Update your app’s .env file with the API Key ID and API Key Secret.
Report incorrect code
Copy
Ask AI
# CDP API KeyCDP_API_KEY_ID=[paste your API Key ID here]CDP_API_KEY_SECRET=[paste your API Key Secret here]
Create a new file lib/cdp-auth.ts in your project root. This file exports helper functions to generate JWTs for authorizing Onramp API calls and provides the base URL for API requests.
lib/cdp-auth.ts
Report incorrect code
Copy
Ask AI
import { generateJwt } from "@coinbase/cdp-sdk/auth";interface CDPAuthConfig { requestMethod: string; requestHost: string; requestPath: string; audience?: string[];}/** * Get CDP API credentials from environment variables * * @throws Error if credentials are not configured */export function getCDPCredentials() { const apiKeyId = process.env.CDP_API_KEY_ID; const apiKeySecret = process.env.CDP_API_KEY_SECRET; if (!apiKeyId || !apiKeySecret) { throw new Error("CDP API credentials not configured"); } return { apiKeyId, apiKeySecret };}/** * Generate JWT token for CDP API authentication * * @param config - Configuration for JWT generation * @returns JWT token string */export async function generateCDPJWT(config: CDPAuthConfig): Promise<string> { const { apiKeyId, apiKeySecret } = getCDPCredentials(); return generateJwt({ apiKeyId, apiKeySecret, requestMethod: config.requestMethod, requestHost: config.requestHost, requestPath: config.requestPath, });}/** * Base URL for ONRAMP API * Can change to api.cdp.coinbase.com/platform once session token endpoints are supported in v2 API */export const ONRAMP_API_BASE_URL = "https://api.developer.coinbase.com";
This utility file provides:
getCDPCredentials(): Reads your API credentials from environment variables
generateCDPJWT(): Creates authenticated JWT tokens for API calls
ONRAMP_API_BASE_URL: The base URL for all Onramp API requests
These functions will be imported and used in your API routes in the next step.
Finally, you are ready to add the FundModal component to your app.
1
Create fetchBuyOptions and fetchBuyQuote
The FundModal component requires fetchBuyOptions and fetchBuyQuote props, which are functions that handle calling the Onramp API via your new server-side endpoints.
lib/onramp-api.ts
Report incorrect code
Copy
Ask AI
import { type FetchBuyOptions, type FetchBuyQuote,} from "@coinbase/cdp-react/components/Fund";/** * Fetches available buy options for onramp * * @param params - Query parameters for buy options * @returns Buy options including payment currencies and purchasable assets */export const getBuyOptions: FetchBuyOptions = async params => { const queryParams = new URLSearchParams(); queryParams.append("country", params.country); if (params?.subdivision) queryParams.append("subdivision", params.subdivision); const queryString = queryParams.toString(); const url = `/api/onramp/buy-options${queryString ? `?${queryString}` : ""}`; const response = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json", }, }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error || "Failed to fetch buy options"); } return await response.json();};/** * Creates a buy quote for onramp purchase * * @param request - Buy quote request parameters * @returns Buy quote with fees and onramp URL */export const createBuyQuote: FetchBuyQuote = async request => { const response = await fetch("/api/onramp/buy-quote", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(request), }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error || "Failed to create buy quote"); } return await response.json();};
2
Render FundModal
components/FundWallet.tsx
Report incorrect code
Copy
Ask AI
"use client";import { FundModal, type FundModalProps,} from "@coinbase/cdp-react";import { useEvmAddress } from "@coinbase/cdp-hooks";import { useCallback } from "react";import { getBuyOptions, createBuyQuote } from "@/lib/onramp-api";/** * A component that wraps the FundModal component * * @param props - The props for the FundWallet component * @param props.onSuccess - The callback function to call when the onramp purchase is successful * @returns The FundWallet component */export default function FundWallet({ onSuccess }: { onSuccess: () => void }) { const { evmAddress } = useEvmAddress(); // Get the user's location (i.e. from IP geolocation) const userCountry = "US"; // If user is in the US, the state is also required const userSubdivision = userCountry === "US" ? "CA" : undefined; // Call your buy quote endpoint const fetchBuyQuote: FundModalProps["fetchBuyQuote"] = useCallback(async params => { return createBuyQuote(params); }, []); // Call your buy options endpoint const fetchBuyOptions: FundModalProps["fetchBuyOptions"] = useCallback(async params => { return getBuyOptions(params); }, []); return ( <FundModal country={userCountry} subdivision={userSubdivision} cryptoCurrency="eth" fiatCurrency="usd" fetchBuyQuote={fetchBuyQuote} fetchBuyOptions={fetchBuyOptions} network="base" presetAmountInputs={[10, 25, 50]} onSuccess={onSuccess} destinationAddress={evmAddress} /> );}
Funding a Solana wallet with FundModal
You may fund your Solana embedded wallets using the same FundModal as in the EVM example above.
Just pass in the appropriate values for the cryptoCurrency, network, and destinationAddress props.
components/FundSolanaWallet.tsx
Report incorrect code
Copy
Ask AI
"use client";import { FundModal, type FundModalProps,} from "@coinbase/cdp-react";import { useSolanaAddress } from "@coinbase/cdp-hooks";import { useCallback } from "react";import { getBuyOptions, createBuyQuote } from "@/lib/onramp-api";/** * A component that wraps the FundModal component * * @param props - The props for the FundWallet component * @param props.onSuccess - The callback function to call when the onramp purchase is successful * @returns The FundWallet component */export default function FundWallet({ onSuccess }: { onSuccess: () => void }) { const { solanaAddress } = useSolanaAddress(); // Get the user's location (i.e. from IP geolocation) const userCountry = "US"; // If user is in the US, the state is also required const userSubdivision = userCountry === "US" ? "CA" : undefined; // Call your buy quote endpoint const fetchBuyQuote: FundModalProps["fetchBuyQuote"] = useCallback(async params => { return createBuyQuote(params); }, []); // Call your buy options endpoint const fetchBuyOptions: FundModalProps["fetchBuyOptions"] = useCallback(async params => { return getBuyOptions(params); }, []); return ( <FundModal country={userCountry} subdivision={userSubdivision} cryptoCurrency="sol" fiatCurrency="usd" fetchBuyQuote={fetchBuyQuote} fetchBuyOptions={fetchBuyOptions} network="solana" presetAmountInputs={[10, 25, 50]} onSuccess={onSuccess} destinationAddress={solanaAddress} /> );}
React Components: Explore all available Embedded Wallet React components, including authentication, wallet management, and transaction components to build complete wallet experiences
Onramp Overview: Learn about the complete Onramp API ecosystem, including advanced features like offramp, webhooks, and transaction monitoring for comprehensive fiat-to-crypto solutions