Content
# Wallet Agent

[](https://github.com/wallet-agent/wallet-agent/actions/workflows/ci.yml)
[](https://codecov.io/gh/wallet-agent/wallet-agent)
MCP server enabling Web3 wallet interactions in AI tools such as Claude Code and Cursor, with support for mock wallets during testing and real wallets via private-key import.
> ⚠️ **WARNING: Beta Software**
>
> This is beta software under active development. **DO NOT use on mainnet or with wallets containing real funds.** This software has not been audited and may contain bugs that could result in loss of funds. Use only on testnets or local development environments.
## Quick Start
### Claude Code
```bash
claude mcp add wallet-agent bunx wallet-agent@latest
```
Verify with `/mcp` in Claude Code.
### Cursor
Add to your `~/.cursor/mcp.json`:
```json
{
"mcpServers": {
"wallet-agent": {
"command": "bunx",
"args": ["wallet-agent"]
}
}
}
```
Then restart 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
First load your wagmi-generated contracts:
```
"Load wagmi config from ./src/generated.ts"
"List all available contracts"
```
Then explore and analyze 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
Test contracts safely without gas costs:
```
"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"
```
Example output for contract analysis:
```
🔬 **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 includes the following chains by default:
- **Anvil** (Local, Chain ID: 31337) - Default chain for local development
- **Ethereum Mainnet** (Chain ID: 1) - Using public RPC
- **Sepolia** (Chain ID: 11155111) - Ethereum testnet
- **Polygon** (Chain ID: 137) - Polygon PoS mainnet
⚠️ **Note**: Built-in chains use public RPC endpoints which may have rate limits. For production use, consider adding custom chains with your own RPC endpoints.
### Custom Chain Support
Add any EVM-compatible chain with the `add_custom_chain` tool:
- Local development networks (Anvil, Hardhat, Ganache)
- Layer 2 networks (Base, Arbitrum, Optimism)
- Alternative L1s (BNB Chain, Avalanche)
- Private/enterprise networks
## Available Tools
### Wallet Management
- `connect_wallet` - Connect to a wallet using the specified address
- `disconnect_wallet` - Disconnect the currently connected wallet
- `get_accounts` - Get the list of available mock accounts
- `get_current_account` - Get the currently connected account information
- `get_wallet_info` - Get current wallet configuration info
- `get_balance` - Get the balance of an address
### Transaction Operations
- `send_transaction` - Send a transaction
- `estimate_gas` - Estimate gas for a transaction before sending
- `get_transaction_status` - Get the status of a transaction by its hash
- `get_transaction_receipt` - Get detailed receipt of a mined transaction
- `simulate_transaction` - Simulate a contract transaction before sending
### Signing
- `sign_message` - Sign a message with the connected wallet
- `sign_typed_data` - Sign EIP-712 typed data
### Chain Management
- `switch_chain` - Switch to a different chain
- `add_custom_chain` - Add a custom EVM-compatible blockchain network
- `update_custom_chain` - Update an existing custom chain's configuration
- `remove_custom_chain` - Remove a previously added custom chain
### Token Operations (ERC-20)
- `transfer_token` - Transfer ERC-20 tokens to another address
- `approve_token` - Approve ERC-20 token spending
- `get_token_balance` - Get ERC-20 token balance
- `get_token_info` - Get ERC-20 token information (name, symbol, decimals)
### NFT Operations (ERC-721)
- `transfer_nft` - Transfer an ERC-721 NFT to another address
- `get_nft_owner` - Get the owner of an ERC-721 NFT
- `get_nft_info` - Get ERC-721 NFT information (name, symbol, tokenURI)
### Contract Operations
- `load_wagmi_config` - Load contract ABIs from a Wagmi-generated file
- `list_contracts` - List all available contracts from Wagmi config
- `read_contract` - Read from a smart contract using Wagmi-generated ABIs
- `write_contract` - Write to a smart contract using Wagmi-generated ABIs
### Contract ABI Analysis
- `extract_wagmi_abi` - Extract ABI for a specific contract in JSON, TypeScript, or human-readable format
- `list_wagmi_functions` - List all callable functions for a contract with filtering by mutability
- `list_wagmi_events` - List all events that a contract can emit
- `export_wagmi_abi` - Export contract ABI to a file in JSON or TypeScript format
- `analyze_wagmi_contract` - Analyze contract capabilities and detect standards (ERC-20, ERC-721, etc.)
### Contract Testing & Validation
- `simulate_contract_call` - Simulate contract function calls without gas costs or state changes
- `test_contract_function` - Generate and run multiple test scenarios for a contract function
- `test_contract` - Analyze all functions in a contract and provide testing guidance
- `dry_run_transaction` - Preview transaction effects before execution
### Private Key Management
- `import_private_key` - Import a private key from environment variable or file
- `list_imported_wallets` - List all imported private key wallets
- `remove_private_key` - Remove an imported private key
- `set_wallet_type` - Switch between mock and private key wallets
### Encrypted Key Management
- `create_encrypted_keystore` - Create a new encrypted key store with master password
- `unlock_keystore` - Unlock encrypted key store for session access
- `lock_keystore` - Lock key store and clear decrypted keys from memory
- `import_encrypted_private_key` - Import private key into encrypted store
- `list_encrypted_keys` - List all encrypted keys (addresses and labels only)
- `remove_encrypted_key` - Remove encrypted key from store
- `update_key_label` - Update label for an encrypted key
- `change_keystore_password` - Change master password for encrypted keys
- `get_keystore_status` - Get current encrypted key store status
### ENS
- `resolve_ens_name` - Resolve an ENS name to an Ethereum address (mainnet only)
## Contract ABI Analysis (Wagmi Integration)
Wallet Agent provides powerful tools for analyzing smart contracts generated by Wagmi. Perfect for developers working with TypeScript contract interactions.
### Getting Started
1. **Generate contracts with Wagmi CLI**:
```bash
bunx @wagmi/cli generate
```
2. **Load contracts into Wallet Agent**:
```
"Load wagmi config from ./src/generated.ts"
```
### Key Features
#### 🔍 **ABI Extraction**
Extract contract ABIs in multiple formats:
```
"Extract ABI for MyToken in JSON format"
"Extract ABI for MyNFT in TypeScript format"
"Extract ABI for MyContract in human-readable format"
```
#### 📋 **Function Analysis**
Analyze contract functions with filtering:
```
"List all functions for MyToken"
"List only view functions for MyContract"
"List payable functions for MyPayableContract"
```
#### 📡 **Event Discovery**
Discover all contract events:
```
"List all events for MyToken"
```
#### 💾 **ABI Export**
Export ABIs to files for external use:
```
"Export MyToken ABI to ./abis/MyToken.json"
"Export MyContract ABI to ./types/contracts.ts in TypeScript format"
```
#### 🔬 **Smart Contract Analysis**
Get comprehensive contract analysis with standard detection:
```
"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"
```
Output shows:
- ERC-20 compliance ✓
- 12 functions (8 view, 4 non-payable)
- Standard Transfer/Approval events
- Recommendations for token operations
#### Working with NFT Collections
```
"List all functions for MyNFTCollection"
"List all events for MyNFTCollection"
"Export MyNFTCollection ABI to ./metadata/nft-abi.json"
```
Perfect for:
- Frontend integration
- Contract verification
- Documentation generation
- Testing preparation
#### 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"
```
The human-readable format is perfect for understanding contract interfaces at a glance, while JSON/TypeScript exports integrate seamlessly with your development toolchain.
## Contract Testing & Validation
Wallet Agent provides advanced tools for testing smart contracts safely and efficiently. Test contract behavior without spending gas or affecting blockchain state.
### Key Features
#### 🧪 **Safe Contract Simulation**
Test contract functions without gas costs using `eth_call`:
```
"Simulate transfer function for MyToken with recipient 0x123... and amount 1000"
"Simulate balanceOf function for MyToken with account 0x456..."
```
#### 🎯 **Automated Test Generation**
Generate comprehensive test scenarios automatically:
```
"Test contract function transfer for MyToken"
"Test contract function approve for MyToken"
```
#### 🔍 **Contract Function Analysis**
Analyze all functions in a contract:
```
"Test contract MyToken"
"Test contract MyNFT with view functions only"
```
#### 🔮 **Transaction Preview**
Preview transaction effects before execution:
```
"Dry run transaction: transfer 100 USDC to 0x123..."
"Dry run transaction: mint NFT with tokenId 42"
```
### Test Scenarios
The automated test generator creates scenarios based on function parameters:
**For functions with numeric parameters:**
- ✅ **Basic Success** - Valid typical values
- ✅ **Zero Values** - Test with zero amounts
- ✅ **Maximum Values** - Test with maximum uint256 values
**For functions with address parameters:**
- ✅ **Valid Address** - Normal Ethereum addresses
- ❌ **Zero Address** - Tests `0x0` address handling (expected to fail)
**For functions with complex parameters:**
- ✅ **Mixed Scenarios** - Combination of edge cases
### 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
Customize wallet behavior using natural language instructions! Create an `instructions.md` file to personalize how Wallet Agent operates.
### Global Instructions
Create `~/.wallet-agent/instructions.md` for user-wide preferences:
```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
Create `.wallet-agent/instructions.md` in your project for context-specific behavior:
```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 agents automatically read your instructions via the `wallet://instructions` MCP resource
- **Project instructions override global instructions** for maximum flexibility
- Instructions are written in plain English - no code required!
- Supports gas preferences, security rules, multi-chain settings, error handling, and more
### 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"
The AI agent will automatically apply your preferences when performing wallet operations!
## Real Wallets (Development Only)
⚠️ **NEVER paste private keys in chat!**
### Option 1: Encrypted Key Store (Recommended)
The most secure way to manage private keys:
```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
Pre-configured for testing:
- `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
See the [Testing Guide](test/README.md) for comprehensive testing documentation, including:
- Running tests in mock and real blockchain modes
- Testing with Anvil
- Writing new tests
- CI/CD integration
## Security
### Encrypted Key Management
- **AES-256-GCM**: Industry-standard authenticated encryption
- **PBKDF2**: 100,000 iterations for key derivation (OWASP recommended)
- **Session Security**: 30-minute timeout with automatic lock
- **Memory Protection**: Keys cleared on session end
- **File Security**: Restrictive permissions (600) on encrypted storage
### General Security
- Private keys never logged or transmitted over network
- Support for environment variables and secure file storage
- Mock wallets for safe testing
- Use testnets for development
- Audit code before mainnet use
Connection Info
You Might Also Like
No recommendations available