Demonstrating autonomous agent-to-agent commerce through x402 micropayments on Solana
Intelligent AI agents that autonomously research websites, analyze traffic data, compete for advertising space, and generate creative content - all coordinated through economic signals powered by x402 micropayments.
This project demonstrates autonomous AI advertising agents that use x402 micropayments to discover opportunities, make data-driven decisions, compete economically, and deliver tangible outcomes - all without human intervention.
Analytical Ad Agents - Two competing AI agents (Crossmint and Coinbase CDP) autonomously:
- Research websites by scraping content via Firecrawl (x402, ~$0.01)
- Purchase traffic analytics data from publishers (x402, $0.01)
- Analyze site relevance and ROI with Gemini AI
- Compete for advertising space through bidding (x402, $1-100)
- Generate creative ad images via Freepik (x402, ~$0.10)
- Display winning ads on the publisher's website
Core Innovation: Economic signals as coordination mechanism. When an agent gets refunded after being outbid, they detect the state change through their balance and automatically re-evaluate their strategy. No polling, no webhooks - just HTTP + x402.
- Node.js 18+
- MongoDB Atlas (free tier works)
- Google Gemini API Key (for AI agents)
- Firecrawl API Key (optional - for web scraping)
- Freepik API Key (for image generation)
- Solana CLI (optional - for wallet management)
git clone https://github.com/your-org/x402-ad-bid.git
cd x402-ad-bid
npm installCopy .env.example to .env.local and fill in values:
cp .env.example .env.localRequired Variables:
SOLANA_NETWORK=devnet(ormainnet-betafor production)SERVER_WALLET_PRIVATE_KEY- Generate Solana keypair (see below)ADDRESS- Your Solana public key (from keypair)MONGODB_URI- Get from MongoDB AtlasMONGODB_DB_NAME=ad-bidFREEPIK_API_KEY- Get from https://www.freepik.com/apiFIRECRAWL_API_KEY- Optional, get from https://firecrawl.dev/
Generate Solana Keypair:
node -e "const {Keypair} = require('@solana/web3.js'); const bs58 = require('bs58'); const kp = Keypair.generate(); console.log('Private:', bs58.encode(kp.secretKey)); console.log('Public:', kp.publicKey.toBase58());"Copy agents/.env.example to agents/.env:
cp agents/.env.example agents/.envRequired Variables:
AGENT_A_PRIVATE_KEY- Solana private key (base58) for Coinbase CDP agentAGENT_B_PRIVATE_KEY- Solana private key (base58) for Crossmint agentBID_GEMINI_API_KEY- Google Gemini API keyBID_SERVER_URL=http://localhost:3000
Generate agent keypairs using the same method as server wallet.
Fund Server Wallet:
# Get SOL for transaction fees
solana airdrop 1 <SERVER_PUBLIC_KEY> --url devnet
# Get USDC from devnet faucet or Jupiter
# Visit: https://faucet.solana.com/ or use Jupiter swapFund Agent Wallets:
# Fund Agent A
solana airdrop 1 <AGENT_A_PUBLIC_KEY> --url devnet
# Then swap some SOL for USDC
# Fund Agent B
solana airdrop 1 <AGENT_B_PUBLIC_KEY> --url devnet
# Then swap some SOL for USDCNote: For production (mainnet), transfer real SOL and USDC from your wallet.
# Terminal 1: Start server
npm run dev
# Terminal 2: Start Crossmint agent
npm run agent:crossmint
# Terminal 3: Start Coinbase CDP agent
npm run agent:cdp
# Browser: Watch the competition
open http://localhost:3000/analytical-agents
# Browser: View the publisher site with winning ads
open http://localhost:3000/devnewsYou can also view detailed auction activity for specific ad spots at:
http://localhost:3000/auction/devnews-banner
http://localhost:3000/auction/devnews-sidebar
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AI Agents ββ Gemini 1.5 Pro (Vercel AI SDK) β
β - Crossmint ββ x402-axios (auto payment handling) β
β - CoinbaseCDP ββ Viem wallet (Base Sepolia + Mainnet) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
HTTP + x402
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Next.js Server ββ Handles 402 responses β
β /api/bid ββ Verifies & settles payments β
β /api/analytics ββ x402-hono middleware β
β /api/generate ββ CDP Server Wallet β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MongoDB Atlas ββ Stores ad spot records β
β - adSpotRecords ββ Stores events for polling β
β - events β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Core Innovation: x402 enables agents to use HTTP status code 402 Payment Required for seamless micropayments.
1. Agent makes request β Server
2. Server responds 402 with payment requirements
3. x402-axios intercepts β Signs EIP-3009 authorization β Auto-retries
4. Server verifies β Settles via facilitator β Updates state
5. If someone was winning β Server refunds them (economic signal!)
ββββββββββββ $0.01 ββββββββββββ $0.01 βββββββββββββ
β Scrape ββββββx402βββ Fetch ββββββx402βββ AI β
β Website β Firecrawl β Analyticsβ Server β Analysis β
ββββββββββββ ββββββββββββ βββββββββββββ
β
βΌ
ββββββββββββ $0.10 ββββββββββββ $1-100 βββββββββββββ
β Display ββββββx402βββ Generate ββββββx402βββ Compete β
β Ad β Freepik β Creative β Server β & Bid β
ββββββββββββ ββββββββββββ βββββββββββββ
| Network | Purpose | Payments |
|---|---|---|
| Solana Devnet | Ad bidding & analytics (testnet) | $0.01-100 USDC (test tokens) |
| Solana Mainnet | External services (production) | $0.01-0.50 USDC (real) |
Why? Test bidding with free tokens, but pay real services (Firecrawl, Freepik) with real USDC.
Agents discover advertising opportunities by scraping publisher websites:
- Pay Firecrawl via x402 to extract content
- Analyze site topic, industry, and audience
- Identify available ad spots
Agents pay the publisher for traffic data:
- Request analytics via x402 payment to server
- Receive visitor counts, demographics, engagement metrics
- Store data for AI analysis
Gemini AI analyzes the opportunity:
- Evaluate site relevance to agent's brand
- Calculate expected ROI based on traffic
- Determine strategic bid amount (not hardcoded!)
- Decide whether to compete
Agents bid on ad spots using x402:
- Propose bid amount to server
- Server responds 402 with exact price requirement
- Agent pays via EIP-3009 authorization
- Server refunds previous highest bidder (economic signal!)
- Outbid agents detect refund and re-evaluate
Winning agent generates ad creative:
- Pay Freepik via x402 for AI image generation
- Provide brand-specific prompt
- Receive production-ready ad image
Publisher automatically displays winning ad:
- Frontend polls for
ad_image_readyevents - Renders winning agent's creative
- Shows brand, image, and ad spot metadata
Traditional: Webhooks, polling, external event systems x402 Way: Refunds are signals
// Agent detects refund automatically
const newBalance = await getUSDCBalance();
if (newBalance > lastBalance) {
console.log("π REFUND DETECTED - I was outbid!");
// Re-evaluate strategy and potentially re-bid
}Same agent, same wallet, multiple x402 services:
- Firecrawl (scraping)
- Publisher (analytics + bidding)
- Freepik (image generation)
No integration complexity - x402 handles all payment flows uniformly.
Not hardcoded:
Agent spends $0.02 on research β
Analyzes data with AI β
Decides budget dynamically β
Competes strategically
Real cost-benefit analysis in every decision.
From research to creative generation, agents:
- β Pay for their own data
- β Make strategic decisions
- β Compete economically
- β Deliver tangible outcomes
- β Zero human intervention
- Framework: Next.js 15 (App Router, Turbopack)
- AI: Vercel AI SDK, Google Gemini 1.5 Pro
- Blockchain: Coinbase CDP SDK, Viem, Wagmi
- Payments: x402 protocol (x402-axios, x402-hono)
- Database: MongoDB Atlas
- Real-time: MongoDB Polling (2-second intervals)
- Styling: Tailwind CSS 4
- External Services: Firecrawl (scraping), Freepik (image generation)
Built with:
- Vercel AI SDK: Tool calling framework with generateText
- Gemini 1.5 Pro: Strategic reasoning and decision-making
- x402-axios: Automatic 402 interception and payment handling
- Viem: Wallet management (private keys β EIP-3009 signatures)
Agent Lifecycle:
1. Initialize β Load brand identity, wallet, budget constraints
2. Discover β Scrape websites to find ad opportunities
3. Research β Purchase analytics data from publishers
4. Analyze β Use Gemini AI to evaluate ROI
5. Compete β Bid on promising ad spots
6. Monitor β Detect refunds (economic signals)
7. Generate β Create ad creative if won
8. Repeat β Until budget exhaustedTools Available:
scrapeWebsite()- Firecrawl integration (x402)fetchAnalytics()- Publisher data (x402)analyzeAndDecide()- Gemini AI analysisplaceBid()- Bid on ad spot (x402)checkBalance()- Monitor for refundsgenerateAdImage()- Freepik integration (x402)
Built with:
- Next.js 15: App Router, API routes
- x402-hono: 402 response middleware
- CDP Server Wallet v2: Receives payments, sends refunds
- MongoDB Atlas: Persistent ad spot state
Core Endpoints:
| Endpoint | Method | x402? | Purpose |
|---|---|---|---|
/api/bid/[adSpotId] |
POST | β | Accept bids with payment |
/api/site-analytics |
GET | β | Sell analytics data to agents |
/api/generate-ad-image |
POST | β | Proxy to Freepik with agent payment |
/api/events/[adSpotId] |
GET | β | Polling endpoint for frontend |
Settlement Lock Pattern:
// Prevent "replacement transaction underpriced" errors
const settlementLocks = new Map<string, Promise<any>>();
// Queue concurrent bids
if (settlementLocks.has(adSpotId)) {
await settlementLocks.get(adSpotId);
}
settlementLocks.set(adSpotId, settlementPromise);Collections:
adSpotRecords:
{
adSpotId: "devnews-banner",
currentBid: 45.00,
currentWinner: { agentId, walletAddress, timestamp },
bidHistory: [{ agentId, amount, txHash }],
adImage: { url, prompt, generatedAt }
}analyticalEvents (for polling):
{
adSpotId: "devnews-banner",
event: {
type: "bid_placed" | "thinking" | "refund" | "ad_image_ready",
agentId: "CrossmintAgent",
// ... event-specific data
},
timestamp: ISODate
}Built with:
- React 19: Server Components + Client Components
- Polling: Fetch
/api/events/[adSpotId]every 2 seconds - Tailwind CSS 4: Grayscale, terminal-style UI
Pages:
/analytical-agents- Terminal panels showing both agents' activity/devnews- Mock publisher site displaying winning ads/auction/[adSpotId]- Detailed auction feed for specific ad spots
Event Flow:
Server broadcasts event β MongoDB β
Frontend polls (2s) β React state update β UI renders
- analytical-agents-flow.md - Detailed step-by-step flow
- analytical-agents-idea.md - High-level concept
- analytical-agents-case-study.md - Complete technical spec
- CLAUDE.md - Comprehensive development guide
# Check agent USDC balances
open https://sepolia.basescan.org/address/[AGENT_ADDRESS]
# View transaction details
open https://sepolia.basescan.org/tx/[TX_HASH]
# Check MongoDB state
# Use MongoDB Compass or Atlas UI to query adSpotRecords collection
# View live agent activity
# Terminal logs show detailed reasoning and decision-making"Replacement transaction underpriced" β Settlement lock prevents this. If it occurs, agents bid too fast (lock queues them).
"Payment verification failed" β Check agent USDC balance and ensure funded on Base Sepolia.
Events not updating in UI
β Check DevTools Network tab for /api/events/[adSpotId] polling every 2s.
Agent not re-bidding after refund β Check balance monitoring loop (2s interval). Verify agent hasn't hit max budget.
- Versatility: Handles $0.01 micropayments to $100 bids
- Composability: Agents combine multiple x402 services seamlessly
- Coordination: Economic signals (refunds) enable agent-to-agent interaction
- Production Ready: Real payments on real services with real outcomes
- Economic Actors: Agents invest in information, analyze ROI, compete strategically
- Practical Utility: Not a toy - real websites, real analytics, real advertising
- Observable Intelligence: Humans watch agents think and make decisions
- Autonomous Commerce: End-to-end workflows without human intervention
- Agent-to-Agent Markets: Brands hire AI agents who discover opportunities and compete
- Dynamic Pricing: Publishers sell data/services via x402 (no pre-negotiation needed)
- Economic Coordination: Payments as signals eliminate polling/webhooks/contracts
MIT
Contributions welcome! This is a demonstration project showcasing x402 capabilities.
Areas for Contribution:
- Additional agent strategies (aggressive, conservative, adaptive)
- More x402 service integrations (research, analytics, creative)
- Enhanced UI/visualization (graphs, charts, history)
- Multi-agent coordination patterns
- Performance optimizations
See CLAUDE.md for development guidelines.
Built with:
- x402 Protocol - HTTP payments
- Coinbase CDP - Server wallets
- Google Gemini - AI reasoning
- Vercel AI SDK - AI SDK with tool calling
- Firecrawl - Web scraping
- Freepik - AI image generation
Questions? See CLAUDE.md for detailed documentation or open an issue.
Ready to see it in action? Follow the Quick Start above!