onchainkit

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OnchainKit

OnchainKit

Build production-ready onchain applications using Coinbase's comprehensive React component library and TypeScript utilities.
使用Coinbase全面的React组件库与TypeScript工具构建可投入生产环境的链上应用。

Overview

概述

OnchainKit provides ready-to-use, full-stack components that abstract blockchain complexity, making it easy to build onchain applications without deep blockchain knowledge. It offers AI-friendly components that work automatically on Base, requires no backend infrastructure, and provides cost-effective transactions (< $0.01 fees).
OnchainKit提供开箱即用的全栈组件,抽象了区块链的复杂性,无需深厚的区块链知识即可轻松构建链上应用。它提供适配AI的组件,可在Base链上自动运行,无需后端基础设施,且交易成本低廉(手续费低于0.01美元)。

Quick Start

快速开始

New Project Setup

新项目搭建

bash
undefined
bash
undefined

Create a new onchain app with all batteries included

Create a new onchain app with all batteries included

scripts/create-onchain-app.py <project-name>
scripts/create-onchain-app.py <project-name>

Verify setup

Verify setup

scripts/validate-setup.py
undefined
scripts/validate-setup.py
undefined

Add to Existing Project

添加至现有项目

bash
npm install @coinbase/onchainkit
bash
npm install @coinbase/onchainkit

Setup configuration and providers

Setup configuration and providers

scripts/setup-environment.py
undefined
scripts/setup-environment.py
undefined

Core Capabilities

核心功能

1. Wallet Connection & Management

1. 钱包连接与管理

Connect users to their crypto wallets with minimal code:
tsx
import { Wallet, ConnectWallet } from '@coinbase/onchainkit/wallet';

function WalletConnection() {
  return (
    <Wallet>
      <ConnectWallet />
    </Wallet>
  );
}
Use cases:
  • Wallet connection flows
  • Display wallet status
  • Manage connection state
  • Handle multiple wallets
Reference: references/wallet-integration.md
只需少量代码即可将用户连接至他们的加密钱包:
tsx
import { Wallet, ConnectWallet } from '@coinbase/onchainkit/wallet';

function WalletConnection() {
  return (
    <Wallet>
      <ConnectWallet />
    </Wallet>
  );
}
使用场景:
  • 钱包连接流程
  • 钱包状态展示
  • 连接状态管理
  • 多钱包支持
参考: references/wallet-integration.md

2. Identity Display

2. 身份展示

Show blockchain identities with ENS names, avatars, and verification badges:
tsx
import { Identity, Avatar, Name, Badge } from '@coinbase/onchainkit/identity';

function UserProfile({ address }) {
  return (
    <Identity address={address}>
      <Avatar />
      <Name />
      <Badge />
    </Identity>
  );
}
Reference: references/identity-components.md
通过ENS名称、头像和验证徽章展示区块链身份:
tsx
import { Identity, Avatar, Name, Badge } from '@coinbase/onchainkit/identity';

function UserProfile({ address }) {
  return (
    <Identity address={address}>
      <Avatar />
      <Name />
      <Badge />
    </Identity>
  );
}
参考: references/identity-components.md

3. Token Operations

3. 代币操作

Handle token swaps, purchases, and transfers:
tsx
import { Swap, SwapAmountInput, SwapButton } from '@coinbase/onchainkit/swap';

function TokenSwap() {
  return (
    <Swap>
      <SwapAmountInput />
      <SwapButton />
    </Swap>
  );
}
Supported operations:
  • Token swaps (any ERC-20)
  • Token purchases with fiat
  • Balance displays
  • Price feeds
Reference: references/token-operations.md
处理代币兑换、购买与转账:
tsx
import { Swap, SwapAmountInput, SwapButton } from '@coinbase/onchainkit/swap';

function TokenSwap() {
  return (
    <Swap>
      <SwapAmountInput />
      <SwapButton />
    </Swap>
  );
}
支持的操作:
  • 代币兑换(所有ERC-20代币)
  • 法币购买代币
  • 余额展示
  • 价格馈送
参考: references/token-operations.md

4. Transaction Building

4. 交易构建

Create and execute blockchain transactions:
tsx
import { Transaction, TransactionButton } from '@coinbase/onchainkit/transaction';

function SendTransaction({ calls }) {
  return (
    <Transaction calls={calls}>
      <TransactionButton />
    </Transaction>
  );
}
Reference: references/transactions.md
创建并执行区块链交易:
tsx
import { Transaction, TransactionButton } from '@coinbase/onchainkit/transaction';

function SendTransaction({ calls }) {
  return (
    <Transaction calls={calls}>
      <TransactionButton />
    </Transaction>
  );
}
参考: references/transactions.md

5. Payment Processing

5. 支付处理

Build checkout flows and payment processing:
tsx
import { Checkout, CheckoutButton } from '@coinbase/onchainkit/checkout';

function PaymentFlow() {
  return (
    <Checkout>
      <CheckoutButton />
    </Checkout>
  );
}
Reference: references/payments.md
构建结账流程与支付处理系统:
tsx
import { Checkout, CheckoutButton } from '@coinbase/onchainkit/checkout';

function PaymentFlow() {
  return (
    <Checkout>
      <CheckoutButton />
    </Checkout>
  );
}
参考: references/payments.md

6. NFT Integration

6. NFT集成

Display, mint, and manage NFTs:
tsx
import { NFTCard } from '@coinbase/onchainkit/nft';

function NFTDisplay({ contract, tokenId }) {
  return <NFTCard contract={contract} tokenId={tokenId} />;
}
Reference: references/nft-integration.md
展示、铸造与管理NFT:
tsx
import { NFTCard } from '@coinbase/onchainkit/nft';

function NFTDisplay({ contract, tokenId }) {
  return <NFTCard contract={contract} tokenId={tokenId} />;
}
参考: references/nft-integration.md

Common Workflows

常见工作流

Setting Up a Complete App

搭建完整应用

  1. Initialize project with
    create-onchain-app.py
  2. Configure providers using setup templates
  3. Add wallet connection with Wallet components
  4. Implement core features (swap, buy, identity)
  5. Test and deploy with validation scripts
  1. 初始化项目:使用
    create-onchain-app.py
  2. 配置提供者:使用设置模板
  3. 添加钱包连接:使用Wallet组件
  4. 实现核心功能(兑换、购买、身份)
  5. 测试与部署:使用验证脚本

Building a Token Swap App

构建代币兑换应用

  1. Start with swap app template from
    assets/templates/swap-app/
  2. Configure token lists and supported chains
  3. Add wallet connection flow
  4. Implement swap interface
  5. Add transaction confirmations
  1. assets/templates/swap-app/
    获取兑换应用模板
  2. 配置代币列表与支持的链
  3. 添加钱包连接流程
  4. 实现兑换界面
  5. 添加交易确认功能

Creating an NFT Marketplace

创建NFT市场

  1. Use NFT template from
    assets/templates/nft-mint/
  2. Set up NFT contract integration
  3. Build minting interface
  4. Add payment processing
  5. Implement collection browsing
  1. 使用
    assets/templates/nft-mint/
    中的NFT模板
  2. 设置NFT合约集成
  3. 构建铸造界面
  4. 添加支付处理
  5. 实现藏品浏览功能

Configuration & Setup

配置与设置

Environment Variables

环境变量

bash
undefined
bash
undefined

Required for API access

Required for API access

NEXT_PUBLIC_CDP_API_KEY="your-api-key" NEXT_PUBLIC_WC_PROJECT_ID="your-walletconnect-id"
NEXT_PUBLIC_CDP_API_KEY="your-api-key" NEXT_PUBLIC_WC_PROJECT_ID="your-walletconnect-id"

Optional configurations

Optional configurations

NEXT_PUBLIC_CHAIN_ID="8453" # Base mainnet

**Reference:** [references/configuration.md](references/configuration.md)
NEXT_PUBLIC_CHAIN_ID="8453" # Base mainnet

**参考:** [references/configuration.md](references/configuration.md)

Provider Setup

提供者设置

OnchainKit requires proper React provider configuration:
tsx
import { OnchainKitProvider } from '@coinbase/onchainkit';
import { WagmiProvider } from 'wagmi';

function App() {
  return (
    <WagmiProvider config={wagmiConfig}>
      <OnchainKitProvider
        apiKey={process.env.NEXT_PUBLIC_CDP_API_KEY}
        chain={base}
      >
        {/* Your app components */}
      </OnchainKitProvider>
    </WagmiProvider>
  );
}
OnchainKit需要正确配置React提供者:
tsx
import { OnchainKitProvider } from '@coinbase/onchainkit';
import { WagmiProvider } from 'wagmi';

function App() {
  return (
    <WagmiProvider config={wagmiConfig}>
      <OnchainKitProvider
        apiKey={process.env.NEXT_PUBLIC_CDP_API_KEY}
        chain={base}
      >
        {/* Your app components */}
      </OnchainKitProvider>
    </WagmiProvider>
  );
}

Component Patterns

组件模式

Progressive Enhancement

渐进式增强

Start simple, add features as needed:
tsx
// Basic wallet connection
<ConnectWallet />

// Enhanced with custom styling
<ConnectWallet className="custom-wallet-button" />

// Full wallet interface with status
<Wallet>
  <ConnectWallet />
  <WalletDropdown>
    <Identity />
    <WalletDropdownDisconnect />
  </WalletDropdown>
</Wallet>
从简单功能开始,按需添加特性:
tsx
// Basic wallet connection
<ConnectWallet />

// Enhanced with custom styling
<ConnectWallet className="custom-wallet-button" />

// Full wallet interface with status
<Wallet>
  <ConnectWallet />
  <WalletDropdown>
    <Identity />
    <WalletDropdownDisconnect />
  </WalletDropdown>
</Wallet>

Composable Architecture

可组合架构

Mix and match components for custom workflows:
tsx
function CustomApp() {
  return (
    <div>
      {/* User identity */}
      <Identity address={address}>
        <Avatar />
        <Name />
      </Identity>
      
      {/* Token operations */}
      <Swap>
        <SwapAmountInput />
        <SwapButton />
      </Swap>
      
      {/* Payment processing */}
      <Checkout>
        <CheckoutButton />
      </Checkout>
    </div>
  );
}
混合搭配组件以实现自定义工作流:
tsx
function CustomApp() {
  return (
    <div>
      {/* User identity */}
      <Identity address={address}>
        <Avatar />
        <Name />
      </Identity>
      
      {/* Token operations */}
      <Swap>
        <SwapAmountInput />
        <SwapButton />
      </Swap>
      
      {/* Payment processing */}
      <Checkout>
        <CheckoutButton />
      </Checkout>
    </div>
  );
}

Best Practices

最佳实践

Performance

性能

  • Use component-level imports:
    import { Wallet } from '@coinbase/onchainkit/wallet'
  • Implement proper loading states
  • Cache API responses appropriately
  • Optimize for mobile experiences
  • 使用组件级导入:
    import { Wallet } from '@coinbase/onchainkit/wallet'
  • 实现合适的加载状态
  • 合理缓存API响应
  • 针对移动端体验优化

Security

安全

  • Never expose private keys in client code
  • Validate all transaction parameters
  • Use official OnchainKit providers
  • Implement proper error boundaries
  • 切勿在客户端代码中暴露私钥
  • 验证所有交易参数
  • 使用官方OnchainKit提供者
  • 实现合适的错误边界

User Experience

用户体验

  • Provide clear transaction confirmations
  • Show loading states during blockchain operations
  • Handle wallet connection failures gracefully
  • Support multiple wallet types
Reference: references/best-practices.md
  • 提供清晰的交易确认提示
  • 在区块链操作过程中展示加载状态
  • 优雅处理钱包连接失败的情况
  • 支持多种钱包类型
参考: references/best-practices.md

Troubleshooting

故障排除

Common Issues

常见问题

  • Wallet connection fails: Check WalletConnect configuration
  • API errors: Verify API key and network settings
  • Transaction reverts: Validate contract calls and gas limits
  • Styling issues: Import OnchainKit CSS properly
  • 钱包连接失败:检查WalletConnect配置
  • API错误:验证API密钥与网络设置
  • 交易回滚:验证合约调用与Gas限制
  • 样式问题:正确导入OnchainKit CSS

Debug Steps

调试步骤

  1. Check browser console for errors
  2. Verify environment variables
  3. Test with different wallets
  4. Use validation script to check setup
Reference: references/troubleshooting.md
  1. 查看浏览器控制台中的错误信息
  2. 验证环境变量
  3. 使用不同钱包进行测试
  4. 使用验证脚本检查设置
参考: references/troubleshooting.md

Templates & Examples

模板与示例

Quick Start Templates

快速启动模板

  • Basic App:
    assets/templates/basic-app/
    - Minimal onchain app
  • Token Swap:
    assets/templates/swap-app/
    - Complete swap interface
  • NFT Minting:
    assets/templates/nft-mint/
    - NFT marketplace
  • Commerce:
    assets/templates/commerce/
    - Onchain store
  • 基础应用
    assets/templates/basic-app/
    - 极简链上应用
  • 代币兑换
    assets/templates/swap-app/
    - 完整兑换界面
  • NFT铸造
    assets/templates/nft-mint/
    - NFT市场
  • 电商
    assets/templates/commerce/
    - 链上商店

Real-World Examples

真实场景示例

  • Wallet connection with identity display
  • Multi-token swap interface
  • NFT collection with minting
  • Payment processing with receipts
Reference: references/examples.md
  • 带身份展示的钱包连接
  • 多代币兑换界面
  • 带铸造功能的NFT藏品
  • 带收据的支付处理
参考: references/examples.md

Advanced Features

高级功能

Custom Chains

自定义链

Support additional EVM chains beyond Base:
tsx
const customChain = {
  id: 123456,
  name: 'Custom Chain',
  // ... chain configuration
};

<OnchainKitProvider chain={customChain}>
支持Base之外的其他EVM兼容链:
tsx
const customChain = {
  id: 123456,
  name: 'Custom Chain',
  // ... chain configuration
};

<OnchainKitProvider chain={customChain}>

MiniKit Integration

MiniKit集成

Build Farcaster Frame applications:
tsx
import { useMiniKit } from '@coinbase/onchainkit/minikit';

function FrameApp() {
  const { isReady } = useMiniKit();
  return isReady ? <YourFrameContent /> : <Loading />;
}
Reference: references/advanced-features.md
构建Farcaster Frame应用:
tsx
import { useMiniKit } from '@coinbase/onchainkit/minikit';

function FrameApp() {
  const { isReady } = useMiniKit();
  return isReady ? <YourFrameContent /> : <Loading />;
}
参考: references/advanced-features.md

API Reference

API参考

OnchainKit provides both React components and utility functions:
  • Components: Pre-built UI components for common onchain operations
  • Hooks: React hooks for blockchain state management
  • Utilities: TypeScript utilities for data formatting and validation
  • Types: Complete TypeScript definitions
Reference: references/api-reference.md
OnchainKit同时提供React组件与工具函数:
  • 组件:针对常见链上操作的预构建UI组件
  • Hooks:用于区块链状态管理的React Hooks
  • 工具函数:用于数据格式化与验证的TypeScript工具
  • 类型定义:完整的TypeScript类型
参考: references/api-reference.md

Resources

资源

Documentation

文档

Support

支持


💡 Pro Tip: Start with
npm create onchain
to bootstrap a working app, then customize components as needed. The quickstart template includes all necessary configuration and examples.
🚀 Quick Win: Use the validation script after setup to ensure everything is working correctly before building custom features.

💡 专业提示:使用
npm create onchain
快速初始化一个可运行的应用,然后按需自定义组件。快速启动模板包含所有必要的配置与示例。
🚀 快速上手:设置完成后使用验证脚本确保所有功能正常,再开始构建自定义特性。