Solana Agent Middleware - Production-ready AI agent framework for blockchain operations
Framework for building autonomous AI agents that interact with the Solana blockchain ecosystem
- Overview
- Key Features
- Quick Start
- Tool Ecosystem
- Architecture
- Configuration
- Plugin System
- Security
- Development
- Documentation
SAM Framework provides a production-ready infrastructure for building AI agents that interact with the Solana blockchain ecosystem. The framework implements an event-driven architecture with plugin support, enabling automated trading, portfolio management, market data analysis, and web research capabilities.
| Category | Description | Tools |
|---|---|---|
| Agent Engine | Multi-LLM orchestration with advanced tool calling | OpenAI, Anthropic, xAI, Local |
| Tool Registry | Production-ready integrations with middleware | 26+ tools |
| Event System | Async pub/sub messaging for component communication | Real-time streaming |
| Plugin SDK | Extensible architecture for custom tools | Entry point discovery |
| Memory System | Persistent conversation context with compression | SQLite-based |
| Security Layer | Encrypted key management and validation | Fernet + OS keyring |
- Automated Trading: Execute trades on Pump.fun, Jupiter DEX, and Aster Futures
- Portfolio Management: Monitor balances, positions, and transaction history
- Market Research: Real-time data from DexScreener and Polymarket analytics
- Prediction Markets: Analyze and trade prediction market opportunities
- Web Intelligence: Search and news aggregation
- Transaction Automation: Safety-controlled blockchain operations
| Feature | Description |
|---|---|
| Multi-LLM Support | OpenAI, Anthropic, xAI, and local models |
| Advanced Tool Calling | Loop prevention and error recovery |
| Event-Driven Design | Async pub/sub messaging system |
| Session Persistence | SQLite-based conversation context |
| Async Optimization | uvloop integration for performance |
| Feature | Description |
|---|---|
| 26+ Production Tools | Complete DeFi ecosystem coverage |
| Plugin Architecture | Extensible with entry point discovery |
| Middleware Pipeline | Configurable logging, rate limiting, retries |
| SDK Integration | Programmatic agent construction |
| Error Handling | Structured error responses and recovery |
| Feature | Description |
|---|---|
| Fernet Encryption | AES-128 encryption for sensitive data |
| OS Keyring Integration | System-level credential storage |
| Transaction Validation | Pre-execution safety checks |
| Rate Limiting | Configurable request throttling |
| Address Validation | Solana address format verification |
git clone https://github.com/prfagit/sam-framework
cd sam-framework
uv syncInteractive Onboarding (Recommended)
uv run sam onboardConfigures:
- LLM provider selection and API key setup
- Wallet private key import (encrypted storage)
- Environment configuration
- Tool enablement preferences
Manual Configuration
Create .env file:
# Provider Selection
LLM_PROVIDER=openai
# API Keys
OPENAI_API_KEY=sk-your-key-here
ANTHROPIC_API_KEY=sk-ant-your-key-here
XAI_API_KEY=xai-your-key-here
# Security
SAM_FERNET_KEY=your-generated-key
# Optional Services
BRAVE_API_KEY=your-brave-search-keyProvider Management
# List available providers
sam provider list
# Switch providers
sam provider switch anthropic
# Test provider connection
sam provider test# Start interactive agent (CLI)
sam run
# Or with custom session
sam run --session trading_sessionWeb Interface (Streamlit)
# Launch the web interface
uv run streamlit run examples/streamlit_app/app.py
# Access at http://localhost:8501Web Features:
- Real-time chat with streaming responses
- Live tool call visualization and event streaming
- Interactive settings, wallet, and tools pages
- Session management with conversation history
- Responsive design with custom styling
Enhanced Status Display:
- Real-time model and wallet information
- Context usage percentage (auto-compacts at 80%)
- Session statistics and performance metrics
Available Commands:
/help- Show available commands/tools- List available tools/config- Show current configuration/provider- Manage LLM providers/settings- Interactive configuration editor/clear-context- Clear conversation context/compact- Compact conversation history/clear-sessions- Clear all sessions and reset to default- ESC - Interrupt current operation
- Ctrl+C - Exit
Session Management:
- Persistent conversation contexts across runs
- Automatic session creation and management
- Session statistics and performance tracking
- Database-backed session storage with indexing
SAM provides 18+ production-ready tools organized by category:
| Tool | Description | Parameters |
|---|---|---|
get_balance |
Complete wallet overview | address (optional) |
transfer_sol |
Send SOL between addresses | to_address, amount |
get_token_data |
Token metadata and supply | address |
| Tool | Description | Parameters |
|---|---|---|
pump_fun_buy |
Execute token purchases | mint, amount, slippage |
pump_fun_sell |
Sell tokens with percentage | mint, percentage, slippage |
get_pump_token_info |
Detailed token information | mint |
get_token_trades |
View trading activity | mint |
| Tool | Description | Parameters |
|---|---|---|
smart_buy |
Buy with fallback (Pump.fun → Jupiter) | token, amount |
smart_sell |
Sell with fallback (Pump.fun → Jupiter) | token, percentage |
| Tool | Description | Parameters |
|---|---|---|
get_swap_quote |
Get swap quotes | input_mint, output_mint, amount |
jupiter_swap |
Execute token swaps | Quote parameters |
| Tool | Description | Parameters |
|---|---|---|
aster_account_info |
Account information and trading status | - |
aster_account_balance |
Account balance and margin details | - |
aster_trade_history |
Recent trade history and performance | limit |
aster_open_long |
Open long position with leverage | symbol, quantity, leverage, price |
aster_close_position |
Close existing position | symbol, quantity, position_side |
aster_position_check |
Check current positions and PnL | - |
| Tool | Description | Parameters |
|---|---|---|
search_pairs |
Search trading pairs | query |
get_token_pairs |
Get pairs for token | address |
get_solana_pair |
Detailed pair information | pair_address |
get_trending_pairs |
Trending pairs by volume | chain |
| Tool | Description | Parameters |
|---|---|---|
polymarket_list_markets |
Discover active Polymarket markets | limit, category, tag, series_slug |
polymarket_opportunity_scan |
Rank markets by ROI/liquidity heuristics | limit, min_volume_24h, max_entry_price, tag |
polymarket_strategy_brief |
Generate entry/exit strategy summaries | count, max_entry_price, category, tag |
| Tool | Description | Parameters |
|---|---|---|
search_web |
Search internet content | query, count |
search_news |
Search news articles | query, count |
"Buy 0.01 SOL worth of BONK on pump.fun"
"Sell 50% of my DOGE position"
"Get swap quote for 1 SOL to USDC on Jupiter"
"Check my wallet balance"
"Show trending pairs on DexScreener"
"Find prediction market opportunities on Polymarket"
"Open a long position on BTC futures with 5x leverage"
"Check my account balance on Aster Futures"sam/
├── cli.py # Enhanced CLI with interactive features
├── core/
│ ├── agent.py # Main SAMAgent with advanced tool calling
│ ├── builder.py # AgentBuilder for modular construction
│ ├── llm_provider.py # Multi-LLM provider abstraction
│ ├── memory.py # SQLite-based conversation persistence
│ ├── tools.py # Tool registry with middleware support
│ ├── events.py # Event system for pub/sub messaging
│ └── middleware.py # Tool middleware pipeline
├── integrations/ # Blockchain and service integrations
│ ├── solana/ # Native Solana RPC operations
│ ├── pump_fun.py # Pump.fun trading interface
│ ├── jupiter.py # Jupiter aggregator integration
│ ├── dexscreener.py # Market data provider
│ ├── polymarket.py # Prediction market analytics
│ ├── aster_futures.py # Futures trading on Aster DEX
│ ├── smart_trader.py # Smart trading with fallbacks
│ └── search.py # Web search via Brave API
├── config/ # Configuration management
│ ├── settings.py # Environment and settings
│ ├── prompts.py # System prompts and templates
│ └── config_loader.py # TOML/JSON configuration loader
├── utils/ # Security and utilities
│ ├── crypto.py # Key encryption with Fernet
│ ├── secure_storage.py # OS keyring integration
│ ├── validators.py # Input validation and safety
│ ├── rate_limiter.py # Request throttling
│ └── connection_pool.py # RPC connection management
├── commands/ # CLI command modules
│ ├── onboard.py # Interactive setup wizard
│ ├── providers.py # LLM provider management
│ ├── health.py # System diagnostics
│ └── maintenance.py # Database maintenance
└── web/ # Web interface components
└── session.py # Web session management
- Event-Driven: Async pub/sub system for component communication
- Plugin Architecture: Entry point discovery for extensibility
- Middleware Pipeline: Configurable tool execution pipeline
- Builder Pattern: Modular agent construction
- Repository Pattern: Data access abstraction
- Connection Pooling: Shared database and HTTP client connections
- Circuit Breaker: API resilience with automatic failure recovery
- Session Management: Persistent conversation contexts with indexing
SAM supports multiple configuration methods with automatic loading priority:
- Environment Variables (highest priority)
- TOML Configuration File (
sam.toml) .envFile (auto-loaded)- Interactive Settings (runtime configuration)
- Sensible Defaults (lowest priority)
| Provider | Environment Variables | Models |
|---|---|---|
| OpenAI | OPENAI_API_KEY, OPENAI_MODEL, OPENAI_BASE_URL |
GPT-4, GPT-3.5 |
| Anthropic | ANTHROPIC_API_KEY, ANTHROPIC_MODEL, ANTHROPIC_BASE_URL |
Claude 3 |
| xAI | XAI_API_KEY, XAI_MODEL, XAI_BASE_URL |
Grok |
| Local | LOCAL_LLM_BASE_URL, LOCAL_LLM_MODEL |
Ollama, LM Studio |
| OpenAI Compat | LOCAL_LLM_BASE_URL, LOCAL_LLM_MODEL |
Custom endpoints |
| Integration | Environment Variables | Description |
|---|---|---|
| Polymarket | - | No API key required (public API) |
| Aster Futures | ASTER_API_KEY, ASTER_API_SECRET, ASTER_BASE_URL, ASTER_DEFAULT_RECV_WINDOW |
Futures trading credentials |
| Brave Search | BRAVE_API_KEY |
Web search and news aggregation |
# sam.toml
[llm]
provider = "anthropic"
model = "claude-3-5-sonnet-latest"
[safety]
max_transaction_sol = 5.0
default_slippage = 2.0
[tools]
enable_solana_tools = true
enable_pump_fun_tools = true
enable_jupiter_tools = true
enable_dexscreener_tools = true
enable_polymarket_tools = true
enable_aster_futures_tools = false
enable_search_tools = false{
"logging": {
"include_args": false,
"include_result": false,
"only": [],
"exclude": []
},
"rate_limit": {
"enabled": true,
"map": {
"search_web": {"type": "search", "identifier_field": "query"},
"pump_fun_buy": {"type": "pump_fun_buy", "identifier_field": "mint"}
}
},
"retry": [
{"only": ["search_web"], "max_retries": 2, "base_delay": 0.25}
]
}SAM supports external tools via Python entry points:
# setup.py or pyproject.toml
[project.entry-points."sam.plugins"]
my_trading_tools = "my_package.tools:register"
[project.entry-points."sam.llm_providers"]
custom_llm = "my_package.llm:create_provider"
[project.entry-points."sam.memory_backends"]
redis_memory = "my_package.memory:create_backend"# my_trading_tools.py
from sam.core.tools import Tool
async def arbitrage_scanner(args: dict) -> dict:
"""Scan for arbitrage opportunities."""
return {
"success": True,
"opportunities": [],
"timestamp": "2024-01-01T12:00:00Z"
}
def register(registry, agent=None):
registry.register(Tool(
name="arbitrage_scanner",
description="Scan for arbitrage opportunities across DEXs",
input_schema={
"type": "object",
"properties": {
"min_profit_percent": {"type": "number", "default": 1.0}
}
},
handler=arbitrage_scanner
))# Load custom plugins
export SAM_PLUGINS="my_package.tools,vendor.tools"
# Use custom memory backend
export SAM_MEMORY_BACKEND="my_package.memory:create_backend"SAM loads third-party plugins only when they are explicitly trusted.
# Enable plugin loading (disabled by default)
export SAM_ENABLE_PLUGINS=true
# Optional settings
export SAM_PLUGIN_ALLOWLIST_FILE=./sam/config/plugin_allowlist.json
export SAM_PLUGIN_ALLOW_UNVERIFIED=false # keep strict mode
# Record a plugin module fingerprint
uv run sam plugins trust my_package.tools --entry-point my-tools --label "Vendor Tools"- The allowlist stores module SHA-256 digests to prevent supply-chain tampering.
- Run
sam debugto review the trusted set and environment state. - When upgrading a plugin, re-run
sam plugins trust …to refresh the recorded hash.
SAM implements multiple layers of security for key management:
| Method | Description | Use Case |
|---|---|---|
| OS Keyring | System-level credential storage | Production deployments |
| Fernet Encryption | AES-128 encryption for keys | Secure storage |
| Environment Variables | Runtime configuration | Development |
- Transaction Validation: Pre-execution safety checks
- Slippage Protection: Configurable slippage tolerance
- Rate Limiting: Request throttling and abuse prevention
- Address Validation: Solana address format verification
- Audit Logging: Tool execution and error tracking
# Security configuration
RATE_LIMITING_ENABLED=true
MAX_TRANSACTION_SOL=5.0
DEFAULT_SLIPPAGE=2.0
LOG_LEVEL=WARNING
# Key management
sam key import # Secure key import
sam key generate # Generate encryption keys
sam key rotate --yes # Rotate SAM_FERNET_KEY and re-encrypt stored secretsSAM includes comprehensive testing infrastructure with 25+ test files covering all major components:
# Run complete test suite
uv run pytest tests/ -v
# Run with coverage reporting
uv run pytest tests/ --cov=sam --cov-report=html
# Run specific test categories
uv run pytest tests/test_integration.py # Integration tests
uv run pytest tests/test_tools.py # Tool registry tests
uv run pytest tests/test_polymarket.py # Polymarket integration
uv run pytest tests/test_aster_futures.py # Futures trading tests
# Run async tests with proper configuration
uv run pytest tests/ --asyncio-mode=auto- Comprehensive Coverage: Unit, integration, and end-to-end tests
- Async Testing: Full asyncio support with pytest-asyncio
- Mock Frameworks: Extensive mocking for external API dependencies
- Environment Testing: Test-specific configurations and fixtures
- Performance Validation: API resilience and error handling tests
# Format code
uv run ruff format
# Check style and fix issues
uv run ruff check --fix
# Type checking
uv run mypy sam/Run before opening a pull request to ensure quality gates stay green:
uv run ruff check # Static analysis
uv run mypy sam/ # Type safety across the package
uv run pytest -v # Full test suiteAll three commands must pass without warnings for CI parity.
SAM ships a single, consolidated decorator toolkit under sam.utils.decorators. These helpers combine rate limiting, error tracking, retry/backoff, and performance telemetry in one place:
from sam.utils.decorators import (
rate_limit,
retry_with_backoff,
log_execution,
safe_async_operation,
performance_monitor,
)
from sam.utils.error_handling import ErrorSeverity
@safe_async_operation(
"dexscreener",
log_result=True,
max_retries=2,
error_severity=ErrorSeverity.MEDIUM,
)
@performance_monitor("dexscreener", warn_threshold=0.5)
@rate_limit("market_data")
async def fetch_pair(mint: str) -> dict:
...All decorator imports that previously referenced sam.utils.enhanced_decorators should now use sam.utils.decorators.
# Setup and development
uv sync # Install dependencies
make install # Alternative setup via Makefile
# Code quality (via Makefile)
make format # Format code with ruff
make lint # Check style and fix issues
make typecheck # Run mypy type checking
make test # Run complete test suite
# Individual commands
sam debug # Show plugins and middleware
sam provider test # Test LLM provider
sam health # System diagnostics
sam settings # Runtime configuration
sam maintenance # Database maintenance operations- Makefile: Standardized development targets for common operations
- Enhanced Testing: 25+ test files with comprehensive coverage
- Async Optimization: uvloop integration for performance
- Connection Pooling: Shared database and HTTP client connections
- Circuit Breakers: API resilience with automatic recovery
import asyncio
from sam.core.builder import AgentBuilder
async def main():
agent = await AgentBuilder().build()
# Direct tool calls
result = await agent.tools.call("get_balance", {"address": "..."})
print(result)
# Headless agent
response = await agent.run("Check my SOL balance", session_id="sdk")
print(response)
asyncio.run(main())- Architecture Guide - System design and components
- Tools Reference - Complete tool documentation
- Configuration Guide - Setup and configuration options
- CLI Reference - Command-line interface documentation
- Security Guide - Security features and best practices
- Getting Started - Step-by-step setup guide
- API Reference - SDK and API documentation
examples/plugins/- Plugin development examplesexamples/sdk/- SDK integration patternstests/- Comprehensive test suite
MIT License with SAM Framework Additional Terms - See LICENSE for complete licensing details.
- Contact Requirement: Must contact @prfa before releasing tools built on SAM Framework
- $SAM Token Benefits: Tools must provide benefits to $SAM token holders
- Ecosystem Participation: Active participation in the $SAM ecosystem rewards program
- Transparency: Clear disclosure of SAM Framework usage and token holder benefits
Contributions welcome. See CONTRIBUTING.md for guidelines.
SAM Framework - Production-ready AI agent infrastructure for Solana blockchain operations.
Built for developers who value technical excellence and production reliability.
SAM encrypts sensitive data (wallet keys, API credentials, wallet configs) using Fernet and the OS keyring by default. The storage layer is now pluggable:
- Base interface:
sam.utils.secure_storage.BaseSecretStoredefines the required methods. The built-inSecureStorageimplementation handles keyring/Fernet encryption with an encrypted file fallback. - Plugins: Provide your own secret store by exposing an entry point in the
sam.secure_storagegroup or by callingconfigure_secure_storage(custom_store). Seeexamples/plugins/secure_storage_dummyfor a simple in-memory example. - Key rotation:
SecureStorage.rotate_encryption_key()migrates stored secrets to a new Fernet key; custom stores should implement similar behavior when possible.
Agent and tool events are published via the async event bus. API adapters can import typed payload definitions from sam/core/event_payloads.py to ensure compatibility. Available payload types include:
AgentStatusPayloadLLMUsagePayloadToolCalledPayloadToolResultPayload/ToolFailedPayloadAgentDeltaPayloadAgentMessagePayload
Every payload includes both session_id and user_id, enabling multi-tenant streaming adapters to filter by caller.
