Python-based backend for ContractMind AI-powered blockchain infrastructure.
- FastAPI - High-performance async web framework
- FastMCP - Model Context Protocol for AI agent integration
- Web3.py - Blockchain interaction with Somnia
- PostgreSQL - Analytics and agent configuration storage
- Redis - Session management and caching
- Anthropic Claude - AI intent parsing
- WebSockets - Real-time chat communication
Frontend (React)
β WebSocket
Backend (FastAPI + FastMCP)
βββΊ AI Service (Claude) β Parse intent
βββΊ Intent Service β Detect contract type
βββΊ Execution Service β Prepare transaction
βββΊ Blockchain Service β Web3 interaction
β
Somnia Blockchain
βββΊ AgentRegistry
βββΊ ContractMindHubV2
βββΊ Protocol Contracts
- Python 3.11+
- PostgreSQL 14+
- Redis 7+
- Poetry (Python package manager)
- Access to Somnia RPC
- Anthropic API key
curl -sSL https://install.python-poetry.org | python3 -cd backend
poetry installcp .env.example .env
# Edit .env with your configurationRequired environment variables:
# Blockchain
SOMNIA_RPC_URL=https://dream-rpc.somnia.network
AGENT_REGISTRY_ADDRESS=0x... # From deployment
CONTRACT_MIND_HUB_ADDRESS=0x... # From deployment
# AI
ANTHROPIC_API_KEY=your-api-key-here
# Database
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/contractmind
# Redis
REDIS_URL=redis://localhost:6379/0# Start PostgreSQL and Redis (using Docker)
docker-compose up -d postgres redis
# Run migrations
poetry run alembic upgrade head# Copy ABIs from contracts deployment
poetry run python scripts/sync_contracts.pypoetry run uvicorn app.main:app --reloadServer will start at: http://localhost:8000
- API Docs: http://localhost:8000/docs
- Health Check: http://localhost:8000/health
backend/
βββ app/
β βββ api/v1/ # API endpoints
β β βββ agents.py # Agent management
β β βββ chat.py # Chat (REST)
β β βββ transactions.py
β β βββ analytics.py
β β βββ websocket.py # WebSocket chat
β β
β βββ services/ # Business logic
β β βββ ai_service.py
β β βββ intent_service.py
β β βββ execution_service.py
β β βββ blockchain_service.py
β β βββ analytics_service.py
β β
β βββ blockchain/ # Web3 layer
β β βββ client.py
β β βββ contracts/
β β βββ events.py
β β
β βββ mcp/ # FastMCP integration
β β βββ server.py
β β βββ tools.py
β β βββ prompts.py
β β
β βββ models/ # Data models
β β βββ database.py
β β βββ schemas.py
β β
β βββ db/ # Database
β βββ session.py
β
βββ tests/ # Tests
βββ scripts/ # Utility scripts
βββ contracts/ # Contract ABIs
1. User WebSocket: "Stake 1000 tokens"
β
2. AI Service (Claude): Parse β {action: "stake", amount: 1000}
β
3. Intent Service:
- Query AgentRegistry
- Detect: hub-aware contract
- Map: stake β stake(uint256)
β
4. Execution Service:
- Prepare: hub.executeOnTarget(...)
- Estimate gas: ~370k
β
5. WebSocket: Send transaction to frontend
β
6. User signs & broadcasts
β
7. Event Listener:
- Monitor transaction
- Parse events
- Store analytics
β
8. WebSocket: Send success notification
1. User: "Swap 100 SOMI for USDC"
β
2. AI Service: Parse β {action: "swap", ...}
β
3. Intent Service:
- Detect: regular contract (Uniswap)
- Map: swap β swapExactTokensForTokens
β
4. Execution Service:
- Prepare: DIRECT to Uniswap
- Estimate gas: ~150k
β
5. WebSocket: Send direct transaction
β
6. User signs & broadcasts (bypasses hub)
β
7. Analytics: Track off-chain
WS /api/v1/ws/chat/{user_address}
Message types:
// Send
{
"type": "chat",
"message": "Stake 1000 tokens"
}
// Receive
{
"type": "transaction_ready",
"transaction": {
"to": "0x...",
"data": "0x...",
"gas": 370000,
"description": "Stake 1000 SOMI"
}
}GET /api/v1/agents # List agents
GET /api/v1/agents/{id} # Get agent
POST /api/v1/chat/message # Process message (REST)
POST /api/v1/transactions/status # Get tx status
POST /api/v1/transactions/validate
GET /api/v1/analytics/user/{address}
GET /api/v1/analytics/agent/{id}
GET /api/v1/analytics/global
# app/config.py
class Settings:
# Blockchain
SOMNIA_RPC_URL: str
CHAIN_ID: int = 50312
# Contracts
AGENT_REGISTRY_ADDRESS: str
CONTRACT_MIND_HUB_ADDRESS: str
# AI
ANTHROPIC_API_KEY: str
# Database
DATABASE_URL: str
# Redis
REDIS_URL: str
# Rate Limiting
RATE_LIMIT_PER_MINUTE: int = 60FastMCP provides structured AI agent context:
from fastmcp import FastMCP
mcp = FastMCP("ContractMind")
@mcp.tool()
async def parse_intent(message: str) -> dict:
"""Parse user intent using Claude"""
# AI parsing logic
pass
@mcp.tool()
async def validate_transaction(...) -> bool:
"""Validate transaction authorization"""
# Blockchain validation
pass
@mcp.resource("contract://agents")
async def list_agents() -> str:
"""Get available agents for AI context"""
pass# app/models/database.py
class Transaction(Base):
id = Column(Integer, primary_key=True)
tx_hash = Column(String, unique=True)
user_address = Column(String, index=True)
agent_id = Column(String, index=True)
target_contract = Column(String)
function_selector = Column(String)
success = Column(Boolean)
gas_used = Column(Integer)
created_at = Column(DateTime)
class AgentAnalytics(Base):
id = Column(Integer, primary_key=True)
agent_id = Column(String, index=True)
total_calls = Column(Integer)
total_gas_used = Column(BigInteger)
success_rate = Column(Float)
updated_at = Column(DateTime)# Run all tests
poetry run pytest
# Run with coverage
poetry run pytest --cov=app tests/
# Run specific test
poetry run pytest tests/test_services/test_intent_service.pyWe keep unit tests fast and offline by default. For a quick live-network sanity check:
# Smoke script: verifies RPC connectivity and that deployed addresses have bytecode
poetry run python scripts/smoke_onchain.py
# Optional pytest on-chain test (opt-in)
RUN_ONCHAIN_TESTS=1 poetry run pytest -m onchain -qCurrent Somnia Testnet deployments:
- AgentRegistry:
0x318FFd8Fc398a3639Faa837307Ffdd0b9E1017c9 - ContractMindHubV2:
0x8244777FAe8F2f4AE50875405AFb34E10164C027 - Chain ID:
50312 - RPC:
https://dream-rpc.somnia.network
# Build image
docker build -t contractmind-backend .
# Run with docker-compose
docker-compose up -d# docker-compose.yml
version: '3.8'
services:
backend:
build: .
ports:
- "8000:8000"
env_file:
- .env
depends_on:
- postgres
- redis
postgres:
image: postgres:15
environment:
POSTGRES_DB: contractmind
POSTGRES_USER: contractmind
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
ports:
- "6379:6379"curl http://localhost:8000/health# View logs
poetry run python -m app.utils.logger
# Database connection pool stats
curl http://localhost:8000/api/v1/analytics/global- WebSocket connection validation
- Rate limiting (Redis-based)
- Transaction validation before execution
- Signature verification (future)
- API key authentication (future)
- Create route in
app/api/v1/ - Add service logic in
app/services/ - Update schema in
app/models/schemas.py - Add tests in
tests/
- Copy ABI to
contracts/abis/ - Create interface in
app/blockchain/contracts/ - Register in blockchain service
- Update AI prompts for intent parsing
See .env.example for all configuration options.
Critical variables:
SOMNIA_RPC_URL- Blockchain RPC endpointAGENT_REGISTRY_ADDRESS- Deployed registryCONTRACT_MIND_HUB_ADDRESS- Deployed hubANTHROPIC_API_KEY- Claude API keyDATABASE_URL- PostgreSQL connectionREDIS_URL- Redis connection
- Fork the repository
- Create feature branch
- Add tests
- Run linting:
poetry run black . && poetry run isort . - Submit pull request
MIT License
- Frontend:
../frontend - Contracts:
../contracts - Documentation:
../docs - API Docs: http://localhost:8000/docs