An autonomous AI agent that plays blackjack on the Base blockchain, powered by Coinbase AgentKit and OpenAI. The agent makes strategic decisions, executes on-chain transactions, and automatically claims winningsโall while streaming real-time gameplay updates to a Next.js dashboard.
- ๐ค Autonomous Gameplay: AI agent makes strategic hit/stand decisions using GPT-4
- ๐ Real-time Dashboard: Live card display and game state visualization via Server-Sent Events (SSE)
- ๐ฒ Provably Fair: Uses Chainlink VRF (Verifiable Random Function) for cryptographically secure card dealing
- ๐ฐ Automatic Claiming: Detects completed games and claims winnings automatically
- ๐ Smart State Management: 11-state game loop handles VRF callbacks and trading periods
- โ๏ธ Base Network: Deployed on Base blockchain for low-cost transactions
- ๐ Statistics Tracking: Monitors wins, losses, pushes, busts, and win streaks
The application uses a dual-path architecture for optimal performance:
-
Direct RPC Path - Efficient contract reads and claiming
- Game status checks (
getGameStatus(),getPlayerStats()) - Direct claiming of winnings bypasses AI for speed
- VRF state polling and trading period detection
- Game status checks (
-
AI Agent Path - Strategic gameplay decisions
- AI analyzes game state and chooses hit/stand
- Executes actions through custom blackjack action provider
- Natural language conversation interface with blockchain execution
1. Check for existing game โ Resume if active
2. Start new game with ETH bet โ Wait for VRF initial deal
3. AI evaluates hand โ Make hit/stand decision
4. Execute action โ Wait for VRF card dealing
5. Repeat until game complete
6. Automatically claim winnings
7. Stop (single-game mode)
The blackjack contract uses Chainlink VRF for provably fair randomness:
- All card dealing is cryptographically secure and verifiable on-chain
- VRF callbacks typically complete within 2-30 seconds
- Application polls contract every 2 seconds for state changes
- Node.js 18+ and npm
- Coinbase Developer Platform API keys
- OpenAI API key
- ETH on Base Sepolia testnet (for development)
-
Clone the repository
git clone <your-repo-url> cd onchain-agent
-
Install dependencies
npm install
-
Configure environment variables
cp .env.example .env
Edit
.envand add your API keys:# Required: OpenAI API Key OPENAI_API_KEY=sk-... # Required: Coinbase Developer Platform credentials CDP_API_KEY_ID=... CDP_API_KEY_SECRET=... # Optional: Will be auto-generated if not provided CDP_WALLET_SECRET=... AI_WALLET=0x... # Contract configuration BLACKJACK_CONTRACT_ADDRESS=0x1234... # Provided in .env.example NETWORK_ID=base-sepolia # Betting configuration BET_AMOUNT=700000000000000 # 0.0007 ETH in wei NEXT_PUBLIC_BET_AMOUNT=0.0007
-
Fund your wallet
The application will generate a wallet on first run and save it to
wallet_data.txt. Fund this address with Sepolia ETH using a Base Sepolia faucet. -
Start the development server
npm run dev
-
Open the dashboard
Navigate to http://localhost:3000 to see the autonomous player dashboard.
The primary interface is the autonomous player dashboard:
- Start Autonomous Play - Click to begin a single game
- Watch Live - Real-time card display shows dealer and player hands
- View Statistics - Track wins, losses, and performance metrics
- Action Log - See detailed event history
The agent will:
- Start a new game (or resume/claim existing)
- Make strategic decisions based on card values
- Execute transactions on-chain
- Wait for VRF callbacks
- Claim winnings automatically
- Stop after one game (click Start again for next game)
You can also interact with the agent via natural language:
You: "Start a blackjack game with 0.001 ETH"
Agent: [Executes startGame transaction and waits for VRF]
You: "What's the game status?"
Agent: "Your hand: 15 (7โ 8โฅ), Dealer: 10โฆ. You can hit or stand."
You: "Hit me"
Agent: [Executes hit transaction, waits for VRF card]
onchain-agent/
โโโ app/
โ โโโ api/
โ โ โโโ agent/ # AI agent endpoints
โ โ โ โโโ action-providers/
โ โ โ โ โโโ blackjack/ # Custom blackjack actions
โ โ โ โโโ prepare-agentkit.ts # AgentKit initialization
โ โ โ โโโ create-agent.ts # OpenAI agent setup
โ โ โ โโโ route.ts # Chat API endpoint
โ โ โโโ autonomous/
โ โ โโโ route.ts # Control autonomous player
โ โ โโโ stream/
โ โ โโโ route.ts # SSE stream endpoint
โ โโโ hooks/
โ โ โโโ useAutonomousPlayer.ts # SSE client hook
โ โโโ page.tsx # Main dashboard page
โโโ components/
โ โโโ GameDashboard.tsx # Main dashboard component
โ โโโ CardDisplay.tsx # Real-time card visualization
โ โโโ StateMachine.tsx # State machine diagram
โ โโโ GameStats.tsx # Statistics display
โ โโโ ActionLog.tsx # Event history
โโโ lib/
โ โโโ game-loop.ts # 11-state game loop
โ โโโ autonomous-player.ts # Player manager singleton
โ โโโ rpc-client.ts # Direct RPC contract interface
โโโ Blackjack.sol # Smart contract source (reference)
โโโ Blackjackabi.json # Contract ABI
โโโ CLAUDE.md # Detailed technical documentation
npm run dev # Start development server
npm run build # Production build
npm start # Run production server
npm run lint # Run ESLintapp/api/agent/prepare-agentkit.ts- Configure AgentKit, wallet provider, and action providersapp/api/agent/create-agent.ts- Configure OpenAI model and system promptslib/game-loop.ts- Adjust game loop behavior and state transitions.env- Environment variables for API keys and contract addresses
The blackjack action provider (app/api/agent/action-providers/blackjack/) implements:
blackjack_start_game- Start game with ETH betblackjack_hit- Draw another cardblackjack_stand- End player's turnblackjack_claim_winnings- Claim winnings from completed gameblackjack_get_game_status- Get full game stateblackjack_get_player_stats- Get lifetime statistics
All actions automatically handle VRF polling and wait for callbacks to complete.
The blackjack game is powered by a smart contract deployed on Base:
- Network: Base Sepolia (testnet) / Base Mainnet (production)
- Contract: See
BLACKJACK_CONTRACT_ADDRESSin.env.example - Source:
Blackjack.sol(included for reference) - Features:
- Chainlink VRF for provably fair randomness
- Prediction market trading period (60 seconds)
- Single game per address constraint
- Automatic payout calculation
- CLAUDE.md - Comprehensive technical documentation
- Architecture deep-dive
- State machine details
- API reference
- Development workflows
Contributions are welcome! This project demonstrates:
- Custom AgentKit action providers
- On-chain gaming with VRF
- Real-time web3 dashboards
- Autonomous agent architectures
Feel free to:
- Add new game strategies
- Improve the AI decision-making
- Enhance the dashboard UI
- Add analytics and insights
MIT License - see LICENSE file for details
- Coinbase AgentKit - AI agent framework
- Coinbase Developer Platform - CDP documentation
- Chainlink VRF - Verifiable randomness
- Base Network - Ethereum L2 blockchain
- Next.js - React framework
Built with โค๏ธ using Coinbase AgentKit