onchainkit
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOnchainKit
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
undefinedbash
undefinedCreate 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
undefinedscripts/validate-setup.py
undefinedAdd to Existing Project
添加至现有项目
bash
npm install @coinbase/onchainkitbash
npm install @coinbase/onchainkitSetup configuration and providers
Setup configuration and providers
scripts/setup-environment.py
undefinedscripts/setup-environment.py
undefinedCore 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
搭建完整应用
- Initialize project with
create-onchain-app.py - Configure providers using setup templates
- Add wallet connection with Wallet components
- Implement core features (swap, buy, identity)
- Test and deploy with validation scripts
- 初始化项目:使用
create-onchain-app.py - 配置提供者:使用设置模板
- 添加钱包连接:使用Wallet组件
- 实现核心功能(兑换、购买、身份)
- 测试与部署:使用验证脚本
Building a Token Swap App
构建代币兑换应用
- Start with swap app template from
assets/templates/swap-app/ - Configure token lists and supported chains
- Add wallet connection flow
- Implement swap interface
- Add transaction confirmations
- 从获取兑换应用模板
assets/templates/swap-app/ - 配置代币列表与支持的链
- 添加钱包连接流程
- 实现兑换界面
- 添加交易确认功能
Creating an NFT Marketplace
创建NFT市场
- Use NFT template from
assets/templates/nft-mint/ - Set up NFT contract integration
- Build minting interface
- Add payment processing
- Implement collection browsing
- 使用中的NFT模板
assets/templates/nft-mint/ - 设置NFT合约集成
- 构建铸造界面
- 添加支付处理
- 实现藏品浏览功能
Configuration & Setup
配置与设置
Environment Variables
环境变量
bash
undefinedbash
undefinedRequired 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
调试步骤
- Check browser console for errors
- Verify environment variables
- Test with different wallets
- Use validation script to check setup
Reference: references/troubleshooting.md
- 查看浏览器控制台中的错误信息
- 验证环境变量
- 使用不同钱包进行测试
- 使用验证脚本检查设置
参考: references/troubleshooting.md
Templates & Examples
模板与示例
Quick Start Templates
快速启动模板
- Basic App: - Minimal onchain app
assets/templates/basic-app/ - Token Swap: - Complete swap interface
assets/templates/swap-app/ - NFT Minting: - NFT marketplace
assets/templates/nft-mint/ - Commerce: - Onchain store
assets/templates/commerce/
- 基础应用:- 极简链上应用
assets/templates/basic-app/ - 代币兑换:- 完整兑换界面
assets/templates/swap-app/ - NFT铸造:- NFT市场
assets/templates/nft-mint/ - 电商:- 链上商店
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
文档
- Official docs: onchainkit.xyz
- GitHub: github.com/coinbase/onchainkit
- Examples: OnchainKit playground
- 官方文档:onchainkit.xyz
- GitHub:github.com/coinbase/onchainkit
- 示例:OnchainKit playground
Support
支持
- Discord: Coinbase Developer Platform
- Twitter: @OnchainKit
💡 Pro Tip: Start with to bootstrap a working app, then customize components as needed. The quickstart template includes all necessary configuration and examples.
npm create onchain🚀 Quick Win: Use the validation script after setup to ensure everything is working correctly before building custom features.
- Discord:Coinbase Developer Platform
- Twitter:@OnchainKit
💡 专业提示:使用快速初始化一个可运行的应用,然后按需自定义组件。快速启动模板包含所有必要的配置与示例。
npm create onchain🚀 快速上手:设置完成后使用验证脚本确保所有功能正常,再开始构建自定义特性。