Getting Started
# https://docs.base.org/builderkits/onchainkit/llms.txt
## OnchainKit Documentation
This file contains structured documentation for AI assistants about OnchainKit, OnchainKit streamlines app development by providing a comprehensive toolkit that combines powerful onchain features with developer-friendly design:
Please refer to https://docs.base.org/llms-full.txt for the complete Base documentation.
On this page
Chevron Right
OnchainKit is your go-to SDK for building beautiful onchain applications. Ship in minutes, not weeks.
Anyone can build an onchain app in 15 minutes with OnchainKit. No blockchain experience required.
## Why OnchainKit?
OnchainKit streamlines app development by providing a comprehensive toolkit that combines powerful onchain features with developer-friendly design:
- **Ergonomic design:** Full-stack tools that make complex onchain interactions intuitive
- **Battle-tested patterns:** Industry best practices packaged into ready-to-use solutions
- **Purpose-built components:** Pre-built modules for common onchain workflows
- **Framework agnostic:** Compatible with any React-supporting framework
- **Supercharged by Base:** Deep integration with Base's protocol features and ecosystem
## Automatic Installation

We recommend starting a new OnchainKit app using `create onchain`, which sets up everything automatically for you. To create a project, run:
Terminal
Terminal
```vocs_Code
Copynpm create onchain@latest
```
After the prompts, `create onchain` will create a folder with your project name and install the required dependencies.
You can also checkout our pre-built templates:
- [Onchain Commerce](https://onchain-commerce-template.vercel.app/)
- [NFT minting](https://ock-mint.vercel.app/)
- [Funding flow](https://github.com/fakepixels/fund-component)
- [Social profile](https://github.com/fakepixels/ock-identity)
## Manual Installation
Add OnchainKit to your existing project manually.
[Next.js\\
\\
Next.js](https://docs.base.org/builderkits/onchainkit/installation/nextjs) [Vite\\
\\
Vite](https://docs.base.org/builderkits/onchainkit/installation/vite) [Remix\\
\\
Remix](https://docs.base.org/builderkits/onchainkit/installation/remix) [Astro\\
\\
Astro](https://docs.base.org/builderkits/onchainkit/installation/astro)
# Start building!
Explore our ready-to-use onchain components:
- [**`Identity`**](https://docs.base.org/builderkits/onchainkit/identity/identity)\- Show [Basenames](https://docs.base.org/builderkits/onchainkit/identity/identity), [avatars](https://docs.base.org/builderkits/onchainkit/identity/avatar), [badges](https://docs.base.org/builderkits/onchainkit/identity/badge), and [addresses](https://docs.base.org/builderkits/onchainkit/identity/address).
- [**`Wallet`**](https://docs.base.org/builderkits/onchainkit/wallet/wallet)\- Create or connect wallets with [Connect Wallet](https://docs.base.org/builderkits/onchainkit/wallet/wallet).
- [**`Transaction`**](https://docs.base.org/builderkits/onchainkit/transaction/transaction)\- Handle [transactions](https://docs.base.org/builderkits/onchainkit/transaction/transaction) using EOAs or Smart Wallets.
- [**`Checkout`**](https://docs.base.org/builderkits/onchainkit/checkout/checkout)\- Integrate USDC [checkout](https://docs.base.org/builderkits/onchainkit/checkout/checkout) flows with ease.
- [**`Fund`**](https://docs.base.org/builderkits/onchainkit/fund/fund-button)\- Create a [funding](https://docs.base.org/builderkits/onchainkit/fund/fund-button) flow to onboard users.
- [**`Tokens`**](https://docs.base.org/builderkits/onchainkit/token/token-chip)\- Search and display [tokens](https://docs.base.org/builderkits/onchainkit/token/token-chip) with various components.
- [**`Swap`**](https://docs.base.org/builderkits/onchainkit/swap/swap)\- Enable [token swaps](https://docs.base.org/builderkits/onchainkit/swap/swap) in your app.
- [**`Mint`**](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card)- [View](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) and [Mint](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) NFTs in your app.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
Skip to content
Search
Logo
GitHub
X
Warpcast
Discord
Logo
Get help
GitHub X Warpcast Discord
Menu
How to Contribute
On this page Chevron Right
Welcome to OnchainKit! So you want to contribute to this project? You came to the right place.
In this guide, you will learn how to:
Set up this project
Navigate the codebase
Accomplish various workflows
Submit a feature request
Setup
Clone the repo
Copygit clone git@github.com:coinbase/onchainkit.git
Install Node and pnpm
Use nvm, mise, n or your favorite version manager to install Node.js.
For pnpm, see the installation instructions on the pnpm website.
Install dependencies
From the root of the repository:
Copypnpm install
Codebase
This project is a monorepo managed with pnpm. The @coinbase/onchainkit package is located in:
Copypackages/onchainkit/
Here is a rough layout of the codebase:
Copypackages/onchainkit/
└── src/
├── api/ - API related components and functions
├── core/ - Files with zero dependencies
├── styles/ - Styles
│ ├── index-with-tailwind.css - CSS entrypoint
├── {Component}/ - Component folder
│ ├── components/ - React components
│ │ ├── {Name}.tsx
│ │ ├── {Name}.test.tsx
│ │ └── {Name}.css
│ ├── core/ - Utility functions
│ ├── index.ts - Entrypoint for the folder
│ └── types.ts - Export types
│
├── index.ts - Main package entry point
├── types.ts - Core types
└── OnchainKitProvider.tsx - OnchainKit provider
Workflows
Development
To work on OnchainKit components with live UI feedback:
Copypnpm f:play dev
This will build the OnchainKit package in watch mode, and start a development environment (the playground) where you can see your components in action.
As you make changes, the playground will update automatically.
Navigate to http://localhost:3000 to open the playground.
Building
To build the package:
Copypnpm f:ock build
Testing
Write and update existing unit tests. You can run tests with:
Copypnpm f:ock test
For watching file changes and rerunning tests automatically:
Copypnpm f:ock test:watch
We expect 100% code coverage for any updates. You can get coverage information with:
Copypnpm f:ock test:coverage
If the coverage drops below 100%, look at the coverage report generated by the above command with:
Copyopen coverage/index.html
Updating changelog
To update the change log, run:
Copypnpm changeset
Select minor and use the following format for the summary:
Copy- **feat**: feature update information. By @your-github-id #XX (XX is the PR number)
Possible values are:
feat
fix
docs
chore
Feature request
Have a component in mind that we are not supporting yet? You can submit a feature request to our Github. Create a "New issue" and label it "Feature Request: ...".
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our Cookie Policy.
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/installation/astro#vocs-content)
Astro
On this page
Chevron Right
Install and configure OnchainKit with Astro.
If you are integrating OnchainKit into an existing project,
skip to the [OnchainKit installation](https://docs.base.org/builderkits/onchainkit/installation/astro#install-onchainkit).
## Install Astro
Create a new Astro project by using the Astro CLI.
More information about Astro can be found [here](https://docs.astro.build/en/install-and-setup/#start-a-new-project).
npmyarnpnpm
Terminal
npm
```vocs_Code
Copynpm create astro@latest
```
## Install React
Astro does not come with React by default, so if you are not already using React
in your application, you will need to install it.
Terminal
Terminal
```vocs_Code
Copynpx astro add react
```
## Install OnchainKit
Add OnchainKit to your project by installing the `@coinbase/onchainkit` package.
npmyarnpnpmbun
Terminal
npm
```vocs_Code
Copynpm install @coinbase/onchainkit
```
## Get A Client API Key
Get your [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.

Create a `.env` file in your project's root directory.

Add your Client API Key to the `.env` file:
File
.env
```vocs_Code
CopyPUBLIC_ONCHAINKIT_API_KEY=YOUR_CLIENT_API_KEY
```
## Add Providers
Create a `providers.tsx` file. Add `OnchainKitProvider` with your desired config.
Under the hood, OnchainKit will create our recommended Wagmi and QueryClient
providers. If you wish to customize these providers, check out [Custom\\
Supplemental Providers](https://docs.base.org/builderkits/onchainkit/config/supplemental-providers).
File
providers.tsx
```vocs_Code
Copy'use client';
import type { ReactNode } from 'react';
import { OnchainKitProvider } from '@coinbase/onchainkit';
import { base } from 'wagmi/chains'; // add baseSepolia for testing
export function Providers(props: { children: ReactNode }) {
return (
{props.children}
);
}
```
## Wrap your OnchainKit components with ``
After configuring the providers in step 4, you will need to wrap your OnchainKit components
with the `` component.
There are two options for this:
1. Create a component, eg. `` that contains all OnchainKit components.
2. Wrap every OnchainKit component individually.
ReactIslandOnchainKit Wrappers
ReactIsland
```vocs_Code
Copyimport { AppProviders } from '../AppProviders';
export default function ReactIsland() {
return (
);
}
```
The advantage of ReactIsland is that you will only have a single provider at any time.
The drawback is that your OnchainKit components will all need to live in the same Island.
The advantage of individual wrappers is that you can use OnchainKit components anywhere in your app.
The drawback is that you will have multiple providers if you use more than one OnchainKit component.
## Add OnchainKit Components to your App
You can add OnchainKit components to your app by using the component(s) you
created above into your `.astro` files.
For example, if you created a ReactIsland, you can add it to your
`src/pages/index.astro` file:
File
src/pages/index.astro
```vocs_Code
Copy---
import Layout from '../layouts/Layout.astro';
import ReactIsland from '../components/ReactIsland';
---
...
...
```
Don't forget to add the `client:only="react"` directive to your OnchainKit component,
as this is required for Astro to render React components.
## Import OnchainKit Styles
OnchainKit components come with pre-configured styles.
To include these styles in your project, add the following import
statement at the top of the `Layout.astro` file:
```vocs_Code
Copyimport '@coinbase/onchainkit/styles.css';
```
This ensures that the OnchainKit styles are loaded and applied to your entire application.
- For Tailwind CSS users, check out our [Tailwind Integration Guide](https://docs.base.org/builderkits/onchainkit/guides/tailwind).
- Update the appearance of components by using our built-in themes or crafting your own custom theme.
Explore the possibilities in our [Theming Guide](https://docs.base.org/builderkits/onchainkit/guides/themes).
# Start building!
Explore our ready-to-use onchain components:
- [**`Identity`**](https://docs.base.org/builderkits/onchainkit/identity/identity)\- Show [Basenames](https://docs.base.org/builderkits/onchainkit/identity/identity), [avatars](https://docs.base.org/builderkits/onchainkit/identity/avatar), [badges](https://docs.base.org/builderkits/onchainkit/identity/badge), and [addresses](https://docs.base.org/builderkits/onchainkit/identity/address).
- [**`Wallet`**](https://docs.base.org/builderkits/onchainkit/wallet/wallet)\- Create or connect wallets with [Connect Wallet](https://docs.base.org/builderkits/onchainkit/wallet/wallet).
- [**`Transaction`**](https://docs.base.org/builderkits/onchainkit/transaction/transaction)\- Handle [transactions](https://docs.base.org/builderkits/onchainkit/transaction/transaction) using EOAs or Smart Wallets.
- [**`Checkout`**](https://docs.base.org/builderkits/onchainkit/checkout/checkout)\- Integrate USDC [checkout](https://docs.base.org/builderkits/onchainkit/checkout/checkout) flows with ease.
- [**`Fund`**](https://docs.base.org/builderkits/onchainkit/fund/fund-button)\- Create a [funding](https://docs.base.org/builderkits/onchainkit/fund/fund-button) flow to onboard users.
- [**`Tokens`**](https://docs.base.org/builderkits/onchainkit/token/token-chip)\- Search and display [tokens](https://docs.base.org/builderkits/onchainkit/token/token-chip) with various components.
- [**`Swap`**](https://docs.base.org/builderkits/onchainkit/swap/swap)\- Enable [token swaps](https://docs.base.org/builderkits/onchainkit/swap/swap) in your app.
- [**`Mint`**](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card)- [View](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) and [Mint](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) NFTs in your app.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/installation/remix#vocs-content)
Remix
On this page
Chevron Right
Install and configure OnchainKit with Remix.
If you are integrating OnchainKit into an existing project,
skip to the [OnchainKit installation](https://docs.base.org/builderkits/onchainkit/installation/remix#install-onchainkit).
## Install Remix
Create a new Remix project by using the Remix CLI.
More information about Remix can be found [here](https://remix.run/docs/en/main/start/quickstart).
Terminal
Terminal
```vocs_Code
Copynpx create-remix@latest
```
## Install OnchainKit
Add OnchainKit to your project by installing the `@coinbase/onchainkit` package.
npmyarnpnpmbun
Terminal
npm
```vocs_Code
Copynpm install @coinbase/onchainkit
```
## Get A Client API Key
Get your [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.

Create a `.env` file in your project's root directory.

Add your Client API Key to the `.env` file:
File
.env
```vocs_Code
CopyPUBLIC_ONCHAINKIT_API_KEY=YOUR_CLIENT_API_KEY
```
Update the `app/root.tsx` file to provide access to your Client API Key
through `window.ENV`:
File
app/root.tsx
```vocs_Code
Copydeclare global {
interface Window {
ENV: {
PUBLIC_ONCHAINKIT_API_KEY: string;
};
}
}
export async function loader() {
return json({
ENV: {
PUBLIC_ONCHAINKIT_API_KEY: process.env.PUBLIC_ONCHAINKIT_API_KEY,
},
});
}
```
If this is the first env variable you've added to your project, you will need to
update the `Layout` component of `app/root.tsx` to make it available to your app:
File
app/root.tsx
```vocs_Code
Copyexport function Layout({ children }: { children: React.ReactNode }) {
const data = useLoaderData();
return (
{children}
);
}
```
## Add Providers
Create a `providers.tsx` file. Add `OnchainKitProvider` with your desired config.
Under the hood, OnchainKit will create our recommended Wagmi and QueryClient
providers. If you wish to customize these providers, check out [Custom\\
Supplemental Providers](https://docs.base.org/builderkits/onchainkit/config/supplemental-providers).
File
providers.tsx
```vocs_Code
Copy'use client';
import type { ReactNode } from 'react';
import { OnchainKitProvider } from '@coinbase/onchainkit';
import { base } from 'wagmi/chains'; // add baseSepolia for testing
export function Providers(props: { children: ReactNode }) {
const apiKey =
typeof window !== 'undefined'
? window.ENV?.PUBLIC_ONCHAINKIT_API_KEY
: undefined;
return (
{props.children}
);
}
```
## Wrap your app with ``
After configuring the providers in step 4, wrap your app with
the `` component.
File
app.tsx
```vocs_Code
Copyimport { AppProviders } from 'src/AppProviders';
export default function App() {
return (
);
}
```
## Import OnchainKit Styles
OnchainKit components come with pre-configured styles.
To include these styles in your project, add the following import
statement at the top of the file where imported ``:
File
app.tsx
```vocs_Code
Copyimport { AppProviders } from 'src/AppProviders';
import '@coinbase/onchainkit/styles.css';
export default function App() {
return (
);
}
```
This ensures that the OnchainKit styles are loaded and applied to your entire application.
- For Tailwind CSS users, check out our [Tailwind Integration Guide](https://docs.base.org/builderkits/onchainkit/guides/tailwind).
- Update the appearance of components by using our built-in themes or crafting your own custom theme.
Explore the possibilities in our [Theming Guide](https://docs.base.org/builderkits/onchainkit/guides/themes).
# Start building!
Explore our ready-to-use onchain components:
- [**`Identity`**](https://docs.base.org/builderkits/onchainkit/identity/identity)\- Show [Basenames](https://docs.base.org/builderkits/onchainkit/identity/identity), [avatars](https://docs.base.org/builderkits/onchainkit/identity/avatar), [badges](https://docs.base.org/builderkits/onchainkit/identity/badge), and [addresses](https://docs.base.org/builderkits/onchainkit/identity/address).
- [**`Wallet`**](https://docs.base.org/builderkits/onchainkit/wallet/wallet)\- Create or connect wallets with [Connect Wallet](https://docs.base.org/builderkits/onchainkit/wallet/wallet).
- [**`Transaction`**](https://docs.base.org/builderkits/onchainkit/transaction/transaction)\- Handle [transactions](https://docs.base.org/builderkits/onchainkit/transaction/transaction) using EOAs or Smart Wallets.
- [**`Checkout`**](https://docs.base.org/builderkits/onchainkit/checkout/checkout)\- Integrate USDC [checkout](https://docs.base.org/builderkits/onchainkit/checkout/checkout) flows with ease.
- [**`Fund`**](https://docs.base.org/builderkits/onchainkit/fund/fund-button)\- Create a [funding](https://docs.base.org/builderkits/onchainkit/fund/fund-button) flow to onboard users.
- [**`Tokens`**](https://docs.base.org/builderkits/onchainkit/token/token-chip)\- Search and display [tokens](https://docs.base.org/builderkits/onchainkit/token/token-chip) with various components.
- [**`Swap`**](https://docs.base.org/builderkits/onchainkit/swap/swap)\- Enable [token swaps](https://docs.base.org/builderkits/onchainkit/swap/swap) in your app.
- [**`Mint`**](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card)- [View](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) and [Mint](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) NFTs in your app.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/installation/nextjs#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Next.js
On this page
Chevron Right
Install and configure OnchainKit with Next.js.
If you are integrating OnchainKit into an existing project,
skip to the [OnchainKit installation](https://docs.base.org/builderkits/onchainkit/installation/nextjs#install-onchainkit).
## Install Next.js
Create a new Next.js project by using the Next.js CLI.
More information about Next.js can be found [here](https://nextjs.org/docs/getting-started/installation).
Terminal
npm
```vocs_Code
Copynpx create-next-app@14
```
During the setup process you will encounter multiple prompts.
Make sure you enable TypeScript, ESLint, and Tailwind CSS.
## Install OnchainKit
Install OnchainKit in your project.
npmyarnpnpmbun
Terminal
npm
```vocs_Code
Copynpm install @coinbase/onchainkit
```
## Get Your Client API Key
Get your [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.

Create a `.env` file in your project's root directory.

Add your Client API Key to the `.env` file:
File
.env
```vocs_Code
CopyNEXT_PUBLIC_ONCHAINKIT_API_KEY=YOUR_CLIENT_API_KEY;
```
## Add Providers
Create a `providers.tsx` file. Add `OnchainKitProvider` with your desired config.
Under the hood, OnchainKit will create our recommended Wagmi and QueryClient
providers. If you wish to customize these providers, check out [Custom\\
Supplemental Providers](https://docs.base.org/builderkits/onchainkit/config/supplemental-providers).
File
providers.tsx
```vocs_Code
Copy'use client';
import type { ReactNode } from 'react';
import { OnchainKitProvider } from '@coinbase/onchainkit';
import { base } from 'wagmi/chains'; // add baseSepolia for testing
export function Providers(props: { children: ReactNode }) {
return (
{props.children}
);
}
```
## Wrap your app with ``
After the setup, wrap your app with the above `` component.
File
app.tsx
```vocs_Code
Copyimport './globals.css';
import { Providers } from './providers';
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode,
}>) {
return (
{children}
);
}
```
## Add Styles
OnchainKit components come with pre-configured styles. To include these styles in your project, add the following import statement at the top of this file:
```vocs_Code
Copyimport '@coinbase/onchainkit/styles.css';
```
For example, if you're using Next.js with the app router, your `app/layout.tsx` might look like this:
File
layout.tsx
```vocs_Code
Copyimport '@coinbase/onchainkit/styles.css';
import './globals.css';
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import { headers } from 'next/headers';
import { type ReactNode } from 'react';
import { cookieToInitialState } from 'wagmi';
import { getConfig } from '../wagmi';
import { Providers } from './providers';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
title: 'Create Wagmi',
description: 'Generated by create-wagmi',
};
export default function RootLayout(props: { children: ReactNode }) {
const initialState = cookieToInitialState(
getConfig(),
headers().get('cookie')
);
return (
{props.children}
);
}
```
This ensures that the OnchainKit styles are loaded and applied to your entire application.
- For Tailwind CSS users, check out our [Tailwind Integration Guide](https://docs.base.org/builderkits/onchainkit/guides/tailwind).
- Update the appearance of components by using our built-in themes or crafting your own custom theme.
Explore the possibilities in our [Theming Guide](https://docs.base.org/builderkits/onchainkit/guides/themes).
# Start building!
Explore our ready-to-use onchain components:
- [**`Identity`**](https://docs.base.org/builderkits/onchainkit/identity/identity)\- Show [Basenames](https://docs.base.org/builderkits/onchainkit/identity/identity), [avatars](https://docs.base.org/builderkits/onchainkit/identity/avatar), [badges](https://docs.base.org/builderkits/onchainkit/identity/badge), and [addresses](https://docs.base.org/builderkits/onchainkit/identity/address).
- [**`Wallet`**](https://docs.base.org/builderkits/onchainkit/wallet/wallet)\- Create or connect wallets with [Connect Wallet](https://docs.base.org/builderkits/onchainkit/wallet/wallet).
- [**`Transaction`**](https://docs.base.org/builderkits/onchainkit/transaction/transaction)\- Handle [transactions](https://docs.base.org/builderkits/onchainkit/transaction/transaction) using EOAs or Smart Wallets.
- [**`Checkout`**](https://docs.base.org/builderkits/onchainkit/checkout/checkout)\- Integrate USDC [checkout](https://docs.base.org/builderkits/onchainkit/checkout/checkout) flows with ease.
- [**`Fund`**](https://docs.base.org/builderkits/onchainkit/fund/fund-button)\- Create a [funding](https://docs.base.org/builderkits/onchainkit/fund/fund-button) flow to onboard users.
- [**`Tokens`**](https://docs.base.org/builderkits/onchainkit/token/token-chip)\- Search and display [tokens](https://docs.base.org/builderkits/onchainkit/token/token-chip) with various components.
- [**`Swap`**](https://docs.base.org/builderkits/onchainkit/swap/swap)\- Enable [token swaps](https://docs.base.org/builderkits/onchainkit/swap/swap) in your app.
- [**`Mint`**](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card)- [View](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) and [Mint](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) NFTs in your app.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/installation/vite#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Vite
On this page
Chevron Right
Install and configure OnchainKit with Vite.
If you are integrating OnchainKit into an existing project,
skip to the [OnchainKit installation](https://docs.base.org/builderkits/onchainkit/installation/vite#install-onchainkit).
## Install Vite
Create a new Vite project by using the Vite CLI.
More information about Vite can be found [here](https://vite.dev/guide/#scaffolding-your-first-vite-project).
npmyarnpnpmbun
Terminal
npm
```vocs_Code
Copynpm create vite@latest
```
During the setup process you will encounter multiple prompts.
Make sure you select React and TypeScript.
## Install OnchainKit
Add OnchainKit to your project by installing the `@coinbase/onchainkit` package.
npmyarnpnpmbun
Terminal
npm
```vocs_Code
Copynpm install @coinbase/onchainkit
```
## Get A Client API Key
Get your [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.

Create a `.env` file in your project's root directory.

Add your Client API Key to the `.env` file:
File
.env
```vocs_Code
CopyVITE_PUBLIC_ONCHAINKIT_API_KEY=YOUR_CLIENT_API_KEY
```
## Add Providers
Create a `providers.tsx` file. Add `OnchainKitProvider` with your desired config.
Under the hood, OnchainKit will create our recommended Wagmi and QueryClient
providers. If you wish to customize these providers, check out [Custom\\
Supplemental Providers](https://docs.base.org/builderkits/onchainkit/config/supplemental-providers).
File
providers.tsx
```vocs_Code
Copy'use client';
import type { ReactNode } from 'react';
import { OnchainKitProvider } from '@coinbase/onchainkit';
import { base } from 'wagmi/chains'; // add baseSepolia for testing
export function Providers(props: { children: ReactNode }) {
return (
{props.children}
);
}
```
## Wrap your app with ``
After configuring the providers in step 4, wrap your app with
the `` component.
File
app.tsx
```vocs_Code
Copyimport { AppProviders } from 'src/AppProviders';
export default function App() {
return (
);
}
```
## Import OnchainKit Styles
OnchainKit components come with pre-configured styles.
To include these styles in your project, add the following import
statement at the top of the file where imported ``:
File
app.tsx
```vocs_Code
Copyimport { AppProviders } from 'src/AppProviders';
import '@coinbase/onchainkit/styles.css';
export default function App() {
return (
);
}
```
This ensures that the OnchainKit styles are loaded and applied to your entire application.
- For Tailwind CSS users, check out our [Tailwind Integration Guide](https://docs.base.org/builderkits/onchainkit/guides/tailwind).
- Update the appearance of components by using our built-in themes or crafting your own custom theme.
Explore the possibilities in our [Theming Guide](https://docs.base.org/builderkits/onchainkit/guides/themes).
# Start building!
Explore our ready-to-use onchain components:
- [**`Identity`**](https://docs.base.org/builderkits/onchainkit/identity/identity)\- Show [Basenames](https://docs.base.org/builderkits/onchainkit/identity/identity), [avatars](https://docs.base.org/builderkits/onchainkit/identity/avatar), [badges](https://docs.base.org/builderkits/onchainkit/identity/badge), and [addresses](https://docs.base.org/builderkits/onchainkit/identity/address).
- [**`Wallet`**](https://docs.base.org/builderkits/onchainkit/wallet/wallet)\- Create or connect wallets with [Connect Wallet](https://docs.base.org/builderkits/onchainkit/wallet/wallet).
- [**`Transaction`**](https://docs.base.org/builderkits/onchainkit/transaction/transaction)\- Handle [transactions](https://docs.base.org/builderkits/onchainkit/transaction/transaction) using EOAs or Smart Wallets.
- [**`Checkout`**](https://docs.base.org/builderkits/onchainkit/checkout/checkout)\- Integrate USDC [checkout](https://docs.base.org/builderkits/onchainkit/checkout/checkout) flows with ease.
- [**`Fund`**](https://docs.base.org/builderkits/onchainkit/fund/fund-button)\- Create a [funding](https://docs.base.org/builderkits/onchainkit/fund/fund-button) flow to onboard users.
- [**`Tokens`**](https://docs.base.org/builderkits/onchainkit/token/token-chip)\- Search and display [tokens](https://docs.base.org/builderkits/onchainkit/token/token-chip) with various components.
- [**`Swap`**](https://docs.base.org/builderkits/onchainkit/swap/swap)\- Enable [token swaps](https://docs.base.org/builderkits/onchainkit/swap/swap) in your app.
- [**`Mint`**](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card)- [View](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) and [Mint](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) NFTs in your app.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/guides/using-ai-powered-ides#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Use AI-powered IDEs
On this page
Chevron Right
## Use AI-powered IDEs
You can also directly download the [context](https://github.com/fakepixels/md-generator/blob/master/combined-ock-docs-0.35.8.mdx) and import it into AI-powered IDE such as Cursor or Replit.
In addition, you can import a `.cursorrules` file in the root of your project via [Cursor Directory](https://cursor.directory/onchainkit). Cursor also has an array of resources [here](https://cursor.directory/learn) on how to use AI-powered IDEs.

## AI Tooling
### Replit
[Replit](https://replit.com/) is a cloud-based coding platform that streamlines the process of setting up, building, sharing, and deploying projects. It allows developers to code in a Google Docs-like environment, and pre-built templates provide a great starting point for building a website, app, or game. Its new AI Agent can assist with the code development process and work with several files at once, making the programming process feel like a one-on-one conversation.
### Cursor
[Cursor](https://cursor.com/) is an AI-powered code editor that makes the programming experience feel like magic. Built as a fork of VS Code, it boasts powerful features like AI code completion, natural language editing, and codebase understanding. Cursor Pro is free for the first two weeks after signup, and offers more powerful models.
### Using OnchainKit with CDP SDK
You can use OnchainKit with [CDP SDK](https://docs.cdp.coinbase.com/get-started/docs/overview) to access additional capabilities such as [AgentKit](https://docs.cdp.coinbase.com/agentkit/docs/welcome).
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/guides/use-basename-in-onchain-app#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Use Basenames
On this page
Chevron Right
Basenames are an essential onchain building block that empowers builders to establish their identity on Base by registering human-readable names for their wallet addresses.
They operate entirely onchain, utilizing the same technology as ENS names, and are deployed on Base.
You can integrate [Basenames](https://www.base.org/names) into your app with these few steps.
### New to OnchainKit?
Follow the [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started) guide to install the package.
### Already using OnchainKit?
Update to the latest version and choose from the following steps: a React component approach, a React hook, or a pure TypeScript utility function.
## React components with `` and ``
Use the [``](https://docs.base.org/builderkits/onchainkit/identity/avatar) and [``](https://docs.base.org/builderkits/onchainkit/identity/name) components to display Basenames associated with Ethereum addresses.
The `chain` prop is optional and setting to Base, it's what makes the components switch from ENS to Basenames.
```vocs_Code
Copyimport { Avatar, Name } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const address = '0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1';
// omitted component code for brevity
```

zizzamia.base.eth
## React hooks with `useAvatar` and `useName`
Use the [`useAvatar`](https://docs.base.org/builderkits/onchainkit/identity/use-avatar) and [`useName`](https://docs.base.org/builderkits/onchainkit/identity/use-name) hooks to get Basenames associated with Ethereum addresses.
The hooks are incredibly useful for building custom components while leveraging OnchainKit for efficient data fetching.
codereturn value
code
```vocs_Code
Copyimport { useAvatar, useName } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const address = '0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1';
const basename = 'zizzamia.base.eth';
const { data: avatar, isLoading: avatarIsLoading } = await useAvatar({ ensName: basename, chain: base });
const { data: name, isLoading: nameIsLoading } = await useName({ address, chain: base });
```
## Typescript utility with `getAvatar` and `getName`
Use the [`getAvatar`](https://docs.base.org/builderkits/onchainkit/identity/get-avatar) and [`getName`](https://docs.base.org/builderkits/onchainkit/identity/get-name) functions to get Basenames associated with Ethereum addresses.
Being pure functions, it seamlessly integrates into any TypeScript project, including Vue, Angular, Svelte, or Node.js.
codereturn value
code
```vocs_Code
Copyimport { getAvatar, getName } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const address = '0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1';
const basename = 'zizzamia.base.eth';
const avatar = await getAvatar({ ensName: basename, chain: base });
const name = await getName({ address, chain: base });
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/guides/troubleshooting#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Troubleshooting
On this page
Chevron Right
This guide covers common issues you may encounter while using OnchainKit. If you don't find your issue here, try searching our [GitHub Issues](https://github.com/coinbase/onchainkit/issues) or joining our [Discord Community](https://discord.gg/invite/cdp).
## Common Issues
### Environment Setup
- **Missing API Key**
- Error: "Project ID is required for this component"
- Solution: Add your Client API Key to `.env`:
```vocs_Code
CopyNEXT_PUBLIC_CDP_API_KEY=YOUR_PUBLIC_API_KEY
```
- **Invalid Environment Variables** - Error: "Cannot find environment variable"
- Solution: Use the correct variable name for your framework:
- Next.js: `NEXT_PUBLIC_CDP_API_KEY`
- Vite: `VITE_PUBLIC_ONCHAINKIT_API_KEY`
- Astro: `PUBLIC_ONCHAINKIT_API_KEY`
- **Contracts Not Available** - Error: "Contracts are not available" or "Contracts not available for LifecycleStatus"
- Solutions:
- Verify `NEXT_PUBLIC_ONCHAINKIT_API_KEY` is set correctly
- For Checkout component with `chargeHandler`, also set:
```vocs_Code
CopyNEXT_PUBLIC_COINBASE_COMMERCE_API_KEY=YOUR_COMMERCE_API_KEY
```
- Ensure API keys are properly exposed in your environment
### Dependencies
- **Version Compatibility** - Issue: Unexpected behavior or type errors
- Solution: Ensure compatible versions:
```vocs_Code
Copy{
"dependencies": {
"@coinbase/onchainkit": "latest",
"viem": "^2.0.0",
"@wagmi/core": "^2.0.0"
}
}
```
### Provider Configuration
- **Missing OnchainKitProvider**
- Error: "OnchainKit context not found"
- Solution: Wrap your app with OnchainKitProvider and [configure](https://docs.base.org/builderkits/onchainkit/getting-started) properly:
```vocs_Code
Copyimport { OnchainKitProvider } from '@coinbase/onchainkit';
import { base } from 'viem/chains';
export default function App({ children }) {
return (
{children}
);
}
```
### Wallet Connection
- **Connection Failed** - Error: "Unable to connect wallet"
- Solutions:
- Verify wallet extension is installed and unlocked
- Check [supported chains configuration](https://docs.base.org/builderkits/onchainkit/wallet/wallet)
- Ensure proper network selection in wallet
- Verify RPC endpoints are accessible
- **Chain Switching Issues** - Error: "Failed to switch chain"
- Solutions:
- Verify chain ID is supported by OnchainKit
- Check wallet has required permissions
- Ensure RPC endpoints are configured correctly
- Add chain to wallet if not already added
### Transaction Issues
- **Gas Estimation Failed** - Error: "Gas estimation failed"
- Solutions:
- Verify sufficient balance for gas
- Check transaction parameters are valid
- Ensure proper network [configuration](https://docs.base.org/builderkits/onchainkit/transaction/transaction)
### Identity Components
### Theme Issues
- **Dark Mode Not Working**
- Error: "Dark mode styles not applying"
- Solution: Configure Tailwind and OnchainKit properly:
```vocs_Code
Copy// tailwind.config.js
module.exports = {
darkMode: ['class'],
safelist: ['dark'],
// ... rest of config
}
```
### React Native
- \\*\\* React Native Support \*\*
- OnchainKit's components are not supported for use in React Native, however, you can use utility functions, like `getName`, as well as some hooks in your React Native app. When using these utility functions, you may need to import them directly rather than through the export file.
- Example: `import { getName } from '@coinbase/onchainkit/esm/identity/utils/getName.js';` rather than `import { getName } from '@coinbase/onchainkit/identity;`
### Module Resolution
- **Module Resolution Errors** - Error: "Cannot find module ... or its corresponding type declarations. Consider updating to 'node16', 'nodenext', or 'bundler'"
- Solution: Update your Node.js version or use a compatible bundler. We recommend using Node 18+ and `"moduleResolution": "NodeNext"` for the best developer experience. OnchainKit supports only ES Modules and does not support CommonJS modules.
## Getting Help
Need more help?
- [Discord Community](https://discord.gg/invite/cdp)
- [X/Twitter Support](https://x.com/onchainkit)
- [GitHub Issues](https://github.com/coinbase/onchainkit/issues)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/guides/themes#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Theme Customization
On this page
Chevron Right

## Overview
OnchainKit provides flexible appearance control through two main features: `mode` and `theme`.
- **Mode**: Controls the light/dark appearance and includes an auto option that inherits the system preference.
- **Theme**: Governs the overall styling across components.
You can choose from built-in themes or dynamically switch modes based on user preference or system settings, allowing for a customized and responsive user interface.
## Built-in Themes
OnchainKit offers multiple themes to quickly style your components. Set the theme via the `OnchainKitProvider` using `config.appearance.theme`:
- `default`: Includes both light and dark modes.
- `base`: Single mode only.
- `cyberpunk`: Single mode only.
- `hacker`: Single mode only.
- `custom`: Single mode only.
If no theme is selected, the **`default`** theme is applied automatically.
```vocs_Code
Copy
```
## Mode
Control the color scheme by setting the `config.appearance.mode` property of the `OnchainKitProvider`:
- `auto`: Automatically switches between light and dark mode based on the user’s OS preference.
- `light`: Forces all components to use the light version of the theme.
- `dark`: Forces all components to use the dark version of the theme.
If no mode is specified, `auto` mode will be applied by default.
```vocs_Code
Copy
```
## CSS Overrides
Fine-tune specific aspects of an existing theme.
This is useful when you want to make adjustments to the appearance of the components without creating an entirely new theme.
```vocs_Code
Copy@layer base {
:root
.default-light,
.default-dark,
.base,
.cyberpunk,
.hacker {
/* Override specific variables as needed */
--ock-font-family: 'your-custom-value';
--ock-border-radius: 'your-custom-value';
--ock-text-primary: 'your-custom-value';
}
}
```
## Custom Theme
Define an entirely new look and feel for your application.
This gives you complete control over all aspects of the design, including colors, fonts, and other visual properties.
#### Usage Options:
##### Automatic Light/Dark Mode Switching:
- To automatically switch between light and dark versions of your custom theme:
```vocs_Code
Copy
```
##### Single Theme Version:
- To use only one version of your custom theme at all times:
```vocs_Code
Copy
```
##### Defining a custom theme
Use CSS variables to define your custom theme.
The class name definitions must include the `-light` or `-dark` suffix.
```vocs_Code
Copy@layer base {
.custom-light {
/* Font and Shape */
--ock-font-family: 'your-custom-value';
--ock-border-radius: 'your-custom-value';
--ock-border-radius-inner: 'your-custom-value';
/* Text Colors */
--ock-text-inverse: 'your-custom-value';
--ock-text-foreground: 'your-custom-value';
--ock-text-foreground-muted: 'your-custom-value';
--ock-text-error: 'your-custom-value';
--ock-text-primary: 'your-custom-value';
--ock-text-success: 'your-custom-value';
--ock-text-warning: 'your-custom-value';
--ock-text-disabled: 'your-custom-value';
/* Background Colors */
--ock-bg-default: 'your-custom-value';
--ock-bg-default-hover: 'your-custom-value';
--ock-bg-default-active: 'your-custom-value';
--ock-bg-alternate: 'your-custom-value';
--ock-bg-alternate-hover: 'your-custom-value';
--ock-bg-alternate-active: 'your-custom-value';
--ock-bg-inverse: 'your-custom-value';
--ock-bg-inverse-hover: 'your-custom-value';
--ock-bg-inverse-active: 'your-custom-value';
--ock-bg-primary: 'your-custom-value';
--ock-bg-primary-hover: 'your-custom-value';
--ock-bg-primary-active: 'your-custom-value';
--ock-bg-primary-washed: 'your-custom-value';
--ock-bg-primary-disabled: 'your-custom-value';
--ock-bg-secondary: 'your-custom-value';
--ock-bg-secondary-hover: 'your-custom-value';
--ock-bg-secondary-active: 'your-custom-value';
--ock-bg-error: 'your-custom-value';
--ock-bg-warning: 'your-custom-value';
--ock-bg-success: 'your-custom-value';
--ock-bg-default-reverse: 'your-custom-value';
/* Icon Colors */
--ock-icon-color-primary: 'your-custom-value';
--ock-icon-color-foreground: 'your-custom-value';
--ock-icon-color-foreground-muted: 'your-custom-value';
--ock-icon-color-inverse: 'your-custom-value';
--ock-icon-color-error: 'your-custom-value';
--ock-icon-color-success: 'your-custom-value';
--ock-icon-color-warning: 'your-custom-value';
/* Border Colors */
--ock-border-line-primary: 'your-custom-value';
--ock-border-line-default: 'your-custom-value';
--ock-border-line-heavy: 'your-custom-value';
--ock-border-line-inverse: 'your-custom-value';
}
.custom-dark {
/* Define dark mode custom classes here */
}
}
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/guides/telemetry#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Telemetry
On this page
Chevron Right
## Telemetry
OnchainKit is introducing an anonymous telemetry system to help us better understand how our library is used in the wild. Participation in this anonymous program is optional—if you'd prefer not to share any usage data, you can easily opt out.
### Why Are We Collecting Telemetry?
OnchainKit has quickly become a go-to full‑stack component library for integrating essential onchain functionality (like ``, ``, and ``) in minutes. Until now, our usage insights have been limited to public npm download counts and API endpoint usage. By collecting telemetry data, we can:
- **Gauge Component Usage**: Understand which components (and their variants) are most popular
- **Data-Informed Improvements**: Help our data science team generate insights that drive future enhancements and refactoring decisions
- **Proactive Monitoring**: Quickly detect issues with new releases or API changes through a dedicated error event stream (with alerts to oncall engineers)
### What Data Will Be Collected?
Telemetry data is completely anonymous and designed to provide aggregated insights. Specifically, we collect:
- **Command Details**: Which commands (or component events) are being invoked (e.g. walletConnection, swapSuccess)
- **Version & App Info**: The OnchainKit version, app name (from window.top.document.title), and origin (the app URL)
- **Usage Metrics**: Information such as the number of unique wallets, transactions, or contracts interacting with OnchainKit
- **Error Events**: Generic error events along with component context to help us triage any issues
No sensitive data—such as environment variables, file paths, or private keys—is ever collected.
### How Does It Work?
Telemetry is integrated directly into each applicable component via our new `sendAnalytics` function. When a component event occurs (e.g. a successful transaction or a wallet connection), this function automatically fires (provided analytics is enabled in your OnchainKit config).
For example, a telemetry event might be sent as follows:
```vocs_Code
Copycurl -X POST https://api.developer.coinbase.com/rpc/analytics \
-H "Content-Type: application/json" \
-H "OnchainKit-Version: 0.37.0" \
-H "OnchainKit-App-Name: My Example App" \
-H "Origin: www.example-app.vercel.app" \
-d '{
"eventType": "transactionSuccess",
"apiKey": "ozpCtG8CfD3TIod_1Va7UBsUm5Rn1",
"data": {
"address": "0x...",
"contract": "0x...",
"transactionHash": "0x...",
"sponsored": true
}
}'
```
### How Do I Opt Out?
By default, telemetry is opt‑out starting with version 0.37.0. If you'd like to disable telemetry, simply set the `analytics` flag to `false` in your OnchainKit configuration:
```vocs_Code
Copyexport function Providers(props: { children: ReactNode }) {
return (
{props.children}
);
}
```
You can also re‑enable analytics later by toggling this flag to `true`.
We believe that this telemetry initiative will help us make OnchainKit even better for all developers—by focusing our improvements on the most used features and catching issues early. If you have any questions or feedback, please reach out to the OnchainKit team.
Happy building!
— The OnchainKit core team
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/guides/tailwind#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Tailwind CSS Integration
On this page
Chevron Right
OnchainKit comes with first class support for `tailwindcss`.
### Use default OnchainKit's style
You can use the default styles without any customization.
Just place this at the top of your application's entry point to have the components work out of the box.
```vocs_Code
Copyimport '@coinbase/onchainkit/styles.css';
```
### Tailwind CSS Config
Depending on your dark mode setup, you may have to add `safelist: ['dark']` to your Tailwind config.
```vocs_Code
Copy/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{ts,tsx}'],
darkMode: ['class'],
safelist: ['dark'],
theme: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
},
plugins: [],
};
```
### Toggling light / dark mode
There are many ways to handle color mode.
In OnchainKit, toggling color mode works by adding / removing class name `dark` to the root html tag.
### Colorscheme override
To override default colorscheme, you need to modify the following css variables:
```vocs_Code
Copy@tailwind base;
@layer base {
:root {
--ock-font-family: 'your-custom-value';
--ock-border-radius: 'your-custom-value';
--ock-border-radius-inner: 'your-custom-value';
--ock-text-inverse: 'your-custom-value';
--ock-text-foreground: 'your-custom-value';
--ock-text-foreground-muted: 'your-custom-value';
--ock-text-error: 'your-custom-value';
--ock-text-primary: 'your-custom-value';
--ock-text-success: 'your-custom-value';
--ock-text-warning: 'your-custom-value';
--ock-text-disabled: 'your-custom-value';
--ock-bg-default: 'your-custom-value';
--ock-bg-default-hover: 'your-custom-value';
--ock-bg-default-active: 'your-custom-value';
--ock-bg-alternate: 'your-custom-value';
--ock-bg-alternate-hover: 'your-custom-value';
--ock-bg-alternate-active: 'your-custom-value';
--ock-bg-inverse: 'your-custom-value';
--ock-bg-inverse-hover: 'your-custom-value';
--ock-bg-inverse-active: 'your-custom-value';
--ock-bg-primary: 'your-custom-value';
--ock-bg-primary-hover: 'your-custom-value';
--ock-bg-primary-active: 'your-custom-value';
--ock-bg-primary-washed: 'your-custom-value';
--ock-bg-primary-disabled: 'your-custom-value';
--ock-bg-secondary: 'your-custom-value';
--ock-bg-secondary-hover: 'your-custom-value';
--ock-bg-secondary-active: 'your-custom-value';
--ock-bg-error: 'your-custom-value';
--ock-bg-warning: 'your-custom-value';
--ock-bg-success: 'your-custom-value';
--ock-bg-default-reverse: 'your-custom-value';
--ock-icon-color-primary: 'your-custom-value';
--ock-icon-color-foreground: 'your-custom-value';
--ock-icon-color-foreground-muted: 'your-custom-value';
--ock-icon-color-inverse: 'your-custom-value';
--ock-icon-color-error: 'your-custom-value';
--ock-icon-color-success: 'your-custom-value';
--ock-icon-color-warning: 'your-custom-value';
--ock-line-primary: 'your-custom-value';
--ock-line-default: 'your-custom-value';
--ock-line-heavy: 'your-custom-value';
--ock-line-inverse: 'your-custom-value';
}
}
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/guides/tailwind#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Tailwind CSS Integration
On this page
Chevron Right
OnchainKit comes with first class support for `tailwindcss`.
### Use default OnchainKit's style
You can use the default styles without any customization.
Just place this at the top of your application's entry point to have the components work out of the box.
```vocs_Code
Copyimport '@coinbase/onchainkit/styles.css';
```
### Tailwind CSS Config
Depending on your dark mode setup, you may have to add `safelist: ['dark']` to your Tailwind config.
```vocs_Code
Copy/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{ts,tsx}'],
darkMode: ['class'],
safelist: ['dark'],
theme: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
},
plugins: [],
};
```
### Toggling light / dark mode
There are many ways to handle color mode.
In OnchainKit, toggling color mode works by adding / removing class name `dark` to the root html tag.
### Colorscheme override
To override default colorscheme, you need to modify the following css variables:
```vocs_Code
Copy@tailwind base;
@layer base {
:root {
--ock-font-family: 'your-custom-value';
--ock-border-radius: 'your-custom-value';
--ock-border-radius-inner: 'your-custom-value';
--ock-text-inverse: 'your-custom-value';
--ock-text-foreground: 'your-custom-value';
--ock-text-foreground-muted: 'your-custom-value';
--ock-text-error: 'your-custom-value';
--ock-text-primary: 'your-custom-value';
--ock-text-success: 'your-custom-value';
--ock-text-warning: 'your-custom-value';
--ock-text-disabled: 'your-custom-value';
--ock-bg-default: 'your-custom-value';
--ock-bg-default-hover: 'your-custom-value';
--ock-bg-default-active: 'your-custom-value';
--ock-bg-alternate: 'your-custom-value';
--ock-bg-alternate-hover: 'your-custom-value';
--ock-bg-alternate-active: 'your-custom-value';
--ock-bg-inverse: 'your-custom-value';
--ock-bg-inverse-hover: 'your-custom-value';
--ock-bg-inverse-active: 'your-custom-value';
--ock-bg-primary: 'your-custom-value';
--ock-bg-primary-hover: 'your-custom-value';
--ock-bg-primary-active: 'your-custom-value';
--ock-bg-primary-washed: 'your-custom-value';
--ock-bg-primary-disabled: 'your-custom-value';
--ock-bg-secondary: 'your-custom-value';
--ock-bg-secondary-hover: 'your-custom-value';
--ock-bg-secondary-active: 'your-custom-value';
--ock-bg-error: 'your-custom-value';
--ock-bg-warning: 'your-custom-value';
--ock-bg-success: 'your-custom-value';
--ock-bg-default-reverse: 'your-custom-value';
--ock-icon-color-primary: 'your-custom-value';
--ock-icon-color-foreground: 'your-custom-value';
--ock-icon-color-foreground-muted: 'your-custom-value';
--ock-icon-color-inverse: 'your-custom-value';
--ock-icon-color-error: 'your-custom-value';
--ock-icon-color-success: 'your-custom-value';
--ock-icon-color-warning: 'your-custom-value';
--ock-line-primary: 'your-custom-value';
--ock-line-default: 'your-custom-value';
--ock-line-heavy: 'your-custom-value';
--ock-line-inverse: 'your-custom-value';
}
}
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/guides/reporting-bug#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Report a Bug
On this page
Chevron Right
We look at all of your bug reports and will do our best to fix them as quickly as possible.
### Create a new issue
Navigate to [Issues tab](https://github.com/coinbase/onchainkit/issues) on Github and click the "New issue" button.
### Select "Bug Report"
Pick the "Bug Report" option and fill out the form to the best of your ability.
### We'll be in touch
We'll do our best to respond to your issue on Github as soon as possible.
### Have a special request?
You can tag us on [Discord](https://discord.com/channels/1220414409550336183/1253768005863739565) or DM us on [X](https://x.com/Onchainkit).
We're most active on X and Discord, so if you're able to, please create an issue there.
### Found a security vulnerability?
If you've found a security vulnerability, please report it to our [HackerOne Program](https://hackerone.com/coinbase?type=team). We offer generous rewards for bounties.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/guides/lifecycle-status#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
Lifecycle Status
On this page
Chevron Right
OnchainKit Lifecycle Status allows you to manage the state of APIs and onchain transactions seamlessly within components.
## How to listen to the Lifecycle Status
The Lifecycle Status is a TypeScript object that provides easy access to the `statusName` and `statusData` properties,
allowing you to stay informed and responsive.
```vocs_Code
Copyimport type { LifecycleStatus } from '@coinbase/onchainkit/transaction';
const handleOnStatus = useCallback((status: LifecycleStatus) => {
console.log('LifecycleStatus', status);
}, []);
// omitted component code for brevity
```
## Lifecycle Status
The Lifecycle Status includes 3 states common to all components:
### `init`
The component is initialized and ready for use.
```vocs_Code
Copy{
statusName: 'init';
statusData: null;
}
```
### `success`
The component has successfully completed its main action, such as `swap` or `transaction`.
```vocs_Code
Copy{
statusName: 'success';
statusData: {
// the data returned from the API or onchain operation
};
}
```
### `error`
The component has encountered an issue while fetching API data, executing an onchain operation,
or needs to display a visual message to the user.
```vocs_Code
Copy{
statusName: 'error';
statusData: {
code: string; // The error code representing the location of the error
error: string; // The error message providing developer details
message: string; // The error message providing user-facing details
};
}
```
Each component brings its own unique experience, and we have explored both the swap and transaction processes.
## Lifecycle Status with [``](https://docs.base.org/builderkits/onchainkit/swap/swap)
### `amountChange`
Any of the Swap Input fields have been updated.
```vocs_Code
Copy{
statusName: 'amountChange';
statusData: {
amountFrom: string;
amountTo: string;
tokenFrom?: Token;
tokenTo?: Token;
isMissingRequiredField: boolean;
};
}
```
### `transactionPending`
The transaction has been submitted to the network but has not yet been confirmed to be included in a block.
During this pending state, the transaction is waiting to be validated by the network's consensus mechanism.
```vocs_Code
Copy{
statusName: 'transactionPending';
statusData: null;
}
```
### `transactionApproved`
The transaction has been verified to be valid and it has been included in a block
however the transaction is not yet finalized.
```vocs_Code
Copy{
statusName: 'transactionApproved';
statusData: {
transactionHash: Hex;
transactionType: 'Batched' | 'ERC20' | 'Permit2' | 'Swap';
};
}
```
### `success`
The transaction has been added to the blockchain and the transaction is considered final.
```vocs_Code
Copy{
statusName: 'success';
statusData: {
transactionReceipt: TransactionReceipt;
};
}
```
## Lifecycle Status with [``](https://docs.base.org/builderkits/onchainkit/transaction/transaction)
### `transactionIdle`
The transaction component is waiting for the user to take action.
```vocs_Code
Copy{
statusName: 'transactionIdle';
statusData: null;
}
```
### `transactionPending`
The transaction has been submitted to the network but has not yet been confirmed to be included in a block.
During this pending state, the transaction is waiting to be validated by the network's consensus mechanism.
```vocs_Code
Copy{
statusName: 'transactionPending';
statusData: null;
}
```
### `success`
The transaction has been added to the blockchain and the transaction is considered final.
```vocs_Code
Copy{
statusName: 'success';
statusData: {
transactionReceipts: TransactionReceipt[];
};
}
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/api/build-deposit-to-morpho-tx#vocs-content)
buildDepositToMorphoTx
On this page
Chevron Right
The `buildDepositToMorphoTx` function is used to build [Calls](https://docs.base.org/builderkits/onchainkit/transaction/types#calls) for depositing an asset to Morpho. These calls can be passed the `` component to send a transaction.
## Usage
code
```vocs_Code
Copyimport { buildDepositToMorphoTx } from '@coinbase/onchainkit/earn';
const calls = await buildDepositToMorphoTx({
vaultAddress: '0x...', // Morpho vault address on Base
tokenAddress: '0x...', // Address of the token to deposit
amount: 1000000000000000000n, // Amount of tokens to deposit
recipientAddress: '0x...', // Address of the recipient
});
```
## Returns
[`Call[]`](https://docs.base.org/builderkits/onchainkit/transaction/types#calls)
## Parameters
[`DepositToMorphoParams`](https://docs.base.org/builderkits/onchainkit/earn/types#deposittomorphoparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/api/build-mint-transaction#vocs-content)
buildMintTransaction
On this page
Chevron Right
The `buildMintTransaction` function is used to get an unsigned transaction for minting an NFT.
Before using them, make sure to obtain a [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.
## Usage
codereturn value
code
```vocs_Code
Copyimport { setOnchainKitConfig } from '@coinbase/onchainkit';
import { buildMintTransaction } from '@coinbase/onchainkit/api';
const response = await buildMintTransaction({
mintAddress: '0x...',
takerAddress: '0x...',
tokenId: '1',
quantity: 1,
network: 'networks/base-mainnet',
});
```
## Returns
[`Promise`](https://docs.base.org/builderkits/onchainkit/api/types#buildminttransactionresponse)
## Parameters
[`BuildMintTransactionParams`](https://docs.base.org/builderkits/onchainkit/api/types#buildminttransactionparams)
## Types
- [`BuildMintTransactionResponse`](https://docs.base.org/builderkits/onchainkit/api/types#buildminttransactionresponse)
- [`BuildMintTransactionParams`](https://docs.base.org/builderkits/onchainkit/api/types#buildminttransactionparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/api/build-swap-transaction#vocs-content)
buildSwapTransaction
On this page
Chevron Right
The `buildSwapTransaction` function is used to get an unsigned transaction for a swap between two Tokens.
Before using this function, make sure to obtain a [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.
## Usage
codereturn value
code
```vocs_Code
Copyimport { setOnchainKitConfig } from '@coinbase/onchainkit';
import { buildSwapTransaction } from '@coinbase/onchainkit/api';
import type { Token } from '@coinbase/onchainkit/token';
setOnchainKitConfig({ apiKey: 'YOUR_API_KEY' });
const fromToken: Token = {
name: 'ETH',
address: '',
symbol: 'ETH',
decimals: 18,
image: 'https://wallet-api-production.s3.amazonaws.com/uploads/tokens/eth_288.png',
chainId: 8453,
};
const toToken: Token = {
name: 'USDC',
address: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
symbol: 'USDC',
decimals: 6,
image:
'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/44/2b/442b80bd16af0c0d9b22e03a16753823fe826e5bfd457292b55fa0ba8c1ba213-ZWUzYjJmZGUtMDYxNy00NDcyLTg0NjQtMWI4OGEwYjBiODE2',
chainId: 8453,
};
const response = await buildSwapTransaction({
fromAddress: '0x...',
from: fromToken,
to: toToken,
amount: '0.1',
useAggregator: false,
});
```
## Returns
[`Promise`](https://docs.base.org/builderkits/onchainkit/api/types#buildswaptransactionresponse)
## Parameters
[`BuildSwapTransactionParams`](https://docs.base.org/builderkits/onchainkit/api/types#buildswaptransactionparams)
## Types
- [`BuildSwapTransactionResponse`](https://docs.base.org/builderkits/onchainkit/api/types#buildswaptransactionresponse)
- [`BuildSwapTransactionParams`](https://docs.base.org/builderkits/onchainkit/api/types#buildswaptransactionparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/earn/types#vocs-content)
Earn
On this page
Chevron Right
## `LifecycleStatus`
```vocs_Code
Copyexport type LifecycleStatus =
| {
statusName: 'init';
statusData: null;
}
| {
statusName: 'amountChange';
statusData: {
amount: string;
token: Token;
};
}
| Extract<
TransactionLifecycleStatus,
{
statusName:
| 'transactionPending'
| 'transactionLegacyExecuted'
| 'success'
| 'error';
}
>;
```
## `EarnReact`
```vocs_Code
Copyexport type EarnReact = {
children?: React.ReactNode;
className?: string;
vaultAddress: Address;
isSponsored?: boolean;
};
```
## `EarnProviderReact`
```vocs_Code
Copyexport type EarnProviderReact = {
children: React.ReactNode;
vaultAddress: Address;
isSponsored?: boolean;
};
```
## `EarnContextType`
```vocs_Code
Copyexport type EarnContextType = {
/** Warns users if vault address is invalid */
error: Error | null;
recipientAddress?: Address;
/** Balance of the underlying asset in the user's wallet, converted to the asset's decimals */
walletBalance?: string;
/** Status of the wallet balance fetch */
walletBalanceStatus: 'pending' | 'success' | 'error';
refetchWalletBalance: () => void;
vaultAddress: Address;
/** The token that is being deposited or withdrawn (the underlying asset of the vault) */
vaultToken: Token | undefined;
vaultName: string | undefined;
/** Total deposits in the vault */
deposits: string | undefined;
/** Total liquidity (available to borrow) in the vault */
liquidity: string | undefined;
/** Total APY of the vault, including rewards */
apy: number | undefined;
nativeApy: UseMorphoVaultReturnType['nativeApy'];
vaultFee: UseMorphoVaultReturnType['vaultFee'];
/** Rewards earned by the user in the vault */
rewards: UseMorphoVaultReturnType['rewards'];
/** The amount of underlying asset that has been deposited in the vault by the connected user */
depositedBalance?: string;
/** Whether the deposited balance is being fetched */
depositedBalanceStatus: 'pending' | 'success' | 'error';
refetchDepositedBalance: () => void;
/** Interest earned by the user in the vault */
interestEarned?: string;
/** Amount that the user has typed into the deposit amount input */
depositAmount: string;
setDepositAmount: (amount: string) => void;
depositAmountError: string | null;
depositCalls: Call[];
/** Amount that the user has typed into the withdraw amount input */
withdrawAmount: string;
setWithdrawAmount: (amount: string) => void;
withdrawAmountError: string | null;
withdrawCalls: Call[];
lifecycleStatus: LifecycleStatus;
updateLifecycleStatus: (
status: LifecycleStatusUpdate,
) => void;
};
```
## `EarnAmountInputReact`
```vocs_Code
Copyexport type EarnAmountInputReact = {
className?: string;
onChange: (value: string) => void;
value: string;
disabled?: boolean;
'aria-label'?: string;
};
```
## `DepositAmountInputReact`
```vocs_Code
Copyexport type DepositAmountInputReact = {
className?: string;
};
```
## `WithdrawAmountInputReact`
```vocs_Code
Copyexport type WithdrawAmountInputReact = {
className?: string;
};
```
## `EarnBalanceReact`
```vocs_Code
Copyexport type EarnBalanceReact = {
className?: string;
onActionPress: () => void;
title: React.ReactNode;
subtitle: string;
showAction?: boolean;
};
```
## `DepositBalanceReact`
```vocs_Code
Copyexport type DepositBalanceReact = {
className?: string;
};
```
## `WithdrawBalanceReact`
```vocs_Code
Copyexport type WithdrawBalanceReact = {
className?: string;
};
```
## `EarnDepositReact`
```vocs_Code
Copyexport type EarnDepositReact = {
children?: React.ReactNode;
className?: string;
};
```
## `EarnWithdrawReact`
```vocs_Code
Copyexport type EarnWithdrawReact = {
children?: React.ReactNode;
className?: string;
};
```
## `EarnDetailsReact`
```vocs_Code
Copyexport type EarnDetailsReact = {
className?: string;
};
```
## `DepositButtonReact`
```vocs_Code
Copyexport type DepositButtonReact = {
className?: string;
};
```
## `WithdrawButtonReact`
```vocs_Code
Copyexport type WithdrawButtonReact = {
className?: string;
};
```
## `DepositToMorphoParams`
```vocs_Code
Copyexport type DepositToMorphoParams = {
/** The address of the Morpho vault */
vaultAddress: Address;
/** The address of the token to deposit */
tokenAddress: Address;
/** The amount of tokens to deposit */
amount: bigint;
/** The address which can withdraw the deposited tokens */
recipientAddress: Address;
};
```
## `WithdrawFromMorphoParams`
```vocs_Code
Copyexport type WithdrawFromMorphoParams = {
/** The address of the Morpho vault */
vaultAddress: Address;
/** The amount of tokens to withdraw */
amount: bigint;
/** The address to which the withdrawn funds will be sent */
recipientAddress: Address;
};
```
## `UseBuildDepositToMorphoTxParams`
```vocs_Code
Copyexport type UseBuildDepositToMorphoTxParams = {
vaultAddress: Address;
recipientAddress?: Address;
amount: string;
};
```
## `UseBuildWithdrawFromMorphoTxParams`
```vocs_Code
Copyexport type UseBuildWithdrawFromMorphoTxParams = {
vaultAddress: Address;
recipientAddress?: Address;
amount: string;
tokenDecimals: number | undefined;
};
```
## `UseMorphoVaultParams`
```vocs_Code
Copyexport type UseMorphoVaultParams = {
vaultAddress: Address;
recipientAddress?: Address;
};
```
## `UseMorphoVaultReturnType`
```vocs_Code
Copyexport type UseMorphoVaultReturnType = {
vaultName: string | undefined;
status: 'pending' | 'success' | 'error';
/** Warns users if vault address is invalid */
error: Error | null;
/** Underlying asset of the vault */
asset: {
address: Address;
symbol: string | undefined;
decimals: number | undefined;
};
/** User's deposits in the vault, adjusted for decimals */
balance: string | undefined;
balanceStatus: 'pending' | 'success' | 'error';
refetchBalance: () => void;
/** Total net APY of the vault after all rewards and fees */
totalApy: number | undefined;
/** Native rewards of the vault (e.g. USDC if the asset is USDC) */
nativeApy: number | undefined;
/** Additional rewards (e.g. MORPHO) */
rewards:
| {
asset: Address;
assetName: string;
apy: number;
}[]
| undefined;
/** Vault fee, in percent (e.g. 0.03 for 3%) */
vaultFee: number | undefined;
/** Number of decimals of the vault's share tokens (not underlying asset) */
vaultDecimals: number | undefined;
/** Total deposits in the vault */
deposits: string | undefined;
/** Total liquidity available to borrow in the vault */
liquidity: string | undefined;
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/api/build-withdraw-from-morpho-tx#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
buildWithdrawFromMorphoTx
On this page
Chevron Right
The `buildWithdrawFromMorphoTx` function is used to build [Calls](https://docs.base.org/builderkits/onchainkit/transaction/types#calls) for withdrawing an asset from Morpho. These calls can be passed the `` component to send a transaction.
## Usage
code
```vocs_Code
Copyimport { buildWithdrawFromMorphoTx } from '@coinbase/onchainkit/earn';
const calls = await buildWithdrawFromMorphoTx({
vaultAddress: '0x...', // Morpho vault address on Base
amount: 1000000000000000000n, // Amount of tokens to withdraw
recipientAddress: '0x...', // Address of the recipient
});
```
## Returns
[`Call[]`](https://docs.base.org/builderkits/onchainkit/transaction/types#calls)
## Parameters
[`WithdrawFromMorphoParams`](https://docs.base.org/builderkits/onchainkit/earn/types#withdrawfrommorphoparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/api/get-mint-details#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
getMintDetails
On this page
Chevron Right
The `getMintDetails` function returns data required to view an NFT to be minted
Before using them, make sure to obtain a [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.
## Usage
codereturn value
code
```vocs_Code
Copyimport { setOnchainKitConfig } from '@coinbase/onchainkit';
import { getMintDetails } from '@coinbase/onchainkit/api';
const response = await getMintDetails({
contractAddress: '0x...',
takerAddress: '0x...',
tokenId: '1',
});
```
## Returns
[`Promise`](https://docs.base.org/builderkits/onchainkit/api/types#getmintdetailsresponse)
## Parameters
[`GetMintDetailsParams`](https://docs.base.org/builderkits/onchainkit/api/types#getmintdetailsparams)
## Types
- [`GetMintDetailsResponse`](https://docs.base.org/builderkits/onchainkit/api/types#getmintdetailsresponse)
- [`GetMintDetailsParams`](https://docs.base.org/builderkits/onchainkit/api/types#getmintdetailsparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/api/get-portfolios#vocs-content)
Search
[](https://docs.base.org/)
[GitHub](https://github.com/base)
[X](http://x.com/buildonbase)
[Warpcast](https://warpcast.com/buildonbase)
[Discord](https://discord.com/invite/buildonbase)
[](https://docs.base.org/)
[Get help](https://discord.com/invite/buildonbase?utm_source=dotorg&utm_medium=nav)
[GitHub](https://github.com/base) [X](http://x.com/buildonbase) [Warpcast](https://warpcast.com/buildonbase) [Discord](https://discord.com/invite/buildonbase)
Menu
getPortfolios
On this page
Chevron Right
The `getPortfolios` function returns an object containing an array of
portfolios for the provided addresses. Each portfolio is an object with the address
of the wallet, the fiat value of the portfolio, and an array of tokens held by the
provided address.
## Usage
codereturn value
code
```vocs_Code
Copyimport { setOnchainKitConfig } from '@coinbase/onchainkit';
import { getPortfolios } from '@coinbase/onchainkit/api';
const response = await getPortfolios({
addresses: ['0x...'],
});
```
## Returns
[`Promise`](https://docs.base.org/builderkits/onchainkit/api/types#getportfoliosresponse)
## Parameters
[`GetPortfoliosParams`](https://docs.base.org/builderkits/onchainkit/api/types#getportfoliosparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/api/get-swap-quote#vocs-content)
getSwapQuote
On this page
Chevron Right
The `getSwapQuote` function is used to get a quote for a swap between two Tokens.
Before using them, make sure to obtain a [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.
## Usage
codereturn value
code
```vocs_Code
Copyimport { setOnchainKitConfig } from '@coinbase/onchainkit';
import { getSwapQuote } from '@coinbase/onchainkit/api';
import type { Token } from '@coinbase/onchainkit/token';
setOnchainKitConfig({ apiKey: 'YOUR_API_KEY' });
const fromToken: Token = {
name: 'ETH',
address: '',
symbol: 'ETH',
decimals: 18,
image: 'https://wallet-api-production.s3.amazonaws.com/uploads/tokens/eth_288.png',
chainId: 8453,
};
const toToken: Token = {
name: 'USDC',
address: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
symbol: 'USDC',
decimals: 6,
image:
'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/44/2b/442b80bd16af0c0d9b22e03a16753823fe826e5bfd457292b55fa0ba8c1ba213-ZWUzYjJmZGUtMDYxNy00NDcyLTg0NjQtMWI4OGEwYjBiODE2',
chainId: 8453,
};
const quote = await getSwapQuote({
from: fromToken,
to: toToken,
amount: '0.001',
useAggregator: false,
});
```
## Returns
[`Promise`](https://docs.base.org/builderkits/onchainkit/api/types#getswapquoteresponse)
## Parameters
[`GetSwapQuoteParams`](https://docs.base.org/builderkits/onchainkit/api/types#getswapquoteparams)
## Types
- [`GetSwapQuoteResponse`](https://docs.base.org/builderkits/onchainkit/api/types#getswapquoteresponse)
- [`GetSwapQuoteParams`](https://docs.base.org/builderkits/onchainkit/api/types#getswapquoteparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/api/get-token-details#vocs-content)
getTokenDetails
On this page
Chevron Right
The `getTokenDetails` function returns data required to view an NFT
Before using them, make sure to obtain a [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.
## Usage
codereturn value
code
```vocs_Code
Copyimport { setOnchainKitConfig } from '@coinbase/onchainkit';
import { getTokenDetails } from '@coinbase/onchainkit/api';
const response = await getTokenDetails({
contractAddress: '0x...',
tokenId: '1',
});
```
## Returns
[`Promise`](https://docs.base.org/builderkits/onchainkit/api/types#gettokendetailsresponse)
## Parameters
[`GetTokenDetailsParams`](https://docs.base.org/builderkits/onchainkit/api/types#gettokendetailsparams)
## Types
- [`GetTokenDetailsResponse`](https://docs.base.org/builderkits/onchainkit/api/types#gettokendetailsresponse)
- [`GetTokenDetailsParams`](https://docs.base.org/builderkits/onchainkit/api/types#gettokendetailsparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/api/get-tokens#vocs-content)
getTokens
On this page
Chevron Right
The `getTokens` function retrieves a list of tokens on Base by searching for the name, symbol, or address of a token.
Before using them, make sure to obtain a [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.
## Usage
Search by symbol
codereturn value
code
```vocs_Code
Copyimport { setOnchainKitConfig } from '@coinbase/onchainkit';
import { getTokens } from '@coinbase/onchainkit/api';
setOnchainKitConfig({ apiKey: 'YOUR_API_KEY' });
const tokens = await getTokens({ limit: '1', search: 'degen' });
```
Search by name
codereturn value
code
```vocs_Code
Copyimport { setOnchainKitConfig } from '@coinbase/onchainkit';
import { getTokens } from '@coinbase/onchainkit/api';
setOnchainKitConfig({ apiKey: 'YOUR_API_KEY' });
const tokens = await getTokens({ limit: '1', search: 'Wrapped Ether' });
```
Search by address
codereturn value
code
```vocs_Code
Copyimport { setOnchainKitConfig } from '@coinbase/onchainkit';
import { getTokens } from '@coinbase/onchainkit/api';
setOnchainKitConfig({ apiKey: 'YOUR_API_KEY' });
const tokens = await getTokens({
limit: '1',
search: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
});
```
## Returns
[`Promise`](https://docs.base.org/builderkits/onchainkit/api/types#gettokensresponse)
## Parameters
[`GetTokensOptions`](https://docs.base.org/builderkits/onchainkit/api/types#gettokensoptions)
## Types
- [`GetTokensResponse`](https://docs.base.org/builderkits/onchainkit/api/types#gettokensresponse)
- [`GetTokensOptions`](https://docs.base.org/builderkits/onchainkit/api/types#gettokensoptions)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/api/types#vocs-content)
API
On this page
Chevron Right
## `APIError`
```vocs_Code
Copytype APIError = {
code: string; // The Error code
error: string; // The Error long message
message: string; // The Error short message
};
```
## `BuildPayTransactionParams`
```vocs_Code
Copytype BuildPayTransactionParams = {
address: Address; // The address of the wallet paying
chainId: number; // The Chain ID of the payment Network (only Base is supported)
chargeId: string; // The ID of the Commerce Charge to be paid
};
```
## `BuildPayTransactionResponse`
```vocs_Code
Copytype BuildPayTransactionResponse = PayTransaction | APIError;
```
## `BuildSwapTransaction`
```vocs_Code
Copytype BuildSwapTransaction = {
approveTransaction?: Transaction; // ERC20 approve transaction which allows token holders to authorize spending
fee: Fee; // The fee for the swap
quote: SwapQuote; // The quote for the swap
transaction: Transaction; // The object developers should pass into Wagmi's signTransaction
warning?: QuoteWarning; // The warning associated with the swap
};
```
## `BuildSwapTransactionParams`
```vocs_Code
Copytype BuildSwapTransactionParams = GetSwapQuoteParams & {
fromAddress: Address; // The address of the user
};
```
## `BuildSwapTransactionResponse`
```vocs_Code
Copytype BuildSwapTransactionResponse = BuildSwapTransaction | APIError;
```
## `GetSwapQuoteParams`
```vocs_Code
Copytype GetSwapQuoteParams = {
amount: string; // The amount to be swapped
amountReference?: string; // The reference amount for the swap
from: Token; // The source token for the swap
isAmountInDecimals?: boolean; // Whether the amount is in decimals
maxSlippage?: string; // The slippage of the swap
to: Token; // The destination token for the swap
useAggregator: boolean; // Whether to use a DEX aggregator
};
```
## `GetSwapQuoteResponse`
```vocs_Code
Copytype GetSwapQuoteResponse = SwapQuote | APIError;
```
## `GetTokensOptions`
```vocs_Code
Copytype GetTokensOptions = {
limit?: string; // The maximum number of tokens to return (default: 50)
page?: string; // The page number to return (default: 1)
search?: string; // A string to search for in the token name, symbol or address
};
```
## `GetTokensResponse`
```vocs_Code
Copytype GetTokensResponse = Token[] | APIError;
```
## `GetTokenDetailsParams`
```vocs_Code
Copytype GetTokenDetailsParams = {
contractAddress: Address;
tokenId?: string;
};
```
## `GetTokenDetailsResponse`
```vocs_Code
Copytype GetTokenDetailsResponse = TokenDetails | APIError;
```
## `GetMintDetailsParams`
```vocs_Code
Copytype GetMintDetailsParams = {
contractAddress: Address;
takerAddress?: Address;
tokenId?: string;
};
```
## `GetMintDetailsResponse`
```vocs_Code
Copytype GetMintDetailsResponse = MintDetails | APIError;
```
## `BuildMintTransactionParams`
```vocs_Code
Copytype BuildMintTransactionParams = {
mintAddress: Address;
takerAddress: Address;
tokenId?: string;
quantity: number;
network?: string;
};
```
## `BuildMintTransactionResponse`
```vocs_Code
Copytype BuildMintTransactionResponse = MintTransaction | APIError;
```
## `GetPortfoliosParams`
```vocs_Code
Copytype GetPortfoliosParams = {
addresses: Address[] | null | undefined;
};
```
## `GetPortfoliosResponse`
```vocs_Code
Copytype GetPortfoliosResponse = {
portfolios: Portfolio[];
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/appchain/bridge#vocs-content)
Bridge
On this page
Chevron Right
The `AppchainBridge` component provides a simple interface for implementing bridging to appchains with OnchainKit.
## Prerequisites
Before using the `AppchainBridge` component, ensure you've completed the [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started) steps.
### Starting a new project
If you're starting a new project, we recommend using `create onchain` to scaffold your project.
```vocs_Code
Copynpm create onchain@latest
```
### Adding to an existing project
If you're adding `AppchainBridge` to an existing project, simply install OnchainKit.
npmyarnpnpmbun
Terminal
npm
```vocs_Code
Copynpm install @coinbase/onchainkit
```
Wrap the `` around your app, following the steps in [Getting Started](https://docs.base.org/builderkits/onchainkit/installation/nextjs#add-providers).
## Quickstart
To use `AppchainBridge`, you'll need to create a custom chain for your network using Viem's [defineChain](https://viem.sh/docs/chains/introduction#custom-chains).
You can retrieve the chain ID and your RPC URL from your appchain's dashboard in Coinbase Developer Platform.
Once successfully created, add the custom chain to your Wagmi configuration, and provide it as a child component to `OnchainKitProvider`.
chain.tsproviders.tsx
File
chain.ts
```vocs_Code
Copyimport { defineChain } from 'viem';
export const EXAMPLE_CHAIN = defineChain({
id: 8453200000,
name: 'Your Appchain Network',
nativeCurrency: {
name: 'Ethereum',
symbol: 'ETH',
decimals: 18,
},
rpcUrls: {
default: {
http: ['https://your-rpc.appchain.base.org'],
},
},
});
```
Use the custom chain to create an `Appchain` object. You can also render an icon in the UI using the `icon` prop.
```vocs_Code
Copyimport type { Appchain } from '@coinbase/onchainkit/appchain';
const EXAMPLE_APPCHAIN: Appchain = {
chain: EXAMPLE_CHAIN,
icon: ,
};
```
Now, you can render the `AppchainBridge` component with the `chain` and `appchain` props.
```vocs_Code
Copyimport { AppchainBridge } from '@coinbase/onchainkit/appchain';
import { baseSepolia } from 'viem/chains';
```
## Custom bridgeable tokens
By default, the bridgeable token is only native ETH. You can customize the bridgeable tokens by providing a `bridgeableTokens` prop to the `AppchainBridge` component.
Let's add a custom "Appchain Token" to the bridgeable tokens array.
```vocs_Code
Copyimport type { BridgeableToken } from '@coinbase/onchainkit/appchain';
const customBridgeableTokens: BridgeableToken[] = [\
{\
name: 'ETH',\
address: '',\
symbol: 'ETH',\
decimals: 18,\
image:\
'https://wallet-api-production.s3.amazonaws.com/uploads/tokens/eth_288.png',\
chainId: 8453200000,\
},\
{\
address: '0x...',\
remoteToken: '0x...',\
name: 'Appchain Token',\
symbol: 'ATKN',\
decimals: 18,\
chainId: 8453200000,\
image: 'https://some-icon.com/icon.png',\
},\
];
```
You can then plug the `customBridgeableTokens` into the `AppchainBridge` component with the `bridgeableTokens` prop.
```vocs_Code
Copyimport { AppchainBridge } from '@coinbase/onchainkit/appchain';
import { baseSepolia } from 'viem/chains';
```
### Chains with custom gas tokens
For chains that use custom gas tokens, simply set the `isCustomGasToken` field to `true` on the custom gas token for your bridgeable token.
```vocs_Code
Copyimport type { BridgeableToken } from '@coinbase/onchainkit/appchain';
const customGasToken: BridgeableToken[] = [\
{\
address: '0x...',\
remoteToken: '0x...',\
name: 'Appchain Token',\
symbol: 'ATKN',\
decimals: 18,\
chainId: 8453200000,\
image: 'https://some-icon.com/icon.png',\
isCustomGasToken: true,\
},\
];
```
### Fetching price for custom tokens
By default, we provide a price feed for ETH and USDC.
To fetch the price of custom ERC-20 tokens, you can override the `handleFetchPrice` function in the `AppchainBridge` component. This callback is run everytime the user changes the input amount.
The function must match the following signature:
```vocs_Code
Copy(amount: string, token: Token) => Promise;
```
```vocs_Code
Copy
import { AppchainBridge } from '@coinbase/onchainkit/appchain';
import { baseSepolia } from 'viem/chains';
const handleFetchPrice = async (amount: string, token: Token) => {
// Example of fetching price
const price = await fetch(`https://api.example.com/price/${token.address}`);
return price * amount;
};
```
## Components
The `AppchainBridge` component includes the following subcomponents:
- `` \- A fully built bridge component that handles deposits and withdrawals. Also includes a `children` prop to render custom components.
- `` \- A headless provider that provides the bridge context to child components.
- `` \- A component that handles the amount input for bridging tokens.
- `` \- A component that displays network information and allows network selection.
- `` \- A component that triggers bridge transactions.
- `` \- A component that handles the withdrawal interface.
- `` \- A button component for toggling between networks.
- `` \- A component that displays transaction success states.
- `` \- A component that handles resuming interrupted bridge transactions.
## Props
- [`Appchain`](https://docs.base.org/builderkits/onchainkit/appchain/types#appchain)
- [`AppchainBridgeReact`](https://docs.base.org/builderkits/onchainkit/appchain/types#appchainbridgereact)
- [`AppchainBridgeProviderReact`](https://docs.base.org/builderkits/onchainkit/appchain/types#appchainbridgeproviderreact)
- [`AppchainBridgeContextType`](https://docs.base.org/builderkits/onchainkit/appchain/types#appchainbridgecontexttype)
- [`BridgeableToken`](https://docs.base.org/builderkits/onchainkit/appchain/types#bridgeabletoken)
- [`ChainWithIcon`](https://docs.base.org/builderkits/onchainkit/appchain/types#chainwithicon)
- [`AppchainConfig`](https://docs.base.org/builderkits/onchainkit/appchain/types#appchainconfig)
- [`AppchainBridgeSuccessReact`](https://docs.base.org/builderkits/onchainkit/appchain/types#appchainbridgesuccessreact)
- [`BridgeParams`](https://docs.base.org/builderkits/onchainkit/appchain/types#bridgeparams)
- [`ChainConfigParams`](https://docs.base.org/builderkits/onchainkit/appchain/types#chainconfigparams)
- [`UseDepositParams`](https://docs.base.org/builderkits/onchainkit/appchain/types#usedepositparams)
- [`UseWithdrawParams`](https://docs.base.org/builderkits/onchainkit/appchain/types#usewithdrawparams)
- [`UseDepositButtonParams`](https://docs.base.org/builderkits/onchainkit/appchain/types#usedepositbuttonparams)
- [`UseWithdrawButtonParams`](https://docs.base.org/builderkits/onchainkit/appchain/types#usewithdrawbuttonparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/appchain/types#vocs-content)
Appchain
On this page
Chevron Right
## `Appchain`
```vocs_Code
Copyexport type Appchain = {
/** The chain to bridge to. */
chain: Chain;
/** Optional icon to display for the appchain. */
icon?: React.ReactNode;
};
```
## `AppchainBridgeReact`
```vocs_Code
Copyexport type AppchainBridgeReact = {
/** The source chain to bridge from. This should be Base or Base Sepolia. */
chain: Chain;
/** The appchain to bridge to. */
appchain: Appchain;
/** Optional children to render within the component. */
children?: React.ReactNode;
/** Optional className override for the component. */
className?: string;
/** Optional title for the component. */
title?: string;
/** Optional array of bridgeable tokens. */
bridgeableTokens?: BridgeableToken[];
/** Optional function to implement fetching the price of the token. */
handleFetchPrice?: (amount: string, token: Token) => Promise;
};
```
## `AppchainBridgeProviderReact`
```vocs_Code
Copyexport type AppchainBridgeProviderReact = {
children: ReactNode;
chain: Chain;
appchain: Appchain;
bridgeableTokens?: BridgeableToken[];
handleFetchPrice?: (amount: string, token: Token) => Promise;
};
```
## `AppchainBridgeContextType`
```vocs_Code
Copyexport type AppchainBridgeContextType = {
// Configuration
config: AppchainConfig;
from: ChainWithIcon;
to: ChainWithIcon;
bridgeParams: BridgeParams;
bridgeableTokens: BridgeableToken[];
// UI State
isPriceLoading: boolean;
isAddressModalOpen: boolean;
isWithdrawModalOpen: boolean;
isSuccessModalOpen: boolean;
isResumeTransactionModalOpen: boolean;
balance: string;
depositStatus: string;
withdrawStatus: string;
direction: string;
depositTransactionHash?: Hex;
finalizedWithdrawalTxHash?: Hex;
resumeWithdrawalTxHash?: Hex;
// Handler Functions
handleToggle: () => void;
handleAmountChange: (params: { amount: string; token: Token }) => void;
handleAddressSelect: (address: Address) => void;
handleResumeTransaction: (txHash: Hex) => void;
handleDeposit: () => void;
handleWithdraw: () => void;
handleOpenExplorer: () => void;
handleResetState: () => void;
waitForWithdrawal: (txHash?: Hex) => Promise;
proveAndFinalizeWithdrawal: () => Promise;
setIsAddressModalOpen: (open: boolean) => void;
setIsWithdrawModalOpen: (open: boolean) => void;
setIsSuccessModalOpen: (open: boolean) => void;
resetDepositStatus: () => void;
setResumeWithdrawalTxHash: (txHash: Hex) => void;
setIsResumeTransactionModalOpen: (open: boolean) => void;
};
```
## `BridgeableToken`
```vocs_Code
Copyexport type BridgeableToken = Token & {
/** The address of the remote token on the appchain. */
remoteToken?: Address;
/** Optional boolean to indicate if the chain uses a custom gas token */
isCustomGasToken?: boolean;
};
```
## `ChainWithIcon`
```vocs_Code
Copyexport type ChainWithIcon = Chain & {
icon: React.ReactNode;
};
```
## `AppchainConfig`
```vocs_Code
Copyexport type AppchainConfig = {
chainId: number;
/** The OP Bedrock contract addresses for an appchain. These are on Base and retrieved from DeployContract. */
contracts: {
l2OutputOracle: Address;
systemConfig: Address;
optimismPortal: Address;
l1CrossDomainMessenger: Address;
l1StandardBridge: Address;
l1ERC721Bridge: Address;
optimismMintableERC20Factory: Address;
};
};
```
## `AppchainBridgeSuccessReact`
```vocs_Code
Copyexport type AppchainBridgeSuccessReact = {
title?: string;
primaryButtonLabel?: string;
secondaryButtonLabel?: string;
};
```
## `BridgeParams`
```vocs_Code
Copyexport type BridgeParams = {
amount: string;
amountUSD: string;
token: BridgeableToken;
recipient?: Address;
};
```
## `ChainConfigParams`
```vocs_Code
Copyexport type ChainConfigParams = {
config: AppchainConfig;
chain: Chain;
};
```
## `UseDepositParams`
```vocs_Code
Copyexport type UseDepositParams = {
config: AppchainConfig;
from: Chain;
bridgeParams: BridgeParams;
};
```
## `UseWithdrawParams`
```vocs_Code
Copyexport type UseWithdrawParams = {
config: AppchainConfig;
chain: Chain;
bridgeParams: BridgeParams;
};
```
## `UseDepositButtonParams`
```vocs_Code
Copyexport type UseDepositButtonParams = {
depositStatus: string;
withdrawStatus: string;
bridgeParams: BridgeParams;
};
```
## `UseWithdrawButtonParams`
```vocs_Code
Copyexport type UseWithdrawButtonParams = {
withdrawStatus: string;
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/buy/buy#vocs-content)
Buy
On this page
Chevron Right

The `Buy` components provide a comprehensive interface for users to purchase [Tokens](https://docs.base.org/builderkits/onchainkit/token/types#token).
The `Buy` component supports token swaps from USDC and ETH by default with the option to provide an additional token of choice using the `fromToken` prop. In addition, users are able to purchase tokens using their Coinbase account, Apple Pay, or debit card.
Before using, ensure you've completed all [Getting Started steps](https://docs.base.org/builderkits/onchainkit/getting-started).
## Usage
Example using `@coinbase/onchainkit/buy`.
```vocs_Code
Copyimport { Buy } from '@coinbase/onchainkit/buy';
import type { Token } from '@coinbase/onchainkit/token';
export default function BuyComponents() {
const degenToken: Token = {
name: 'DEGEN',
address: '0x4ed4e862860bed51a9570b96d89af5e1b0efefed',
symbol: 'DEGEN',
decimals: 18,
image:
'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/3b/bf/3bbf118b5e6dc2f9e7fc607a6e7526647b4ba8f0bea87125f971446d57b296d2-MDNmNjY0MmEtNGFiZi00N2I0LWIwMTItMDUyMzg2ZDZhMWNm',
chainId: 8453,
};
return (
)
}
```
DEGEN
Buy
### Sponsor gas with Paymaster
To sponsor swap transactions for your users, toggle the Paymaster using the `isSponsored` prop.
By default, this will use the [Coinbase Developer Platform](https://portal.cdp.coinbase.com/products/bundler-and-paymaster) Paymaster.
You can configure sponsorship settings on the [Paymaster](https://portal.cdp.coinbase.com/products/bundler-and-paymaster) page.
For security reasons, we recommend setting up a contract allowlist in the Portal. Without a contract allowlist defined, your Paymaster will only be able to sponsor up to $1.
The contract used in our Swap API is Uniswap's [Universal Router](https://basescan.org/address/0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD), which is deployed on Base at `0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD`.
Note that gas sponsorship will only work for Smart Wallets.
```vocs_Code
Copyimport { Buy } from '@coinbase/onchainkit/buy';
import type { Token } from '@coinbase/onchainkit/token';
export default function BuyComponents() {
const degenToken: Token = {
name: 'DEGEN',
address: '0x4ed4e862860bed51a9570b96d89af5e1b0efefed',
symbol: 'DEGEN',
decimals: 18,
image:
'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/3b/bf/3bbf118b5e6dc2f9e7fc607a6e7526647b4ba8f0bea87125f971446d57b296d2-MDNmNjY0MmEtNGFiZi00N2I0LWIwMTItMDUyMzg2ZDZhMWNm',
chainId: 8453,
};
return (
)
}
```
## Props
- [`BuyReact`](https://docs.base.org/builderkits/onchainkit/buy/types#buyreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/checkout/checkout#vocs-content)
Checkout
On this page
Chevron Right
The `Checkout` component provides a one-click checkout experience for onchain commerce - all for free.
Our all-in-one solution simplifies payment processing for onchain developers, removing complex integrations, high fees, and onboarding friction. Whether you're selling digital goods, services, or in-game items, this tool is for you.

## Features
- **Plug-and-Play Integration:** Add our `Checkout` button with just a few lines of code. No backend required.
- **Seamless Onboarding:** Support Passkey wallets to eliminate onboarding drop-offs.
- **Real-time Merchant Tooling:** Get instant payment tracking, analytics, and reporting.
- **Dynamic Payment Flows:** Generate charges on the fly, handle variable pricing, and pass in custom metadata.
## Prerequisites
Before using the `Checkout` component, ensure you've completed the [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started) steps.
### Starting a new project
If you're starting a new project, we recommend using `create onchain` to scaffold your project.
```vocs_Code
Copynpm create onchain@latest
```
### Adding to an existing project
If you're adding `Checkout` to an existing project, simply install OnchainKit.
npmyarnpnpmbun
Terminal
npm
```vocs_Code
Copynpm install @coinbase/onchainkit
```
Wrap the `` around your app, following the steps in [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started#add-providers).
## Quickstart
### Option 1: Simple Product Checkout
Ideal for fixed-price items. Get started with minimal setup.
### Sign up for a Coinbase Commerce account
Head to [Coinbase Commerce](https://beta.commerce.coinbase.com/) and sign up. This is where you’ll manage transactions, view reports, and configure payments.
### Create a product and copy the `productId`
In the Coinbase Commerce dashboard, create a new product and copy the `productId`.
### Import the component
```vocs_Code
Copyimport { Checkout, CheckoutButton, CheckoutStatus } from '@coinbase/onchainkit/checkout';
// set coinbaseBranded for branding
```
### Option 2: Dynamic Charges
For variable pricing, custom metadata, or multi-product checkouts, use backend-generated charges.
### Sign up for a Coinbase Commerce account
Head to [Coinbase Commerce](https://beta.commerce.coinbase.com/) and sign up. This is where you’ll manage transactions, view reports, and configure payments.
### Create a Coinbase Commerce API Key
In the [Coinbase Commerce dashboard](https://beta.commerce.coinbase.com/settings/security), create a new API Key under `Security` in `Settings`.
### Set up a backend to create charges dynamically using the Coinbase Commerce API.
See [Using chargeHandler](https://docs.base.org/builderkits/onchainkit/checkout/checkout#using-chargehandler) for a code example.
### Pass the chargeID into Checkout via the chargeHandler prop.
```vocs_Code
Copyconst chargeHandler = async () => {
const response = await fetch('/createCharge', { method: 'POST' });
const { id } = await response.json();
return id; // Return charge ID
};
```
That's it! Start selling onchain with just a few lines of code.
## Usage
### Configuring a checkout
#### Using `productId`
You can create products on the Coinbase Commerce Portal and use them in the `Checkout` component through the `productId` prop.
```vocs_Code
Copy
```
Pay
#### Using `chargeHandler`
Alternatively, you can create charges dynamically using the Coinbase Commerce API [Create Charge](https://docs.cdp.coinbase.com/commerce-onchain/reference/creates-a-charge) endpoint by passing the chargeID into Checkout via the `chargeHandler` prop.
This function must have the signature `() => Promise` and must return a valid chargeId created by the create charge endpoint.
backend.tsfrontend.tsx
File
backend.ts
```vocs_Code
Copy// This backend endpoint should create a charge and return the response.
app.post('/createCharge', async (req: Request, res: Response) => {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CC-Api-Key': 'your_api_key_here' // Replace this with your Coinbase Commerce API Key
},
body: JSON.stringify({
local_price: { amount: '1', currency: 'USDC' },
pricing_type: 'fixed_price',
metadata: { some_field: "some_value" } // Optional: Attach metadata like order ID or customer details
}),
};
const response = await fetch('https://api.commerce.coinbase.com/charges', options);
const data = await response.json();
res.json(data);
});
```
Note that `productId` and `chargeHandler` are mutually exclusive and only one can be provided as a prop to Checkout.
### Handling a successful checkout
To handle successful checkouts, use the `onStatus` prop to listen for the `success` callback.
This callback will return a [LifecycleStatusData](https://docs.base.org/builderkits/onchainkit/checkout/checkout#advanced-usage) object including the [TransactionReceipt](https://github.com/wevm/viem/blob/main/src/types/transaction.ts#L38) and `chargeId`.
For idempotent actions, like rendering your own success screen, you can simply check that the `statusName` is equal to `success`.
For non-idempotent actions, like order fulfillment, we recommend one of the following approaches to verify a charge has been fully paid.
1. ( **Recommended**) Check the status of the `chargeId` using the [Coinbase Commerce API](https://docs.cdp.coinbase.com/commerce-onchain/docs/web3-payments-faq#how-can-i-verify-if-a-charge-has-been-fully-paid).
2. Set up a [Coinbase Commerce Webhook](https://docs.cdp.coinbase.com/commerce-onchain/docs/webhooks) which will notify you for successful payments.
```vocs_Code
Copyimport type { LifecycleStatus } from '@coinbase/onchainkit/checkout';
const statusHandler = async (status: LifecycleStatus) => {
const { statusName, statusData } = status;
switch (statusName) {
case 'success':
// handle success
const { chargeId } = statusData;
// use the charges api to verify the chargeId
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CC-Api-Key': 'your_api_key_here' // Replace this with your Coinbase Commerce API Key
}
};
const response = await fetch(`https://api.commerce.coinbase.com/charges/${chargeId}`);
}
}
```
### Viewing successful checkouts
You can view successful checkouts on the [Coinbase Commerce Merchant Dashboard](https://beta.commerce.coinbase.com/payments).

## Customization
### Add name and logo
To customize the name and logo of your application rendered in the popup, set the `name` and `logo` values inside [OnchainKitProvider](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider#usage).
File
providers.tsx
```vocs_Code
Copyimport { OnchainKitProvider } from '@coinbase/onchainkit';
{children}
```

### Add Coinbase branding
You can add Coinbase branding to the component by using the `coinbaseBranded` prop on `CheckoutButton`.
```vocs_Code
Copy
```
Pay
### Disabling the button
You can disable the button using the `disabled` prop on `CheckoutButton`.
```vocs_Code
Copy
```
Pay
### Customize button
You can customize the button text using the `text` prop on `CheckoutButton`.
```vocs_Code
Copy
```
Checkout with USDC
### Override styles
We recommend style customization by setting a custom [OnchainKit theme](https://docs.base.org/builderkits/onchainkit/guides/themes#custom-theme). You can also override individual component styles using `className`.
```vocs_Code
Copy
```
Pay
## Advanced Usage
### Listening to the component lifecycle
You can use our Checkout [`LifecycleStatus`](https://docs.base.org/builderkits/onchainkit/checkout/types#lifecyclestatus) and the `onStatus` prop to listen to transaction states.
```vocs_Code
Copyimport type { LifecycleStatus } from '@coinbase/onchainkit/checkout';
const statusHandler = (status: LifecycleStatus) => {
const { statusName, statusData } = status;
switch (statusName) {
case 'success': // handle success
case 'pending': // handle payment pending
case 'error': // handle error
default:
// handle 'init' state
}
}
```
## Example use cases
- **Demand-based pricing:** Allow users to select seats or ticket types for events, and dynamically calculate charges based on availability and demand.
- **Product bundles:** Provide users with the option to create custom product bundles, applying discounts or special pricing based on the selected items.
- **Freelance Services:** Allow clients to specify project details such as hours, deliverables, and deadlines, and generate charges based on these custom inputs.
## Components
The components are designed to work together hierarchically. For each component, ensure the following:
- `` \- Sets the `productId` or `chargeHandler` prop.
- `` \- Branding and customization of the payment button.
- `` \- The status of the payment.
## Props
- [`LifecycleStatus`](https://docs.base.org/builderkits/onchainkit/checkout/types#lifecyclestatus)
- [`CheckoutReact`](https://docs.base.org/builderkits/onchainkit/checkout/types#checkoutreact)
- [`CheckoutButtonReact`](https://docs.base.org/builderkits/onchainkit/checkout/types#checkoutbuttonreact)
- [`CheckoutStatusReact`](https://docs.base.org/builderkits/onchainkit/checkout/types#checkoutstatusreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/checkout/types#vocs-content)
Checkout
On this page
Chevron Right
## `LifecycleStatus`
```vocs_Code
Copytype LifecycleStatus =
| {
statusName: 'init';
statusData: LifecycleStatusDataShared;
}
| {
statusName: 'error';
statusData: TransactionError;
}
| {
statusName: 'fetchingData';
statusData: LifecycleStatusDataShared;
}
| {
statusName: 'ready';
statusData: {
chargeId: string;
contracts: ContractFunctionParameters[];
};
}
| {
statusName: 'pending';
statusData: LifecycleStatusDataShared;
}
| {
statusName: 'success'; // if the last mutation attempt was successful
statusData: {
transactionReceipts: TransactionReceipt[];
chargeId: string;
receiptUrl: string;
};
};
```
## `CheckoutButtonReact`
```vocs_Code
Copytype CheckoutButtonReact = {
className?: string;
coinbaseBranded?: boolean;
disabled?: boolean;
icon?: React.ReactNode;
text?: string;
};
```
## `CheckoutReact`
```vocs_Code
Copytype CheckoutReact = {
chargeHandler?: () => Promise;
children: React.ReactNode;
className?: string;
isSponsored?: boolean;
onStatus?: (status: LifecycleStatus) => void;
productId?: string;
};
```
## `CheckoutStatusReact`
```vocs_Code
Copytype CheckoutStatusReact = { className?: string };
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/config/is-base#vocs-content)
isBase
On this page
Chevron Right
The `isBase` utility is designed to verify if the chain id is a valid Base or Base Sepolia chain id.
## Usage
codereturn value
code
```vocs_Code
Copyimport { isBase } from '@coinbase/onchainkit';
// Base Mainnet (chain ID: 8453)
isBase({ chainId: 8453 }); // returns true
// Base Sepolia (chain ID: 84532)
isBase({ chainId: 84532 }); // returns true
// Ethereum (chain ID: 1)
isBase({ chainId: 1 }); // returns false
```
## Returns
`boolean` \- Returns `true` if the chain id is Base or Base Sepolia, otherwise `false`.
## Parameters
[`IsBaseOptions`](https://docs.base.org/types#isbaseoptions) \- See [`IsBaseOptions`](https://docs.base.org/types#isbaseoptions) for more details.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/config/is-ethereum#vocs-content)
isEthereum
On this page
Chevron Right
The `isEthereum` utility is designed to verify if the chain id is a valid Ethereum Mainnet or Ethereum Sepolia chain id.
## Usage
codereturn value
code
```vocs_Code
Copyimport { isEthereum } from '@coinbase/onchainkit';
// Ethereum Mainnet (chain ID: 1)
isEthereum({ chainId: 1 }); // returns true
// Ethereum Sepolia (chain ID: 11155111)
isEthereum({ chainId: 11155111 }); // returns true
// Base (chain ID: 8453)
isEthereum({ chainId: 8453 }); // returns false
```
## Returns
`boolean` \- Returns `true` if the chain id is Ethereum Mainnet or Ethereum Sepolia, otherwise `false`.
## Parameters
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider#vocs-content)
OnchainKitProvider
On this page
Chevron Right
Provides the OnchainKit React Context to the app.
## Usage
File
app.tsx
```vocs_Code
Copyimport { base } from 'viem/chains';
import { OnchainKitProvider } from '@coinbase/onchainkit';
const App = () => {
return (
);
};
```
## Props
[`OnchainKitProviderReact`](https://docs.base.org/builderkits/onchainkit/config/types#onchainkitproviderreact)
| Prop | Description | Required |
| --- | --- | --- |
| [`chain`](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider#chain) | The chain that your OnchainKit project supports. | Yes |
| [`apiKey`](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider#apikey) | Client API Key from Coinbase Developer Platform. | No |
| [`rpcUrl`](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider#rpc-url) | RPC URL for onchain requests. | No |
| [`projectId`](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider#project-id) | Your Coinbase Developer Platform Project ID. | No |
| [`config`](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider#config) | \- `config.appearance` — Customize your OnchainKit project's appearance \- `config.paymaster` — Paymaster URL for gas sponsorship \- `config.wallet` — Wallet configuration options | No |
| [`schemaId`](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider#schema-id) | _\[Deprecation Pending\]_ The schema ID for attestations from the Ethereum Attestation Service (EAS). | No |
| [`address`](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider#address) | _\[Deprecation Pending\]_ This prop is no longer used. | No |
### Chain
`chain` specifies the chain on which your OnchainKit project will operate.
This prop is required for all OnchainKit components.
We recommend importing chain data from [viem](https://viem.sh/docs/chains/introduction).
### `apiKey`
`apiKey` is your Coinbase Developer Platform Client API Key.
This prop is required for most OnchainKit components, including:
- [``](https://docs.base.org/builderkits/onchainkit/checkout/checkout)
- [``](https://docs.base.org/builderkits/onchainkit/mint/nft-card)
- [``](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card)
- [``](https://docs.base.org/builderkits/onchainkit/swap/swap)
- [``](https://docs.base.org/builderkits/onchainkit/transaction/transaction)
You can get a [Client API Key](https://portal.cdp.coinbase.com/projects/project-id/api-keys/client-key)
from Coinbase Developer Platform.

### RPC URL
`rpcUrl` is required for any onchain requests. If you provide your own RPC URL,
OnchainKit will use it.
If you do not provide your own RPC URL, you must provide an `apiKey`, which
enables OnchainKit to use the
[Coinbase Developer Platform Node](https://portal.cdp.coinbase.com/products/node).
### Project ID
`projectId` is your Coinbase Developer Platform Project ID.
This prop is required for the `` component.
You can obtain a Project ID from the [Coinbase Developer Platform](https://portal.cdp.coinbase.com/projects).

### Config
`config` is an object that can be used to customize the appearance and behavior
of the OnchainKit components.
This prop has three keys: `appearance`, `paymaster`, and `wallet`.
#### Appearance
`appearance` manages the appearance of the OnchainKit components and has the following properties:
- `name` — The name of your OnchainKit project
- `logo` — The URL of the logo for your OnchainKit project
- `mode` — The mode of the OnchainKit components. Can be `auto`, `dark`, or `light`.
- `theme` — The theme of the OnchainKit components. Can be `base`, `cyberpunk`, `default`, `hacker`, or a custom theme.
Explore appearance options in the [OnchainKit Playground](https://onchainkit.xyz/playground).
#### Paymaster
`paymaster` represents the Paymaster URL that enables you to sponsor gas for your users.
You can configure your Paymaster and obtain your Paymaster URL from the
[Coinbase Developer Platform](https://portal.cdp.coinbase.com/products/bundler-and-paymaster).
#### Wallet
`wallet` configures the wallet connection experience and has the following properties:
- `display` — The display mode for the wallet interface. Can be either:
- `'modal'` — Shows wallet connection in a modal overlay with wallet aggregation
- `'classic'` — Shows wallet connection in the traditional inline style
- `termsUrl` — URL to your terms of service
- `privacyUrl` — URL to your privacy policy
### Address _\[Deprecation Pending\]_
`address` is no longer used and will be removed in a future version of
OnchainKit.
### Schema ID _\[Deprecation Pending\]_
`schemaId` is no longer used as OnchainKit now defaults to using Coinbase
attestations for the `` component.
This prop will be removed in a future version of OnchainKit.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/config/supplemental-providers#vocs-content)
Custom Supplemental Providers
On this page
Chevron Right
Under the hood, OnchainKit will create our recommended Wagmi and QueryClient
providers. If you wish to customize the providers, you can do so by creating
these providers with your own configuration.
For example, the following code creates custom Wagmi and QueryClient providers:
wagmi.tsproviders.tsx
File
wagmi.ts
```vocs_Code
Copyimport { http, cookieStorage, createConfig, createStorage } from 'wagmi';
import { base } from 'wagmi/chains'; // add baseSepolia for testing
import { coinbaseWallet } from 'wagmi/connectors';
export function getConfig() {
return createConfig({
chains: [base], // add baseSepolia for testing
connectors: [\
coinbaseWallet({\
appName: 'OnchainKit',\
preference: 'smartWalletOnly',\
version: '4',\
}),\
],
storage: createStorage({
storage: cookieStorage,
}),
ssr: true,
transports: {
[base.id]: http(), // add baseSepolia for testing
},
});
}
declare module 'wagmi' {
interface Register {
config: ReturnType;
}
}
```
# Start building!
Explore our ready-to-use onchain components:
- [**`Identity`**](https://docs.base.org/builderkits/onchainkit/identity/identity)\- Show [Basenames](https://docs.base.org/builderkits/onchainkit/identity/identity), [avatars](https://docs.base.org/builderkits/onchainkit/identity/avatar), [badges](https://docs.base.org/builderkits/onchainkit/identity/badge), and [addresses](https://docs.base.org/builderkits/onchainkit/identity/address).
- [**`Wallet`**](https://docs.base.org/builderkits/onchainkit/wallet/wallet)\- Create or connect wallets with [Connect Wallet](https://docs.base.org/builderkits/onchainkit/wallet/wallet).
- [**`Transaction`**](https://docs.base.org/builderkits/onchainkit/transaction/transaction)\- Handle [transactions](https://docs.base.org/builderkits/onchainkit/transaction/transaction) using EOAs or Smart Wallets.
- [**`Checkout`**](https://docs.base.org/builderkits/onchainkit/checkout/checkout)\- Integrate USDC [checkout](https://docs.base.org/builderkits/onchainkit/checkout/checkout) flows with ease.
- [**`Fund`**](https://docs.base.org/builderkits/onchainkit/fund/fund-button)\- Create a [funding](https://docs.base.org/builderkits/onchainkit/fund/fund-button) flow to onboard users.
- [**`Tokens`**](https://docs.base.org/builderkits/onchainkit/token/token-chip)\- Search and display [tokens](https://docs.base.org/builderkits/onchainkit/token/token-chip) with various components.
- [**`Swap`**](https://docs.base.org/builderkits/onchainkit/swap/swap)\- Enable [token swaps](https://docs.base.org/builderkits/onchainkit/swap/swap) in your app.
- [**`Mint`**](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card)- [View](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) and [Mint](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card) NFTs in your app.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/config/types#vocs-content)
Config
On this page
Chevron Right
## `AppConfig`
```vocs_Code
Copytype AppConfig = {
appearance?: {
name?: string | null; // The name of your application
logo?: string | null; // The URL of your application logo
mode?: Mode | null; // Optionally determines color scheme based on OS preference or user selection
theme?: ComponentTheme | null; // Optionally sets the visual style for components
};
paymaster?: string | null; // Paymaster URL for gas sponsorship
};
```
## `isBaseOptions`
```vocs_Code
Copytype isBaseOptions = {
chainId: number;
isMainnetOnly?: boolean; // If the chainId check is only allowed on mainnet
};
```
## `isEthereumOptions`
```vocs_Code
Copytype isEthereumOptions = {
chainId: number;
isMainnetOnly?: boolean; // If the chainId check is only allowed on mainnet
};
```
## `OnchainKitConfig`
```vocs_Code
Copytype OnchainKitConfig = {
address: Address | null; // Address is optional as we may not have an address for new users
apiKey: string | null; // ApiKey for Coinbase Developer Platform APIs
chain: Chain; // Chain must be provided as we need to know which chain to use
config?: AppConfig; // Configuration options for the app
rpcUrl: string | null; // RPC URL for onchain requests. Defaults to using CDP Node if the API Key is set
schemaId: EASSchemaUid | null; // SchemaId is optional as not all apps need to use EAS
projectId: string | null; // ProjectId from Coinbase Developer Platform, only required for Coinbase Onramp support
};
```
## `OnchainKitContextType`
```vocs_Code
Copytype OnchainKitContextType = OnchainKitConfig;
```
## `OnchainKitProviderReact`
```vocs_Code
Copytype OnchainKitProviderReact = {
address?: Address;
apiKey?: string;
chain: Chain;
children: ReactNode;
config?: AppConfig;
rpcUrl?: string;
schemaId?: EASSchemaUid;
projectId?: string;
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/earn/earn#vocs-content)
Earn
On this page
Chevron Right
The `Earn` component provides a simple interface for earning interest on your crypto via Morpho vaults on Base.
## Prerequisites
Before using the `Earn` component, ensure you've completed the [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started) steps.
### Starting a new project
If you're starting a new project, we recommend using `create onchain` to scaffold your project.
```vocs_Code
Copynpm create onchain@latest
```
### Adding to an existing project
If you're adding `Earn` to an existing project, simply install OnchainKit.
npmyarnpnpmbun
Terminal
npm
```vocs_Code
Copynpm install @coinbase/onchainkit
```
Wrap the `` around your app, following the steps in [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started#add-providers).
## Quickstart
To use `Earn`, you'll need to provide a `vaultAddress` prop. A vault address can be obtained from Morpho's [Vaults page](https://app.morpho.org/base/earn).
```vocs_Code
Copyimport { Earn } from '@coinbase/onchainkit/earn';
```
DepositWithdraw
Spark USDC VaultInfo
APY 5.28%Info
Wallet not connected
Connect wallet to deposit
Connect to deposit
## Customization
### Custom components and layouts
`Earn` accepts a `children` prop that can be used to render `Earn` subcomponents or custom components.
For instance, you can render the `EarnDeposit` component by itself within the `Earn` component, along with any other custom components you'd like to render.
```vocs_Code
Copyimport { Earn, EarnDeposit } from '@coinbase/onchainkit/earn';
Custom header
Custom footer
```
Custom header
Spark USDC VaultInfo
APY 5.28%Info
Wallet not connected
Connect wallet to deposit
Connect to deposit
Custom footer
For more granular control, you can also render lower level subcomponents within `EarnDeposit` and `EarnWithdraw`. These subcomponents accept `className` props to customize their styles.
```vocs_Code
Copyimport { Earn,
EarnDeposit,
EarnDetails,
DepositBalance,
DepositAmountInput,
DepositButton } from '@coinbase/onchainkit/earn';
```
Spark USDC VaultInfo
APY 5.28%Info
Wallet not connected
Connect wallet to deposit
Connect to deposit
### Customizing styles
The `Earn` component is best styled via a [OnchainKit theme](https://docs.base.org/builderkits/onchainkit/guides/themes#custom-theme). You can also override individual component styles using `className`.
## Advanced Usage
If you'd like to implement your own custom components, you can use `useEarnContext` within an `Earn` component to access context and build your own components.
You can find the full interface for `EarnContextType` on the [Types page](https://docs.base.org/builderkits/onchainkit/earn/types#earncontexttype).
Below, we use `useEarnContext` to implement a custom deposit interface by using `useEarnContext` to access the `depositAmount` and `setDepositAmount` context values.
index.tsxcustom-deposit-buttons.tsx
File
index.tsx
```vocs_Code
Copyimport { Earn, useEarnContext } from '@coinbase/onchainkit/earn';
import { CustomDepositButtons } from '@/custom-deposit-buttons';
```
Spark USDC VaultInfo
APY 5.28%Info
0.1110
Connect to deposit
Taking advantage of the data and methods provided by `useEarnContext`, developers can implement fully custom deposit and withdraw interfaces, modifying everything from UI elements to input behavior.
## Examples
### Sponsoring transactions
To sponsor transactions, you can use the `isSponsored` prop.
```vocs_Code
Copy
```
Ensure that your `OnchainKitProvider` has a `paymaster` configured:
```vocs_Code
Copy
```
## Components
The `Earn` component includes the following subcomponents:
- `` \- A fully built Withdraw and Deposit component. Also includes a `children` prop to render custom components and provides `useEarnContext` to access the context values.
- `` \- A headless provider that provides the `useEarnContext` hook to the `Earn` component.
- `` \- A fully built deposit card.
- `` \- A fully built withdraw card.
- `` \- A component that displays the details of the vault.
- `` \- A component that handles the deposit amount input.
- `` \- A component that displays the balance underlying asset in the user's wallet.
- `` \- A component that triggers the deposit transaction.
- `` \- A component that handles the withdraw amount input.
- `` \- A component that displays how much the user can withdraw from a vault.
- `` \- A component that triggers the withdraw transaction.
- `` \- A component that displays the yield details of the vault.
- `` \- A component that displays the vault details.
## Hooks
- [`useEarnContext`](https://docs.base.org/builderkits/onchainkit/hooks/use-earn-context) \- A hook that provides the context values of the `Earn` component.
- [`useBuildDepositToMorphoTx`](https://docs.base.org/builderkits/onchainkit/hooks/use-build-deposit-to-morpho-tx) \- A hook that builds a deposit transaction to Morpho.
- [`useBuildWithdrawFromMorphoTx`](https://docs.base.org/builderkits/onchainkit/hooks/use-build-withdraw-from-morpho-tx) \- A hook that builds a withdraw transaction from Morpho.
- [`useMorphoVault`](https://docs.base.org/builderkits/onchainkit/hooks/use-morpho-vault) \- A hook that provides the details of a Morpho vault.
## Props
- [`LifecycleStatus`](https://docs.base.org/builderkits/onchainkit/earn/types#lifecyclestatus)
- [`EarnReact`](https://docs.base.org/builderkits/onchainkit/earn/types#earnreact)
- [`EarnProviderReact`](https://docs.base.org/builderkits/onchainkit/earn/types#earnproviderreact)
- [`EarnContextType`](https://docs.base.org/builderkits/onchainkit/earn/types#earncontexttype)
- [`EarnAmountInputReact`](https://docs.base.org/builderkits/onchainkit/earn/types#earnamountinputreact)
- [`DepositAmountInputReact`](https://docs.base.org/builderkits/onchainkit/earn/types#depositamountinputreact)
- [`WithdrawAmountInputReact`](https://docs.base.org/builderkits/onchainkit/earn/types#withdrawamountinputreact)
- [`EarnBalanceReact`](https://docs.base.org/builderkits/onchainkit/earn/types#earnbalancereact)
- [`DepositBalanceReact`](https://docs.base.org/builderkits/onchainkit/earn/types#depositbalancereact)
- [`WithdrawBalanceReact`](https://docs.base.org/builderkits/onchainkit/earn/types#withdrawbalancereact)
- [`EarnDepositReact`](https://docs.base.org/builderkits/onchainkit/earn/types#earndepositreact)
- [`EarnWithdrawReact`](https://docs.base.org/builderkits/onchainkit/earn/types#earnwithdrawreact)
- [`EarnDetailsReact`](https://docs.base.org/builderkits/onchainkit/earn/types#earndetailsreact)
- [`DepositButtonReact`](https://docs.base.org/builderkits/onchainkit/earn/types#depositbuttonreact)
- [`WithdrawButtonReact`](https://docs.base.org/builderkits/onchainkit/earn/types#withdrawbuttonreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/earn/types#vocs-content)
Earn
On this page
Chevron Right
## `LifecycleStatus`
```vocs_Code
Copyexport type LifecycleStatus =
| {
statusName: 'init';
statusData: null;
}
| {
statusName: 'amountChange';
statusData: {
amount: string;
token: Token;
};
}
| Extract<
TransactionLifecycleStatus,
{
statusName:
| 'transactionPending'
| 'transactionLegacyExecuted'
| 'success'
| 'error';
}
>;
```
## `EarnReact`
```vocs_Code
Copyexport type EarnReact = {
children?: React.ReactNode;
className?: string;
vaultAddress: Address;
isSponsored?: boolean;
};
```
## `EarnProviderReact`
```vocs_Code
Copyexport type EarnProviderReact = {
children: React.ReactNode;
vaultAddress: Address;
isSponsored?: boolean;
};
```
## `EarnContextType`
```vocs_Code
Copyexport type EarnContextType = {
/** Warns users if vault address is invalid */
error: Error | null;
recipientAddress?: Address;
/** Balance of the underlying asset in the user's wallet, converted to the asset's decimals */
walletBalance?: string;
/** Status of the wallet balance fetch */
walletBalanceStatus: 'pending' | 'success' | 'error';
refetchWalletBalance: () => void;
vaultAddress: Address;
/** The token that is being deposited or withdrawn (the underlying asset of the vault) */
vaultToken: Token | undefined;
vaultName: string | undefined;
/** Total deposits in the vault */
deposits: string | undefined;
/** Total liquidity (available to borrow) in the vault */
liquidity: string | undefined;
/** Total APY of the vault, including rewards */
apy: number | undefined;
nativeApy: UseMorphoVaultReturnType['nativeApy'];
vaultFee: UseMorphoVaultReturnType['vaultFee'];
/** Rewards earned by the user in the vault */
rewards: UseMorphoVaultReturnType['rewards'];
/** The amount of underlying asset that has been deposited in the vault by the connected user */
depositedBalance?: string;
/** Whether the deposited balance is being fetched */
depositedBalanceStatus: 'pending' | 'success' | 'error';
refetchDepositedBalance: () => void;
/** Interest earned by the user in the vault */
interestEarned?: string;
/** Amount that the user has typed into the deposit amount input */
depositAmount: string;
setDepositAmount: (amount: string) => void;
depositAmountError: string | null;
depositCalls: Call[];
/** Amount that the user has typed into the withdraw amount input */
withdrawAmount: string;
setWithdrawAmount: (amount: string) => void;
withdrawAmountError: string | null;
withdrawCalls: Call[];
lifecycleStatus: LifecycleStatus;
updateLifecycleStatus: (
status: LifecycleStatusUpdate,
) => void;
};
```
## `EarnAmountInputReact`
```vocs_Code
Copyexport type EarnAmountInputReact = {
className?: string;
onChange: (value: string) => void;
value: string;
disabled?: boolean;
'aria-label'?: string;
};
```
## `DepositAmountInputReact`
```vocs_Code
Copyexport type DepositAmountInputReact = {
className?: string;
};
```
## `WithdrawAmountInputReact`
```vocs_Code
Copyexport type WithdrawAmountInputReact = {
className?: string;
};
```
## `EarnBalanceReact`
```vocs_Code
Copyexport type EarnBalanceReact = {
className?: string;
onActionPress: () => void;
title: React.ReactNode;
subtitle: string;
showAction?: boolean;
};
```
## `DepositBalanceReact`
```vocs_Code
Copyexport type DepositBalanceReact = {
className?: string;
};
```
## `WithdrawBalanceReact`
```vocs_Code
Copyexport type WithdrawBalanceReact = {
className?: string;
};
```
## `EarnDepositReact`
```vocs_Code
Copyexport type EarnDepositReact = {
children?: React.ReactNode;
className?: string;
};
```
## `EarnWithdrawReact`
```vocs_Code
Copyexport type EarnWithdrawReact = {
children?: React.ReactNode;
className?: string;
};
```
## `EarnDetailsReact`
```vocs_Code
Copyexport type EarnDetailsReact = {
className?: string;
};
```
## `DepositButtonReact`
```vocs_Code
Copyexport type DepositButtonReact = {
className?: string;
};
```
## `WithdrawButtonReact`
```vocs_Code
Copyexport type WithdrawButtonReact = {
className?: string;
};
```
## `DepositToMorphoParams`
```vocs_Code
Copyexport type DepositToMorphoParams = {
/** The address of the Morpho vault */
vaultAddress: Address;
/** The address of the token to deposit */
tokenAddress: Address;
/** The amount of tokens to deposit */
amount: bigint;
/** The address which can withdraw the deposited tokens */
recipientAddress: Address;
};
```
## `WithdrawFromMorphoParams`
```vocs_Code
Copyexport type WithdrawFromMorphoParams = {
/** The address of the Morpho vault */
vaultAddress: Address;
/** The amount of tokens to withdraw */
amount: bigint;
/** The address to which the withdrawn funds will be sent */
recipientAddress: Address;
};
```
## `UseBuildDepositToMorphoTxParams`
```vocs_Code
Copyexport type UseBuildDepositToMorphoTxParams = {
vaultAddress: Address;
recipientAddress?: Address;
amount: string;
};
```
## `UseBuildWithdrawFromMorphoTxParams`
```vocs_Code
Copyexport type UseBuildWithdrawFromMorphoTxParams = {
vaultAddress: Address;
recipientAddress?: Address;
amount: string;
tokenDecimals: number | undefined;
};
```
## `UseMorphoVaultParams`
```vocs_Code
Copyexport type UseMorphoVaultParams = {
vaultAddress: Address;
recipientAddress?: Address;
};
```
## `UseMorphoVaultReturnType`
```vocs_Code
Copyexport type UseMorphoVaultReturnType = {
vaultName: string | undefined;
status: 'pending' | 'success' | 'error';
/** Warns users if vault address is invalid */
error: Error | null;
/** Underlying asset of the vault */
asset: {
address: Address;
symbol: string | undefined;
decimals: number | undefined;
};
/** User's deposits in the vault, adjusted for decimals */
balance: string | undefined;
balanceStatus: 'pending' | 'success' | 'error';
refetchBalance: () => void;
/** Total net APY of the vault after all rewards and fees */
totalApy: number | undefined;
/** Native rewards of the vault (e.g. USDC if the asset is USDC) */
nativeApy: number | undefined;
/** Additional rewards (e.g. MORPHO) */
rewards:
| {
asset: Address;
assetName: string;
apy: number;
}[]
| undefined;
/** Vault fee, in percent (e.g. 0.03 for 3%) */
vaultFee: number | undefined;
/** Number of decimals of the vault's share tokens (not underlying asset) */
vaultDecimals: number | undefined;
/** Total deposits in the vault */
deposits: string | undefined;
/** Total liquidity available to borrow in the vault */
liquidity: string | undefined;
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/fund/fetch-onramp-config#vocs-content)
fetchOnrampConfig
On this page
Chevron Right
The `fetchOnrampConfig` utility fetches the list of countries supported by Coinbase Onramp and their available payment methods. This is useful when you need to validate user eligibility or display available payment options.
## Usage
codereturn value
code
```vocs_Code
Copyimport { fetchOnrampConfig } from '@coinbase/onchainkit/fund';
// When using with OnchainKitProvider
const config = await fetchOnrampConfig();
// When using without OnchainKitProvider or in non-React environment
const config2 = await fetchOnrampConfig('your-api-key');
```
## Parameters
```vocs_Code
Copy/**
* Optional API key for Coinbase Onramp. If not provided, the API key from
* OnchainKitProvider will be used. Required when using the utility without
* OnchainKitProvider or in a non-React environment.
*/
apiKey?: string;
```
## Returns
`Promise` \- Returns a promise that resolves to the configuration data containing supported countries and their payment methods.
See [`OnrampConfigResponseData`](https://docs.base.org/builderkits/onchainkit/fund/types#onrampconfigresponsedata) for response type details.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/fund/fetch-onramp-options#vocs-content)
fetchOnrampOptions
On this page
Chevron Right
The `fetchOnrampOptions` utility retrieves supported fiat currencies and available crypto assets for a specific country. This information is essential for determining which assets can be purchased in the user's jurisdiction.
## Usage
codereturn value
code
```vocs_Code
Copyimport { fetchOnrampOptions } from '@coinbase/onchainkit/fund';
const options = await fetchOnrampOptions({
country: 'US',
subdivision: 'CA', // Required for US residents
apiKey: 'your-api-key', // Required when using without OnchainKitProvider or in non-React environment
});
```
## Parameters
```vocs_Code
Copy{
/**
* ISO 3166-1 two-letter country code string representing
* the purchasing user’s country of residence, e.g., US.
*/
country: string;
/**
* ISO 3166-2 two-letter country subdivision code representing
* the purchasing user’s subdivision of residence within their country,
* e.g. NY. Required if the country=“US” because certain states (e.g., NY)
* have state specific asset restrictions.
*/
subdivision?: string;
/**
* Optional API key for Coinbase Onramp. If not provided, the API key from
* OnchainKitProvider will be used. Required when using the utility without
* OnchainKitProvider or in a non-React environment.
*/
apiKey?: string;
}
```
## Returns
`Promise` \- Returns a promise that resolves to the available options for the specified location.
See [`OnrampOptionsResponseData`](https://docs.base.org/builderkits/onchainkit/fund/types#onrampoptionsresponsedata) for full response type details.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/fund/fetch-onramp-quote#vocs-content)
fetchOnrampQuote
On this page
Chevron Right
The `fetchOnrampQuote` utility provides a quote based on the asset the user would like to purchase, plus the network, fiat payment, payment currency, payment method, and country. This is useful for getting pricing information and fees before initiating a transaction.
## Usage
codereturn value
code
```vocs_Code
Copyimport { fetchOnrampQuote } from '@coinbase/onchainkit/fund';
const quote = await fetchOnrampQuote({
purchaseCurrency: 'ETH',
purchaseNetwork: 'ethereum',
paymentCurrency: 'USD',
paymentMethod: 'CARD',
paymentAmount: '100.00',
country: 'US',
subdivision: 'CA', // Required for US residents
apiKey: 'your-api-key', // Required when using without OnchainKitProvider or in non-React environment
});
```
## Parameters
```vocs_Code
Copy{
/**
* ID of the crypto asset the user wants to purchase.
* Retrieved from the options API.
*/
purchaseCurrency: string;
/**
* Name of the network that the purchase currency should be purchased on.
* Retrieved from the options API. If omitted, the default network for
* the crypto currency is used.
*/
purchaseNetwork?: string;
/**
* Fiat currency of the payment amount, e.g., USD.
*/
paymentCurrency: string;
/**
* ID of payment method used to complete the purchase.
* Retrieved from the options API.
*/
paymentMethod: string;
/**
* Fiat amount the user wants to spend to purchase the crypto currency,
* inclusive of fees with two decimals of precision, e.g., "100.00".
*/
paymentAmount: string;
/**
* ISO 3166-1 two-digit country code string representing the purchasing
* user's country of residence, e.g., US.
*/
country: string;
/**
* ISO 3166-2 two-digit country subdivision code. Required if country="US"
* because certain states (e.g., NY) have state specific asset restrictions.
*/
subdivision?: string;
/**
* Optional API key for Coinbase Onramp. If not provided, the API key from
* OnchainKitProvider will be used. Required when using the utility without
* OnchainKitProvider or in a non-React environment.
*/
apiKey?: string;
}
```
## Returns
`Promise` \- Returns a promise that resolves to the quote data containing payment amounts, fees, and quote ID.
See [`OnrampQuoteResponseData`](https://docs.base.org/builderkits/onchainkit/fund/types#onrampquoteresponsedata) for full response type details.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/fund/fetch-onramp-transaction-status#vocs-content)
fetchOnrampTransactionStatus
On this page
Chevron Right
The `fetchOnrampTransactionStatus` utility retrieves the status of onramp transactions for a specific user. This is useful for tracking the progress of crypto purchases and displaying transaction history.
## Usage
codereturn value
code
```vocs_Code
Copyimport { fetchOnrampTransactionStatus } from '@coinbase/onchainkit/fund';
const transactions = await fetchOnrampTransactionStatus({
partnerUserId: 'user123',
nextPageKey: '',
pageSize: '10',
apiKey: 'your-api-key', // Required when using without OnchainKitProvider or in non-React environment
});
```
## Parameters
```vocs_Code
Copy{
/**
* A unique identifier that will be associated with any transactions created
* by the user during their Onramp session. You can use this with the
* Transaction Status API to check the status of the user's transaction.
* See https://docs.cdp.coinbase.com/onramp/docs/api-reporting#buy-transaction-status
*/
partnerUserId: string; // Your unique identifier for the user
nextPageKey: string; // Token for pagination
pageSize: string; // Number of transactions per page
/**
* Optional API key for Coinbase Onramp. If not provided, the API key from
* OnchainKitProvider will be used. Required when using the utility without
* OnchainKitProvider or in a non-React environment.
*/
apiKey?: string;
}
```
## Returns
`Promise` \- Returns a promise that resolves to the transaction status data.
See [`OnrampTransactionStatusResponseData`](https://docs.base.org/builderkits/onchainkit/fund/types#onramptransactionstatusresponsedata) for full response type details.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/fund/fund-button#vocs-content)
FundButton
On this page
Chevron Right
The `` component provides a way for users to fund their wallet without leaving your app. It automatically
detects the user's wallet type (EOA vs Smart Wallet) and directs them to the appropriate funding URL.
If your user connects a Coinbase Smart Wallet, it provides an easy way to access the Coinbase Smart Wallet
[Fund](https://keys.coinbase.com/fund) flow. Users will be able to buy and receive crypto, or use their Coinbase
balances onchain with [Magic Spend](https://www.smartwallet.dev/guides/magic-spend).
If your user connects any other EOA wallet, it provides an easy way to access [Coinbase Onramp](https://docs.cdp.coinbase.com/onramp/docs/welcome/)
where your users will also be able to buy crypto using a fiat payment method, or transfer existing crypto from their
Coinbase account.
Before using it, ensure you've completed all [Getting Started steps](https://docs.base.org/builderkits/onchainkit/getting-started).
## Walkthrough
### Get your Project ID
1. Get your Project ID from the [Coinbase Developer Platform Dashboard](https://portal.cdp.coinbase.com/).

2. Add your Project ID to your `.env` file.
File
.env
```vocs_Code
CopyNEXT_PUBLIC_ONCHAINKIT_API_KEY=YOUR_PUBLIC_API_KEY
NEXT_PUBLIC_CDP_PROJECT_ID=YOUR_CDP_PROJECT_ID
```
### Add Project ID to OnchainKitProvider
```vocs_Code
Copy
{props.children}
```
### Drop in the `` component
```vocs_Code
Copyimport { FundButton } from '@coinbase/onchainkit/fund';
```
Connect Wallet
## Customizing the funding experience
You can customize the Coinbase Onramp experience by bringing your own Onramp URL and passing it to the ``
component. We provide the [`getOnrampBuyUrl`](https://docs.base.org/builderkits/onchainkit/fund/get-onramp-buy-url) utility to help you generate a Coinbase Onramp
URL tailored to your use case.
```vocs_Code
Copyimport { FundButton, getOnrampBuyUrl } from '@coinbase/onchainkit/fund';
import { useAccount } from 'wagmi';
const projectId = 'YOUR_CDP_PROJECT_ID';
const { address } = useAccount();
const onrampBuyUrl = getOnrampBuyUrl({
projectId,
addresses: { [address]: ['base'] },
assets: ['USDC'],
presetFiatAmount: 20,
fiatCurrency: 'USD'
});
```
Connect Wallet
You can choose to have the funding URL open in a popup or a new tab using the `openIn` prop.
```vocs_Code
Copy
```
Connect Wallet
## Customizing the fund button
You can override the text on the fund button using the `text` prop, and hide the icon with the `hideIcon` prop.
```vocs_Code
Copy
```
Connect Wallet
You can hide the text with the `hideText` prop.
```vocs_Code
Copy
```
Connect Wallet
See [`FundButtonReact`](https://docs.base.org/builderkits/onchainkit/fund/types#fundbuttonreact) for the full list of customization options.
## Props
- [`FundButtonReact`](https://docs.base.org/builderkits/onchainkit/fund/types#fundbuttonreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/fund/fund-card#vocs-content)
FundCard
On this page
Chevron Right

The `` component provides a complete fiat onramp experience within your app. It includes:
- Amount input with fiat/crypto switching
- Payment method selection (Coinbase, Apple Pay, Debit Card)
- Automatic exchange rate updates
- Smart handling of payment method restrictions (based on country and subdivision)
## Prerequisites
Before using the `FundCard` component, ensure you've completed the [Getting Started](https://docs.base.org/builderkits/onchainkit/installation/nextjs#get-your-client-api-key) steps.
## Usage
### Drop in the `` component
```vocs_Code
Copyimport { FundCard } from '@coinbase/onchainkit/fund';
;
```
Connect Wallet
## Customization
### Custom Header and Button Text
You can customize the header and button text:
```vocs_Code
Copy
```
Connect Wallet
### Custom Currency
You can specify which fiat currency to use:
```vocs_Code
Copy
```
### Preset Amount Inputs
You can specify preset amount buttons:
```vocs_Code
Copyconst presetAmountInputs = ['10', '20', '50'] as const;
;
```
### Custom Content
You can provide custom children to completely customize the card content while keeping the fund button functionality:
```vocs_Code
Copy
Custom Header
```
You can also reuse the existing children from the default implementation and add your own custom content.
```vocs_Code
Copyimport {
FundCardHeader,
FundCardAmountInput,
FundCardAmountInputTypeSwitch,
FundCardPresetAmountInputList,
FundCardPaymentMethodDropdown,
FundCardSubmitButton,
} from '@coinbase/onchainkit/fund';
Custom Header instead of the default "FundCardHeader"
Any custom content
Any custom content
```
```vocs_Code
Copyconst {
asset,
currency,
selectedPaymentMethod,
setSelectedPaymentMethod,
fundAmountFiat,
setFundAmountFiat,
fundAmountCrypto,
setFundAmountCrypto,
selectedInputType,
setSelectedInputType,
exchangeRate,
setExchangeRate,
exchangeRateLoading,
setExchangeRateLoading,
submitButtonState,
setSubmitButtonState,
paymentMethods,
setPaymentMethods,
paymentMethodsLoading,
setPaymentMethodsLoading,
headerText,
buttonText,
country,
subdivision,
lifecycleStatus,
updateLifecycleStatus,
presetAmountInputs,
} = useFundContext();
```
## Props
- [`FundCardPropsReact`](https://docs.base.org/builderkits/onchainkit/fund/types#fundcardpropsreact)
## Related Components
- [``](https://docs.base.org/builderkits/onchainkit/fund/fund-button)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/fund/get-onramp-buy-url#vocs-content)
getOnrampBuyUrl
On this page
Chevron Right
The `getOnrampBuyUrl` utility is a helper method to generate a Coinbase Onramp URL. It helps you customize the funding
experience for your users. For example:
- Selecting which assets should be available to buy/send
- Selecting which networks crypto should be received on
- Setting a default buy/send amount
- Setting a redirect URL to return your users to your app after they complete the fund flow
## Usage
codereturn value
code
```vocs_Code
Copyimport { getOnrampBuyUrl } from '@coinbase/onchainkit/fund';
const projectId = 'YOUR_CDP_PROJECT_ID';
const onrampBuyUrl = getOnrampBuyUrl({
projectId,
addresses: { '0x1': ['base'] },
assets: ['USDC'],
presetFiatAmount: 20,
fiatCurrency: 'USD',
redirectUrl: 'https://yourapp.com/onramp-return?param=foo',
});
```
## Returns
`string` \- Returns a full Coinbase Onramp URL that you can redirect your users to, or open in a popup.
## Parameters
[`GetOnrampUrlWithProjectIdParams`](https://docs.base.org/builderkits/onchainkit/fund/types#getonrampurlwithprojectidparams) \| [`GetOnrampUrlWithSessionTokenParams`](https://docs.base.org/builderkits/onchainkit/fund/types#getonrampurlwithsessiontokenparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/fund/setup-onramp-event-listeners#vocs-content)
setupOnrampEventListeners
On this page
Chevron Right
The `setupOnrampEventListeners` utility sets up event listeners for the Coinbase Onramp widget. It helps you handle various events like successful purchases, exits, and other user interactions.
## Usage
codereturn value
code
```vocs_Code
Copyimport { setupOnrampEventListeners } from '@coinbase/onchainkit/fund';
import type { SuccessEventData, OnrampError, EventMetadata } from '@coinbase/onchainkit/fund';
const unsubscribe = setupOnrampEventListeners({
onSuccess: (data: SuccessEventData) => {
console.log('Purchase successful:', data);
},
onExit: (error: OnrampError) => {
if (error) {
console.error('Exit with error:', error);
}
},
onEvent: (event: EventMetadata) => {
console.log('Event received:', event);
},
});
// Clean up when done
unsubscribe();
```
## Parameters
```vocs_Code
Copy{
host?: string; // Optional custom host URL
onSuccess?: (data?: SuccessEventData) => void; // Success callback
onExit?: (error?: OnrampError) => void; // Exit callback
onEvent?: (event: EventMetadata) => void; // General event callback
}
```
## Returns
`() => void` \- Returns an unsubscribe function that removes the event listeners when called.
## Event Types
See the following type definitions for event data:
- [`SuccessEventData`](https://docs.base.org/builderkits/onchainkit/fund/types#successeventdata)
- [`OnrampError`](https://docs.base.org/builderkits/onchainkit/fund/types#onramperror)
- [`EventMetadata`](https://docs.base.org/builderkits/onchainkit/fund/types#eventmetadata)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/fund/types#vocs-content)
Fund
On this page
Chevron Right
## `FundCardPropsReact`
```vocs_Code
Copytype FundCardPropsReact = {
children?: ReactNode;
assetSymbol: string;
placeholder?: string | React.ReactNode;
headerText?: string;
buttonText?: string;
country: string;
subdivision?: string;
currency?: string;
className?: string;
presetAmountInputs?: PresetAmountInputs;
} & LifecycleEvents;
```
## `LifecycleStatus`
```vocs_Code
Copytype LifecycleStatus =
| {
statusName: 'init';
statusData: null;
}
| {
statusName: 'exit';
statusData: null;
}
| {
statusName: 'error';
statusData: OnrampError;
}
| {
statusName: 'transactionSuccess';
statusData: SuccessEventData;
}
| {
statusName: 'transactionPending';
statusData: null;
};
```
## `PresetAmountInputs`
```vocs_Code
Copy type PresetAmountInputItemPropsReact = {
presetAmountInput: string;
currency: string;
onClick: (presetAmountInput: string) => void;
};
/**
* To use this type, you must provide a tuple of strings with a length of 3.
*
* Example:
*
* const presetAmountInputs: PresetAmountInputs = ['100', '200', '300'];
*/
type PresetAmountInputs = readonly [string, string, string];
```
## `FundButtonReact`
```vocs_Code
Copytype FundButtonReact = {
className?: string; // An optional CSS class name for styling the button component
disabled?: boolean; // An optional prop to disable the fund button
text?: string; // An optional text to be displayed in the button component
hideText?: boolean; // An optional prop to hide the text in the button component
hideIcon?: boolean; // An optional prop to hide the icon in the button component
fundingUrl?: string; // An optional prop to provide a custom funding URL
openIn?: 'popup' | 'tab'; // Whether to open the funding flow in a tab or a popup window
/**
* Note: popupSize will be ignored when using a Coinbase Onramp URL
* (i.e. https://pay.coinbase.com/*) as it requires a fixed popup size.
*/
popupSize?: 'sm' | 'md' | 'lg'; // Size of the popup window if `openIn` is set to `popup`
rel?: string; // Specifies the relationship between the current document and the linked document
target?: string; // Where to open the target if `openIn` is set to tab
};
```
## `GetOnrampUrlWithProjectIdParams`
Props used to get an Onramp buy URL by directly providing a CDP project ID.
See [https://docs.cdp.coinbase.com/onramp/docs/api-initializing#generating-the-coinbase-onramp-buysell-url](https://docs.cdp.coinbase.com/onramp/docs/api-initializing#generating-the-coinbase-onramp-buysell-url)
```vocs_Code
Copytype GetOnrampUrlWithProjectIdParams = {
/**
* The Project ID of your CDP project created at {@link https://portal.cdp.coinbase.com/}
* This must be provided if you don't provide a sessionToken.
*/
projectId: string;
sessionToken?: never; // You cannot provide sessionToken when using projectId
/**
* The addresses to which the customer's funds should be delivered.
*
* Each entry in the record represents a wallet address and the networks it is valid for. There should only be a
* single address for each network your app supports. Users will be able to buy/send any asset supported by any of
* the networks you specify. See the assets param if you want to restrict the available assets.
*
* Some common examples:
*
* Support all assets that are available for sending on the base network, only on the base network:
*
* `{ "0x1": ["base"] }`
*/
addresses: Record;
/**
* This optional parameter will restrict the assets available for the user to buy/send. It acts as a filter on the
* networks specified in the {addresses} param.
*
* Some common examples:
*
* Support only USDC on either the base network or the ethereum network:
*
* `addresses: { "0x1": ["base", "ethereum"] }, assets: ["USDC"]`
*
* The values in this list can either be asset symbols like BTC, ETH, or asset UUIDs that you can get from the Buy
* Options API {@link https://docs.cdp.coinbase.com/onramp/docs/api-configurations/#buy-options}.
*/
assets?: string[];
} & GetOnrampBuyUrlOptionalProps;
```
## `GetOnrampUrlWithSessionTokenParams`
Props used to get an Onramp buy URL using a session token created using the Onramp session token API.
See [https://docs.cdp.coinbase.com/onramp/docs/api-initializing#getting-an-coinbase-onramp-buysell-session-token](https://docs.cdp.coinbase.com/onramp/docs/api-initializing#getting-an-coinbase-onramp-buysell-session-token)
```vocs_Code
Copytype GetOnrampUrlWithSessionTokenParams = {
/**
* A session token created using the Onramp session token API. The token will
* be linked to the project ID, addresses, and assets params provided in the
*/
sessionToken: string;
projectId?: never; // You cannot provide projectId when using sessionToken
addresses?: never; // You cannot provide addresses when using sessionToken
assets?: never; // You cannot provide assets when using sessionToken
} & GetOnrampBuyUrlOptionalProps;
```
## `GetOnrampBuyUrlOptionalProps`
The optional properties that can be used to create an Onramp buy URL.
```vocs_Code
Copytype GetOnrampBuyUrlOptionalProps = {
/**
* If specified, this asset will be automatically selected for the user in
* the Onramp UI. Should be a valid asset symbol e.g. BTC, ETH, USDC.
*/
defaultAsset?: string;
/**
* If specified, this network will be automatically selected for the user in
* the Onramp UI. Should be a valid network name in lower case e.g. ethereum,
* base.
*/
defaultNetwork?: string;
/**
* A unique identifier that will be associated with any transactions created
* by the user during their Onramp session. You can use this with the
* Transaction Status API to check the status of the user's transaction.
* See https://docs.cdp.coinbase.com/onramp/docs/api-reporting#buy-transaction-status
*/
partnerUserId?: string;
/**
* This amount will be used to pre-fill the amount of crypto the user is
* buying or sending. The user can choose to change this amount in the UI.
* Only one of presetCryptoAmount or presetFiatAmount should be provided.
*/
presetCryptoAmount?: number;
/**
* This amount will be used to pre-fill the fiat value of the crypto the user
* is buying or sending. The user can choose to change this amount in the UI.
* Only one of presetCryptoAmount or presetFiatAmount should be provided.
*/
presetFiatAmount?: number;
/**
* The currency code of the fiat amount provided in the presetFiatAmount
* param e.g. USD, CAD, EUR.
*/
fiatCurrency?: string;
/**
* A URL that the user will be automatically redirected to after a successful
* buy/send. The domain must match a domain on the domain allowlist in
* Coinbase Developer Platform (https://portal.cdp.coinbase.com/products/onramp).
*/
redirectUrl?: string;
};
```
## `OnrampConfigResponseData`
```vocs_Code
Copytype OnrampConfigResponseData = {
countries: OnrampConfigCountry[];
};
type OnrampConfigCountry = {
id: string;
/**
* ISO 3166-2 two-digit country subdivision code representing
* the purchasing user’s subdivision of residence within their country,
* e.g. NY. Required if the country=“US” because certain states (e.g., NY)
* have state specific asset restrictions.
*/
subdivisions: string[];
paymentMethods: OnrampPaymentMethod[];
};
type OnrampPaymentMethod = {
id: string;
};
```
## `OnrampOptionsResponseData`
```vocs_Code
Copytype OnrampOptionsResponseData = {
/**
* List of supported fiat currencies that can be exchanged for crypto on Onramp in the given location.
* Each currency contains a list of available payment methods, with min and max transaction limits for that currency.
*/
paymentCurrencies: OnrampPaymentCurrency[];
/**
* List of available crypto assets that can be bought on Onramp in the given location.
*/
purchaseCurrencies: OnrampPurchaseCurrency[];
};
type OnrampPurchaseCurrency = {
id: string;
name: string;
symbol: string;
iconUrl: string;
networks: OnrampNetwork[];
};
type OnrampPaymentCurrency = {
id: string;
limits: OnrampPaymentMethodLimit[];
iconUrl: string;
};
type OnrampNetwork = {
name: string;
displayName: string;
chainId: string;
contractAddress: string;
};
type OnrampPaymentMethodLimit = {
id: string;
min: number;
max: number;
};
```
## `OnrampTransactionStatusResponseData`
```vocs_Code
Copytype OnrampTransactionStatusResponseData = {
/** List of `OnrampTransactions` in reverse chronological order. */
transactions: OnrampTransaction[];
/** A reference to the next page of transactions. */
nextPageKey: string;
/** The total number of transactions made by the user. */
totalCount: string;
};
type OnrampTransaction = {
status: OnrampTransactionStatusName;
purchaseCurrency: string;
purchaseNetwork: string;
purchaseAmount: OnrampAmount;
paymentTotal: OnrampAmount;
paymentSubtotal: OnrampAmount;
coinbaseFee: OnrampAmount;
networkFee: OnrampAmount;
exchangeRate: OnrampAmount;
txHash: string;
createdAt: string;
country: string;
userId: string;
paymentMethod: string;
transactionId: string;
};
```
## `SuccessEventData`
```vocs_Code
Copytype SuccessEventData = {
assetImageUrl: string;
assetName: string;
assetSymbol: string;
chainId: string;
};
```
## `OnrampError`
```vocs_Code
Copytype OnrampError = {
errorType:
| 'internal_error'
| 'handled_error'
| 'network_error'
| 'unknown_error';
code?: string;
debugMessage?: string;
};
```
## `EventMetadata`
```vocs_Code
Copytype EventMetadata =
| OpenEvent
| TransitionViewEvent
| PublicErrorEvent
| ExitEvent
| SuccessEvent
| RequestOpenUrlEvent;
```
## `OnrampQuoteResponseData`
```vocs_Code
Copytype OnrampQuoteResponseData = {
/**
* Object with amount and currency of the total fiat payment required to complete the purchase, inclusive of any fees.
* The currency will match the `paymentCurrency` in the request if it is supported, otherwise it falls back to USD.
*/
paymentTotal: OnrampAmount;
/**
* Object with amount and currency of the fiat cost of the crypto asset to be purchased, exclusive of any fees.
* The currency will match the `paymentCurrency`.
*/
paymentSubtotal: OnrampAmount;
/**
* Object with amount and currency of the crypto that to be purchased.
* The currency will match the `purchaseCurrency` in the request.
* The number of decimals will be based on the crypto asset.
*/
purchaseAmount: OnrampAmount;
/**
* Object with amount and currency of the fee charged by the Coinbase exchange to complete the transaction.
* The currency will match the `paymentCurrency`.
*/
coinbaseFee: OnrampAmount;
/**
* Object with amount and currency of the network fee required to send the purchased crypto to the user’s wallet.
* The currency will match the `paymentCurrency`.
*/
networkFee: OnrampAmount;
/**
* Reference to the quote that should be passed into the initialization parameters when launching the Coinbase Onramp widget via the SDK or URL generator.
*/
quoteId: string;
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/hooks/use-build-deposit-to-morpho-tx#vocs-content)
useBuildDepositToMorphoTx
On this page
Chevron Right
The `useBuildDepositToMorphoTx` hook is used to build a deposit transaction to Morpho from within a React component.
The hook handles the following:
- Fetching data required to build the transaction
- Using [`buildDepositToMorphoTx`](https://docs.base.org/builderkits/onchainkit/api/build-deposit-to-morpho-tx) to build the transaction
- Returning the transaction calls to be used with the `` component
## Usage
code
```vocs_Code
Copyimport { useBuildDepositToMorphoTx } from '@coinbase/onchainkit/earn';
const { calls } = useBuildDepositToMorphoTx({
vaultAddress: '0x...',
recipientAddress: '0x...',
amount: '1000000000000000000',
});
```
## Returns
[`{ calls: Call[] }`](https://docs.base.org/builderkits/onchainkit/transaction/types#calls)
## Parameters
[`UseBuildDepositToMorphoTxParams`](https://docs.base.org/builderkits/onchainkit/earn/types#usebuilddeposittomorphotxparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/hooks/use-build-withdraw-from-morpho-tx#vocs-content)
useBuildWithdrawFromMorphoTx
On this page
Chevron Right
The `useBuildWithdrawFromMorphoTx` hook is used to build a withdraw transaction from Morpho from within a React component.
The hook handles the following:
- Fetching data required to build the transaction
- Using [`buildWithdrawFromMorphoTx`](https://docs.base.org/builderkits/onchainkit/api/build-withdraw-from-morpho-tx) to build the transaction
- Returning the transaction calls to be used with the `` component
## Usage
code
```vocs_Code
Copyimport { useBuildWithdrawFromMorphoTx } from '@coinbase/onchainkit/earn';
const { calls } = useBuildWithdrawFromMorphoTx({
vaultAddress: '0x...',
recipientAddress: '0x...',
amount: '1000000000000000000',
tokenDecimals: 18,
});
```
## Returns
[`{ calls: Call[] }`](https://docs.base.org/builderkits/onchainkit/transaction/types#calls)
## Parameters
[`UseBuildWithdrawFromMorphoTxParams`](https://docs.base.org/builderkits/onchainkit/earn/types#usebuildwithdrawfrommorphotxparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/hooks/use-earn-context#vocs-content)
useEarnContext
On this page
Chevron Right
The `useEarnContext` hook is used to access the context values of the `Earn` component.
It can be used to build fully custom deposit and withdraw interfaces and contains all relevant data about a Morpho vault.
## Usage
Note: This hook should be used within a `` or `` (headless) component.
code
```vocs_Code
Copyimport { useEarnContext } from '@coinbase/onchainkit/earn';
const { depositAmount,
setDepositAmount,
apy,
nativeApy,
rewards,
vaultFee,
vaultToken,
liquidity,
deposits
// ...
} = useEarnContext();
// Use the values to build a custom deposit interface!
```
## Returns
[`EarnContextType`](https://docs.base.org/builderkits/onchainkit/earn/types#earncontexttype)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/hooks/use-mint-details#vocs-content)
useMintDetails
On this page
Chevron Right
The `useMintDetails` hook implements the `getMintDetails` API, returning the data required to view an NFT to be minted.
It is implemented with [useQuery](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery) from `@tanstack/react-query`, and returns a `UseQueryResult` object, allowing you to pass through all `@tanstack/react-query` options.
Before using them, make sure to obtain a [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.
## Usage
codescaffoldingreturn value
code
```vocs_Code
Copyimport { useMintDetails } from '@coinbase/onchainkit/nft';
const Component = () => {
const { data, isLoading, error } = useMintDetails({
contractAddress: '0x...',
takerAddress: '0x...',
tokenId: '1',
});
if (isLoading) return
Loading...
;
return
{JSON.stringify(data)}
;
};
```
## Returns
[`UseQueryResult`](https://docs.base.org/builderkits/onchainkit/api/types#getmintdetailsresponse)
## Parameters
[`GetMintDetailsParams`](https://docs.base.org/builderkits/onchainkit/api/types#getmintdetailsparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/hooks/use-morpho-vault#vocs-content)
useMorphoVault
On this page
Chevron Right
The `useMorphoVault` hook fetches and returns comprehensive data about a Morpho vault, including APYs, balances, and rewards.
## Usage
```vocs_Code
Copyimport { useMorphoVault } from '@coinbase/onchainkit/earn';
const {
balance,
totalApy,
rewards,
deposits,
liquidity,
// ... other values
} = useMorphoVault({
vaultAddress: '0x...',
recipientAddress: '0x...',
});
```
## Returns
[`UseMorphoVaultReturnType`](https://docs.base.org/builderkits/onchainkit/earn/types#usemorphovaultreturntype)
## Parameters
[`UseMorphoVaultParams`](https://docs.base.org/builderkits/onchainkit/earn/types#usemorphovaultparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/hooks/use-token-details#vocs-content)
useTokenDetails
On this page
Chevron Right
The `useTokenDetails` hook implements the `getTokenDetails` API, returning the data required to view an NFT.
It is implemented with [useQuery](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery) from `@tanstack/react-query`, and returns a `UseQueryResult` object, allowing you to pass through all `@tanstack/react-query` options.
Before using them, make sure to obtain a [Client API Key](https://portal.cdp.coinbase.com/projects/api-keys/client-key) from Coinbase Developer Platform.
## Usage
codescaffoldingreturn value
code
```vocs_Code
Copyimport { useTokenDetails } from '@coinbase/onchainkit/nft';
const Component = () => {
const { data, isLoading, error } = useTokenDetails({
contractAddress: '0x...',
tokenId: '1',
});
if (isLoading) return
Loading...
;
return
{JSON.stringify(data)}
;
};
```
## Returns
[`UseQueryResult`](https://docs.base.org/builderkits/onchainkit/api/types#gettokendetailsresponse)
## Parameters
[`GetTokenDetailsParams`](https://docs.base.org/builderkits/onchainkit/api/types#gettokendetailsparams)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/address#vocs-content)
Address
On this page
Chevron Right
The `Address` component is used to render a shortened user account address.
## Usage
Sliced account address:
```vocs_Code
Copyimport { Address } from '@coinbase/onchainkit/identity';
```
0x02fe...B6B1Copy
### Display full address
Set `isSliced` to false, to display the full address:
```vocs_Code
Copyimport { Address } from '@coinbase/onchainkit/identity';
```
0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1Copy
### Override styles
You can override component styles using `className`.
```vocs_Code
Copyimport { Address } from '@coinbase/onchainkit/identity';
```
0x02fe...B6B1Copy
## Props
[`AddressReact`](https://docs.base.org/builderkits/onchainkit/identity/types#addressreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/avatar#vocs-content)
Avatar
On this page
Chevron Right
The `Avatar` component is used to display ENS or [Basenames](https://www.base.org/names) avatar associated with Ethereum addresses.
When an avatar is not available, it defaults to blue color avatar.
## Usage
Address with an ENS avatar:
```vocs_Code
Copyimport { Avatar } from '@coinbase/onchainkit/identity';
```

Address without an ENS or Basenames avatar defaults to a plain avatar:
```vocs_Code
Copyimport { Avatar } from '@coinbase/onchainkit/identity';
```
Address with a Basename avatar:
```vocs_Code
Copyimport { Avatar } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
```

Override styles via `className` prop:
```vocs_Code
Copyimport { Avatar } from '@coinbase/onchainkit/identity';
```
Use `defaultComponent` prop to change the default avatar when ENS avatar is not found.
Use `loadingComponent` prop to change the loading placeholder:
```vocs_Code
Copyimport { Avatar } from '@coinbase/onchainkit/identity';
)}
defaultComponent={(
)}
/>
```
Show attestation on ENV avatar with [`Badge`](https://docs.base.org/builderkits/onchainkit/identity/badge) component.
Use [`OnchainKitProvider`](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider) or [`Identity`](https://docs.base.org/builderkits/onchainkit/identity/identity) component with the `schemaId` prop.
```vocs_Code
Copyimport { Avatar, Badge, Identity } from '@coinbase/onchainkit/identity';
```

## Props
[`AvatarReact`](https://docs.base.org/builderkits/onchainkit/identity/types#AvatarReact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/badge#vocs-content)
Badge
On this page
Chevron Right
Use `Badge` component along with [`Avatar`](https://docs.base.org/builderkits/onchainkit/identity/avatar) or [`Name`](https://docs.base.org/builderkits/onchainkit/identity/name) components to display user attestations attached to their account
## Usage
Badge with default colors:
tsxcss
tsx
```vocs_Code
Copyimport { Badge } from '@coinbase/onchainkit/identity';
```
Badge with custom colors:
```vocs_Code
Copyimport { Badge } from '@coinbase/onchainkit/identity';
```
## Badge with Tooltip
You can enable a tooltip for the attestation badge to provide context about what the badge represents:
```vocs_Code
Copyimport { Badge } from '@coinbase/onchainkit/identity';
```
With custom tooltip text:
```vocs_Code
Copyimport { Badge } from '@coinbase/onchainkit/identity';
```
## Props
[`BadgeReact`](https://docs.base.org/builderkits/onchainkit/identity/types#badgereact)
| Prop | Type | Description |
| --- | --- | --- |
| `className` | `string` | Optional className override for top span element |
| `tooltip` | `boolean | string` | Controls whether the badge shows a tooltip on hover. When `true`, displays the attestation name. When a string is provided, shows that custom text instead. Defaults to `false` |
## Badge on `` and ``
Badge with [``](https://docs.base.org/builderkits/onchainkit/identity/name), best used when [``](https://docs.base.org/builderkits/onchainkit/identity/name) are displayed alongside [``](https://docs.base.org/builderkits/onchainkit/identity/avatar) components.
In both examples we use the Coinbase [Verified Account](https://base.easscan.org/schema/view/0xf8b05c79f090979bf4a80270aba232dff11a10d9ca55c4f88de95317970f0de9) schema ID to show the Coinbase verified badge on the Name and Avatar components.
```vocs_Code
Copyimport { base } from 'viem/chains';
import { Badge, Name, Identity } from '@coinbase/onchainkit/identity';
const address = '0x838aD0EAE54F99F1926dA7C3b6bFbF617389B4D9';
const COINBASE_VERIFIED_ACCOUNT_SCHEMA_ID =
'0xf8b05c79f090979bf4a80270aba232dff11a10d9ca55c4f88de95317970f0de9';
{/* With tooltip that shows attestation name */}
```
Badge with [``](https://docs.base.org/builderkits/onchainkit/identity/avatar), best used when [``](https://docs.base.org/builderkits/onchainkit/identity/avatar) is not paired with any labels.
```vocs_Code
Copyimport { base } from 'viem/chains';
import { Avatar, Badge, Identity } from '@coinbase/onchainkit/identity';
const address = '0x838aD0EAE54F99F1926dA7C3b6bFbF617389B4D9';
const COINBASE_VERIFIED_ACCOUNT_SCHEMA_ID =
'0xf8b05c79f090979bf4a80270aba232dff11a10d9ca55c4f88de95317970f0de9';
{/* With custom tooltip text */}
```
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/get-address#vocs-content)
getAddress
On this page
Chevron Right
The `getAddress` utility is designed to retrieve an address from an onchain identity provider for a given name.
## Usage
Get ENS Name from mainnet chain
codereturn value
code
```vocs_Code
Copyimport { getAddress } from '@coinbase/onchainkit/identity';
const address = await getAddress({ name: 'zizzamia.eth' });
```
Get Basename from base chain
codereturn value
code
```vocs_Code
Copyimport { getAddress } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const address = await getAddress({ name: 'zizzamia.base.eth', chain: base });
```
## Returns
See [`GetAddressReturnType`](https://docs.base.org/builderkits/onchainkit/identity/types#getaddressreturntype) and [`GetAddress`](https://docs.base.org/builderkits/onchainkit/identity/types#getaddress) for more details.
## Parameters
See [`GetAddressReturnType`](https://docs.base.org/builderkits/onchainkit/identity/types#getaddressreturntype) and [`GetAddress`](https://docs.base.org/builderkits/onchainkit/identity/types#getaddress) for more details.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/get-attestations#vocs-content)
getAttestations
On this page
Chevron Right
The `getAttestations` function fetches attestations for a specified address
and blockchain in Ethereum Attestation Service (EAS). It allows optional filtering
based on schema IDs, revocation status, expiration time, and the number of attestations to return.
In the example, we use the Coinbase [Verified Account](https://base.easscan.org/schema/view/0xf8b05c79f090979bf4a80270aba232dff11a10d9ca55c4f88de95317970f0de9) schema ID.
## Usage
codereturn value
code
```vocs_Code
Copyimport { getAttestations } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const COINBASE_VERIFIED_ACCOUNT_SCHEMA_ID =
'0xf8b05c79f090979bf4a80270aba232dff11a10d9ca55c4f88de95317970f0de9';
const address = '0x1234567890abcdef1234567890abcdef12345678';
const attestationsOptions = {
schemas: [COINBASE_VERIFIED_ACCOUNT_SCHEMA_ID],
};
const attestations = await getAttestations(address, base, attestationsOptions);
```
## Returns
[`Promise`](https://docs.base.org/builderkits/onchainkit/identity/types#attestation)
See [Attestation](https://docs.base.org/builderkits/onchainkit/identity/types#attestation) and [GetEASAttestationsOptions](https://docs.base.org/builderkits/onchainkit/identity/types#geteasttestationsoptions) for more details.
## Parameters
### Address
```vocs_Code
Copytype Address = `0x${string}`; // The address for which attestations are being queried.
```
### Chain
```vocs_Code
Copytype Chain = { // The blockchain of interest.
id: string;
name: string;
network: string;
chainId: number;
nativeCurrency: {
name: string;
symbol: string;
decimals: number;
};
rpcUrls: string[];
blockExplorerUrls: string[];
};
```
### GetAttestationsOptions
[GetEASAttestationsOptions](https://docs.base.org/builderkits/onchainkit/identity/types#geteasttestationsoptions)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/get-avatar#vocs-content)
getAvatar
On this page
Chevron Right
The `getAvatar` utility is designed to retrieve an avatar image
URL from an onchain identity provider for a given name.
Consider the utility instead of the hook when you
use it with Next.js or any Node.js backend.
Supported providers:
- [Basenames](https://www.base.org/names)
- ENS
## Usage
Get Basename avatar:
codereturn value
code
```vocs_Code
Copyimport { getAvatar } from '@coinbase/onchainkit/identity';
import { base, mainnet } from 'viem/chains';
const baseAvatar = await getAvatar({ ensName: 'paulcramer.eth', chain: base });
```
Get ENS avatar:
codereturn value
code
```vocs_Code
Copyimport { getAvatar } from '@coinbase/onchainkit/identity';
import { mainnet } from 'viem/chains';
const ensAvatar = await getAvatar({ ensName: 'paulcramer.eth', chain: mainnet });
```
## Returns
[`Promise`](https://docs.base.org/builderkits/onchainkit/identity/types#getavatarreturntype)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/get-avatars#vocs-content)
getAvatars
On this page
Chevron Right
The `getAvatars` utility is designed to retrieve multiple avatars from an onchain identity
provider for an array of ENS names or Basenames in a single batch request.
Consider the utility instead of the hook when you
use it with Next.js or any Node.js backend.
## Usage
Get avatars for multiple ENS names:
codereturn value
code
```vocs_Code
Copyimport { getAvatars } from '@coinbase/onchainkit/identity';
const ensNames = ['vitalik.eth', 'zizzamia.eth'];
const avatars = await getAvatars({ ensNames });
```
Get avatars for multiple Basenames:
codereturn value
code
```vocs_Code
Copyimport { getAvatars } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const ensNames = ['zizzamia.base.eth', 'coinbase.base.eth'];
const avatars = await getAvatars({ ensNames, chain: base });
```
Get avatars for a mix of ENS names and Basenames:
codereturn value
code
```vocs_Code
Copyimport { getAvatars } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const ensNames = ['vitalik.eth', 'zizzamia.base.eth'];
const avatars = await getAvatars({ ensNames, chain: base });
```
## Returns
Array of [`GetAvatarReturnType`](https://docs.base.org/builderkits/onchainkit/identity/types#getavatarreturntype)
## Parameters
### GetAvatars
[`GetAvatars`](https://docs.base.org/builderkits/onchainkit/identity/types#getavatars)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/get-name#vocs-content)
getName
On this page
Chevron Right
The `getName` utility is designed to retrieve a name from an onchain identity
provider for a specific address.
Consider the utility instead of the hook when you
use it with Next.js or any Node.js backend.
## Usage
Get ENS name from an address:
codereturn value
code
```vocs_Code
Copyimport { getName } from '@coinbase/onchainkit/identity';
const address = '0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1';
const name = await getName({ address });
```
Get Basename from an address:
codereturn value
code
```vocs_Code
Copyimport { getName } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const address = '0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1';
const name = await getName({ address, chain: base });
```
Get a sliced address when address does not have an ENS name:
codereturn value
code
```vocs_Code
Copyimport { getName } from '@coinbase/onchainkit/identity';
const address = '0x1234567890abcdef1234567890abcdef12345678';
const name = await getName({ address });
```
## Returns
See [GetNameReturnType](https://docs.base.org/builderkits/onchainkit/identity/types#getnamereturntype) and [GetName](https://docs.base.org/builderkits/onchainkit/identity/types#getname) for more details.
## Parameters
See [GetNameReturnType](https://docs.base.org/builderkits/onchainkit/identity/types#getnamereturntype) and [GetName](https://docs.base.org/builderkits/onchainkit/identity/types#getname) for more details.
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/mint/types#vocs-content)
Mint
On this page
Chevron Right
## `LifecycleStatus`
```vocs_Code
Copyexport type LifecycleStatus =
| {
statusName: 'init';
statusData: null;
}
| {
statusName: 'error';
statusData: NFTError;
}
| {
statusName: 'mediaLoading';
statusData: {
mediaType: MediaType;
mediaUrl: string;
};
}
| {
statusName: 'mediaLoaded';
statusData: null;
}
| {
statusName: 'transactionPending';
statusData: null;
}
| {
statusName: 'transactionLegacyExecuted';
statusData: {
transactionHashList: Address[];
};
}
| {
// NFTCard success state represents media loaded
// NFTMintCard success state represents successful Mint
statusName: 'success';
statusData: {
transactionReceipts?: TransactionReceipt[];
};
};
```
## `NFTCardReact`
```vocs_Code
Copytype NFTCardReact = {
children: React.ReactNode;
// Optional className override for top div element.
className?: string;
// Contract address of the NFT
contractAddress: Hex;
// Required Token ID of the NFT
tokenId: string;
// Optional hook to override the default useNftData hook
useNFTData?: UseNFTData;
// An optional callback function that handles errors within the provider.
onError?: (error: NFTError) => void;
// An optional callback function that exposes the component lifecycle state
onStatus?: (lifecycleStatus: LifecycleStatus) => void;
// card will not pass transactionReceipt
onSuccess?: (transactionReceipt?: TransactionReceipt) => void;
};
```
## `NFTMintCardReact`
```vocs_Code
Copytype NFTMintCardReact = {
children: ReactNode;
// Optional className override for top div element.
className?: string;
// Contract address of the NFT
contractAddress: Hex;
// Token ID of the NFT only required for ERC1155
tokenId?: string;
// Optional boolean to determine if the mint is sponsored by paymaster
isSponsored?: boolean;
// Optional hook to override the default useNFTData hook
useNFTData?: UseNFTData;
// Optional function to override the default function that builds the mint transaction
buildMintTransaction?: BuildMintTransaction;
// An optional callback function that handles errors within the provider.
onError?: (error: NFTError) => void;
// An optional callback function that exposes the component lifecycle state
onStatus?: (lifecycleStatus: LifecycleStatus) => void;
// MintCard will pass transactionReceipt
onSuccess?: (transactionReceipt?: TransactionReceipt) => void;
};
```
## `NFTData`
```vocs_Code
Copytype NFTData = {
// card components
name?: string; // required for NFTTitle and NFTCollectionTitle
description?: string; // not currently used
imageUrl?: string; // required for NFTMedia
animationUrl?: string; // required for NFTMedia (audio and video types)
/* supported mimeTypes:
* image = image/*
* video = video/*
* audio = audio/* | application/*
*/
lastSoldPrice?: NFTPrice; // required for NFTLastSoldPrice
mimeType?: string; // required for NFTMedia (falls back to image)
// mint components
ownerAddress?: `0x${string}`; // required for NFTOwner
contractType?: ContractType;
mintDate?: Date; // required for NFTMintDate
price?: NFTPrice; // required for NFTAssetCost, NftTotalCost
mintFee?: NFTPrice; // required for NFTTotalCost
creatorAddress?: Hex; // required for NFTCreator
maxMintsPerWallet?: number; // required for NFTMintButton
isEligibleToMint?: boolean; // required for NFTMintButton
totalOwners?: string; // required for NFTMinters
recentOwners?: Address[]; // required for NFTMinters
network?: string; // required for default BuildMintTransaction implementation
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/get-names#vocs-content)
getNames
On this page
Chevron Right
The `getNames` utility is designed to retrieve multiple names from an onchain identity
provider for an array of addresses in a single batch request.
Consider the utility instead of the hook when you
use it with Next.js or any Node.js backend.
## Usage
Get ENS names from multiple addresses:
codereturn value
code
```vocs_Code
Copyimport { getNames } from '@coinbase/onchainkit/identity';
const addresses = [\
'0x4bEf0221d6F7Dd0C969fe46a4e9b339a84F52FDF',\
'0x838aD0EAE54F99F1926dA7C3b6bFbF617389B4D9'\
];
const names = await getNames({ addresses });
```
Get Basenames from multiple addresses:
codereturn value
code
```vocs_Code
Copyimport { getNames } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const addresses = [\
'0x4bEf0221d6F7Dd0C969fe46a4e9b339a84F52FDF',\
'0x4bEf0221d6F7Dd0C969fe46a4e9b339a84F52FDF'\
];
const names = await getNames({ addresses, chain: base });
```
Get a mix of ENS names and sliced addresses when some addresses don't have names:
codereturn value
code
```vocs_Code
Copyimport { getNames } from '@coinbase/onchainkit/identity';
const addresses = [\
'0x4bEf0221d6F7Dd0C969fe46a4e9b339a84F52FDF',\
'0x1234567890abcdef1234567890abcdef12345678'\
];
const names = await getNames({ addresses });
```
## Returns
Array of [`GetNameReturnType`](https://docs.base.org/builderkits/onchainkit/identity/types#getnamereturntype)
## Parameters
### GetNames
[`GetNames`](https://docs.base.org/builderkits/onchainkit/identity/types#getnames)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/identity-card#vocs-content)
IdentityCard
On this page
Chevron Right
The `IdentityCard` component provides a comprehensive way to display user identity information, including ENS names, avatars, and chain-specific name resolution.
## Features
- **Name Resolution:** Resolves both Basenames and ENS names automatically
- **Avatar Support:** Displays ENS and chain-specific avatars
- **Flexible Display:** Customizable layout and styling options
- **Chain-Aware:** Works across different EVM chains that support name resolution
- **Tooltip Support:** Displays attestation information on badge hover
## Usage
### Basic Usage
```vocs_Code
Copyimport { IdentityCard } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
```

paul.base.eth
0x4bEf...2FDFCopy
[twitter](https://x.com/PaulCramer_) [github](https://github.com/cpcramer) [farcaster](https://warpcast.com/paulcramer) [website](https://onchainkit.xyz/)
### Badge Tooltip
You can enable a tooltip for the attestation badge to provide context about what the badge represents:
```vocs_Code
Copyimport { IdentityCard } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
```

paul.base.eth
0x4bEf...2FDFCopy
[twitter](https://x.com/PaulCramer_) [github](https://github.com/cpcramer) [farcaster](https://warpcast.com/paulcramer) [website](https://onchainkit.xyz/)
You can also provide custom tooltip text:
```vocs_Code
Copyimport { IdentityCard } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
```

paul.base.eth
0x4bEf...2FDFCopy
[twitter](https://x.com/PaulCramer_) [github](https://github.com/cpcramer) [farcaster](https://warpcast.com/paulcramer) [website](https://onchainkit.xyz/)
## Customization
You can override styles using `className` or by setting a custom [OnchainKit theme](https://docs.base.org/builderkits/onchainkit/guides/themes#custom-theme). You can also set the `mainnet` chain for ENS name resolution:
```vocs_Code
Copyimport { IdentityCard } from '@coinbase/onchainkit/identity';
import { mainnet } from 'viem/chains';
```

paulcramer.eth
0x4bEf...2FDFCopy
[twitter](https://x.com/PaulCramer_) [github](https://github.com/cpcramer)
## Props
[`IdentityCardReact`](https://docs.base.org/builderkits/onchainkit/identity/types#identitycardreact)
| Prop | Type | Description |
| --- | --- | --- |
| `address` | `string` | The wallet address to display identity for |
| `chain` | `Chain` | The chain to resolve the identity on |
| `className` | `string` | Additional CSS classes to apply |
| `schemaId` | `Address | null` | The schema ID for attestation |
| `badgeTooltip` | `boolean | string` | When `true`, displays the attestation name in tooltip. When a string is provided, shows that custom text instead. Defaults to `false` |
## Error Handling
The component handles various error states gracefully:
- Invalid addresses display a shortened address format
- Missing ENS names fallback to shortened addresses
- Failed avatar fetches show a default avatar
- Network errors maintain a degraded but functional display
## Best Practices
1. Always provide a valid chain object from viem/chains
2. Handle loading states in parent components when address might be undefined
3. Implement proper error boundaries in parent components
4. Consider mobile responsiveness when styling
5. Use `badgeTooltip` to provide context about what the verification badge represents
## Related Components
- [``](https://docs.base.org/builderkits/onchainkit/identity/avatar) \- Displays user avatars
- [``](https://docs.base.org/builderkits/onchainkit/identity/name) \- Displays resolved names
- [``](https://docs.base.org/builderkits/onchainkit/identity/identity) \- Simplified identity display
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/identity#vocs-content)
Identity
On this page
Chevron Right
`Identity` is a React context provider and arranges identity components.
## Usage
Show user avatar, name with attestation and address:
```vocs_Code
Copyimport { Avatar, Identity, Name, Badge, Address } from '@coinbase/onchainkit/identity';
```

nickprince.eth
0x838a...B4D9Copy
### Badge with Tooltip
You can enable a tooltip for the attestation badge to provide context about what the badge represents:
```vocs_Code
Copyimport { Avatar, Identity, Name, Badge, Address } from '@coinbase/onchainkit/identity';
```

nickprince.eth
0x838a...B4D9Copy
You can also provide custom tooltip text:
```vocs_Code
Copyimport { Avatar, Identity, Name, Badge, Address } from '@coinbase/onchainkit/identity';
```

nickprince.eth
0x838a...B4D9Copy
Modify any styles with `className` prop.
```vocs_Code
Copyimport { Avatar, Identity, Name, Badge, Address } from '@coinbase/onchainkit/identity';
```

nickprince.eth
0x838a...B4D9Copy
Choose which identity components to render:
```vocs_Code
Copyimport { Avatar, Identity, Name, Badge, Address } from '@coinbase/onchainkit/identity';
```

nickprince.eth
nickprince.eth
0x838a...B4D9Copy
## Props
[IdentityReact](https://docs.base.org/builderkits/onchainkit/identity/types#identityreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/name#vocs-content)
Name
On this page
Chevron Right
The `Name` component is used to display ENS or [Basenames](https://www.base.org/names) associated with Ethereum addresses.
## Usage
Address with an ENS:
```vocs_Code
Copyimport { Name } from '@coinbase/onchainkit/identity';
const address = '0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1';
```
zizzamia.eth
Address with a Basename:
```vocs_Code
Copyimport { Name } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const address = '0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1';
```
zizzamia.base.eth
### Override styles
You can override component styles using `className`.
```vocs_Code
Copyimport { Name } from '@coinbase/onchainkit/identity';
const address = '0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1';
```
zizzamia.eth
### Add attestation badge
Show attestation on ENV name with [`Badge`](https://docs.base.org/builderkits/onchainkit/identity/badge) component.
Use [`OnchainKitProvider`](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider) or [`Identity`](https://docs.base.org/builderkits/onchainkit/identity/identity) component with the `schemaId` prop.
```vocs_Code
Copyimport { Badge, Name, Identity } from '@coinbase/onchainkit/identity';
const address = '0x838aD0EAE54F99F1926dA7C3b6bFbF617389B4D9';
```
nickprince.eth
## Props
[`NameReact`](https://docs.base.org/builderkits/onchainkit/identity/types#namereact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/socials#vocs-content)
Socials
On this page
Chevron Right
The `Socials` component displays social media links associated with Basenames and ENS names.
It automatically fetches and renders social links stored in text records.
## Features
- **Name Resolution:** Resolves both Basenames and ENS names to fetch associated social links
- **Multiple Platform Support:** Supports Twitter, GitHub, Discord, and other major platforms
- **Customizable Display:** Flexible styling options to match your app's design
- **Chain-Aware:** Works across different EVM chains that support ENS
## Usage
### Basic Usage
```vocs_Code
Copyimport {
Address,
Avatar,
Badge,
Identity,
Name,
Socials,
} from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
```

paul.base.eth
0x4bEf...2FDFCopy
[twitter](https://x.com/PaulCramer_) [github](https://github.com/cpcramer) [farcaster](https://warpcast.com/paulcramer) [website](https://onchainkit.xyz/)
### Standalone Usage
You can also use the `Socials` component independently by providing an address:
```vocs_Code
Copyimport { Socials } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
export default function StandaloneSocials() {
return (
);
}
```
[twitter](https://x.com/PaulCramer_) [github](https://github.com/cpcramer) [farcaster](https://warpcast.com/paulcramer) [website](https://onchainkit.xyz/)
### Custom Chain
Specify a different chain for ENS resolution:
```vocs_Code
Copyimport {
Address,
Avatar,
Badge,
Identity,
Name,
Socials,
} from '@coinbase/onchainkit/identity';
import { mainnet } from 'viem/chains';
```

paulcramer.eth
0x4bEf...2FDFCopy
[twitter](https://x.com/PaulCramer_) [github](https://github.com/cpcramer)
## Props
The `Socials` component accepts the following props:
| Prop | Type | Description |
| --- | --- | --- |
| `address` | `Address | null` | The Ethereum address to resolve social links for |
| `ensName` | `string` | Optional ENS name to resolve social links for |
| `chain` | `Chain` | The chain to use for ENS resolution |
| `className` | `string` | Custom CSS classes to apply to the component |
## Error Handling
The component handles various edge cases:
- Returns `null` if no social links are found
- Shows empty state while loading
- Gracefully handles ENS resolution errors
- Validates social links before display
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/types#vocs-content)
Identity
On this page
Chevron Right
## `AddressReact`
```vocs_Code
Copytype AddressReact = {
address?: Address | null; // The Ethereum address to render.
className?: string; // Optional className override for top span element.
isSliced?: boolean; // Determines if the displayed address should be sliced.
hasCopyAddressOnClick?: boolean; // Defaults to true. Optional boolean to disable copy address on click functionality.
};
```
## `Attestation`
```vocs_Code
Copytype Attestation = {
attester: Address; // the attester who created the attestation.
decodedDataJson: string; // The attestation data decoded to JSON.
expirationTime: number; // The Unix timestamp when the attestation expires (0 for no expiration).
id: string; // The unique identifier of the attestation.
recipient: Address; // The Ethereum address of the recipient of the attestation.
revocationTime: number; // The Unix timestamp when the attestation was revoked, if applicable.
revoked: boolean; // A boolean indicating whether the attestation is revocable or not.
schemaId: EASSchemaUid; // The schema identifier associated with the attestation.
time: number; // The Unix timestamp when the attestation was created.
};
```
## `AvatarReact`
```vocs_Code
Copytype AvatarReact = {
address?: Address | null; // The Ethereum address to fetch the avatar for.
chain?: Chain; // Optional chain for domain resolution
className?: string; // Optional className override for top div element.
loadingComponent?: JSX.Element; // Optional custom component to display while the avatar data is loading.
defaultComponent?: JSX.Element; // Optional custom component to display when no ENS name or avatar is available.
children?: ReactNode; // Optional attestation by passing Badge component as its children
} & ImgHTMLAttributes; // Optional additional image attributes to apply to the avatar.
```
## `BadgeReact`
```vocs_Code
Copytype BadgeReact = {
className?: string; // Optional className override for top span element.
tooltip?: boolean | string; // Controls whether the badge shows a tooltip on hover. When true, the tooltip displays the attestation's name. When a string is provided, that text overrides the default display. Defaults to false.
};
```
## `BaseMainnetName`
```vocs_Code
Copyexport type BaseMainnetName = `${string}.base.eth`;
```
## `Basename`
```vocs_Code
Copytype Basename = BaseMainnetName | BaseSepoliaName;
```
## `BaseSepoliaName`
```vocs_Code
Copytype BaseSepoliaName = `${string}.basetest.eth`;
```
## `EASSchemaUid`
```vocs_Code
Copytype EASSchemaUid = `0x${string}`;
```
## `EASChainDefinition`
```vocs_Code
Copytype EASChainDefinition = {
easGraphqlAPI: string; // EAS GraphQL API endpoint
id: number; // blockchain source id
schemaUids: EASSchemaUid[]; // Array of EAS Schema UIDs
};
```
## `EthBalanceReact`
```vocs_Code
Copytype EthBalanceReact = {
address?: Address;
className?: string;
};
```
## `GetAddress`
```vocs_Code
Copytype GetAddress = {
name: string | Basename; // Name to resolve
chain?: Chain; // Optional chain for domain resolution
};
```
## `GetAddressReturnType`
```vocs_Code
Copytype GetAddressReturnType = Address | null;
```
## `GetAttestationsOptions`
```vocs_Code
Copytype GetAttestationsOptions = {
schemas?: EASSchemaUid[];
revoked?: boolean;
expirationTime?: number;
limit?: number;
};
```
## `GetAvatar`
```vocs_Code
Copytype GetAvatar = {
ensName: string; // The ENS name to fetch the avatar for.
chain?: Chain; // Optional chain for domain resolution
};
```
## `GetAvatarReturnType`
```vocs_Code
Copytype GetAvatarReturnType = string | null;
```
## `GetName`
```vocs_Code
Copytype GetName = {
address: Address;
chain?: Chain;
};
```
## `GetNameReturnType`
```vocs_Code
Copytype GetNameReturnType = string | null;
```
## `GetNames`
```vocs_Code
Copytype GetNames = {
addresses: Address[]; // Array of Ethereum addresses to resolve names for
chain?: Chain; // Optional chain for domain resolution
};
```
## `IdentityCardReact`
```vocs_Code
Copytype IdentityCardReact = {
address?: Address;
chain?: Chain;
className?: string;
schemaId?: Address | null;
badgeTooltip?: boolean | string; // Controls whether the badge shows a tooltip on hover. When true, the tooltip displays the attestation's name. When a string is provided, that text overrides the default display. Defaults to false.
};
```
## `IdentityContextType`
```vocs_Code
Copytype IdentityContextType = {
address: Address; // The Ethereum address to fetch the avatar and name for.
schemaId?: Address | null; // The Ethereum address of the schema to use for EAS attestation.
};
```
## `IdentityReact`
```vocs_Code
Copytype IdentityReact = {
address?: Address; // The Ethereum address to fetch the avatar and name for.
chain?: Chain; // Optional chain for domain resolution
children: ReactNode;
className?: string; // Optional className override for top div element.
schemaId?: Address | null; // The Ethereum address of the schema to use for EAS attestation.
hasCopyAddressOnClick?: boolean; // Optional boolean to disable copy address on click functionality.
};
```
## `NameReact`
```vocs_Code
Copytype NameReact = {
address?: Address | null; // Ethereum address to be displayed.
children?: ReactNode; // Optional attestation by passing Badge component as its children
chain?: Chain; // Optional chain for domain resolution
className?: string; // Optional className override for top span element.
} & HTMLAttributes; // Optional additional span attributes to apply to the name.
```
## `UseAddressOptions`
```vocs_Code
Copytype UseAddressOptions = {
name: string | Basename; // The ENS or Basename for which the Ethereum address is to be fetched
chain?: Chain; // Optional chain for domain resolution
};
```
## `UseAvatarOptions`
```vocs_Code
Copytype UseAvatarOptions = {
ensName: string;
chain?: Chain; // Optional chain for domain resolution
};
```
## `UseAvatarsOptions`
```vocs_Code
Copytype UseAvatarsOptions = {
ensNames: string[]; // Array of ENS names to resolve avatars for
chain?: Chain; // Optional chain for domain resolution
};
```
## `UseNameOptions`
```vocs_Code
Copytype UseNameOptions = {
address: Address; // The address for which the ENS or Basename is to be fetched.
chain?: Chain; // Optional chain for domain resolution
};
```
## `UseNamesOptions`
```vocs_Code
Copytype UseNamesOptions = {
addresses: Address[]; // Array of addresses to resolve ENS or Basenames for
chain?: Chain; // Optional chain for domain resolution
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/use-address#vocs-content)
useAddress
On this page
Chevron Right
The `useAddress` hook is used to get an address from an onchain identity provider for a given name.
It is implemented with [useQuery](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery) from `@tanstack/react-query`, and returns a `UseQueryResult` object, allowing you to pass through all `@tanstack/react-query` options.
## Usage
```vocs_Code
Copyimport { useAddress } from '@coinbase/onchainkit/identity';
const { data: address, isLoading } = useAddress({ name: 'zizzamia.base.eth' });
```
## Returns
[`useQuery>`](https://docs.base.org/builderkits/onchainkit/identity/types#getaddressreturntype)
## Parameters
### UseAddressOptions
[`UseAddressOptions`](https://docs.base.org/builderkits/onchainkit/identity/types#useaddressoptions)
### UseQueryOptions
[`UseQueryOptions`](https://docs.base.org/builderkits/onchainkit/identity/types#usequeryoptions)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/use-avatar#vocs-content)
useAvatar
On this page
Chevron Right
The `useAvatar` hook is used to get avatar image URL from an onchain identity
provider for a given name.
It is implemented with [useQuery](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery) from `@tanstack/react-query`, and returns a `UseQueryResult` object, allowing you to pass through all `@tanstack/react-query` options.
## Usage
```vocs_Code
Copyimport { useAvatar } from '@coinbase/onchainkit/identity';
const { data: avatar, isLoading } = useAvatar({ ensName: 'vitalik.eth' });
```
## Returns
[`useQuery>`](https://docs.base.org/builderkits/onchainkit/identity/types#getaddressreturntype)
## Parameters
### UseAvatarOptions
[`UseAvatarOptions`](https://docs.base.org/builderkits/onchainkit/identity/types#useavataroptions)
### UseQueryOptions
[`UseQueryOptions`](https://docs.base.org/builderkits/onchainkit/identity/types#usequeryoptions)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/use-avatars#vocs-content)
useAvatars
On this page
Chevron Right
The `useAvatars` hook is used to get multiple avatar image URLs from an onchain identity
provider for an array of ENS names or Basenames in a single batch request.
It is implemented with [useQuery](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery) from `@tanstack/react-query`, and returns a `UseQueryResult` object, allowing you to pass through all `@tanstack/react-query` options.
## Usage
Get avatars for multiple ENS names:
codereturn value
code
```vocs_Code
Copyimport { useAvatars } from '@coinbase/onchainkit/identity';
const ensNames = ['vitalik.eth', 'paulcramer.eth'];
const { data: avatars, isLoading } = useAvatars({ ensNames });
```
Get avatars for multiple Basenames:
codereturn value
code
```vocs_Code
Copyimport { useAvatars } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const ensNames = ['paul.base.eth', 'coinbase.base.eth'];
const { data: avatars, isLoading } = useAvatars({ ensNames, chain: base });
```
## Returns
[`useQuery>`](https://docs.base.org/builderkits/onchainkit/identity/types#getavatarreturntype)
## Parameters
### UseAvatarsOptions
[`UseAvatarsOptions`](https://docs.base.org/builderkits/onchainkit/identity/types#useavatarsoptions)
### UseQueryOptions
[`UseQueryOptions`](https://docs.base.org/builderkits/onchainkit/identity/types#usequeryoptions)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/use-name#vocs-content)
useName
On this page
Chevron Right
The `useName` hook is used to get name from an onchain identity provider
for a given address.
It is implemented with [useQuery](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery) from `@tanstack/react-query`, and returns a `UseQueryResult` object, allowing you to pass through all `@tanstack/react-query` options.
## Usage
Get ENS name from an address:
codereturn value
code
```vocs_Code
Copyimport { useName } from '@coinbase/onchainkit/identity';
const address = '0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1';
const { data: name, isLoading } = await useName({ address });
```
Get Basename from an address:
codereturn value
code
```vocs_Code
Copyimport { useName } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const address = '0x02feeb0AdE57b6adEEdE5A4EEea6Cf8c21BeB6B1';
const { data: name, isLoading } = await useName({ address, chain: base });
```
## Returns
[`useQuery>`](https://docs.base.org/builderkits/onchainkit/identity/types#getaddressreturntype)
## Parameters
### UseNameOptions
[`UseNameOptions`](https://docs.base.org/builderkits/onchainkit/identity/types#usenameoptions)
### UseQueryOptions
[`UseQueryOptions`](https://docs.base.org/builderkits/onchainkit/identity/types#usequeryoptions)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/identity/use-names#vocs-content)
useNames
On this page
Chevron Right
The `useNames` hook is used to get multiple names from an onchain identity provider
for an array of addresses in a single batch request.
It is implemented with [useQuery](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery) from `@tanstack/react-query`, and returns a `UseQueryResult` object, allowing you to pass through all `@tanstack/react-query` options.
## Usage
Get ENS names from multiple addresses:
codereturn value
code
```vocs_Code
Copyimport { useNames } from '@coinbase/onchainkit/identity';
const addresses = [\
'0x4bEf0221d6F7Dd0C969fe46a4e9b339a84F52FDF',\
'0x838aD0EAE54F99F1926dA7C3b6bFbF617389B4D9'\
];
const { data: names, isLoading } = useNames({ addresses });
```
Get Basenames from multiple addresses:
codereturn value
code
```vocs_Code
Copyimport { useNames } from '@coinbase/onchainkit/identity';
import { base } from 'viem/chains';
const addresses = [\
'0x4bEf0221d6F7Dd0C969fe46a4e9b339a84F52FDF',\
'0x4bEf0221d6F7Dd0C969fe46a4e9b339a84F52FDF'\
];
const { data: names, isLoading } = useNames({ addresses, chain: base });
```
## Returns
[`useQuery>`](https://docs.base.org/builderkits/onchainkit/identity/types#getnamereturntype)
## Parameters
### UseNamesOptions
[`UseNamesOptions`](https://docs.base.org/builderkits/onchainkit/identity/types#usenamesoptions)
### UseQueryOptions
[`UseQueryOptions`](https://docs.base.org/builderkits/onchainkit/identity/types#usequeryoptions)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/mint/nft-card#vocs-content)
NFTCard
On this page
Chevron Right
The `NFTCard` component provides an easy way to view any NFT. Just enter the NFT contract address and token Id and include the child components you want to render.

## Prerequisites
Before using the `NFTCard` component, ensure you've completed the [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started) steps.
To use the `NFTCard` component, you'll need to provide an API Key in `OnchainKitProvider`. You can get one following our [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started#get-your-public-api-key) steps.
### Starting a new project
If you're starting a new project, we recommend using `create onchain` to scaffold your project.
```vocs_Code
Copynpm create onchain@latest
```
### Adding to an existing project
If you're adding `NFTCard` to an existing project, simply install OnchainKit.
npmyarnpnpmbun
Terminal
npm
```vocs_Code
Copynpm install @coinbase/onchainkit
```
Wrap the `` around your app, following the steps in [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started#add-providers).
## Quickstart
The `NFTCardDefault` component is a simplified version of the `NFTCard` component, designed to streamline the integration process for developers. Instead of manually defining each subcomponent, developers can use this shorthand version which renders our suggested implementation of the component and includes `NFTTitle`, `NFTMedia`, `NFTOwner`, `NFTLastSoldPrice` and `NFTNetwork`.
```vocs_Code
Copyimport { NFTCardDefault } from '@coinbase/onchainkit/nft';
```
If you'd like more customization you can follow the steps below to customize which subcomponents are rendered.
### Add the NFTCard
```vocs_Code
Copyimport { NFTCard } from '@coinbase/onchainkit/nft';
```
### Add the NFTCard components
```vocs_Code
Copyimport { NFTCard } from '@coinbase/onchainkit/nft';
import {
NFTLastSoldPrice,
NFTMedia,
NFTNetwork,
NFTOwner,
NFTTitle,
} from '@coinbase/onchainkit/nft/view';
```
Base Around The World 2024 Recap Video #1
Owned by

cryptostatuette.eth
Last sale price
0.0004 ETH
~
$0.98
Network
Base
That's it! You've now created an NFT card.
## Customization
### Add the NFTCard subcomponents in any order
If you prefer to have the title above the media, you can easily change the order of the subcomponents and they will render in the new order.
```vocs_Code
Copy
```
Job's Not Finished

### Customize the `` aspect ratio
By default, we display all media scaled to fit the card. If you would prefer to show the media at its original aspect ratio you can set `square={false}` on the `` component.
```vocs_Code
Copy
```
| Scaled to fit (default) | Original Aspect Ratio |
| --- | --- |
| | |
### Override styles
We recommend style customization by setting a custom [OnchainKit theme](https://docs.base.org/builderkits/onchainkit/guides/themes#custom-theme). You can also override individual component styles using `className`.
```vocs_Code
Copy
```

Job's Not Finished
## Advanced Usage
### Bring your own data
The default `NFTCard` implementation uses Coinbase Developer Platform to provide the data and requires an API key. If you would like to use your own data, you can use the `useNFTData` prop to pass in a hook which fetches the NFT data from a source of your choice. As long as this hook returns an object with the same shape as the [`NFTData`](https://docs.base.org/builderkits/onchainkit/mint/types#nftdata) type, the NFTCard will render.
```vocs_Code
Copy
function useNFTData() {
return {
title: 'My NFT',
imageUrl: 'https://example.com/image.png',
}
}
export default function NFTComponent() {
return (
);
}
```
### Listening to the component lifecycle
You can use our NFT [`LifecycleStatus`](https://docs.base.org/builderkits/onchainkit/mint/types#lifecyclestatus) and the `onStatus` prop to listen to transaction states.
NFTCard has 4 lifecycle states:
- `init` \- The component is initialized
- `error` \- The component has encountered an error
- `mediaLoading` \- The media is loading
- `success` \- The media has been loaded
```vocs_Code
Copyimport type { LifecycleStatus } from '@coinbase/onchainkit/nft';
const statusHandler = (status: LifecycleStatus) => {
const { statusName, statusData } = status;
switch (statusName) {
case 'success':
// handle success
case 'error':
// handle error
default:
// handle 'init' state
}
}
```
## Example use cases
- **Display your favorite NFT:** Create your own gallery showcasing your favorite NFTs
- **Display a minted in game avatar:** Allow your users to mint and then view a minted avatar
## Components
The `NFTCard` component can be customized with the following components:
- `` \- The media for the NFT, this includes support for images, videos and audio NFTs.
- `` \- The title of the NFT.
- `` \- Displays the Owners Avatar, name or address and badge (if applicable).
- `` \- The last sold price of the NFT in native currency and USD.
- `` \- The network the NFT is on, currently only BASE NFTs are supported.
## Props
- [`LifecycleStatus`](https://docs.base.org/builderkits/onchainkit/mint/types#lifecyclestatus)
- [`NFTCardReact`](https://docs.base.org/builderkits/onchainkit/mint/types#nftcardreact)
- [`NFTData`](https://docs.base.org/builderkits/onchainkit/mint/types#nftdata)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card#vocs-content)
NFTMintCard
On this page
Chevron Right
The `NFTMintCard` component provides an easy way to mint an NFT. Just enter the NFT contract address and token Id (for ERC1155 contracts) and include the subcomponents you want to render.

## Prerequisites
Before using the `NFTMintCard` component, ensure you've completed the [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started) steps.
To use the `NFTMintCard` component, you'll need to provide an API Key in `OnchainKitProvider`. You can get one following our [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started#get-your-public-api-key) steps.
### Starting a new project
If you're starting a new project, we recommend using `create onchain` to scaffold your project.
```vocs_Code
Copynpm create onchain@latest
```
### Adding to an existing project
If you're adding `NFTMintCard` to an existing project, simply install OnchainKit.
npmyarnpnpmbun
Terminal
npm
```vocs_Code
Copynpm install @coinbase/onchainkit
```
Wrap the `` around your app, following the steps in [Getting Started](https://docs.base.org/builderkits/onchainkit/getting-started#add-providers).
## Quickstart
The `NFTMintCardDefault` component is a simplified version of the `NFTMintCard` component, designed to streamline the integration process for developers. Instead of manually defining each subcomponent, developers can use this shorthand version which renders our suggested implementation of the component and includes `NFTCreator`, `NFTMedia`, `NFTCollectionTitle`, `NFTQuantitySelector`, `NFTAssetCost` and `NFTMintButton`.
```vocs_Code
Copyimport { NFTMintCardDefault } from '@coinbase/onchainkit/nft';
```
If you'd like more customization you can follow the steps below to customize which subcomponents are rendered.
### Add the NFTMintCard
```vocs_Code
Copyimport { NFTMintCard } from '@coinbase/onchainkit/nft';
```
### Add the NFTMintCard components
```vocs_Code
Copyimport { NFTMintCard } from '@coinbase/onchainkit/nft';
import { NFTMedia } from '@coinbase/onchainkit/nft/view';
import {
NFTCreator,
NFTCollectionTitle,
NFTQuantitySelector,
NFTAssetCost,
NFTMintButton,
} from '@coinbase/onchainkit/nft/mint';
```

tina.base.eth
OCK Mint Component
-
+
0.000111 ETH
~
$0.26
Connect Wallet
That's it! You've now created an NFT mint card.
## Not sure what to mint?
You can create your own NFT to mint at [Coinbase Wallets create a Mint flow](https://wallet.coinbase.com/home/create). Just follow the instructions to create your NFT and then copy the contract address out of the url into an NFTMintCard.
## Customization
### Add the NFTMintCard components in any order
If you prefer to have the collection title above the media, you can easily change the order of the subcomponents and they will render in the new order.
```vocs_Code
Copy
```
Job's Not Finished

### Customize the `` aspect ratio
By default, we display all media scaled to fit the card. If you would prefer to show the media at its original aspect ratio you can set `square={false}` on the `` component.
```vocs_Code
Copy
```
| Scaled to fit (default) | Original Aspect Ratio |
| --- | --- |
| | |
### Override styles
We recommend style customization by setting a custom [OnchainKit theme](https://docs.base.org/builderkits/onchainkit/guides/themes#custom-theme). You can also override individual component styles using `className`.
```vocs_Code
Copy
```

Job's Not Finished
## Compatibility
The mint component uses a custom buildMintTransaction implementation which supports Coinbase mints as well as [`these supported platforms on reservoir`](https://docs.reservoir.tools/docs/minting#platform-support). If your contract is not supported, please follow the [`bring your own data instructions`](https://docs.base.org/builderkits/onchainkit/mint/nft-mint-card#bring-your-own-data) below.
## Advanced Usage
### Bring your own data
The default `NFTMintCard` implementation uses Coinbase Developer Platform to provide the data and requires an API key. You can use the `useNFTData` prop to pass in a hook which fetches the NFT data from a source of your choice. As long as this hook returns an object with the same shape as the [`NFTData`](https://docs.base.org/builderkits/onchainkit/mint/types#nftdata) type, the NFTMintCard will render.
You can also use a custom `buildMintTransaction` function to create your own Mint transaction.
```vocs_Code
Copy
function useNFTData() {
return {
title: 'My NFT',
imageUrl: 'https://example.com/image.png',
}
}
async function buildMintTransaction() {
const response = await fetch('https://api.minttransaction.com');
return await response.json();
}
export default function NFTComponent() {
return (
);
}
```
### Listening to the component lifecycle
You can use our NFT [`LifecycleStatus`](https://docs.base.org/builderkits/onchainkit/mint/types#lifecyclestatus) and the `onStatus` prop to listen to transaction states.
NFTMintCard has 6 lifecycle states:
- `init` \- The component is initialized
- `error` \- The component has encountered an error
- `mediaLoading` \- The media is loading
- `mediaLoaded` \- The media has been loaded
- `transactionPending` \- The mint transaction is pending
- `transactionLegacyExecuted` \- The mint transaction has been executed
- `success` \- The mint transaction has been successful
```vocs_Code
Copyimport type { LifecycleStatus } from '@coinbase/onchainkit/nft';
const statusHandler = (status: LifecycleStatus) => {
const { statusName, statusData } = status;
switch (statusName) {
case 'success':
// handle success
case 'error':
// handle error
default:
// handle 'init' state
}
}
```
## Example use cases
- **Create a gallery of your mintable NFTs:** Create a gallery of NFTs you created for users to mint
- **Minted in game avatar:** Allow your users to mint and then view a minted avatar
## Components
The `NFTMintCard` component can be customized with the following components:
- `` \- The creator of the NFT.
- `` \- The media for the NFT, this includes support for images, videos and audio NFTs.
- `` \- The title of the NFT collection.
- `` \- The quantity selector for the NFT.
- `` \- The cost of the NFT in native currency and USD.
- `` \- The mint button for the NFT.
## Props
- [`LifecycleStatus`](https://docs.base.org/builderkits/onchainkit/mint/types#lifecyclestatus)
- [`NFTMintCardReact`](https://docs.base.org/builderkits/onchainkit/mint/types#nftmintcardreact)
- [`NFTData`](https://docs.base.org/builderkits/onchainkit/mint/types#nftdata)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/mint/types#vocs-content)
Mint
On this page
Chevron Right
## `LifecycleStatus`
```vocs_Code
Copyexport type LifecycleStatus =
| {
statusName: 'init';
statusData: null;
}
| {
statusName: 'error';
statusData: NFTError;
}
| {
statusName: 'mediaLoading';
statusData: {
mediaType: MediaType;
mediaUrl: string;
};
}
| {
statusName: 'mediaLoaded';
statusData: null;
}
| {
statusName: 'transactionPending';
statusData: null;
}
| {
statusName: 'transactionLegacyExecuted';
statusData: {
transactionHashList: Address[];
};
}
| {
// NFTCard success state represents media loaded
// NFTMintCard success state represents successful Mint
statusName: 'success';
statusData: {
transactionReceipts?: TransactionReceipt[];
};
};
```
## `NFTCardReact`
```vocs_Code
Copytype NFTCardReact = {
children: React.ReactNode;
// Optional className override for top div element.
className?: string;
// Contract address of the NFT
contractAddress: Hex;
// Required Token ID of the NFT
tokenId: string;
// Optional hook to override the default useNftData hook
useNFTData?: UseNFTData;
// An optional callback function that handles errors within the provider.
onError?: (error: NFTError) => void;
// An optional callback function that exposes the component lifecycle state
onStatus?: (lifecycleStatus: LifecycleStatus) => void;
// card will not pass transactionReceipt
onSuccess?: (transactionReceipt?: TransactionReceipt) => void;
};
```
## `NFTMintCardReact`
```vocs_Code
Copytype NFTMintCardReact = {
children: ReactNode;
// Optional className override for top div element.
className?: string;
// Contract address of the NFT
contractAddress: Hex;
// Token ID of the NFT only required for ERC1155
tokenId?: string;
// Optional boolean to determine if the mint is sponsored by paymaster
isSponsored?: boolean;
// Optional hook to override the default useNFTData hook
useNFTData?: UseNFTData;
// Optional function to override the default function that builds the mint transaction
buildMintTransaction?: BuildMintTransaction;
// An optional callback function that handles errors within the provider.
onError?: (error: NFTError) => void;
// An optional callback function that exposes the component lifecycle state
onStatus?: (lifecycleStatus: LifecycleStatus) => void;
// MintCard will pass transactionReceipt
onSuccess?: (transactionReceipt?: TransactionReceipt) => void;
};
```
## `NFTData`
```vocs_Code
Copytype NFTData = {
// card components
name?: string; // required for NFTTitle and NFTCollectionTitle
description?: string; // not currently used
imageUrl?: string; // required for NFTMedia
animationUrl?: string; // required for NFTMedia (audio and video types)
/* supported mimeTypes:
* image = image/*
* video = video/*
* audio = audio/* | application/*
*/
lastSoldPrice?: NFTPrice; // required for NFTLastSoldPrice
mimeType?: string; // required for NFTMedia (falls back to image)
// mint components
ownerAddress?: `0x${string}`; // required for NFTOwner
contractType?: ContractType;
mintDate?: Date; // required for NFTMintDate
price?: NFTPrice; // required for NFTAssetCost, NftTotalCost
mintFee?: NFTPrice; // required for NFTTotalCost
creatorAddress?: Hex; // required for NFTCreator
maxMintsPerWallet?: number; // required for NFTMintButton
isEligibleToMint?: boolean; // required for NFTMintButton
totalOwners?: string; // required for NFTMinters
recentOwners?: Address[]; // required for NFTMinters
network?: string; // required for default BuildMintTransaction implementation
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/swap/swap-settings#vocs-content)
SwapSettings
On this page
Chevron Right
The `SwapSettings` component enables customizable slippage configuration in the `Swap` component.
## Usage
```vocs_Code
Copy// omitted for brevity
import {
Swap,
SwapSettings,
SwapSettingsSlippageDescription,
SwapSettingsSlippageInput,
SwapSettingsSlippageTitle,
} from '@coinbase/onchainkit/swap';
Max. slippage
Your swap will revert if the prices change by more than the selected
percentage.
```
Connect Wallet
### Override styles
You can override component styles using `className`.
```vocs_Code
Copy// omitted for brevity
Max. slippage
Your swap will revert if the prices change by more than the selected
percentage.
```
Connect Wallet
### Override icon
You can override the icon using the icon prop.
```vocs_Code
Copy// omitted for brevity
```
Connect Wallet
### Add text
You can add text next to the `SwapSettings` component using text.
```vocs_Code
Copy// omitted for brevity
```
Connect Wallet
### Override text
You can override component text by providing children text.
```vocs_Code
Copy// omitted for brevity
Slippage Settings
Set a max slippage you are willing to accept.
```
Connect Wallet
## Components
- `` \- Container component for swap slippage settings.
- `` \- Displays description text explaining the slippage setting.
- `` \- Input field for users to enter their desired max slippage percentage
- `` \- Displays the title for the slippage settings section
## Props
- [`SwapSettingsReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swapsettingsreact)
- [`SwapSettingsSlippageDescriptionReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swapsettingsslippagedescriptionreact)
- [`SwapSettingsSlippageInputReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swapsettingsslippageinputreact)
- [`SwapSettingsSlippageTitleReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swapsettingsslippagetitlereact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/swap/swap#vocs-content)
Swap
On this page
Chevron Right
The `Swap` components provide a comprehensive interface for users to execute [Token](https://docs.base.org/builderkits/onchainkit/token/types#token) swaps.
Before using them, ensure you've completed all [Getting Started steps](https://docs.base.org/builderkits/onchainkit/getting-started).
## Quick start
The `SwapDefault` component is a simplified version of the `Swap` component, designed to streamline the integration process for developers. Instead of manually defining each subcomponent and prop, developers can use this shorthand version which renders our suggested implementation of the component and includes `SwapAmountInput`, `SwapSettings`, `SwapToggleButton`, `SwapButton`, and `SwapToast`.
If you'd like more customization, follow the implementation guide for our `Swap` component below.
```vocs_Code
Copyimport { SwapDefault } from '@coinbase/onchainkit/swap';
import type { Token } from '@coinbase/onchainkit/token';
const eth: Token = {
name: 'ETH',
address: '',
symbol: 'ETH',
decimals: 18,
image:
'https://wallet-api-production.s3.amazonaws.com/uploads/tokens/eth_288.png',
chainId: 8453,
};
const usdc: Token = {
name: 'USDC',
address: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
symbol: 'USDC',
decimals: 6,
image:
'https://d3r81g40ycuhqg.cloudfront.net/wallet/wais/44/2b/442b80bd16af0c0d9b22e03a16753823fe826e5bfd457292b55fa0ba8c1ba213-ZWUzYjJmZGUtMDYxNy00NDcyLTg0NjQtMWI4OGEwYjBiODE2',
chainId: 8453,
};
```
### Props
[`SwapDefaultReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swapdefaultreact)
## Usage
Example using `@coinbase/onchainkit/swap` and `@coinbase/onchainkit/wallet`.
```vocs_Code
Copyimport { Avatar, Name } from '@coinbase/onchainkit/identity';
import {
Swap,
SwapAmountInput,
SwapToggleButton,
SwapButton,
SwapMessage,
SwapToast,
} from '@coinbase/onchainkit/swap';
import { Wallet, ConnectWallet } from '@coinbase/onchainkit/wallet';
import { useAccount } from 'wagmi';
import type { Token } from '@coinbase/onchainkit/token';
export default function SwapComponents() {
const { address } = useAccount();
const ETHToken: Token = {
address: "",
chainId: 8453,
decimals: 18,
name: "Ethereum",
symbol: "ETH",
image: "https://dynamic-assets.coinbase.com/dbb4b4983bde81309ddab83eb598358eb44375b930b94687ebe38bc22e52c3b2125258ffb8477a5ef22e33d6bd72e32a506c391caa13af64c00e46613c3e5806/asset_icons/4113b082d21cc5fab17fc8f2d19fb996165bcce635e6900f7fc2d57c4ef33ae9.png",
};
const USDCToken: Token = {
address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
chainId: 8453,
decimals: 6,
name: "USDC",
symbol: "USDC",
image: "https://dynamic-assets.coinbase.com/3c15df5e2ac7d4abbe9499ed9335041f00c620f28e8de2f93474a9f432058742cdf4674bd43f309e69778a26969372310135be97eb183d91c492154176d455b8/asset_icons/9d67b728b6c8f457717154b3a35f9ddc702eae7e76c4684ee39302c4d7fd0bb8.png",
};
// add other tokens here to display them as options in the swap
const swappableTokens: Token[] = [ETHToken, USDCToken];
return address ? (
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
) : (
);
}
```
### Supported Swap Routers
The `Swap` component supports two swap routers:
- [Uniswap V3](https://app.uniswap.org/) (default)
- [0x Aggregator](https://0x.org/)
To use the 0x Aggregator, set the `experimental.useAggregator` prop to `true`.
### Sponsor gas with Paymaster
To sponsor swap transactions for your users, toggle the Paymaster using the `isSponsored` prop.
By default, this will use the [Coinbase Developer Platform](https://portal.cdp.coinbase.com/products/bundler-and-paymaster) Paymaster.
You can configure sponsorship settings on the [Paymaster](https://portal.cdp.coinbase.com/products/bundler-and-paymaster) page.
For security reasons, we recommend setting up a contract allowlist in the Portal. Without a contract allowlist defined, your Paymaster will only be able to sponsor up to $1.
The contract used in our Swap API is Uniswap's [Universal Router](https://basescan.org/address/0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD), which is deployed on Base at `0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD`.
Note that gas sponsorship will only work for Smart Wallets.
```vocs_Code
Copy// omitted for brevity
// Set isSponsored to true
// [!code focus]
...
```
### Custom token pair
You can adjust to only allow swap between a token pair.
```vocs_Code
Copy// omitted for brevity
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
```
### Remove toggle button
You can remove `SwapToggleButton` to make swap unidirectional.
```vocs_Code
Copy// omitted for brevity
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
```
### Remove swap message
You can remove `SwapMessage` component.
```vocs_Code
Copy// omitted for brevity
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
// [!code focus]
```
### Override styles
You can override component styles using `className`.
```vocs_Code
Copy// omitted for brevity
// [!code focus]
// [!code focus]
```
## Components
The components are designed to work together hierarchically. For each component, ensure the following:
- `` \- Set the user's address and error handling.
- `` \- Set the [Token](https://docs.base.org/builderkits/onchainkit/token/types#token) to swap and specify the input type ( `from` or `to`).
- `` \- Optional component to toggle between input types.
- `` \- Optional component that displays a message related to the swap operation's current state.
- `` \- Set the onSuccess and onError callbacks.
- `` \- Optional component to notify user of successful swap transaction.
## Props
- [`SwapReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swapreact)
- [`SwapDefaultReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swapdefaultreact)
- [`SwapAmountInputReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swapamountinputreact)
- [`SwapButtonReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swapbuttonreact)
- [`SwapMessageReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swapmessagereact)
- [`SwapToggleButtonReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swaptogglebuttonreact)
- [`SwapToastReact`](https://docs.base.org/builderkits/onchainkit/swap/types#swaptoastreactt)
[Skip to content](https://docs.base.org/builderkits/onchainkit/swap/types#vocs-content)
Swap
On this page
Chevron Right
## `Fee`
```vocs_Code
Copytype Fee = {
amount: string; // The amount of the fee
baseAsset: Token; // The base asset for the fee
percentage: string; // The percentage of the fee
};
```
## `QuoteWarning`
```vocs_Code
Copytype QuoteWarning = {
description?: string; // The description of the warning
message?: string; // The message of the warning
type?: string; // The type of the warning
};
```
## `LifecycleStatus`
```vocs_Code
Copytype LifecycleStatusDataShared = {
isMissingRequiredField: boolean;
maxSlippage: number;
};
type LifecycleStatus =
| {
statusName: 'init';
statusData: LifecycleStatusDataShared;
}
| {
statusName: 'error';
statusData: SwapError & LifecycleStatusDataShared;
}
| {
statusName: 'amountChange';
statusData: {
amountFrom: string;
amountTo: string;
tokenFrom?: Token;
tokenTo?: Token;
} & LifecycleStatusDataShared;
}
| {
statusName: 'slippageChange';
statusData: LifecycleStatusDataShared;
}
| {
statusName: 'transactionPending';
statusData: LifecycleStatusDataShared;
}
| {
statusName: 'transactionApproved';
statusData: {
transactionHash: Hex;
transactionType: 'ERC20' | 'Permit2';
} & LifecycleStatusDataShared;
}
| {
statusName: 'success';
statusData: {
transactionReceipt: TransactionReceipt;
} & LifecycleStatusDataShared;
};
```
## `SwapAmountInputReact`
```vocs_Code
Copytype SwapAmountInputReact = {
className?: string; // Optional className override for top div element.
delayMs?: number; // The debounce delay in milliseconds
label: string; // Descriptive label for the input field
swappableTokens?: Token[]; // Swappable tokens
token?: Token; // Selected token
type: 'to' | 'from'; // Identifies if component is for toToken or fromToken
};
```
## `SwapButtonReact`
```vocs_Code
Copytype SwapButtonReact = {
className?: string; // Optional className override for top div element.
disabled?: boolean; // Disables swap button
};
```
## `SwapError`
```vocs_Code
Copytype SwapError = {
code: string; // The error code representing the type of swap error.
error: string; // The error message providing details about the swap error.
message: string; // The error message providing details about the swap error.
};
```
```vocs_Code
Copytype SwapMessageReact = {
className?: string; // Optional className override for top div element.
};
```
## `SwapQuote`
```vocs_Code
Copytype SwapQuote = {
amountReference: string; // The reference amount for the quote
from: Token; // The source token for the swap
fromAmount: string; // The amount of the source token
fromAmountUSD: string; // The USD value of the source token
hasHighPriceImpact: boolean; // Whether the price impact is high
priceImpact: string; // The price impact of the swap
slippage: string; // The slippage of the swap
to: Token; // The destination token for the swap
toAmount: string; // The amount of the destination token
toAmountUSD: string; // The USD value of the destination token
warning?: QuoteWarning; // The warning associated with the quote
};
```
## `SwapReact`
```vocs_Code
Copytype SwapReact = {
children: ReactNode;
className?: string; // Optional className override for top div element.
config?: {
maxSlippage: number; // Maximum acceptable slippage for a swap (e.g., 3 for 3%). This is a percentage, not basis points;
};
experimental?: {
/**
* Whether to use a DEX aggregator.
* true - 0x Aggregator
* false - Uniswap V3
* @default false
*/
useAggregator: boolean;
};
isSponsored?: boolean; // An optional setting to sponsor swaps with a Paymaster. (default: false)
onError?: (error: SwapError) => void; // An optional callback function that handles errors within the provider.
onStatus?: (lifecycleStatus: LifecycleStatus) => void; // An optional callback function that exposes the component lifecycle state
onSuccess?: (transactionReceipt: TransactionReceipt) => void; // An optional callback function that exposes the transaction receipt
title?: string; // Title for the Swap component. (default: "Swap")
};
```
## `SwapDefaultReact`
```vocs_Code
Copyexport type SwapDefaultReact = {
to: Token[]; // Swappable tokens (first token in array will be initial token selected)
from: Token[]; // Swappable tokens (first token in array will be initial token selected)
disabled?: boolean; // Disables swap button
} & Omit;
```
## `SwapSettingsReact`
```vocs_Code
Copytype SwapSettingsReact = {
children: ReactNode;
className?: string; // Optional className override for top div element.
icon?: ReactNode; // Optional icon override
text?: string; // Optional text override
};
```
## `SwapSettingsSlippageDescriptionReact`
```vocs_Code
Copytype SwapSettingsSlippageDescriptionReact = {
children: ReactNode;
className?: string; // Optional className override for top div element.
};
```
## `SwapSettingsSlippageInputReact`
```vocs_Code
Copytype SwapSettingsSlippageInputReact = {
className?: string; // Optional className override for top div element.
};
```
## `SwapSettingsSlippageTitleReact`
```vocs_Code
Copytype SwapSettingsSlippageTitleReact = {
children: ReactNode;
className?: string; // Optional className override for top div element.
};
```
## `SwapToastReact`
```vocs_Code
Copytype SwapToastReact = {
className?: string; // An optional CSS class name for styling the toast component.
durationMs?: number; // An optional value to customize time until toast disappears
position?: 'top-center' | 'top-right' | 'bottom-center' | 'bottom-right'; // An optional position property to specify the toast's position on the screen.
};
```
## `SwapToggleButtonReact`
```vocs_Code
Copytype SwapToggleButtonReact = {
className?: string; // Optional className override for top div element.
};
```
## `Transaction`
```vocs_Code
Copytype Transaction = {
chainId: number; // The chain ID
data: Hex; // The data for the transaction
gas: bigint; // The gas limit
maxFeePerGas?: bigint | undefined; // The maximum fee per gas
maxPriorityFeePerGas?: bigint | undefined; // The maximum priority fee per gas
nonce?: number; // The nonce for the transaction
to: Address; // The recipient address
value: bigint; // The value of the transaction
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/token/format-amount#vocs-content)
formatAmount
On this page
Chevron Right
The `formatAmount` utility is designed for consistent number formatting.
## Usage
codereturn value
code
```vocs_Code
Copyimport { formatAmount } from '@coinbase/onchainkit/token';
const amount = formatAmount('10000', { minimumFractionDigits: 2 });
```
## Returns
`string` \- The formatted amount.
## Parameters
[`FormatAmountOptions`](https://docs.base.org/builderkits/onchainkit/token/types#formatamountoptions)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/token/token-chip#vocs-content)
TokenChip
On this page
Chevron Right
The `TokenChip` component is a button that displays the token symbol.
## Usage
```vocs_Code
Copyimport { TokenChip } from '@coinbase/onchainkit/token';
import '@coinbase/onchainkit/styles.css';
const token = {
address: '0x1234',
chainId: 1,
decimals: 18,
image:
'https://dynamic-assets.coinbase.com/dbb4b4983bde81309ddab83eb598358eb44375b930b94687ebe38bc22e52c3b2125258ffb8477a5ef22e33d6bd72e32a506c391caa13af64c00e46613c3e5806/asset_icons/4113b082d21cc5fab17fc8f2d19fb996165bcce635e6900f7fc2d57c4ef33ae9.png',
name: 'Ethereum',
symbol: 'ETH',
};
;
```
ETH
## Props
[`TokenChipReact`](https://docs.base.org/builderkits/onchainkit/token/types#tokenchipreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/token/token-image#vocs-content)
TokenImage
On this page
Chevron Right
The `TokenImage` component is an image that crops token image to a circle with an adjustable size.
With `token` props has no image, render partial token symbol and deterministic dark color.
## Usage
`TokenImage` with an url
```vocs_Code
Copy
```

`TokenImage` with null as src
```vocs_Code
Copy
```
## Props
[`TokenSelectorReact`](https://docs.base.org/builderkits/onchainkit/token/types#tokenselectorreact)
## CSS
```vocs_Code
Copy.ock-tokenimage {
@apply overflow-hidden rounded-[50%];
}
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/token/token-row#vocs-content)
TokenRow
On this page
Chevron Right
The `TokenRow` component displays token information in a row format to be used in list components.
## Usage
Token with an image url
```vocs_Code
Copyimport { TokenRow } from '@coinbase/onchainkit/token';
const token = { ... };
;
```
EthereumETH
Token without an image url
```vocs_Code
Copyimport { TokenRow } from '@coinbase/onchainkit/token';
const token = { ... };
;
```
EthereumETH1,000.00
Token with an amount
```vocs_Code
Copyimport { TokenRow } from '@coinbase/onchainkit/token';
const token = { ... };
;
;
```
EthereumETH1,000.00EthereumETH0.00235
Variations with `hideImage` and `hideSymbol`
```vocs_Code
Copyimport { TokenRow } from '@coinbase/onchainkit/token';
const token = { ... };
;
;
;
```
EthereumEthereumETHEthereum
## Props
[`TokenRowReact`](https://docs.base.org/builderkits/onchainkit/token/types#tokenrowreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/token/token-search#vocs-content)
TokenSearch
On this page
Chevron Right
The `` is a search component with an optional debounce delay.
If you want to handle debounce delay outside of this component, set `delayMs` to `0`.
## Usage
Use [`getTokens`](https://docs.base.org/builderkits/onchainkit/api/get-tokens) and `` combined to search the [`Token`](https://docs.base.org/builderkits/onchainkit/token/types#token).
```vocs_Code
Copyimport { OnchainKitProvider } from '@coinbase/onchainkit';
import { getTokens } from '@coinbase/onchainkit/api';
import { TokenSearch } from '@coinbase/onchainkit/token';
import type { Token } from '@coinbase/onchainkit/token';
...
// example of async onChange handler
const handleChange = useCallback((value: string) => {
async function getData(value) {
const tokens: Token[] = await getTokens({ search: value });
// Do something with tokens here
}
getData(value);
}, []);
...
```
## Props
[`TokenSearchReact`](https://docs.base.org/builderkits/onchainkit/token/types#tokensearchreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/token/token-select-dropdown#vocs-content)
TokenSelectDropdown
On this page
Chevron Right
The `TokenSelectDropdown` component is a dropdown component that selects a token in a given list of tokens.
## Usage
```vocs_Code
Copy
```
Select token
## Props
[`TokenSelectDropdownReact`](https://docs.base.org/builderkits/onchainkit/token/types#tokenselectdropdownreact)
## CSS
```vocs_Code
Copy.ock-scrollbar {
scrollbar-width: thin;
scrollbar-color: #d1d5db #ffffff;
}
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/token/types#vocs-content)
Token
On this page
Chevron Right
## `FormatAmountOptions`
```vocs_Code
Copytype FormatAmountOptions = {
locale?: string; // User locale (default: browser locale)
minimumFractionDigits?: number; // Minimum fraction digits for number decimals (default: 0)
maximumFractionDigits?: number; // Maximum fraction digits for number decimals (default: 0)
};
```
## `FormatAmountResponse`
```vocs_Code
Copytype FormatAmountResponse = string; // See Number.prototype.toLocaleString for more info
```
## `Token`
```vocs_Code
Copytype Token = {
address: Address; // The address of the token contract
chainId: number; // The chain id of the token contract
decimals: number; // The number of token decimals
image: string | null; // A string url of the token logo
name: string;
symbol: string; // A ticker symbol or shorthand, up to 11 characters
};
```
## `TokenChipReact`
```vocs_Code
Copytype TokenChipReact = {
token: Token; // Rendered token
onClick?: (token: Token) => void;
className?: string;
isPressable?: boolean; // Default: true
};
```
## `TokenImageReact`
```vocs_Code
Copytype TokenImageReact = {
className?: string; // Optional additional CSS class to apply to the component
size?: number; // size of the image in px (default: 24)
token: Token;
};
```
## `TokenRowReact`
```vocs_Code
Copytype TokenRowReact = {
amount?: string; // Token amount
className?: string;
hideImage?: boolean;
hideSymbol?: boolean;
onClick?: (token: Token) => void; // Component on click handler
token: Token; // Rendered token
};
```
## `TokenSearchReact`
```vocs_Code
Copytype TokenSearchReact = {
className?: string;
delayMs?: number; // Debounce delay in milliseconds
onChange: (value: string) => void; // Search callback function
};
```
## `TokenSelectButtonReact`
```vocs_Code
Copytype TokenSelectDropdownReact = {
className?: string;
isOpen: boolean; // Determines carot icon direction
onClick: () => void; // Button on click handler
token?: Token; // Selected token
};
```
## `TokenSelectDropdownReact`
```vocs_Code
Copytype TokenSelectDropdownReact = {
options: Token[]; // List of tokens
setToken: (token: Token) => void; // Token setter
token?: Token; // Selected token
};
```
## `TokenSelectModalReact`
```vocs_Code
Copytype TokenSelectModalReact = {
options: Token[]; // List of tokens
setToken: (token: Token) => void; // Token setter
token?: Token; // Selected token
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/transaction/transaction#vocs-content)
Transaction
On this page
Chevron Right
The `` components provide a high-level wrap around the entire transaction flow.
It handles the transaction lifecycle, including gas estimation, fee sponsorship, and status updates.
Before using them, ensure you've completed all [Getting Started steps](https://docs.base.org/builderkits/onchainkit/getting-started).
## Quick start
The `Transaction` component now supports a simplified shorthand version to streamline the integration process for developers. Instead of manually defining each subcomponent and prop, you can render `Transaction` without children, and it will automatically include our suggested implementation — complete with the `TransactionButton` and `TransactionToast` components.
If you'd like more customization, follow the implementation guide for our `Transaction` components below.
```vocs_Code
Copyimport { Transaction } from "@coinbase/onchainkit/transaction"
const calls = [...];
```
Connect Wallet
### Props
[`TransactionReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactionreact)
## Walkthrough
### Add `calls`
Execute one or multiple transactions using the Transaction component. You can pass transactions in either `Call` or `ContractFunctionParameters` format. The component will automatically apply batching logic if the user's wallet supports it.
#### Types
- [`ContractFunctionParameters`](https://github.com/wevm/viem/blob/ce1b8aff4d4523d3a324e500261c8c0867fd35e9/src/types/contract.ts#L188)
- [`Call`](https://docs.base.org/builderkits/onchainkit/transaction/types#call)
TransactionComponents.tsxcalls.ts
File
TransactionComponents.tsx
```vocs_Code
Copyimport { useCallback } from 'react';
import { Avatar, Name } from '@coinbase/onchainkit/identity';
import {
Transaction,
TransactionButton,
TransactionSponsor,
TransactionStatus,
TransactionStatusAction,
TransactionStatusLabel,
} from '@coinbase/onchainkit/transaction';
import type { LifecycleStatus } from '@coinbase/onchainkit/transaction';
import { Wallet, ConnectWallet } from '@coinbase/onchainkit/wallet';
import { useAccount } from 'wagmi';
import { calls } from '@/calls';
export default function TransactionComponents() {
const { address } = useAccount();
const handleOnStatus = useCallback((status: LifecycleStatus) => {
console.log('LifecycleStatus', status);
}, []);
return address ? (
) : (
);
};
```
Connect Wallet
### Listen to `LifecycleStatus`
Take full control of your transactions data with the `LifecycleStatus` object via the `onStatus` prop.
This TypeScript object provides `statusName` and `statusData` to keep you informed.
```vocs_Code
Copy
import type { LifecycleStatus } from '@coinbase/onchainkit/transaction';
// omitted for brevity
const handleOnStatus = useCallback((status: LifecycleStatus) => {
console.log('Transaction status:', status);
}, []);
// omitted for brevity
// Usage in component
```
The Lifecycle Status features seven states for the transaction experience.
```vocs_Code
Copytype LifecycleStatus =
| {
statusName: 'init';
statusData: null;
}
| {
statusName: 'error';
statusData: TransactionError;
}
| {
statusName: 'transactionIdle'; // initial status prior to the mutation function executing
statusData: null;
}
| {
statusName: 'buildingTransaction'; // resolving calls or contracts promise
statusData: null;
}
| {
statusName: 'transactionPending'; // if the mutation is currently executing
statusData: null;
}
| {
statusName: 'transactionLegacyExecuted';
statusData: {
transactionHashList: string[];
};
}
| {
statusName: 'success'; // if the last mutation attempt was successful
statusData: {
transactionReceipts: TransactionReceipt[];
};
};
```
### Sponsor with Paymaster capabilities
To sponsor your transactions with Paymaster capabilities, configure your [`OnchainKitProvider`](https://docs.base.org/builderkits/onchainkit/config/onchainkit-provider) with the appropriate `config.paymaster` URL, then pass `isSponsored={true}` to the `Transaction` component.
Obtain a Paymaster and Bundler endpoint from the [Coinbase Developer Platform](https://portal.cdp.coinbase.com/products/bundler-and-paymaster).

```vocs_Code
Copy
```
Next, pass `isSponsored={true}` to the `Transaction` component.
```vocs_Code
Copy// omitted for brevity
```
### Using `calls` with Promises
`Calls` also accepts asynchronous functions that are resolved on each button click. This can be useful if you're calling an API to retrieve transaction data.
These functions must resolve to `Call[]` or `ContractFunctionParameters[]`.
In the example the calls data will be fetched from api.transaction.com when the user clicks the Transaction Button.
```vocs_Code
Copy
const callsCallback = async () => {
const res = await fetch('api.transaction.com/createTransaction');
const callData = await res.json();
return callData;
}
export default function TransactionWithCalls() {
return (
console.log('Transaction status:', status)}
>
);
}
```
## Components

The components are designed to work together hierarchically. For each component, ensure the following:
- `` \- Serves as the main container for all transaction-related components.
- `` \- Handles the transaction initiation process.
- `` \- Displays information about the sponsorship of transaction gas fees.
- `` \- Contains transaction status information and actions.
- `` \- Displays the current status of the transaction.
- `` \- Provides additional actions based on the transaction status.
- `` \- Displays a toast notification for the transaction status.
- `` \- Displays an icon in the transaction toast notification.
- `` \- Displays the label text in the transaction toast notification.
- `` \- Provides additional actions within the transaction toast notification.
## Component types
- [`TransactionButtonReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactionbuttonreact)
- [`TransactionError`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactionerror)
- [`TransactionDefaultReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactiondefaultreact)
- [`TransactionReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactionreact)
- [`TransactionSponsorReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactionsponsorreact)
- [`TransactionStatusReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactionstatusreact)
- [`TransactionStatusActionReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactionstatusactionreact)
- [`TransactionStatusLabelReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactionstatuslabelreact)
- [`TransactionToastReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactiontoastreact)
- [`TransactionToastActionReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactiontoastactionreact)
- [`TransactionToastIconReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactiontoasticonreact)
- [`TransactionToastLabelReact`](https://docs.base.org/builderkits/onchainkit/transaction/types#transactiontoastlabelreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/transaction/types#vocs-content)
Transaction
On this page
Chevron Right
## `Call`
```vocs_Code
Copytype Call = { to: Hex; data?: Hex; value?: bigint };
```
## `Calls`
```vocs_Code
Copytype Calls = Call[] | Promise | (() => Promise);
```
## `Contracts`
```vocs_Code
Copytype Contracts =
| ContractFunctionParameters[]
| Promise
| (() => Promise);
```
## `LifecycleStatus`
```vocs_Code
Copytype LifecycleStatus =
| {
statusName: 'init';
statusData: null;
}
| {
statusName: 'error';
statusData: TransactionError;
}
| {
statusName: 'transactionIdle'; // initial status prior to the mutation function executing
statusData: null;
}
| {
statusName: 'buildingTransaction'; // resolving calls or contracts promise
statusData: null;
}
| {
statusName: 'transactionPending'; // if the mutation is currently executing
statusData: null;
}
| {
statusName: 'transactionLegacyExecuted';
statusData: {
transactionHashList: Address[];
};
}
| {
statusName: 'success'; // if the last mutation attempt was successful
statusData: {
transactionReceipts: TransactionReceipt[];
};
};
```
## `TransactionButtonReact`
```vocs_Code
Copytype TransactionButtonReact = {
className?: string; // An optional CSS class name for styling the button component.
disabled?: boolean; // A optional prop to disable the submit button
text?: string; // An optional text to be displayed in the button component.
};
```
## `TransactionError`
```vocs_Code
Copytype TransactionError = {
code: string; // The error code representing the type of transaction error.
error: string; // The error message providing details about the transaction error.
message: string; // The error message providing details about the transaction error.
};
```
## `TransactionReact`
```vocs_Code
Copytype TransactionReact = {
calls?: Calls | Contracts | (Call | ContractFunctionParameters)[]; // An array of calls to be made in the transaction.
isSponsored?: boolean; // Whether or not the transaction is sponsored.
/** @deprecated Use `isSponsored` instead. */
capabilities?: WalletCapabilities; // Capabilities that a wallet supports (e.g. paymasters, session keys, etc).
chainId?: number; // The chainId for the transaction.
className?: string; // An optional CSS class name for styling the component.
contracts?: Calls | Contracts | (Call | ContractFunctionParameters)[]; // An array of calls to be made in the transaction.
onError?: (e: TransactionError) => void; // An optional callback function that handles transaction errors.
onStatus?: (lifecycleStatus: LifecycleStatus) => void; // An optional callback function that exposes the component lifecycle state
onSuccess?: (response: TransactionResponse) => void; // An optional callback function that exposes the transaction receipts
} & (
| {
children: ReactNode;
/** An optional prop to disable submit button. Only available when children are not provided. */
disabled?: never;
}
| {
children?: never;
/** An optional prop to disable submit button. Only available when children are not provided. */
disabled?: boolean;
}
);
```
## `TransactionDefaultReact`
```vocs_Code
Copyexport type TransactionDefaultReact = {
disabled?: boolean;
} & Omit;
```
## `TransactionResponse`
```vocs_Code
Copytype TransactionResponse = {
transactionReceipts: TransactionReceipt[]; // An array containing the transaction receipts
};
```
## `TransactionSponsorReact`
```vocs_Code
Copytype TransactionSponsorReact = {
className?: string; // An optional CSS class name for styling the sponsor component.
};
```
## `TransactionStatusReact`
```vocs_Code
Copytype TransactionStatusReact = {
children?: ReactNode; // The child components to be rendered within the status component.
className?: string; // An optional CSS class name for styling the status component.
};
```
## `TransactionStatusActionReact`
```vocs_Code
Copytype TransactionStatusActionReact = {
className?: string; // An optional CSS class name for styling.
};
```
## `TransactionStatusLabelReact`
```vocs_Code
Copytype TransactionStatusLabelReact = {
className?: string; // An optional CSS class name for styling.
};
```
## `TransactionToastReact`
```vocs_Code
Copytype TransactionToastReact = {
children?: ReactNode; // The child components to be rendered within the toast component.
className?: string; // An optional CSS class name for styling the toast component.
durationMs?: number; // An optional value to customize time until toast disappears
position?: 'top-center' | 'top-right' | 'bottom-center' | 'bottom-right'; // An optional position property to specify the toast's position on the screen.
};
```
## `TransactionToastActionReact`
```vocs_Code
Copytype TransactionToastActionReact = {
className?: string; // An optional CSS class name for styling.
};
```
## `TransactionToastIconReact`
```vocs_Code
Copytype TransactionToastIconReact = {
className?: string; // An optional CSS class name for styling.
};
```
## `TransactionToastLabelReact`
```vocs_Code
Copytype TransactionToastLabelReact = {
className?: string; // An optional CSS class name for styling.
};
```
## `WalletCapabilities`
```vocs_Code
Copytype WalletCapabilities = {
paymasterService?: PaymasterService;
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/wallet/is-valid-aa-entrypoint#vocs-content)
isValidAAEntrypoint
On this page
Chevron Right
The `isValidAAEntrypoint` utility is designed to verify the Account-Abstraction entrypoint before sponsoring a transaction.
## Usage
codereturn value
code
```vocs_Code
Copyimport { isValidAAEntrypoint } from '@coinbase/onchainkit/wallet';
const AAImplementationAddress = '0x123';
const isValid = isValidAAEntrypoint({ entrypoint: AAImplementationAddress });
if (isValid) {
console.log('The entrypoint is valid.');
} else {
console.log('Invalid entrypoint.');
}
```
## Returns
`boolean` \- Returns `true` if the account abstraction entrypoint address is v06, otherwise `false`.
## Parameters
[`isValidAAEntrypointOptions`](https://docs.base.org/builderkits/onchainkit/wallet/types#isvalidaaentrypointoptions)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/wallet/is-wallet-a-coinbase-smart-wallet#vocs-content)
isWalletACoinbaseSmartWallet
On this page
Chevron Right
The `isWalletACoinbaseSmartWallet` utility is designed to verify if a given sender address is a Smart Wallet proxy with the expected implementation before sponsoring a transaction.
## Usage
codereturn value
code
```vocs_Code
Copyimport { isWalletACoinbaseSmartWallet } from '@coinbase/onchainkit/wallet';
import { http } from 'viem';
import { baseSepolia } from 'viem/chains';
import type { UserOperation } from 'permissionless';
import { type PublicClient, createPublicClient } from 'viem';
export const publicClient = createPublicClient({
chain: baseSepolia,
transport: http(),
});
const userOperation = { sender: '0x123' } as UserOperation<'v0.6'>;
if (isWalletACoinbaseSmartWallet({ client: publicClient, userOp: userOperation })) {
console.log('The sender address is a valid smart wallet proxy.');
} else {
console.log('The sender address is not a valid smart wallet proxy.');
}
```
## Returns
[`IsWalletACoinbaseSmartWalletResponse`](https://docs.base.org/builderkits/onchainkit/wallet/types#iswalletacoinbasesmartwalletresponse)
## Parameters
[`isWalletACoinbaseSmartWalletOptions`](https://docs.base.org/builderkits/onchainkit/wallet/types#iswalletacoinbasesmartwalletoptions)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/wallet/types#vocs-content)
Wallet
On this page
Chevron Right
## `ConnectWalletReact`
```vocs_Code
Copytype ConnectWalletReact = {
children?: React.ReactNode; // Children can be utilized to display customized content when the wallet is connected.
className?: string; // Optional className override for button element
text?: string; // Optional text override for button. Note: Prefer using `ConnectWalletText` component instead as this will be deprecated in a future version.
onConnect?: () => void; // Optional callback function that is called when the wallet is connected. Can be used to trigger SIWE prompts or other actions.
};
```
## `IsValidAAEntrypointOptions`
```vocs_Code
Copyexport type IsValidAAEntrypointOptions = {
entrypoint: string;
};
```
## `IsWalletACoinbaseSmartWalletOptions`
```vocs_Code
Copyexport type IsWalletACoinbaseSmartWalletOptions = {
client: PublicClient;
userOp: UserOperation<'v0.6'>;
};
```
## `IsWalletACoinbaseSmartWalletResponse`
```vocs_Code
Copyexport type IsWalletACoinbaseSmartWalletResponse =
| { isCoinbaseSmartWallet: true }
| { isCoinbaseSmartWallet: false; error: string; code: string };
```
## `WalletContextType`
```vocs_Code
Copytype WalletContextType = {
address?: Address | null; // The Ethereum address to fetch the avatar and name for.
chain?: Chain; // Optional chain for domain resolution
isConnectModalOpen: boolean;
setIsConnectModalOpen: Dispatch>;
isSubComponentOpen: boolean;
setIsSubComponentOpen: Dispatch>;
isSubComponentClosing: boolean;
setIsSubComponentClosing: Dispatch>;
handleClose: () => void;
connectRef: React.RefObject;
showSubComponentAbove: boolean;
alignSubComponentRight: boolean;
};
```
## `WalletReact`
```vocs_Code
Copytype WalletReact = {
children: React.ReactNode;
className?: string;
} & (
| { draggable?: true; draggableStartingPosition?: { x: number; y: number } }
| { draggable?: false; draggableStartingPosition?: never }
); // discriminated union to allow for optional draggable and draggableStartingPosition
```
## `WalletDropdownBasenameReact`
```vocs_Code
Copytype WalletDropdownBasenameReact = {
className?: string; // Optional className override for the element
};
```
## `WalletDropdownReact`
```vocs_Code
Copytype WalletDropdownReact = {
children: React.ReactNode;
className?: string; // Optional className override for top div element
};
```
## `WalletDropdownDisconnectReact`
```vocs_Code
Copyexport type WalletDropdownDisconnectReact = {
className?: string; // Optional className override for the element
text?: string; // Optional text override for the button
};
```
## `WalletDropdownFundLinkReact`
```vocs_Code
Copyexport type WalletDropdownFundLinkReact = {
className?: string; // Optional className override for the element
icon?: ReactNode; // Optional icon override
openIn?: 'popup' | 'tab'; // Whether to open the funding flow in a tab or a popup window
popupSize?: 'sm' | 'md' | 'lg'; // Size of the popup window if `openIn` is set to `popup`
rel?: string; // Specifies the relationship between the current document and the linked document
target?: string; // Where to open the target if `openIn` is set to tab
text?: string; // Optional text override
};
```
## `WalletDropdownLinkReact`
```vocs_Code
Copyexport type WalletDropdownLinkReact = {
children: string;
className?: string; // Optional className override for the element
href: string;
icon?: 'wallet' & ReactNode;
rel?: string;
target?: string;
};
```
## `WalletAdvancedReact`
```vocs_Code
Copyexport type WalletAdvancedReact = {
children: React.ReactNode;
swappableTokens?: Token[];
};
```
## `WalletAdvancedContextType`
```vocs_Code
Copyexport type WalletAdvancedContextType = {
showSwap: boolean;
setShowSwap: Dispatch>;
isSwapClosing: boolean;
setIsSwapClosing: Dispatch>;
showQr: boolean;
setShowQr: Dispatch>;
isQrClosing: boolean;
setIsQrClosing: Dispatch>;
tokenBalances: PortfolioTokenWithFiatValue[] | undefined;
portfolioFiatValue: number | undefined;
isFetchingPortfolioData: boolean;
portfolioDataUpdatedAt: number | undefined;
refetchPortfolioData: () => Promise<
QueryObserverResult
>;
animations: {
container: string;
content: string;
};
};
```
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/wallet/wallet-dropdown-basename#vocs-content)
WalletDropdownBasename
On this page
Chevron Right
The `WalletDropdownBasename` component adds a [Basename](https://www.base.org/names) tab to the Wallet Component. This tab serves two purposes:
1. For users with a Basename: It provides a link to their Basename profile page.
2. For users without a Basename: It provides a link to a page where they can create one.
This component enhances the wallet interface by providing easy access to Basename functionality, whether for viewing an existing profile or setting up a new one.
## Usage
```vocs_Code
Copyimport {
Address,
Avatar,
Name,
Identity,
EthBalance,
} from '@coinbase/onchainkit/identity';
import { color } from '@coinbase/onchainkit/theme';
import {
ConnectWallet,
Wallet,
WalletDropdown,
WalletDropdownBasename,
WalletDropdownDisconnect,
} from '@coinbase/onchainkit/wallet';
export function WalletComponents() {
return (
);
}
```
Log In
### Override styles
You can override component styles using `className`.
```vocs_Code
Copy// omitted for brevity
```
Log In
## Props
- [`WalletDropdownBasenameReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdownbasenamereact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/wallet/wallet-dropdown-disconnect#vocs-content)
WalletDropdownDisconnect
On this page
Chevron Right
The `WalletDropdownDisconnect` component is used to disconnect the wallet from the application.
## Usage
```vocs_Code
Copyimport {
Address,
Avatar,
Name,
Identity,
EthBalance,
} from '@coinbase/onchainkit/identity';
import { color } from '@coinbase/onchainkit/theme';
import {
ConnectWallet,
Wallet,
WalletDropdown,
WalletDropdownDisconnect,
} from '@coinbase/onchainkit/wallet';
export function WalletComponents() {
return (
);
}
```
Connect Wallet
### Override styles
You can override component styles using `className`.
```vocs_Code
Copy// omitted for brevity
```
Log In
### Override text
You can override component text using `text`.
```vocs_Code
Copy// omitted for brevity
```
Log In
## Props
- [`WalletDropdownDisconnectReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdowndisconnectreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/wallet/wallet-dropdown-fund-link#vocs-content)
WalletDropdownFundLink
On this page
Chevron Right
The `WalletDropdownFundLink` works just like the [`FundButton`](https://docs.base.org/builderkits/onchainkit/fund/fund-button) except that it's inside your wallet
dropdown menu.
If your user connects a Coinbase Smart Wallet, it provides an easy way to access the Coinbase Smart Wallet
[Fund](https://keys.coinbase.com/fund) flow. Users will be able to buy and receive crypto, or use their Coinbase
balances onchain with [Magic Spend](https://www.smartwallet.dev/guides/magic-spend).
If your user connects any other EOA wallet, it provides an easy way to access [Coinbase Onramp](https://docs.cdp.coinbase.com/onramp/docs/welcome/)
where your users will also be able to buy crypto using a fiat payment method, or transfer existing crypto from their
Coinbase account.
## Usage
```vocs_Code
Copyimport {
ConnectWallet,
Wallet,
WalletDropdown,
WalletDropdownDisconnect,
WalletDropdownFundLink,
} from '@coinbase/onchainkit/wallet';
import {
Address,
Avatar,
Name,
Identity,
EthBalance,
} from '@coinbase/onchainkit/identity';
import { color } from '@coinbase/onchainkit/theme';
export function WalletComponents() {
return (
);
}
```
Connect Wallet
### Override text
You can override component text using the `text` prop.
```vocs_Code
Copy
```
Connect Wallet
### Override icon
You can override the icon using the `icon` prop.
```vocs_Code
Copy} />
```
Connect Wallet
### Customizing the popup size
You're able to customize the size of the popup window using the `popupSize` prop. Valid values are `sm`, `md`, and `lg`.
```vocs_Code
Copy
```
Connect Wallet
### Override default behavior
You can override default link behavior by using the `openIn` prop. Valid values are `popup` and `tab`.
```vocs_Code
Copy
```
Connect Wallet
### Override funding URL
You can override the default URL by using the `fundingUrl` prop.
```vocs_Code
Copy
```
Connect Wallet
## Props
- [`WalletDropdownFundLinkReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdownfundlinkreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/wallet/wallet-dropdown-link#vocs-content)
WalletDropdownLink
On this page
Chevron Right
The `WalletDropdownLink` component creates customizable, interactive links within the wallet dropdown menu.
## Usage
```vocs_Code
Copyimport {
Address,
Avatar,
Name,
Identity,
EthBalance,
} from '@coinbase/onchainkit/identity';
import { color } from '@coinbase/onchainkit/theme';
import {
ConnectWallet,
Wallet,
WalletDropdown,
WalletDropdownLink,
WalletDropdownDisconnect,
} from '@coinbase/onchainkit/wallet';
export function WalletComponents() {
return (
Wallet
);
}
```
Connect Wallet
### Custom link
Add a custom link to the wallet dropdown menu, allowing users to navigate to external resources directly from the wallet interface.
```vocs_Code
Copy// omitted for brevity
Base.org
```
Connect Wallet
### Custom children components
Accepts React children, enabling the use of custom elements, styled text, icons, and complex components.
This allows for diverse customizations, including complex layouts and conditional rendering based on your app's state.
```vocs_Code
Copy// omitted for brevity
Profile 🔵
```
Connect Wallet
### Override styles
You can override component styles using className.
```vocs_Code
Copy// omitted for brevity
Wallet
```
Connect Wallet
## Props
See the [types](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdownlinkreact) for more details.
[WalletDropdownLinkReact](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdownlinkreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/wallet/wallet-island#vocs-content)
WalletIsland
On this page
Chevron Right

`WalletIsland` is our flagship implementation of the new advanced Wallet
components, providing an advanced Wallet interface for users, including:
- a QR code for receiving funds
- a link to buy crypto with fiat
- a swap interface
- the user's token portfolio
- a button that moves anywhere on the screen
Designed for desktop experiences, `WalletIsland` component gives
users a seamless way to interact with their wallet and manage their assets.
Before using these components, ensure you've completed all [Getting Started steps](https://docs.base.org/builderkits/onchainkit/getting-started).
## Quick start
Advanced `Wallet` has two default implementations:
- `WalletAdvancedDefault`
- `WalletIsland`
`WalletAdvancedDefault` provides the user with an advanced wallet
interface, anchored to the screen like our standard `Wallet` component.
`WalletIsland` provides the same powerful interface, while enabling
the user to drag the component around the window.
If you'd like more customization, follow the implementation guide below.
```vocs_Code
Copyimport { WalletAdvancedDefault } from '@coinbase/onchainkit/wallet';
import { WalletIsland } from '@coinbase/onchainkit/wallet';
<>
>
```
You will see two Wallet buttons below. Right below is `WalletAdvancedDefault`.
This version will stay anchored to its current position.
`WalletIsland` is in the bottom-right corner of the window. Feel free to drag
it around.
Connect Wallet
Portfolio
While this behavior is more noticeable with the `WalletIsland` component, you'll
notice that for both components, the `WalletAdvanced` container will appear in
different positions depending on the component's location in the window:
- If there is sufficient space to the right, it will be left-aligned.
- If there is not enough space to the right, it will be right-aligned.
- If there is enough space below, it will open below.
- If there is not enough space below, it will open above.
## Configuring `WalletIsland` and advanced `Wallet`
Experience the magic by simply dropping in `` and advanced `Wallet`
components, and watch your component seamlessly come to life.
As with [`WalletDefault`](https://docs.base.org/builderkits/onchainkit/wallet/wallet) , `WalletAdvancedDefault` leverages
several [``](https://docs.base.org/builderkits/onchainkit/identity/identity) components like [``](https://docs.base.org/builderkits/onchainkit/identity/avatar),
[``](https://docs.base.org/builderkits/onchainkit/identity/name), and [``](https://docs.base.org/builderkits/onchainkit/identity/address).
We've introduces several advanced wallet components, including
``, ``, and
``.
```vocs_Code
Copyimport {
ConnectWallet,
Wallet,
WalletDropdown,
WalletAdvancedAddressDetails,
WalletAdvancedTokenHoldings,
WalletAdvancedTransactionActions,
WalletAdvancedWalletActions,
} from '@coinbase/onchainkit/wallet';
import { Address, Avatar, Name, Identity } from '@coinbase/onchainkit/identity';
import { color } from '@coinbase/onchainkit/theme';
export function YourWalletAdvanced() {
return (
);
}
```
Connect Wallet
When customizing your advanced `Wallet` implementation, use the `draggable` prop on
`Wallet` to enable draggability. `draggable` defaults to `false`, but
when `draggable` is set to `true`, you can also set a `draggableStartingPosition` prop to
specify the initial position of your `WalletIsland`.
```vocs_Code
Copyimport {
ConnectWallet,
Wallet,
WalletDropdown,
WalletAdvancedAddressDetails,
WalletAdvancedTokenHoldings,
WalletAdvancedTransactionActions,
WalletAdvancedWalletActions,
} from '@coinbase/onchainkit/wallet';
import { Address, Avatar, Name, Identity } from '@coinbase/onchainkit/identity';
import { color } from '@coinbase/onchainkit/theme';
export function DraggableWalletAdvanced() {
return (
);
}
```
## Customize Connect button text and style
Each OnchainKit component offers the flexibility to customize `className`
and adjust the style of the React components it represents.
Explore the options for customizing the Connect button text and style [here](https://docs.base.org/builderkits/onchainkit/wallet/wallet#customize-connect-button-text-and-style).
## Using Wallet Modal

Wallet modal offers users multiple wallet connection options. Explore these options
[here](https://docs.base.org/builderkits/onchainkit/wallet/wallet-modal).
## Example usage
### Usage with Sign In With Ethereum (SIWE)
To use [Sign In With Ethereum (SIWE)](https://docs.login.xyz/general-information/siwe-overview) with OnchainKit,
check out our [SIWE example](https://docs.base.org/builderkits/onchainkit/wallet/wallet#usage-with-sign-in-with-ethereum-siwe).
## Components
The components are designed to work together hierarchically. For each component, ensure the following:
- `` \- Serves as the main container for all wallet-related components.
- `` \- Contains additional wallet information and options. Place inside the `` component.
- `` \- Provides wallet actions like View Transaction History, view QR Code, and Disconnect wallet. Place inside the `` component.
- `` \- Displays user address, avatar, and portfolio balance in fiat. Place inside the `` component.
- `` \- Buttons for buying crypto with fiat, transferring crypto, and swapping. Place inside the `` component.
- `` \- Displays token balances and their value in fiat. Place inside the `` component.
- `` \- Handles the wallet connection process. Place child components inside to customize the connect button appearance.
- `` \- Enables a wallet aggregation experience.
- `` \- Displays user identity information. Place inside `` for a complete profile view.
- `` \- Displays the user's Basename within the dropdown.
- `` \- Creates a custom link within the dropdown. Use the `icon` prop to add an icon, and `href` to specify the destination.
- `` \- Provides a disconnect option within the dropdown.
Additional components for customizing the wallet interface include:
- `` \- Displays the user's avatar image.
- `` \- Shows the user's name or ENS.
- `` \- Can be used to display additional user status or information.
- `` \- Shows the user's wallet address.
- `` \- Displays the user's ETH balance.
The Wallet component automatically handles the wallet connection state and updates the UI accordingly.
You need to wrap your application or relevant part of it with these components
to provide a complete wallet interaction experience.
## Component types
- [`WalletReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletreact)
- [`ConnectWalletReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#connectwalletreact)
- [`WalletDropdownReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdownreact)
- [`WalletDropdownBasenameReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdownbasenamereact)
- [`WalletDropdownDisconnectReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdowndisconnectreact)
- [`WalletDropdownLinkReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdownlinkreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all
[Skip to content](https://docs.base.org/builderkits/onchainkit/wallet/wallet-modal#vocs-content)
WalletModal
On this page
Chevron Right

`WalletModal` offers users multiple wallet connection options. The modal automatically appears when users click the `ConnectWallet` component and provides several connection paths:
1. Quickly create a new smart wallet for new users
2. Coinbase Wallet connection (supporting both smart wallets and EOA)
3. MetaMask connection
4. Phantom connection
5. Rabby, Frame, and Trust Wallet connections (optional)
## Walkthrough
### Configure the `OnchainKitProvider` with modal settings:
File
providers.tsx
```vocs_Code
Copy
{children}
```
### Use the `ConnectWallet` component in your UI:
File
App.tsx
```vocs_Code
Copy
```
## Components
The Wallet Modal components are designed to work together hierarchically:
- `` \- Configures the modal settings and appearance
- `` \- Triggers the modal to open when clicked
- `` \- The modal interface itself, containing:
- Smart wallet creation flow
- Coinbase Wallet connection
- MetaMask connection
- Phantom connection
- Rabby, Trust, and Frame Wallet connections (if enabled)
- Terms and privacy policy links
The modal automatically handles:
- Wallet connection states
- Error handling
- Mobile/desktop responsive behavior
- Theme customization
- Terms/privacy policy display
## Additional Wallet Support
By default, the wallet modal includes Coinbase Wallet, MetaMask, and Phantom as connection options. You can enable additional wallet support by configuring the `supportedWallets` object in the `OnchainKitProvider`:
```vocs_Code
Copy
{children}
```
Each wallet can be individually enabled or disabled as needed. If no `supportedWallets` configuration is provided, the additional wallets will be disabled by default.
::::
[Skip to content](https://docs.base.org/builderkits/onchainkit/wallet/wallet#vocs-content)
Wallet
On this page
Chevron Right
The `` components provide an interface for users to connect their
Smart Wallet with their identity information like Basename and ETH balance.
It features built-in polished user experiences for both web and mobile web,
making it incredibly easy to enhance with drop-in components.
Before using them, ensure you've completed all [Getting Started steps](https://docs.base.org/builderkits/onchainkit/getting-started).
## Quick start
To streamline the integration process and integrate a simplified version of the `Wallet` component, you can render the `Wallet` component without children.
If you'd like more customization, follow the implementation guide for our `Wallet` component below where you can manually define each subcomponent and prop.
```vocs_Code
Copyimport { Wallet } from '@coinbase/onchainkit/wallet';
```
Connect Wallet
## Walkthrough
### Set up your wallet connections
Kick off your wallet connection setup by configuring the `wagmi` provider.
And make sure to update the `appName` as that will be displayed to
the user when they connect their wallet.
```vocs_Code
Copyimport { ReactNode } from 'react';
import { WagmiProvider, createConfig, http } from 'wagmi';
import { baseSepolia } from 'wagmi/chains';
import { coinbaseWallet } from 'wagmi/connectors';
const wagmiConfig = createConfig({
chains: [baseSepolia],
connectors: [\
coinbaseWallet({\
appName: 'onchainkit',\
}),\
],
ssr: true,
transports: {
[baseSepolia.id]: http(),
},
});
function App({ children }: { children: ReactNode }) {
return {children};
}
```
### Drop in the `` components
Experience the magic by simply dropping in the `` component
and watch it seamlessly come to life.
Additionally, you can see the [``](https://docs.base.org/builderkits/onchainkit/identity/identity) components
like [``](https://docs.base.org/builderkits/onchainkit/identity/avatar), [``](https://docs.base.org/builderkits/onchainkit/identity/name),
and [``](https://docs.base.org/builderkits/onchainkit/identity/address) are used in a composable way.
Explore their documentation pages to discover various customization options.
```vocs_Code
Copyimport {
ConnectWallet,
Wallet,
WalletDropdown,
WalletDropdownDisconnect,
} from '@coinbase/onchainkit/wallet';
import {
Address,
Avatar,
Name,
Identity,
} from '@coinbase/onchainkit/identity';
import { color } from '@coinbase/onchainkit/theme';
export function WalletComponents() {
return (
);
}
```
Connect Wallet
### Drop in pre-made wallet components
Expand the user experience with pre-made components like [``](https://docs.base.org/builderkits/onchainkit/wallet/wallet-dropdown-link),
[``](https://docs.base.org/builderkits/onchainkit/wallet/wallet-dropdown-basename),
[``](https://docs.base.org/builderkits/onchainkit/wallet/wallet-dropdown-fund-link),
or ``, to help you build a seamless wallet experience for your users.
The `` is highly versatile and will likely be your go-to choice
for adding more links to the dropdown, connecting your users to various pages of your onchain app.
```vocs_Code
Copyimport {
ConnectWallet,
Wallet,
WalletDropdown,
WalletDropdownBasename,
WalletDropdownFundLink,
WalletDropdownLink,
WalletDropdownDisconnect,
} from '@coinbase/onchainkit/wallet';
import {
Address,
Avatar,
Name,
Identity,
EthBalance,
} from '@coinbase/onchainkit/identity';
// omitted for brevity
Wallet
```
Connect Wallet
## Customize Connect button text and style
Each OnchainKit component offers the flexibility to customize `className`
and adjust the style of the React components it represents.
Customize the connect wallet text by using directly the `` component.
```vocs_Code
Copy// omitted for brevity
Log In
Wallet
```
Log In
## Example usage
### Usage with Sign In With Ethereum (SIWE)
To use [Sign In With Ethereum (SIWE)](https://docs.login.xyz/general-information/siwe-overview) with OnchainKit, you can use the `onConnect` prop in the `` component. This will trigger the SIWE prompt when the user connects their wallet.
```vocs_Code
Copyimport { ConnectWallet } from '@coinbase/onchainkit/wallet';
import { base } from 'wagmi/chains';
import { createSiweMessage } from 'viem/siwe'
import { useSignMessage } from 'wagmi';
const message = createSiweMessage({
address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
chainId: base.id,
domain: 'example.com',
nonce: 'foobarbaz',
uri: 'https://example.com/path',
version: '1',
})
export function WalletComponents() {
const { signMessage } = useSignMessage();
return (
{signMessage({ message })}} />
);
}
```
## Components
The components are designed to work together hierarchically. For each component, ensure the following:
- `` \- Serves as the main container for all wallet-related components.
- `` \- Handles the wallet connection process. Place child components inside to customize the connect button appearance.
- `` \- Enables a wallet aggregation experience.
- `` \- Contains additional wallet information and options. Place inside the `` component.
- `` \- Displays user identity information. Place inside `` for a complete profile view.
- `` \- Displays the user's Basename within the dropdown.
- `` \- Creates a custom link within the dropdown. Use the `icon` prop to add an icon, and `href` to specify the destination.
- `` \- Provides a disconnect option within the dropdown.
Additional components for customizing the wallet interface include:
- `` \- Displays the user's avatar image.
- `` \- Shows the user's name or ENS.
- `` \- Can be used to display additional user status or information.
- `` \- Shows the user's wallet address.
- `` \- Displays the user's ETH balance.
The Wallet component automatically handles the wallet connection state and updates the UI accordingly.
You need to wrap your application or relevant part of it with these components
to provide a complete wallet interaction experience.
## Component types
- [`WalletReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletreact)
- [`ConnectWalletReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#connectwalletreact)
- [`WalletDropdownReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdownreact)
- [`WalletDropdownBasenameReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdownbasenamereact)
- [`WalletDropdownDisconnectReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdowndisconnectreact)
- [`WalletDropdownLinkReact`](https://docs.base.org/builderkits/onchainkit/wallet/types#walletdropdownlinkreact)
We use cookies and similar technologies on our websites to enhance and tailor your experience, analyze our traffic, and for security and marketing. You can choose not to allow some type of cookies by clicking Manage Settings. For more information see our [Cookie Policy](https://docs.base.org/cookie-policy).
Manage settings
Accept all