Imported from SynergiaOS/SOL_SNIPER_PRO (
AGENTS.md). Install upstream withnpx skills add SynergiaOS/SOL_SNIPER_PRO. Copyright stays with the author.
š¤ AI Agent System Documentation
Overview
The HFT Sniper Bot includes a comprehensive AI agent system designed for automated Solana token trading, market analysis, and risk management. The system is built with a modular, event-driven architecture that supports high-performance trading operations.
Architecture
Core Components
src/agents/
āāā mod.rs # Main agents module and orchestrator
āāā base/ # Base agent framework
ā āāā mod.rs # Base module exports
ā āāā agent.rs # Core Agent trait and BaseAgent implementation
ā āāā message.rs # Message types and communication structures
ā āāā config.rs # Agent configuration structures
āāā communication/ # Message bus and communication
ā āāā mod.rs # Communication module exports
ā āāā message_bus.rs # Central message bus implementation
āāā manager/ # Agent lifecycle management
ā āāā mod.rs # Manager module exports
ā āāā agent_manager.rs # Agent manager and orchestration
āāā sniper/ # Solana token sniper agent
āāā mod.rs # Sniper module exports
āāā solana_token_sniper.rs # Main sniper implementation
Agent System Features
šļø Base Agent Framework
The base agent framework provides:
- Agent Trait: Core interface for all agents
- Message Handling: Asynchronous message processing
- Health Monitoring: Built-in health checks and status reporting
- Lifecycle Management: Initialization, startup, shutdown, and recovery
- Statistics: Performance metrics and execution tracking
- Configuration: Flexible configuration system
š” Communication System
The message bus provides:
- Pub/Sub Messaging: Flexible publish-subscribe patterns
- Direct Messaging: Point-to-point communication
- Message Filtering: Advanced routing and filtering capabilities
- Delivery Guarantees: Message confirmation and retry logic
- Priority Queuing: Message prioritization for critical operations
- Statistics: Real-time message metrics and monitoring
šļø Agent Manager
The agent manager handles:
- Agent Registration: Dynamic agent discovery and registration
- Lifecycle Orchestration: Coordinated startup and shutdown
- Health Monitoring: Continuous health checks with auto-restart
- Event Management: Comprehensive lifecycle event tracking
- Resource Management: Memory, CPU, and connection limits
- Dependencies: Agent dependency resolution and ordering
šÆ Solana Token Sniper
The sniper agent provides:
- Real-time Scanning: Continuous monitoring for new token launches
- Risk Analysis: Multi-factor token analysis and scoring
- High-Frequency Execution: Optimized trading execution with MEV protection
- Position Management: Automated position monitoring and profit taking
- Risk Controls: Comprehensive risk management and loss prevention
Configuration
Enable Agent System
In config/config.toml:
[agents]
enabled = true
health_check_interval_seconds = 10
shutdown_timeout_seconds = 30
enable_auto_restart = true
max_restart_attempts = 3
restart_backoff_seconds = 5
Sniper Configuration
[agents.sniper]
max_sol_amount = 0.1
min_liquidity_sol = 50.0
max_slippage_percent = 5.0
max_price_impact_percent = 2.0
priority_fee_multiplier = 2.0
execution_interval_ms = 100
enable_simulation = true
enable_preflight = true
max_retries = 3
Token Filters
[agents.sniper.filters]
min_holders = 1
required_features = ["mutable"]
forbidden_features = ["freeze_authority"]
max_initial_supply = null
[agents.sniper.filters.metadata]
required_keywords = []
forbidden_keywords = ["scam", "rug"]
min_name_length = 3
max_name_length = 50
min_symbol_length = 2
max_symbol_length = 10
Risk Management
[agents.sniper.risk_management]
max_position_percent = 5.0
stop_loss_percent = 50.0
take_profit_percent = 200.0
max_trades_per_hour = 10
trade_cooldown_seconds = 30
enable_position_scaling = true
Performance Settings
[agents.sniper.performance]
connection_timeout_ms = 5000
confirmation_timeout_seconds = 30
max_concurrent_connections = 10
enable_simulation = true
enable_preflight = true
max_retries = 3
Message System
Message Types
The agent system supports various message types:
- System Messages: Heartbeat, status, shutdown, restart
- Trading Messages: Trade requests, executions, confirmations
- Market Data: Price updates, volume alerts, liquidity changes
- Risk Management: Risk assessments, warnings, position updates
- Signals: Trading signals and confirmations
- Token Sniping: Launch detection, analysis, execution results
Message Priority
Messages are prioritized as follows:
- Critical - Token launch detection, emergency shutdowns
- High - Trade executions, risk warnings
- Normal - Market data, analysis results
- Low - Heartbeat, status updates
Communication Patterns
Publish/Subscribe
// Subscribe to token launch events
let filter = MessageFilter::new()
.with_message_type(MessageType::TokenLaunchDetected);
let subscription = message_bus.subscribe(agent_id, filter).await?;
Direct Messaging
// Send direct message to another agent
let message = Message::builder()
.from(sender_id)
.to(recipient_id)
.message_type(MessageType::TradeRequest)
.payload(trade_data)
.priority(Priority::High)
.build();
message_bus.send_message(message).await?;
Agent Lifecycle
States
Agents progress through these states:
- Initializing - Setting up resources and connections
- Running - Normal operation and message processing
- Stopped - Gracefully stopped, can be restarted
- Error - Error state, may attempt recovery
Health Monitoring
- Automatic Health Checks: Configurable interval health monitoring
- Auto-Restart: Automatic recovery from failures
- Graceful Degradation: Reduced functionality on partial failures
- Resource Monitoring: Memory, CPU, and connection tracking
Integration with Main System
Initialization
The agent system is initialized in src/main.rs:
// Initialize agent system if enabled
let agents = if config.agents.enabled {
let mut agent_system = Agents::new();
agent_system.initialize().await?;
// Create and register sniper agent
let sniper_agent = Box::new(SolanaTokenSniper::new(sniper_config));
let agent_manager = agent_system.get_manager().await;
agent_manager.write().await.register_agent(sniper_agent, config).await?;
// Start all agents
agent_system.start_all_agents().await?;
Some(Arc::new(agent_system))
} else {
None
};
Monitoring Integration
The agent system integrates with existing monitoring:
- Metrics: Prometheus metrics for agent performance
- Dashboard: Real-time agent status in the terminal dashboard
- Netdata: Integration with Netdata for cloud monitoring
- Logging: Structured logging with tracing
Performance Considerations
High-Frequency Operations
- Async/Await: Non-blocking operations throughout
- Message Queuing: Buffered message processing
- Connection Pooling: Reused connections for better performance
- Pre-flight Checks: Transaction simulation to avoid failures
Memory Management
- Arc: Thread-safe shared state
- Message History: Limited history with automatic cleanup
- Resource Limits: Configurable memory and connection limits
- Graceful Shutdown: Proper resource cleanup
Error Handling
- Retry Logic: Configurable retry policies with exponential backoff
- Circuit Breakers: Automatic failure detection and recovery
- Fallback Mechanisms: Alternative strategies on failures
- Comprehensive Logging: Detailed error tracking and analysis
Security
Message Security
- Message Validation: Input validation and sanitization
- Access Control: Agent-to-agent communication controls
- Audit Logging: Complete message audit trail
- Rate Limiting: Protection against message flooding
Trading Security
- Risk Limits: Configurable position and loss limits
- Blacklist Filtering: Token blacklist and scam detection
- Slippage Protection: Maximum slippage and price impact limits
- Multi-signature: Support for multi-signature wallets
Extending the System
Adding New Agents
- Implement Agent Trait: Create a new agent implementing the
Agenttrait - Configuration: Add configuration structures for your agent
- Registration: Register the agent in the main system
- Message Handling: Define message types and handling logic
Custom Message Types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum MessageType {
// Existing types...
Custom(String), // Custom message type
}
impl MessageType {
pub fn custom(name: &str) -> Self {
MessageType::Custom(name.to_string())
}
}
Agent Communication
async fn handle_message(&mut self, message: Message) -> Result<AgentResult> {
match message.message_type {
MessageType::Custom(name) => {
// Handle custom message
Ok(AgentResult::Success)
}
_ => self.base.handle_message(message).await
}
}
Troubleshooting
Common Issues
- Agent Not Starting: Check configuration and dependencies
- Message Delivery Failures: Verify message bus connectivity
- Performance Issues: Monitor resource usage and message queues
- Health Check Failures: Review agent logs and error messages
Debugging
- Log Levels: Increase log verbosity for debugging
- Message Tracing: Enable message flow tracing
- Health Reports: Review agent health status reports
- Performance Metrics: Monitor agent performance metrics
Monitoring
- Agent Status: Check real-time agent status in dashboard
- Message Statistics: Monitor message flow and delivery rates
- Error Rates: Track agent error rates and types
- Resource Usage: Monitor memory, CPU, and network usage
Best Practices
Configuration
- Start Small: Begin with conservative settings and adjust gradually
- Risk Management: Always configure appropriate risk limits
- Monitoring: Enable comprehensive monitoring and alerting
- Testing: Thoroughly test agents with small amounts first
Operations
- Gradual Rollout: Deploy agents gradually with monitoring
- Backup Plans: Have manual override capabilities
- Regular Updates: Keep agents and dependencies updated
- Performance Tuning: Regularly review and optimize performance
Security
- Principle of Least Privilege: Minimize permissions and access
- Regular Audits: Review agent activities and configurations
- Secure Communication: Use secure channels for sensitive data
- Monitoring: Monitor for unusual activity and security events
Future Enhancements
Planned Features
- Multi-Chain Support: Extend to other blockchain networks
- Machine Learning: AI-powered market analysis and prediction
- Advanced Risk Models: More sophisticated risk management
- Social Sentiment: Integration with social media analysis
- DEX Aggregation: Multi-DEX trading and arbitrage
Scalability
- Horizontal Scaling: Support for multiple agent instances
- Load Balancing: Intelligent workload distribution
- Caching: Advanced caching strategies for performance
- Database Integration: Enhanced data persistence and analysis
[byterover-mcp]
[byterover-mcp]
You are given two tools from Byterover MCP server, including
1. byterover-store-knowledge
You MUST always use this tool when:
- Learning new patterns, APIs, or architectural decisions from the codebase
- Encountering error solutions or debugging techniques
- Finding reusable code patterns or utility functions
- Completing any significant task or plan implementation
2. byterover-retrieve-knowledge
You MUST always use this tool when:
- Starting any new task or implementation to gather relevant context
- Before making architectural decisions to understand existing patterns
- When debugging issues to check for previous solutions
- Working with unfamiliar parts of the codebase