内容
# Wallet Agent

[](https://github.com/wallet-agent/wallet-agent/actions/workflows/ci.yml)
[](https://codecov.io/gh/wallet-agent/wallet-agent)
MCP server,支持在 Claude Code 和 Cursor 等 AI 工具中进行 Web3 钱包交互,在测试期间支持模拟钱包,并通过私钥导入支持真实钱包。
> ⚠️ **WARNING: Beta Software**
>
> 这是正在积极开发中的 Beta 软件。**请勿在主网上或包含真实资金的钱包中使用。** 此软件未经审计,可能包含导致资金损失的错误。 仅在测试网或本地开发环境中使用。
## Quick Start
### Claude Code
```bash
claude mcp add wallet-agent bunx wallet-agent@latest
```
在 Claude Code 中使用 `/mcp` 进行验证。
### Cursor
添加到你的 `~/.cursor/mcp.json`:
```json
{
"mcpServers": {
"wallet-agent": {
"command": "bunx",
"args": ["wallet-agent"]
}
}
}
```
然后重启 Cursor。
## Usage Examples
### Basic Flow
```
"Connect to 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
"Check my balance"
"Send 0.1 ETH to shanev.eth"
"Switch to Polygon"
```
### Token Operations
```
"Transfer 100 USDC to 0x..."
"Get my DOGE balance"
"Approve USDC spending for 0xDEX..."
```
### Contract Development with Wagmi
首先加载你用 Wagmi 生成的合约:
```
"Load wagmi config from ./src/generated.ts"
"List all available contracts"
```
然后探索和分析合约:
```
"Extract ABI for MyToken contract in human-readable format"
"List all view functions for MyToken"
"Analyze MyToken contract capabilities"
"Export MyToken ABI to ./abis/MyToken.json"
```
### Contract Testing & Validation
安全地测试合约,无需 gas 费用:
```
"Test contract function transfer for MyToken"
"Simulate balanceOf function for MyToken with account 0x..."
"Dry run transaction: approve 1000 USDC for 0xDEX..."
"Test contract MyNFT with view functions only"
```
合约分析的示例输出:
```
🔬 **Contract Analysis: MyToken**
📊 **Overview:**
- Functions: 15 total
- Events: 3
- Custom Errors: 2
🔧 **Function Breakdown:**
- View (read-only): 8
- Non-payable (state-changing): 6
- Payable (accepts ETH): 1
🏷️ **Detected Standards:**
- ERC-20
- Ownable
💡 **Recommendations:**
- This is a token contract - use token transfer tools
- This contract has an owner - check ownership functions
- Contract accepts ETH payments - ensure proper value handling
```
## Supported Chains
### Built-in Chains
Wallet Agent 默认包含以下链:
- **Anvil** (Local, Chain ID: 31337) - 本地开发的默认链
- **Ethereum Mainnet** (Chain ID: 1) - 使用公共 RPC
- **Sepolia** (Chain ID: 11155111) - Ethereum 测试网
- **Polygon** (Chain ID: 137) - Polygon PoS 主网
⚠️ **Note**: 内置链使用公共 RPC 端点,这些端点可能有速率限制。 对于生产用途,请考虑添加具有你自己的 RPC 端点的自定义链。
### Custom Chain Support
使用 `add_custom_chain` 工具添加任何 EVM 兼容链:
- 本地开发网络 (Anvil, Hardhat, Ganache)
- Layer 2 网络 (Base, Arbitrum, Optimism)
- Alternative L1s (BNB Chain, Avalanche)
- 私有/企业网络
## Available Tools
### Wallet Management
- `connect_wallet` - 使用指定的地址连接到钱包
- `disconnect_wallet` - 断开当前连接的钱包
- `get_accounts` - 获取可用的模拟账户列表
- `get_current_account` - 获取当前连接的账户信息
- `get_wallet_info` - 获取当前钱包配置信息
- `get_balance` - 获取地址的余额
### Transaction Operations
- `send_transaction` - 发送交易
- `estimate_gas` - 在发送交易之前估算交易的 gas
- `get_transaction_status` - 按哈希获取交易的状态
- `get_transaction_receipt` - 获取已挖掘交易的详细收据
- `simulate_transaction` - 在发送之前模拟合约交易
### Signing
- `sign_message` - 使用连接的钱包签署消息
- `sign_typed_data` - 签署 EIP-712 类型化数据
### Chain Management
- `switch_chain` - 切换到不同的链
- `add_custom_chain` - 添加自定义的 EVM 兼容区块链网络
- `update_custom_chain` - 更新现有自定义链的配置
- `remove_custom_chain` - 删除先前添加的自定义链
### Token Operations (ERC-20)
- `transfer_token` - 将 ERC-20 代币转移到另一个地址
- `approve_token` - 批准 ERC-20 代币支出
- `get_token_balance` - 获取 ERC-20 代币余额
- `get_token_info` - 获取 ERC-20 代币信息(名称、符号、小数位数)
### NFT Operations (ERC-721)
- `transfer_nft` - 将 ERC-721 NFT 转移到另一个地址
- `get_nft_owner` - 获取 ERC-721 NFT 的所有者
- `get_nft_info` - 获取 ERC-721 NFT 信息(名称、符号、tokenURI)
### Contract Operations
- `load_wagmi_config` - 从 Wagmi 生成的文件加载合约 ABI
- `list_contracts` - 列出 Wagmi 配置中所有可用的合约
- `read_contract` - 使用 Wagmi 生成的 ABI 从智能合约读取
- `write_contract` - 使用 Wagmi 生成的 ABI 写入智能合约
### Contract ABI Analysis
- `extract_wagmi_abi` - 以 JSON、TypeScript 或人类可读格式提取特定合约的 ABI
- `list_wagmi_functions` - 列出合约的所有可调用函数,并按可变性进行过滤
- `list_wagmi_events` - 列出合约可以发出的所有事件
- `export_wagmi_abi` - 以 JSON 或 TypeScript 格式将合约 ABI 导出到文件
- `analyze_wagmi_contract` - 分析合约功能并检测标准(ERC-20、ERC-721 等)
### Contract Testing & Validation
- `simulate_contract_call` - 模拟合约函数调用,无需 gas 费用或状态更改
- `test_contract_function` - 为合约函数生成并运行多个测试场景
- `test_contract` - 分析合约中的所有函数并提供测试指导
- `dry_run_transaction` - 在执行之前预览交易效果
### Private Key Management
- `import_private_key` - 从环境变量或文件导入私钥
- `list_imported_wallets` - 列出所有导入的私钥钱包
- `remove_private_key` - 删除导入的私钥
- `set_wallet_type` - 在模拟钱包和私钥钱包之间切换
### Encrypted Key Management
- `create_encrypted_keystore` - 使用主密码创建新的加密密钥库
- `unlock_keystore` - 解锁加密密钥库以进行会话访问
- `lock_keystore` - 锁定密钥库并从内存中清除解密的密钥
- `import_encrypted_private_key` - 将私钥导入加密存储
- `list_encrypted_keys` - 列出所有加密密钥(仅地址和标签)
- `remove_encrypted_key` - 从存储中删除加密密钥
- `update_key_label` - 更新加密密钥的标签
- `change_keystore_password` - 更改加密密钥的主密码
- `get_keystore_status` - 获取当前加密密钥库状态
### ENS
- `resolve_ens_name` - 将 ENS 名称解析为 Ethereum 地址(仅限主网)
## Contract ABI Analysis (Wagmi Integration)
Wallet Agent 提供了强大的工具来分析由 Wagmi 生成的智能合约。 非常适合使用 TypeScript 合约交互的开发人员。
### Getting Started
1. **使用 Wagmi CLI 生成合约**:
```bash
bunx @wagmi/cli generate
```
2. **将合约加载到 Wallet Agent 中**:
```
"Load wagmi config from ./src/generated.ts"
```
### Key Features
#### 🔍 **ABI Extraction**
以多种格式提取合约 ABI:
```
"Extract ABI for MyToken in JSON format"
"Extract ABI for MyNFT in TypeScript format"
"Extract ABI for MyContract in human-readable format"
```
#### 📋 **Function Analysis**
分析合约函数并进行过滤:
```
"List all functions for MyToken"
"List only view functions for MyContract"
"List payable functions for MyPayableContract"
```
#### 📡 **Event Discovery**
发现所有合约事件:
```
"List all events for MyToken"
```
#### 💾 **ABI Export**
将 ABI 导出到文件中以供外部使用:
```
"Export MyToken ABI to ./abis/MyToken.json"
"Export MyContract ABI to ./types/contracts.ts in TypeScript format"
```
#### 🔬 **Smart Contract Analysis**
获取全面的合约分析和标准检测:
```
"Analyze MyToken contract capabilities"
```
**Detects Standards:**
- **ERC-20** - Token contracts
- **ERC-721** - NFT contracts
- **ERC-1155** - Multi-token contracts
- **Ownable** - Contracts with ownership
- **AccessControl** - Role-based permissions
- **Upgradeable** - Proxy patterns
**Function Categories:**
- **View** - Read-only functions
- **Pure** - No state access
- **Payable** - Accept ETH payments
- **Non-payable** - State-changing functions
### Real-World Examples
#### Analyzing a DeFi Token
```
"Load wagmi config from ./src/generated.ts"
"Analyze USDCToken contract capabilities"
```
输出显示:
- ERC-20 合规性 ✓
- 12 个函数(8 个 view,4 个 non-payable)
- 标准的 Transfer/Approval 事件
- 代币操作建议
#### Working with NFT Collections
```
"List all functions for MyNFTCollection"
"List all events for MyNFTCollection"
"Export MyNFTCollection ABI to ./metadata/nft-abi.json"
```
Perfect for:
- 前端集成
- 合约验证
- 文档生成
- 测试准备
#### Development Workflow Integration
```
# After contract deployment
"Load wagmi config from ./src/generated.ts"
"Analyze all contracts"
"Export all ABIs to ./build/contracts/"
# For specific contract work
"List view functions for MyContract"
"Extract ABI for MyContract in human-readable format"
```
人类可读的格式非常适合一目了然地理解合约接口,而 JSON/TypeScript 导出可以与你的开发工具链无缝集成。
## Contract Testing & Validation
Wallet Agent 提供了高级工具,可以安全有效地测试智能合约。 在不花费 gas 或影响区块链状态的情况下测试合约行为。
### Key Features
#### 🧪 **Safe Contract Simulation**
使用 `eth_call` 测试合约函数,无需 gas 费用:
```
"Simulate transfer function for MyToken with recipient 0x123... and amount 1000"
"Simulate balanceOf function for MyToken with account 0x456..."
```
#### 🎯 **Automated Test Generation**
自动生成全面的测试场景:
```
"Test contract function transfer for MyToken"
"Test contract function approve for MyToken"
```
#### 🔍 **Contract Function Analysis**
分析合约中的所有函数:
```
"Test contract MyToken"
"Test contract MyNFT with view functions only"
```
#### 🔮 **Transaction Preview**
在执行之前预览交易效果:
```
"Dry run transaction: transfer 100 USDC to 0x123..."
"Dry run transaction: mint NFT with tokenId 42"
```
### Test Scenarios
自动测试生成器根据函数参数创建场景:
**对于具有数字参数的函数:**
- ✅ **Basic Success** - 有效的典型值
- ✅ **Zero Values** - 使用零金额进行测试
- ✅ **Maximum Values** - 使用最大 uint256 值进行测试
**对于具有地址参数的函数:**
- ✅ **Valid Address** - 普通 Ethereum 地址
- ❌ **Zero Address** - 测试 `0x0` 地址处理(预计会失败)
**对于具有复杂参数的函数:**
- ✅ **Mixed Scenarios** - 边缘案例的组合
### Real-World Examples
#### Testing a DeFi Token Contract
```
"Load wagmi config from ./src/generated.ts"
"Test contract function transfer for USDCToken"
```
**Sample Output:**
```
🧪 Function Test Results: USDCToken.transfer()
📊 Summary:
- Total Tests: 4
- Passed: 3 ✅
- Failed: 1 ❌
- Success Rate: 75%
📋 Test Scenarios:
**Basic Success** - ✅ PASS
Test transfer with typical valid inputs
📤 Returned: true
**Zero Values** - ✅ PASS
Test transfer with zero values for numeric inputs
📤 Returned: true
**Maximum Values** - ✅ PASS
Test transfer with maximum values for numeric inputs
📤 Returned: true
**Zero Address** - ❌ FAIL
Test transfer with zero address (0x0)
🚨 Reason: ERC20: transfer to the zero address
💡 Recommendations:
- Review failed test cases to understand function behavior
- Consider edge cases when calling this function
- Add proper error handling in your application
```
#### Simulating Complex DeFi Operations
```
"Simulate swap function for MyDEX with tokenIn USDC, tokenOut WETH, amount 1000"
```
**Benefits:**
- ✅ **Gas-free testing** - No transaction fees
- ✅ **State preservation** - Blockchain state unchanged
- ✅ **Error detection** - Catch reverts before execution
- ✅ **Return value preview** - See function outputs
#### Contract Development Workflow
1. **Deploy Contract** (to testnet/local)
```
"Load wagmi config from ./src/generated.ts"
```
2. **Analyze Contract Functions**
```
"Test contract MyNewContract"
```
3. **Test Critical Functions**
```
"Test contract function mint for MyNewContract"
"Test contract function burn for MyNewContract"
```
4. **Simulate Before Execution**
```
"Dry run transaction: mint NFT with tokenId 1 to 0x123..."
```
5. **Execute with Confidence**
```
"Write contract MyNewContract function mint with args [1, '0x123...']"
```
### Security Benefits
#### Pre-execution Validation
- **Revert Detection**: Identify transactions that would fail
- **Gas Estimation**: Preview gas requirements
- **Parameter Validation**: Test edge cases and invalid inputs
- **State Requirements**: Verify preconditions are met
#### Smart Testing
- **Automatic Scenarios**: No manual test case creation
- **Edge Case Coverage**: Tests boundary conditions
- **Standard Patterns**: Recognizes common validation patterns
- **Error Analysis**: Detailed revert reason extraction
### Integration with Development Tools
Perfect for:
- **Frontend Development** - Test contract calls before user interactions
- **Smart Contract Testing** - Complement traditional test suites
- **DeFi Protocol Integration** - Validate complex multi-step operations
- **Contract Auditing** - Discover edge cases and potential issues
- **Documentation** - Generate examples of contract behavior
### Best Practices
1. **Test Before Deploy**: Use simulation during contract development
2. **Validate User Inputs**: Test with edge cases before user interactions
3. **Batch Testing**: Use `test_contract` to analyze entire contracts
4. **Preview Transactions**: Always dry-run high-value operations
5. **Document Behavior**: Use test results to understand contract logic
The contract testing tools integrate seamlessly with Wagmi ABI extraction, providing a complete contract development and interaction workflow.
## User Instructions
使用自然语言指令自定义钱包行为! 创建一个 `instructions.md` 文件来个性化 Wallet Agent 的运行方式。
### Global Instructions
创建 `~/.wallet-agent/instructions.md` 以获取用户范围内的首选项:
```markdown
# My Wallet Instructions
## Gas Settings
- Always use "fast" gas prices for DEX trades
- Use "standard" gas for simple transfers
- Warn me if gas cost exceeds $20
## Security Rules
- Never approve unlimited token allowances
- Always simulate high-value transactions first
- Require confirmation for new contracts
## Multi-chain Preferences
- Prefer Polygon for small transfers (<$100)
- Use Arbitrum for DeFi to save fees
- Default to mainnet for large transfers (>$1000)
```
### Project Instructions
在你的项目中创建 `.wallet-agent/instructions.md` 以获取特定于上下文的行为:
```markdown
# Project Instructions
## For This DApp
- Use conservative gas settings
- Always simulate before executing
- Show detailed transaction breakdowns
- Prefer Layer 2 networks when possible
```
### How It Works
- AI 代理通过 `wallet://instructions` MCP 资源自动读取你的指令
- **项目指令覆盖全局指令**,以实现最大的灵活性
- 指令以纯英文编写 - 无需代码!
- 支持 gas 首选项、安全规则、多链设置、错误处理等
### Example Customizations
- **Gas Strategy**: "Use slow gas for non-urgent transactions"
- **Security**: "Always double-check recipient addresses"
- **Multi-chain**: "Prefer Polygon for transfers under $50"
- **Error Handling**: "Auto-retry failed transactions with 10% higher gas"
- **Display**: "Show both ETH and USD values for all transactions"
AI 代理将在执行钱包操作时自动应用你的首选项!
## Real Wallets (Development Only)
⚠️ **NEVER paste private keys in chat!**
### Option 1: Encrypted Key Store (Recommended)
管理私钥的最安全方法:
```bash
# Create encrypted key store
"Create encrypted keystore with master password"
"Import encrypted private key from WALLET_PRIVATE_KEY with master password"
"Set wallet type to privateKey"
"Connect to my wallet"
```
**Security Features:**
- AES-256-GCM authenticated encryption
- PBKDF2 key derivation (100,000 iterations)
- Session-based access (30-minute timeout)
- Automatic memory clearing on lock
- File stored with restrictive permissions
### Option 2: Environment Variable
```bash
# When adding server
claude mcp add wallet-agent bunx wallet-agent -e WALLET_PRIVATE_KEY=0x...
# Or in shell
export WALLET_PRIVATE_KEY="0x..."
```
Then: "Import private key from WALLET_PRIVATE_KEY"
### Option 3: Secure File
```bash
echo "0x..." > ~/.wallet-key
chmod 600 ~/.wallet-key
```
Then: "Import private key from ~/.wallet-key"
### Standard Workflow
1. "Set wallet type to privateKey"
2. "Connect to my wallet"
3. Use normally
## Mock Accounts
预配置用于测试:
- `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266`
- `0x70997970C51812dc3A010C7d01b50e0d17dc79C8`
- `0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC`
## Development
```bash
git clone https://github.com/wallet-agent/wallet-agent.git
cd wallet-agent
bun install
bun run dev
```
For local testing:
```bash
claude mcp add wallet-agent bun /path/to/wallet-agent/dist/index.ts
```
### Testing
有关全面的测试文档,请参阅 [Testing Guide](test/README.md),包括:
- 在模拟和真实区块链模式下运行测试
- 使用 Anvil 进行测试
- 编写新测试
- CI/CD 集成
## Security
### Encrypted Key Management
- **AES-256-GCM**: 行业标准身份验证加密
- **PBKDF2**: 100,000 次迭代用于密钥派生(OWASP 推荐)
- **Session Security**: 30 分钟超时,自动锁定
- **Memory Protection**: 会话结束时清除密钥
- **File Security**: 加密存储上的限制性权限 (600)
### General Security
- 私钥永远不会通过网络记录或传输
- 支持环境变量和安全文件存储
- 用于安全测试的模拟钱包
- 使用测试网进行开发
- 在主网使用前审核代码
连接信息
猜你喜欢
Vibe-Trading
Vibe-Trading:您的个人交易代理
ai-berkshire
AI 时代的伯克希尔:基于 Claude Code 的价值投资研究框架。巴菲特·芒格·段永平·李录四大师方法论 + 多Agent并行研究。
HexStrike AI
HexStrike AI是一个AI驱动的MCP网络安全自动化平台,拥有150多个工具。
valuecell
Valuecell是一个用于高效数据管理的Python项目。
tradingview-mcp
AI辅助TradingView图表分析 — 将Claude Code连接到您的TradingView Desktop,实现个人工作流自动化
tradingview-mcp
TradingView MCP Server 提供加密货币和股票的实时市场分析。