This repository contains a comprehensive Web3 AI trading agent for Uniswap V4 on BASE blockchain. When working on the project interactively with an agent (e.g. the Codex CLI) please follow the guidelines below for safe development, testing, and deployment.
- Always use Foundry fork for testing trading strategies.
- Never connect to mainnet during agent development sessions.
- Use paper trading exclusively until thoroughly tested.
- Top up test accounts with fake ETH using Foundry cheats.
Start Foundry fork before any testing:
anvil --fork-url YOUR_CHAINSTACK_BASE_RPC --chain-id 8453Follow this progression path for safe development:
- Test basic swaps with scripts
python on-chain/usdc_to_eth_swap.py python on-chain/eth_to_usdc_swap.py
- Run stateless agent with pre-trained models
python on-chain/uniswap_v4_stateless_trading_agent.py
- Test stateful agent with observation mode first
python on-chain/uniswap_v4_stateful_trading_agent.py --observe-cycles 50
- Collect data → Generate synthetic → Distill → Fine-tune → Deploy
Ensure all services are running before development:
| Service | Purpose | Start Command |
|---|---|---|
| Foundry | Local blockchain fork | anvil --fork-url YOUR_RPC --chain-id 8453 |
| Ollama | LLM inference | ollama serve |
| MLX-LM | Model training (Mac) | Installed via pip |
Edit config.py with required settings:
# CRITICAL: Use test wallet with minimal funds
PRIVATE_KEY = "YOUR_TEST_WALLET_PRIVATE_KEY"
# Chainstack RPC endpoints
BASE_RPC_URLS = "YOUR_CHAINSTACK_ENDPOINT"
# Model selection
MODEL_KEY = "fin-r1" # or "qwen-trader" for custom
USE_MLX_MODEL = False # Use Ollama by default
# Trading parameters
REBALANCE_THRESHOLD = 0.5 # High to force LLM decisions
TRADE_INTERVAL = 10 # Seconds between tradesFor custom model training, follow this sequence:
# 1. Collect real swap data from BASE
python on-chain/collect_raw_data.py
# 2. Process raw data
python off-chain/process_raw_data.py# 3. Train GAN (use CPU fallback on Mac if needed)
PYTORCH_ENABLE_MPS_FALLBACK=1 python off-chain/generate_synthetic_data.py train --quick-test
# 4. Generate synthetic data
python off-chain/generate_synthetic_data.py generate
# 5. Validate synthetic data quality
python off-chain/validate_synthetic_gan_data.py# 6. Generate teacher data (requires OpenRouter API)
python off-chain/distill_data_from_teacher.py
# 7. Prepare for MLX training
python off-chain/prepare_teacher_data_for_mlx.py
# 8. Fine-tune with LoRA
mlx_lm.lora --config off-chain/data/mlx_lm_prepared/teacher_lora_config.yamlChoose deployment strategy based on needs:
mlx_lm.generate --model Qwen/Qwen2.5-3B \
--adapter-path off-chain/models/trading_model_lora \
--prompt "Trading prompt here" --temp 0.3mlx_lm.fuse --model Qwen/Qwen2.5-3B \
--adapter-path off-chain/models/trading_model_lora \
--save-path off-chain/models/fused_qwen# Convert to GGUF and create Ollama model
# (See main README for detailed steps)
ollama create trader-qwen:latest -f ModelfileFor advanced RL-enhanced models:
# Train DQN agent
python off-chain/rl_trading/train_dqn.py --timesteps 100000
# Create RL dataset
python off-chain/rl_trading/create_distillation_dataset.py
# Prepare for MLX
python off-chain/rl_trading/prepare_rl_data_for_mlx.py
# Second-stage fine-tuning
mlx_lm.lora --config off-chain/rl_trading/data/rl_data/mlx_lm_prepared/rl_lora_config.yamlAlways validate at each stage:
python on-chain/fetch_pool_data.py
python on-chain/fetch_pool_stats_from_fork.py# Test current model configuration
ollama run YOUR_MODEL "Given ETH price is $2500..."- Check transaction hashes in Foundry terminal
- Monitor portfolio balance changes
- Verify Canary words appear in custom models
- Track context usage in stateful agents
Be aware of hardware requirements:
| Component | Minimum RAM | Recommended |
|---|---|---|
| Basic Trading | 8GB | 16GB |
| GAN Training | 16GB | 32GB |
| Model Fine-tuning | 16GB | 18GB+ (Apple Silicon) |
| RL Training | 16GB | 32GB |
# ETH balance (Wei)
cast balance YOUR_ADDRESS --rpc-url http://localhost:8545
# USDC balance (need to convert from hex)
cast call 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 "balanceOf(address)" YOUR_ADDRESS --rpc-url http://localhost:8545ollama list
ollama show MODEL_NAMEtime ollama run MODEL_NAME "Trading prompt..."Before any mainnet deployment:
- Extensively tested on Foundry fork
- All unit swaps verified
- Model responses validated
- Risk parameters configured
- Small test amounts only
- Stop-loss mechanisms in place
- Performance metrics tracked
- Emergency shutdown ready
"Model failed to respond"
- Increase
TRADE_INTERVALin config.py - Check Ollama is running:
curl http://localhost:11434/api/version
"MPS backend out of memory" (Mac)
- Use CPU fallback:
PYTORCH_ENABLE_MPS_FALLBACK=1 - Reduce batch size or model size
"Transaction failed"
- Check account has sufficient ETH for gas
- Verify USDC approval for Universal Router
- Confirm pool has adequate liquidity
"Context window exceeded"
- Agent will auto-summarize at 90% capacity
- Reduce observation cycles if needed
- Check
CONTEXT_WARNING_THRESHOLDsetting
- Start with observation mode to understand market behavior.
- Use smallest viable models first, scale up gradually.
- Always verify Canary words in custom models.
- Monitor gas costs even in test environments.
- Keep detailed logs of all training experiments.
- Version control model checkpoints and configs.
- Document any custom modifications clearly.
| Task | Command |
|---|---|
| Start Foundry fork | anvil --fork-url YOUR_RPC --chain-id 8453 |
| Run stateless agent | python on-chain/uniswap_v4_stateless_trading_agent.py |
| Run stateful agent | python on-chain/uniswap_v4_stateful_trading_agent.py |
| Train GAN | python off-chain/generate_synthetic_data.py train |
| Fine-tune model | mlx_lm.lora --config CONFIG_PATH |
| Test model | ollama run MODEL_NAME "prompt" |
Following these practices ensures safe development, prevents loss of funds, and maintains system stability. Always prioritize testing and validation over speed of deployment. Remember: this is a learning project—treat it as such and never risk funds you cannot afford to lose.