Ethereum analytics API monetized via x402 micropayments on Base Sepolia testnet.
Q-guard is an Ethereum analytics API demonstrating the x402 micropayment protocol. It provides real-time gas predictions through a pay-per-request model using USDC on Base Sepolia testnet.
Key Features:
- Real-time gas prediction with exponential weighted average algorithm
- x402 micropayment integration with tiered pricing
- ERC-8004 agent reputation for dynamic pricing (up to 50% discounts)
- MEV opportunity detection (sandwich attacks, arbitrage)
- Payment verification via onchain USDC transactions
- Redis caching for < 200ms response times
- WebSocket dashboard for real-time monitoring
- Docker deployment ready
Tech Stack:
- Language: Rust 2021
- Framework: Axum 0.7
- Blockchain: Ethereum mainnet (data), Base Sepolia (payments)
- Payment: x402 protocol with USDC
- Cache: Redis with moka in-memory fallback
- Rust 1.75+
- Docker & Docker Compose
- Base Sepolia ETH (for gas fees)
- Base Sepolia USDC (for testing payments)
git clone https://github.com/mjohnson518/Q-guard.git
cd Q-guardCopy the example environment file and fill in your credentials:
cp env.example .envRequired Environment Variables:
# Ethereum Mainnet (for data)
ETH_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY
ETH_RPC_FALLBACK=https://mainnet.infura.io/v3/YOUR_BACKUP_KEY
ETH_WS_URL=wss://eth-mainnet.g.alchemy.com/v2/YOUR_KEY
# Base Sepolia (for payments)
BASE_SEPOLIA_RPC_URL=https://base-sepolia.g.alchemy.com/v2/YOUR_KEY
USDC_ADDRESS=0x036CbD53842c5426634e7929541eC2318f3dCF7e
# Your Wallet
RECIPIENT_ADDRESS=0xYourBaseSepoliaAddress
SELLER_PRIVATE_KEY=0xYourPrivateKey
# Testing
TEST_WALLET_ADDRESS=0xYourTestWalletAddress
TEST_WALLET_PRIVATE_KEY=0xYourTestWalletPrivateKeydocker-compose up -dThe API will be available at http://localhost:8080
# Start Redis
docker-compose up -d redis
# Run the server
cargo run
# In another terminal, test the payment flow
cargo run --bin test-agentGET /healthResponse:
{
"status": "healthy",
"version": "0.1.0",
"redis": true,
"ethereum_rpc": true,
"uptime_seconds": 3600,
"timestamp": "2025-11-02T10:30:00Z"
}GET /statsResponse:
{
"total_payments": 42,
"revenue_today_usd": 0.42,
"requests_today": 42,
"cache_hit_rate": 0.85,
"avg_response_time_ms": 150.5
}WS /ws/dashboardReal-time stats updates every second.
Real-time gas price prediction for the next Ethereum block.
Without Payment:
GET /api/gas/predictionResponse (402 Payment Required):
{
"success": false,
"error": "Payment required: 0.01 USDC",
"error_code": "PAYMENT_REQUIRED",
"timestamp": "2025-11-02T10:30:00Z",
"request_id": "uuid-here",
"payment_instructions": {
"type": "x402.payment_required",
"version": "1.0.0",
"payment": {
"chain": "base-sepolia",
"asset": "USDC",
"amount": "0.01",
"recipient": "0xYourAddress",
"facilitator": "https://x402-facilitator.example.com"
},
"instructions": {
"header": "X-Payment",
"format": "transaction_hash"
}
}
}With Payment:
curl -H "X-Payment: 0x<transaction_hash>" \
http://localhost:8080/api/gas/predictionResponse (200 OK):
{
"success": true,
"data": {
"base_fee_gwei": 25.3,
"priority_fee_gwei": 2.0,
"max_fee_gwei": 32.36,
"confidence": 0.92,
"block_number": 18500000,
"predicted_at": "2025-11-02T10:30:00Z",
"next_block_time_seconds": 12
},
"timestamp": "2025-11-02T10:30:00Z",
"cache_hit": true,
"data_source": "ethereum-mainnet",
"request_id": "uuid-here"
}Detect profitable MEV opportunities in the mempool (sandwich attacks, arbitrage, etc).
Without Payment:
GET /api/mev/opportunitiesResponse (402 Payment Required):
{
"success": false,
"error": "Payment required: 0.10 USDC",
"error_code": "PAYMENT_REQUIRED",
"payment_instructions": {
"type": "x402.payment_required",
"version": "1.0.0",
"payment": {
"chain": "base-sepolia",
"asset": "USDC",
"amount": "0.10",
"recipient": "0xYourAddress",
"facilitator": "https://x402-facilitator.example.com"
}
}
}With Payment:
curl -H "X-Payment: 0x<transaction_hash>" \
http://localhost:8080/api/mev/opportunitiesResponse (200 OK):
{
"success": true,
"data": [
{
"opportunity_type": "Sandwich",
"profit_usd": 25.50,
"gas_cost_usd": 5.50,
"net_profit_usd": 20.00,
"confidence": 0.75,
"target_transaction": "0xabc...",
"suggested_gas_price": 50.0,
"execution_details": {
"target_pool": "0x...",
"token_in": "0x...",
"token_out": "0x...",
"amount_in": "1000.0",
"expected_profit": "20.0"
},
"expires_in_blocks": 1
}
],
"timestamp": "2025-11-02T10:30:00Z",
"cache_hit": false,
"data_source": "ethereum-mempool",
"request_id": "uuid-here"
}Q-guard implements ERC-8004 agent reputation for dynamic pricing. Agents with higher reputation scores receive discounts on all endpoints.
- 0-99: Access denied
- 100-500: Standard pricing
- 501-1000: 20% discount
- 1000+: 50% discount
Include your agent address in requests using the X-Agent-Address header:
curl -H "X-Agent-Address: 0x2222222222222222222222222222222222222222" \
-H "X-Payment: 0x<tx_hash>" \
http://localhost:8080/api/gas/predictionThe system will:
- Extract your agent address
- Query your reputation score (cached 1 hour)
- Calculate your discounted price
- Verify payment meets discounted amount
- Grant access to data
When no ERC-8004 contract is deployed, these addresses have fixed reputation scores:
0x1111111111111111111111111111111111111111- Reputation: 100 (minimum access, full price)0x2222222222222222222222222222222222222222- Reputation: 500 (standard pricing)0x3333333333333333333333333333333333333333- Reputation: 1000 (20% discount)
Gas Prediction (base $0.01):
- Anonymous: $0.01
- Reputation 250: $0.01
- Reputation 750: $0.008 (20% off)
- Reputation 1500: $0.005 (50% off)
MEV Opportunities (base $0.10):
- Anonymous: $0.10
- Reputation 250: $0.10
- Reputation 750: $0.08 (20% off)
- Reputation 1500: $0.05 (50% off)
-
Make Initial Request
GET /api/gas/prediction
-
Receive 402 Payment Required
- Contains payment instructions
- Specifies amount, recipient, and payment network
-
Send USDC Payment
- Transfer required USDC amount to recipient address on Base Sepolia
- Wait for transaction confirmation
-
Retry with Payment Proof
curl -H "X-Payment: 0x<tx_hash>" /api/gas/prediction -
Receive Data
- Payment is verified onchain
- Request processed and data returned
┌────────┐ ┌─────────┐ ┌──────────────┐
│ Client │ │ Q-guard │ │ Base Sepolia │
└───┬────┘ └────┬────┘ └──────┬───────┘
│ │ │
│ GET /api/gas │ │
├──────────────────►│ │
│ │ │
│ 402 Payment Req │ │
│◄──────────────────┤ │
│ │ │
│ Send USDC tx │ │
├───────────────────┼────────────────────►│
│ │ │
│ tx hash │ │
│◄──────────────────┼─────────────────────┤
│ │ │
│ GET + X-Payment │ │
├──────────────────►│ │
│ │ │
│ │ Verify tx │
│ ├────────────────────►│
│ │ │
│ │ tx confirmed │
│ │◄────────────────────┤
│ │ │
│ 200 OK + data │ │
│◄──────────────────┤ │
│ │ │
The test agent performs a complete payment flow:
cargo run --bin test-agentWhat it does:
- Checks your USDC balance
- Makes initial request (expects 402)
- Sends USDC payment on Base Sepolia
- Retries with payment proof
- Displays gas prediction data
Example Output:
Q-guard Test Agent
===================
Server: http://localhost:8080
Recipient: 0x1234...
Your USDC balance: 1.000000
Testing payment flow...
Step 1: Making initial request (expecting 402)...
[OK] Received 402 Payment Required
Step 2: Sending USDC payment on Base Sepolia...
[OK] Payment sent: 0xabc123...
View on BaseScan: https://sepolia.basescan.org/tx/0xabc123...
Step 3: Retrying request with payment proof...
[OK] Payment verified!
[SUCCESS] Received gas prediction:
{
"success": true,
"data": {
"base_fee_gwei": 25.3,
"priority_fee_gwei": 2.0,
"max_fee_gwei": 32.36,
"confidence": 0.92,
...
}
}
Q-guard uses an exponential weighted average algorithm to predict next-block gas prices:
- Fetch last 20 blocks from Ethereum mainnet
- Apply exponential weights (more recent = higher weight)
- Calculate weighted average of base fees
- Add 20% safety buffer for max fee
- Compute confidence score based on variance
// Recent blocks weighted more heavily
weights = [0.95^19, 0.95^18, ..., 0.95^1, 0.95^0]
weighted_base_fee = Σ(block_fee[i] * weight[i]) / Σ(weight[i])
max_fee = weighted_base_fee * 1.2 + priority_fee- Gas predictions: 12 seconds (1 Ethereum block time)
- Payment verifications: No cache (always verify onchain)
- Analytics: 1 day retention in Redis
- Cached responses: < 200ms
- Uncached responses: < 1s
- Payment verification: 2-5 seconds (depends on Base Sepolia)
- Rate limit: 10 requests/second per IP, burst 30
# Build image
docker-compose build
# Start services
docker-compose up -d
# View logs
docker-compose logs -f q-guard
# Stop services
docker-compose downThe docker-compose.yml automatically:
- Loads
.envfile - Sets
REDIS_URLto connect to Redis container - Waits for Redis to be healthy before starting
Q-guard/
├── src/
│ ├── main.rs # Axum server entry point
│ ├── lib.rs # Library exports
│ ├── config.rs # Configuration loading
│ ├── error.rs # Custom error types
│ ├── models/ # Data models
│ │ ├── gas.rs
│ │ ├── mev.rs
│ │ ├── payment.rs
│ │ └── response.rs
│ ├── services/ # Business logic
│ │ ├── cache.rs # Redis + moka cache
│ │ ├── ethereum.rs # Gas prediction
│ │ ├── mempool.rs # Mempool monitoring
│ │ ├── mev_detector.rs # MEV detection
│ │ ├── analytics.rs # Payment tracking
│ │ └── reputation.rs # ERC-8004 reputation
│ ├── contracts/ # Smart contract ABIs
│ │ └── agent_registry.rs # ERC-8004 interface
│ ├── middleware/ # Request middleware
│ │ ├── x402.rs # Payment verification
│ │ ├── reputation.rs # Agent identification
│ │ └── rate_limit.rs # Rate limiting
│ ├── handlers/ # HTTP handlers
│ │ ├── gas.rs
│ │ ├── mev.rs
│ │ ├── health.rs
│ │ ├── stats.rs
│ │ └── dashboard.rs
│ └── client/ # Test client
│ ├── payment.rs # USDC payment logic
│ └── test_agent.rs # CLI test tool
├── scripts/
│ ├── test_endpoints.sh
│ └── fund_testnet.sh
├── Cargo.toml
├── Dockerfile
├── docker-compose.yml
└── README.md
# Check code
cargo check
# Run tests
cargo test
# Format code
cargo fmt
# Lint
cargo clippy
# Build release
cargo build --release- Private keys in environment variables only
- All Ethereum addresses validated
- Payment verification via onchain data
- Rate limiting per IP address
- CORS configured appropriately
- No sensitive data in logs
- Onchain Verification: Every payment is verified by checking the actual USDC transfer transaction on Base Sepolia
- Amount Validation: Ensures payment amount meets or exceeds the required price
- Recipient Validation: Confirms USDC was sent to the correct recipient address
- No Trusted Intermediaries: Direct onchain verification, no reliance on external payment processors
Solution:
- Get USDC from Base Sepolia faucet or bridge from Ethereum Sepolia
- Check balance:
cast balance <address> --rpc-url $BASE_SEPOLIA_RPC_URL
Possible causes:
- Transaction not confirmed yet (wait a few seconds)
- Wrong recipient address
- Insufficient USDC amount
- Transaction failed onchain
Check transaction:
# View on BaseScan
https://sepolia.basescan.org/tx/<tx_hash>Solution:
- Verify RPC URL is correct
- Check API key hasn't exceeded rate limits
- Try fallback RPC if configured
- Use a different RPC provider (Alchemy, Infura, Ankr)
Impact: API still works, uses in-memory cache only
Solution:
# Check Redis is running
docker-compose ps redis
# Restart Redis
docker-compose restart redis
# Check logs
docker-compose logs redisConnect to ws://localhost:8080/ws/dashboard for real-time metrics updated every second.
MIT License - see LICENSE file for details
Contributions welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
- GitHub Issues: https://github.com/mjohnson518/Q-guard/issues
- x402 Documentation: https://x402.org
- Base Sepolia Faucet: https://www.coinbase.com/faucets/base-ethereum-goerli-faucet
Built with Rust, Axum, and x402