A revolutionary prediction market platform built entirely on WhatsApp, enabling users to create, bet on, and resolve markets through conversational interface with blockchain-backed treasury management.
- ๐ฎ WhatsApp-Native Interface: Complete prediction market experience through WhatsApp chat
- ๐ฐ Blockchain Treasury: Solana-based wallet system with automatic escrow management
- โฝ Sports Markets: Real-time sports betting with ESPN API integration
- ๐ค Automatic Resolution: Oracle-based market resolution with instant payouts
- ๐ฆ Secure Escrow: Isolated treasury wallets for each market
- ๐ Real-time Odds: Dynamic odds calculation based on betting activity
- ๐ธ Instant Payouts: Automatic winner distribution with creator fees
- ๐ Production Security: Webhook verification, rate limiting, and audit trails
Watch OYA in action: Technical Demo Video
- Node.js 16+
- MongoDB (local or cloud)
- WhatsApp Business API account
- Solana testnet/mainnet access
# Clone the repository
git clone https://github.com/your-username/oya-prediction-market.git
cd oya-prediction-market
# Install dependencies
npm install
# Run setup script
node scripts/setup.jsCreate a .env file with your credentials:
# WhatsApp Business API
ACCESS_TOKEN=your_whatsapp_access_token
PHONE_NUMBER_ID=your_phone_number_id
VERIFY_TOKEN=your_custom_verify_token
APP_SECRET=your_app_secret
# Database
MONGODB_URI=mongodb://localhost:27017/oya_prediction_market
# Solana Treasury (Testnet)
TREASURY_PUBLIC_KEY=your_treasury_public_key
TREASURY_PRIVATE_KEY=your_treasury_private_key
SOLANA_NETWORK=testnet
# External APIs
ESPN_API_KEY=your_espn_api_key
# System Configuration
NODE_ENV=development
PORT=8000
LOG_LEVEL=info# Development mode with auto-restart
npm run dev
# Production mode
npm start
# Seed sample markets (optional)
npm run seed:markets- Start your server (use ngrok for local testing)
- Configure webhook in WhatsApp Business API dashboard:
- Webhook URL:
https://your-domain.com/webhook - Verify token: Match your
VERIFY_TOKEN - Subscribe to:
messagesevents
- Webhook URL:
- Test the bot by sending "Hi" to your WhatsApp Business number
-
Onboarding: Send "Hi" to get started
- Automatic Solana wallet creation
- Username setup (@yourname)
- 1000 USDC testnet balance
-
Create Markets: Use "โ Create Market"
- Choose sports events or custom topics
- Set minimum/maximum stakes
- Add optional creator stake
- Get unique market code (OYA123456)
-
Join Markets: Through Game Center or market codes
- Browse active markets
- View real-time odds
- Place bets with instant confirmation
- Funds locked in secure escrow
-
Automatic Resolution:
- ESPN API monitors sports results
- Instant market resolution
- Automatic payout distribution
- Creator receives 2.5% fee
You: Hi
OYA: ๐ Welcome to OYA! Creating your wallet...
โ
Wallet created: 9Wz...WM
๐ฐ Balance: 1000 USDC
Choose an option:
[๐ฑ My Wallet] [๐ฎ Game Center] [โ Create Market]
You: ๐ฎ Game Center
OYA: ๐ Active Markets
โฝ Arsenal vs Chelsea
Pool: 450 USDC | Ends in 2h
[Join Market]
๐ Lakers vs Warriors
Pool: 320 USDC | Ends in 4h
[Join Market]
You: Joins Arsenal vs Chelsea
OYA: ๐ฏ Arsenal vs Chelsea
Current Pool: 450 USDC
Choose your prediction:
[โฝ Arsenal Wins (2.1x)] [โฝ Chelsea Wins (1.8x)]
You: Arsenal Wins, stakes 50 USDC
OYA: ๐ Bet placed successfully!
Stake: 50 USDC
Potential Win: 105 USDC
New Balance: 950 USDC
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ WhatsApp โ โ OYA Platform โ โ Blockchain โ
โ Business API โโโโโบโ Node.js/Expressโโโโโบโ Solana โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโ
โ External APIs โ
โ ESPN, Crypto โ
โโโโโโโโโโโโโโโโโโโโ
โโโ app/
โ โโโ config/ # Configuration and logging
โ โโโ models/ # MongoDB schemas
โ โ โโโ database.js # User, Market, Bet, Treasury models
โ โโโ routes/ # Express routes
โ โ โโโ webhook.js # WhatsApp webhook handlers
โ โโโ services/ # Core business logic
โ โ โโโ onboarding/ # User registration and wallet creation
โ โ โโโ wallet/ # Treasury and wallet management
โ โ โ โโโ treasuryManager.js # Escrow and payout system
โ โ โ โโโ walletManager.js # User wallet operations
โ โ โโโ markets/ # Market creation and betting
โ โ โ โโโ customMarketCreationFlow.js
โ โ โ โโโ betPlacementFlow.js
โ โ โโโ gameCenter/ # Market discovery
โ โ โโโ resolution/ # Automatic market resolution
โ โ โโโ blockchain/ # Solana integration
โ โโโ utils/ # Utilities and helpers
โ โโโ whatsappUtils.js # Message routing and formatting
โโโ scripts/ # Setup and seeding scripts
โโโ logs/ # Application logs
โโโ server.js # Main application entry point
โโโ package.json # Dependencies and scripts
OYA uses Solana blockchain for secure, transparent treasury management:
- Platform Treasury: Main treasury wallet for system operations
- Market Escrows: Isolated wallets for each prediction market
- User Wallets: Individual Solana wallets for each user
- Automatic Payouts: Smart contract-like payout distribution
// Market Creation
const escrow = await treasuryManager.createMarketEscrow(marketId);
// Bet Placement
await treasuryManager.lockFundsInEscrow(marketId, userId, amount, betId);
// Market Resolution
await treasuryManager.processMarketResolution(marketId, payoutData);- Market Creation: Alice creates "Arsenal vs Chelsea" with 100 USDC pool
- Bet Placement: Bob bets 25 USDC on Arsenal (locked in escrow)
- Market Resolution: Arsenal wins, Bob gets 121.87 USDC, Alice gets 3.13 USDC fee
{
userId: "2347043163283",
username: "@lucky",
wallet: {
publicKey: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
balance: 1000,
totalStaked: 250,
totalWon: 180
},
stats: {
marketsCreated: 3,
betsPlaced: 12,
winRate: 0.67
}
}{
marketId: "MKT_123456",
marketCode: "OYA123456",
title: "Arsenal vs Chelsea",
description: "Premier League Match",
outcomes: [
{ name: "Arsenal Wins", bets: [], totalStaked: 150 },
{ name: "Chelsea Wins", bets: [], totalStaked: 100 }
],
escrowWallet: "ESCROW_MKT_123456",
totalPool: 250,
status: "active",
resolutionSource: "espn_api",
createdBy: "2347043163283"
}{
betId: "BET_789012",
userId: "2347043163283",
marketId: "MKT_123456",
outcomeIndex: 0,
stake: 50,
potentialPayout: 87.5,
status: "active",
placedAt: "2024-01-15T10:30:00Z"
}{
treasuryId: "TREASURY_MAIN",
type: "platform",
publicKey: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
balance: 10000,
totalReceived: 50000,
totalPaid: 40000,
transactions: []
}GET /webhook- WhatsApp webhook verificationPOST /webhook- Message processing and routingGET /health- System health check and status
{
"status": "ok",
"timestamp": "2024-01-15T10:30:00.000Z",
"service": "OYA Prediction Market",
"components": {
"database": "connected",
"treasury": "initialized",
"resolution": "active",
"whatsapp": "verified"
}
}- Create Market Template:
// In app/services/markets/marketTemplates.js
const cryptoMarketTemplate = {
category: 'crypto',
title: 'Bitcoin Price Prediction',
outcomes: ['Above $50k', 'Below $50k'],
resolutionSource: 'coinbase_api'
};- Add Resolution Logic:
// In app/services/resolution/resolvers/cryptoResolver.js
async resolveCryptoMarket(market) {
const price = await coinbaseAPI.getBTCPrice();
return price > 50000 ? 0 : 1; // outcome index
}// In app/utils/whatsappUtils.js
async function processWhatsAppMessage(body) {
const message = body.entry[0].changes[0].value.messages[0];
// Add custom command routing
if (message.text.body.includes('leaderboard')) {
return leaderboardManager.showLeaderboard(userId);
}
// Handle button interactions
if (message.interactive?.button_reply) {
return handleButtonInteraction(userId, message.interactive.button_reply);
}
}Production Environment Variables:
NODE_ENV=production
PORT=8000
# Database
MONGODB_URI=mongodb://your-production-cluster/oya_production
# WhatsApp Business API
ACCESS_TOKEN=your_production_access_token
PHONE_NUMBER_ID=your_production_phone_id
VERIFY_TOKEN=your_secure_verify_token
APP_SECRET=your_app_secret
# Solana Mainnet
TREASURY_PUBLIC_KEY=your_mainnet_treasury_public
TREASURY_PRIVATE_KEY=your_mainnet_treasury_private
SOLANA_NETWORK=mainnet
# External APIs
ESPN_API_KEY=your_production_espn_key
# Security
LOG_LEVEL=warn
RATE_LIMIT_WINDOW=900000
RATE_LIMIT_MAX=50Using PM2 for Production:
# Install PM2 globally
npm install -g pm2
# Start OYA with PM2
pm2 start server.js --name oya-prediction-market
# Configure auto-restart on server reboot
pm2 startup
pm2 save
# Monitor the application
pm2 monit
# View logs
pm2 logs oya-prediction-marketFROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 8000
CMD ["npm", "start"]# Build and run
docker build -t oya-prediction-market .
docker run -p 8000:8000 --env-file .env oya-prediction-marketLog Files (automatically created in logs/):
error.log- Error messages and exceptionscombined.log- All application logstreasury.log- Treasury operations and transactionsresolution.log- Market resolution activities
Health Monitoring:
# Check system health
curl https://your-domain.com/health
# Monitor treasury balance
curl https://your-domain.com/health | jq '.components.treasury'- Webhook Verification: Validates WhatsApp signatures using APP_SECRET
- Rate Limiting: 50 requests per 15 minutes per IP
- Input Validation: Sanitizes all incoming messages and interactions
- CORS Protection: Configurable cross-origin request policies
- Private Key Management: Environment-only storage, never in database
- Transaction Validation: All treasury operations validated and logged
- Escrow Isolation: Each market has isolated escrow wallet
- Balance Consistency: Automatic balance reconciliation and alerts
- Helmet.js: Security headers and XSS protection
- Request Validation: Schema validation for all inputs
- Error Handling: Secure error responses without internal exposure
- Audit Logging: Comprehensive transaction and operation logging
- Environment variables secured
- HTTPS/TLS enabled
- Database access restricted
- Private keys rotated regularly
- Monitoring and alerting configured
- Backup and recovery procedures tested
# Run all tests
npm test
# Run specific test suites
npm test -- --grep "Treasury"
npm test -- --grep "Market"
npm test -- --grep "WhatsApp"
# Run tests with coverage
npm test -- --coverageWebhook Verification:
curl -X GET "http://localhost:8000/webhook?hub.mode=subscribe&hub.verify_token=your_token&hub.challenge=test_challenge"Health Check:
curl http://localhost:8000/healthWhatsApp Integration Test:
- Send "Hi" to your WhatsApp Business number
- Complete onboarding flow
- Create a test market
- Place a bet
- Verify treasury balances
Seed Test Markets:
npm run seed:marketsThis creates sample markets for testing:
- Arsenal vs Chelsea (Football)
- Lakers vs Warriors (Basketball)
- Bitcoin Price Prediction (Crypto)
1. Webhook Verification Fails
# Check webhook configuration
curl -X GET "http://localhost:8000/webhook?hub.mode=subscribe&hub.verify_token=YOUR_TOKEN&hub.challenge=test"
# Verify environment variables
echo $VERIFY_TOKEN
echo $APP_SECRET- Ensure VERIFY_TOKEN matches WhatsApp dashboard
- Confirm webhook URL is publicly accessible
- Check APP_SECRET is correctly set
2. Messages Not Processing
- Verify ACCESS_TOKEN has correct permissions
- Check webhook subscription includes 'messages' events
- Review logs:
tail -f logs/combined.log - Confirm PHONE_NUMBER_ID matches your WhatsApp Business account
3. Treasury Operations Failing
# Check treasury initialization
curl http://localhost:8000/health | jq '.components.treasury'
# Verify Solana network connection
node -e "console.log(require('./app/services/blockchain/walletService').validateNetwork())"- Verify TREASURY_PRIVATE_KEY is valid
- Check Solana network connectivity
- Ensure sufficient SOL for transaction fees
4. Database Connection Issues
# Test MongoDB connection
node -e "require('./app/models/database').testConnection()"- Verify MONGODB_URI is correct
- Check MongoDB service is running
- Ensure database user has proper permissions
5. Market Resolution Not Working
- Check ESPN_API_KEY is valid
- Verify internet connectivity for API calls
- Review resolution logs:
tail -f logs/resolution.log
Enable Verbose Logging:
LOG_LEVEL=debug npm run devComponent-Specific Debugging:
# Treasury operations
DEBUG=treasury npm run dev
# WhatsApp webhook
DEBUG=webhook npm run dev
# Market resolution
DEBUG=resolution npm run devKey Log Files:
logs/error.log- Application errorslogs/treasury.log- Treasury operationslogs/resolution.log- Market resolutionlogs/webhook.log- WhatsApp interactions
Common Error Patterns:
# Find treasury errors
grep "Treasury Error" logs/error.log
# Check failed webhook deliveries
grep "Webhook failed" logs/webhook.log
# Monitor resolution failures
grep "Resolution failed" logs/resolution.log- Concurrent Users: 1000+ simultaneous WhatsApp conversations
- Markets: Unlimited active markets with isolated escrows
- Transactions: 100+ treasury operations per minute
- Resolution: Real-time sports data processing
- Database: MongoDB with replica sets for high availability
- Treasury: Multiple treasury wallets for load distribution
- API Limits: WhatsApp Business API rate limits (1000 messages/second)
- Caching: Redis for session management and market data
We welcome contributions to make OYA even better!
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Install dependencies:
npm install - Set up test environment:
cp .env.example .env.test - Run tests:
npm test
- Code Style: Follow existing patterns and ESLint rules
- Testing: Add tests for new features
- Documentation: Update README and inline comments
- Security: Never commit private keys or sensitive data
- ๐ฎ New market types (politics, entertainment, etc.)
- ๐ Additional blockchain integrations
- ๐ฑ Mobile app companion
- ๐ Advanced analytics and reporting
- ๐ Multi-language support
MIT License - see LICENSE file for details.
- GitHub Issues: Report bugs and request features
- Discussions: Community discussions and Q&A
- Discord: Join our developer community
For production deployments and enterprise features:
- ๐ง Email: enterprise@oya-markets.com
- ๐ผ Custom integrations and white-label solutions
- ๐ง Priority support and SLA agreements
- API Documentation: Full API reference
- Developer Guide: Integration tutorials
- Video Tutorials: YouTube channel
๐ WhatsApp-First: No app downloads, works on any phone with WhatsApp
๐ฐ Real Money: Blockchain-backed with real USDC transactions
โก Instant: Automatic resolution and payouts within seconds
๐ Secure: Military-grade security with isolated escrow wallets
๐ Global: Works anywhere WhatsApp is available
๐ฎ Fun: Gamified experience with leaderboards and achievements
Ready to revolutionize prediction markets? Let's build the future together! ๐
Built with โค๏ธ by the OYA team. Making prediction markets accessible to everyone, everywhere.