Skip to content

Vitthal-Agarwal/MBC

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

212 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PlayBase Games - Battle Royale Betting Platform

Decentralized prediction gaming on Base with real-time NFL props, powered by Chainlink oracles

License: MIT Built on Base Powered by Chainlink

🎮 Overview

PlayBase Games is a cutting-edge Web3 gaming platform featuring three unique prediction-based games built on Base (Coinbase's Layer 2). Our flagship game, Battle Royale, combines the excitement of elimination-style gaming with real-time NFL predictions verified by Chainlink oracles.

Key Features

  • 🏈 Real-Time NFL Props - Live propositions from actual NFL games
  • Instant Elimination - Wrong predictions = out of the game
  • 🔗 Chainlink Oracle Verification - Trustless outcome resolution
  • 💰 USDC Payments - Native Circle USDC integration on Base
  • 🎯 Multiple Game Modes - Battle Royale, Degen League, Touchdown Tokens
  • 🚀 Base Layer 2 - Low fees, fast transactions
  • 📱 Mobile-First Design - Optimized for smartphones and tablets

🏆 Game Modes

1. Battle Royale (Primary)

100 enter. 10 win. Only the sharpest survive.

  • Entry Fee: $10 USDC
  • Maximum Players: 100
  • Winners: Last 10 survivors split the prize pool ($1,000)
  • Duration: 15-20 rounds (~1 hour)
  • Prediction Time: 30 seconds per prop

How It Works:

  1. Join a lobby with 99 other players
  2. Every 3-5 minutes, a new NFL prop appears
  3. Lock your prediction (YES or NO) within 30 seconds
  4. Wrong predictions = eliminated
  5. Last 10 standing share the pot equally

Oracle Integration:

  • Props selected from live NFL games via Sportradar API
  • Outcomes verified by Chainlink Functions (decentralized oracle network)
  • ESPN API integration for real-time game data
  • Cryptographic proof of all results

2. Degen League (Secondary)

Draft your betting portfolio. Compete for the top spot.

  • Entry Fee: $25 USDC
  • Snake Draft Format: Pick 10 props from a pool of 50
  • Scoring: Points based on bet difficulty and outcome
  • Duration: Full NFL week
  • Prize Structure: Top 3 players win (60%/30%/10%)

Features:

  • Live prop trading (buy/sell positions)
  • Real-time leaderboard
  • Portfolio analytics and insights
  • Matchup comparison tool

3. Touchdown Tokens (Experimental)

Player tokens on bonding curves. Score = moon.

  • Buy/Sell tokens for NFL players
  • Price increases with each touchdown scored
  • Bonding curve mechanics (constant product formula)
  • Real-time event processing
  • Secondary market for token trading

🛠 Technical Architecture

Smart Contracts (Solidity 0.8.20)

BattleRoyaleOracle.sol

Main contract for the Battle Royale game with Chainlink integration.

Key Features:

  • Game state management (players, rounds, eliminations)
  • Chainlink Functions oracle integration
  • USDC payment handling (ERC20)
  • Prediction locking with time constraints
  • Automated settlement via oracle callback
  • Winner payout distribution

Functions:

createGame(uint256 entryFee, uint256 maxPlayers) returns (uint256 gameId)
joinGame(uint256 gameId) payable
lockPrediction(uint256 gameId, uint256 round, Choice choice)
requestOutcome(uint256 gameId, uint256 round) // Triggers Chainlink
settleRound(uint256 gameId, uint256 round, Choice outcome) // Auto-called by oracle
claimWinnings(uint256 gameId)

Deployed Contracts:

  • BattleRoyaleOracle: 0x6F1422A4077eaE78f2482bD1f4340219AF42b092 (Base Sepolia)
  • USDC: 0xC9617BeE6Afa6223fE8Fa9C4B6Fbd885bF9006d1 (Base Sepolia)
  • Chain ID: 84532

DegenLeague.sol

Draft-based betting competition contract.

TouchdownTokens.sol

Bonding curve implementation for player tokens.

Backend Architecture

backend/
├── orchestrator/
│   ├── game-loop-oracle.ts        # Main oracle game loop
│   ├── game-loop.ts                # Simulated game loop (testing)
│   ├── prop-selector-astera.ts     # Prop selection via Astera
│   ├── prop-selector-sportradar.ts # Real NFL game data
│   └── outcome-checker-astera.ts   # Outcome verification
├── api/
│   ├── astera-mcp-client.ts        # Astera MCP integration
│   ├── astera-supabase.ts          # Direct Supabase access
│   ├── sportradar.ts               # NFL game data API
│   ├── odds-api.ts                 # Betting odds aggregator
│   └── espn.ts                     # ESPN scoreboard API
├── websocket/
│   └── server.ts                   # Real-time client updates
├── scripts/
│   ├── test-oracle-complete.ts     # Full oracle test
│   ├── create-oracle-test-game.ts  # Game creation
│   └── run-game-loop-oracle.ts     # Start game loop
└── utils/
    ├── blockchain.ts               # Viem client setup
    └── types.ts                    # Shared TypeScript types

Frontend (Next.js 14)

app/
├── battle-royale/
│   ├── page.tsx                    # Game selection
│   ├── lobby/page.tsx              # Waiting room
│   ├── lobbies/page.tsx            # Active lobbies list
│   ├── game/page.tsx               # Active gameplay
│   └── dashboard/page.tsx          # Player stats
├── game2-draft/
│   ├── page.tsx                    # Degen League home
│   ├── draft-board/page.tsx        # Snake draft UI
│   ├── portfolio/page.tsx          # Your positions
│   └── matchup/page.tsx            # Opponent comparison
├── touchdown-tokens/
│   ├── page.tsx                    # Token marketplace
│   ├── [playerId]/page.tsx         # Individual token page
│   └── portfolio/page.tsx          # Your tokens
└── components/
    ├── WalletConnect.tsx           # Coinbase Wallet integration
    ├── PropCard.tsx                # Prop display
    └── DevToolbar.tsx              # Development tools

Tech Stack

Blockchain:

  • Solidity 0.8.20
  • Hardhat 2.19.4
  • OpenZeppelin Contracts 5.0.1
  • Viem 2.7.0
  • Wagmi 2.5.0

Oracles & Data:

  • Chainlink Functions (outcome verification)
  • Sportradar NFL API (live game data)
  • ESPN API (scoreboard)
  • Astera (betting odds aggregation)

Frontend:

  • Next.js 14.0.4
  • React 18.2.0
  • TypeScript 5.3.3
  • TailwindCSS 3.4.0
  • Framer Motion 12.23.25
  • OnchainKit (Coinbase)

Backend:

  • Node.js + tsx
  • WebSocket (ws 8.16.0)
  • Anthropic Claude API (prop enhancement)
  • Supabase (data storage)

Deployment:

  • Vercel (frontend + serverless functions)
  • Railway (backend services)
  • Docker (containerized backend)

🚀 Quick Start

Prerequisites

node >= 18.0.0
npm >= 9.0.0

Installation

# Clone repository
git clone https://github.com/Vitthal-Agarwal/MBC.git
cd MBC

# Install dependencies
npm install

# Copy environment variables
cp .env.example .env

Environment Configuration

Edit .env with your values:

# Blockchain
PRIVATE_KEY=0x...                              # Your wallet private key
NEXT_PUBLIC_BATTLE_ROYALE_ADDRESS=0x6F1422A4077eaE78f2482bD1f4340219AF42b092
NEXT_PUBLIC_USDC_ADDRESS=0xC9617BeE6Afa6223fE8Fa9C4B6Fbd885bF9006d1
NEXT_PUBLIC_CHAIN_ID=84532

# Game Mode
USE_ORACLE_MODE=true                           # true=oracle, false=simulated
DEMO_MODE=false                                # true=demo game, false=live NFL

# APIs (Optional)
SPORTRADAR_API_KEY=...                         # For live NFL data
ANTHROPIC_API_KEY=...                          # For AI prop enhancement
PUBLIC_SUPABASE_URL=...                        # For data storage
SUPABASE_SERVICE_ROLE_KEY=...

Development

# Start frontend (Next.js)
npm run dev

# Start backend (WebSocket server)
npm run backend

# Run oracle game loop
npm run game:run 0

Testing

# Compile contracts
npm run compile

# Run contract tests
npm test

# Test oracle integration
npx hardhat run scripts/test-oracle-complete.ts --network base-sepolia

# Test local build
npm run build

Deployment

# Deploy contracts to Base Sepolia
npx hardhat run scripts/deploy-battle-royale-oracle.ts --network base-sepolia

# Deploy frontend to Vercel
npx vercel --prod

# Deploy backend to Railway
railway up

🎯 Game Mode Switching

The platform supports two operational modes:

Oracle Mode (Production)

Uses Chainlink Functions for trustless outcome verification.

# In .env
USE_ORACLE_MODE=true

# Run oracle game loop
npm run game:run 0

Flow:

  1. Select prop from live NFL game
  2. Broadcast to players (30s prediction window)
  3. Send Chainlink Functions request
  4. Oracle fetches ESPN data off-chain
  5. Oracle calls fulfillRequest() on contract
  6. Round auto-settled with verified outcome
  7. Players eliminated based on results

Monitoring:

Simulated Mode (Testing)

Uses instant random outcomes for rapid development.

# In .env
USE_ORACLE_MODE=false

# Run simulated game loop
npm run game:run:simulated 0

Flow:

  1. Select prop
  2. Broadcast to players
  3. Generate random outcome (1s)
  4. Admin manually settles round
  5. Continue game

📡 API Integrations

Chainlink Functions (Oracle)

Purpose: Decentralized outcome verification

Implementation:

// chainlink-functions/sportradar-outcome-fetcher.js
const espnUrl = `https://site.api.espn.com/apis/site/v2/sports/football/nfl/summary`;
const response = await Functions.makeHttpRequest({ url: espnUrl });
// Parse outcome, return YES/NO
return Functions.encodeUint256(outcome ? 1 : 0);

Configuration:

  • Subscription ID: 525
  • DON ID: fun-base-sepolia-1
  • Gas Limit: 300,000

Sportradar NFL API

Purpose: Real-time game data and play-by-play

Endpoints:

  • /games/{id}/summary.json - Game summary and stats
  • /games/{id}/pbp.json - Play-by-play data
  • /seasons/{year}/REG/schedule.json - Weekly schedule

Rate Limits: 1,000 requests/month (trial)

Astera Betting Intelligence

Purpose: Prop selection with expected value (EV) analysis

Features:

  • EV calculation for all props
  • Cross-market odds comparison
  • Confidence scoring
  • Real-time updates via MCP server

ESPN API

Purpose: Live scoreboard and outcome verification

Endpoint: https://site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard

Data: Scores, time remaining, play-by-play events


🎨 Frontend Features

Wallet Integration

  • Coinbase Wallet (primary)
  • MetaMask support
  • WalletConnect compatible
  • Smart wallet support (ERC-4337)

Real-Time Updates

  • WebSocket connection for live game events
  • Server-Sent Events (SSE) for prop broadcasts
  • Optimistic UI updates
  • Automatic reconnection

Responsive Design

  • Mobile-first approach
  • Touch-optimized controls
  • Progressive Web App (PWA) ready
  • Dark mode support

Game UI Components

  • PropCard: Display current proposition with odds comparison
  • OddsComparison: Multi-market odds widget
  • PlayerFeed: Live activity stream
  • GameStats: Header with survivors, pot, round
  • CountdownTimer: Visual 30-second countdown

🔒 Security & Testing

Smart Contract Security

  • OpenZeppelin battle-tested contracts
  • ReentrancyGuard on all payment functions
  • Access control with Ownable pattern
  • Chainlink request validation
  • Emergency pause functionality

Test Coverage

# Run all contract tests
npm test

# Specific test suites
npx hardhat test test/BattleRoyaleOracle.test.ts
npx hardhat test test/DegenLeague.test.ts
npx hardhat test test/TouchdownTokens.test.ts

Test Results:

  • ✅ 26/26 tests passing
  • ✅ Gas optimization verified
  • ✅ Edge cases covered
  • ✅ Oracle callback tested

Oracle Testing

# Complete oracle integration test
npm run test:oracle

# Creates game, adds players, sends oracle request, monitors settlement

📊 Game Economics

Battle Royale

Entry Fee: $10 USDC
Max Players: 100
Prize Pool: $1,000 USDC
Platform Fee: 0% (initially)
Winner Split: $100 each (10 survivors)
Expected ROI: 10x if you're in top 10%

Degen League

Entry Fee: $25 USDC
Max Players: 12
Prize Pool: $300 USDC
Distribution:
  - 1st Place: $180 (60%)
  - 2nd Place: $90 (30%)
  - 3rd Place: $30 (10%)

Touchdown Tokens

Initial Price: $1.00
Bonding Curve: y = x²
Price Impact: Increases with supply
Liquidity: Constant product formula

🗺️ Roadmap

Phase 1: MVP (Current)

  • ✅ Battle Royale game logic
  • ✅ Chainlink oracle integration
  • ✅ USDC payments on Base
  • ✅ WebSocket real-time updates
  • ✅ Mobile-responsive UI

Phase 2: Enhancement (Q1 2025)

  • 🔄 Degen League full launch
  • 🔄 Touchdown Tokens beta
  • 🔄 Gasless transactions (paymasters)
  • 🔄 Farcaster social integration
  • 🔄 Base App featured listing

Phase 3: Scale (Q2 2025)

  • 📋 Multi-sport support (NBA, MLB)
  • 📋 Live streaming integration
  • 📋 DAO governance for prop selection
  • 📋 NFT achievements and rewards
  • 📋 Mobile native app

Phase 4: Ecosystem (Q3 2025)

  • 📋 API for third-party integrations
  • 📋 White-label solution for partners
  • 📋 Cross-chain expansion (Optimism, Arbitrum)
  • 📋 Tournament system with leaderboards
  • 📋 Referral and affiliate programs

🤝 Contributing

We welcome contributions! Please see our contributing guidelines.

Development Workflow

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

Code Standards

  • ESLint + Prettier for formatting
  • TypeScript strict mode
  • Comprehensive JSDoc comments
  • Unit tests for new features
  • Gas optimization for contracts

📚 Documentation

All documentation is located in /documentation/:

Game Documentation

  • GAME-MODES.md - Detailed game mode switching guide
  • DEMO-MODE-README.md - Testing with demo games
  • DEGEN-LEAGUE-COMPLETE.md - Degen League implementation

Technical Documentation

  • ORACLE-IMPLEMENTATION-COMPLETE.md - Chainlink oracle setup
  • SPORTSRADAR-UPDATED-ORACLE.md - Sportradar integration
  • CIRCLE-INTEGRATION.md - USDC payment flows
  • ASTERA-MCP-INTEGRATION.md - Astera API usage

Deployment Documentation

  • DEPLOYMENT-GUIDE.md - Complete deployment guide
  • DEPLOYMENT-QUICKSTART.md - Quick deployment steps
  • VERCEL-DEPLOYMENT.md - Vercel-specific guide

Development Documentation

  • DATA-SOURCES.md - API documentation
  • WEBSOCKET-IMPLEMENTATION.md - Real-time updates
  • FRONTEND-INTEGRATION.md - UI components

🏗️ Project Structure

MBC/
├── contracts/                 # Solidity smart contracts
│   ├── BattleRoyaleOracle.sol
│   ├── DegenLeague.sol
│   └── TouchdownTokens.sol
├── chainlink-functions/       # Oracle source code
│   ├── minimal-outcome.js
│   └── sportradar-outcome-fetcher.js
├── backend/                   # Node.js backend
│   ├── orchestrator/          # Game loop logic
│   ├── api/                   # External API clients
│   ├── websocket/             # WebSocket server
│   └── scripts/               # Utility scripts
├── app/                       # Next.js frontend
│   ├── battle-royale/         # Battle Royale UI
│   ├── game2-draft/           # Degen League UI
│   └── touchdown-tokens/      # Token marketplace UI
├── scripts/                   # Hardhat deployment scripts
├── test/                      # Contract tests
├── lib/                       # Shared utilities
├── documentation/             # Project documentation (84 files)
├── deployments/               # Contract deployment info
└── public/                    # Static assets

🐛 Troubleshooting

Common Issues

1. Contract reads returning $0:

# Check RPC connection
curl https://sepolia.base.org -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'

# Verify contract addresses in .env

2. Oracle request timing out:

# Check Chainlink subscription has LINK
# Monitor at: https://functions.chain.link/base-sepolia/525

# Verify contract is added as consumer
npx hardhat run scripts/configure-oracle.ts --network base-sepolia

3. WebSocket disconnecting:

# Check backend is running
npm run backend

# Verify WebSocket URL in frontend
# Should be: ws://localhost:8080 (development)

4. Build failing:

# Clear Next.js cache
rm -rf .next

# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install

# Rebuild
npm run build

📞 Support

Resources

Contact


📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


🙏 Acknowledgments

  • Base - L2 infrastructure and developer support
  • Chainlink - Decentralized oracle network
  • Circle - USDC integration and payment rails
  • Coinbase - OnchainKit and wallet integration
  • Anthropic - Claude AI for prop enhancement
  • Sportradar - Real-time NFL game data
  • ESPN - Play-by-play data API

⚡ Built for MBC Hackathon 2025

Tracks:

  • 🏆 Base Track - Building on Base L2
  • 💰 Circle/USDC Bounty - Native USDC payments
  • 🔮 Chainlink Bounty - Functions oracle integration
  • 📊 Polymarket Bounty - Prediction market integration

Team:

  • Smart Contract Development
  • Backend Architecture
  • Frontend Development
  • Oracle Integration
  • DevOps & Deployment

Made with ⚡ on Base

WebsiteTwitterGitHub

About

MBC Hackathon Repo

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors