Skip to content

tomdan-ai/OYA

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

28 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐ŸŽฏ OYA - WhatsApp Prediction Market Platform

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.

๐Ÿš€ Features

  • ๐ŸŽฎ 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

๐ŸŽฌ Demo Video

Watch OYA in action: Technical Demo Video

๐Ÿ Quick Start

1. Prerequisites

  • Node.js 16+
  • MongoDB (local or cloud)
  • WhatsApp Business API account
  • Solana testnet/mainnet access

2. Installation

# 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.js

3. Environment Configuration

Create 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

4. Start the Platform

# Development mode with auto-restart
npm run dev

# Production mode
npm start

# Seed sample markets (optional)
npm run seed:markets

5. WhatsApp Integration Setup

  1. Start your server (use ngrok for local testing)
  2. Configure webhook in WhatsApp Business API dashboard:
    • Webhook URL: https://your-domain.com/webhook
    • Verify token: Match your VERIFY_TOKEN
    • Subscribe to: messages events
  3. Test the bot by sending "Hi" to your WhatsApp Business number

๐ŸŽฎ How It Works

User Journey

  1. Onboarding: Send "Hi" to get started

    • Automatic Solana wallet creation
    • Username setup (@yourname)
    • 1000 USDC testnet balance
  2. Create Markets: Use "โž• Create Market"

    • Choose sports events or custom topics
    • Set minimum/maximum stakes
    • Add optional creator stake
    • Get unique market code (OYA123456)
  3. 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
  4. Automatic Resolution:

    • ESPN API monitors sports results
    • Instant market resolution
    • Automatic payout distribution
    • Creator receives 2.5% fee

Sample Conversation

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

๐Ÿ—๏ธ System Architecture

Core Components

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   WhatsApp      โ”‚    โ”‚   OYA Platform   โ”‚    โ”‚   Blockchain    โ”‚
โ”‚   Business API  โ”‚โ—„โ”€โ”€โ–บโ”‚   Node.js/Expressโ”‚โ—„โ”€โ”€โ–บโ”‚   Solana        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚
                                โ–ผ
                       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                       โ”‚   External APIs  โ”‚
                       โ”‚   ESPN, Crypto   โ”‚
                       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Project Structure

โ”œโ”€โ”€ 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

๐Ÿ’ฐ Treasury System

Blockchain Integration

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

Treasury Operations

// Market Creation
const escrow = await treasuryManager.createMarketEscrow(marketId);

// Bet Placement  
await treasuryManager.lockFundsInEscrow(marketId, userId, amount, betId);

// Market Resolution
await treasuryManager.processMarketResolution(marketId, payoutData);

Financial Flow Example

  1. Market Creation: Alice creates "Arsenal vs Chelsea" with 100 USDC pool
  2. Bet Placement: Bob bets 25 USDC on Arsenal (locked in escrow)
  3. Market Resolution: Arsenal wins, Bob gets 121.87 USDC, Alice gets 3.13 USDC fee

๐Ÿ“Š Database Models

UserProfile

{
  userId: "2347043163283",
  username: "@lucky",
  wallet: {
    publicKey: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
    balance: 1000,
    totalStaked: 250,
    totalWon: 180
  },
  stats: {
    marketsCreated: 3,
    betsPlaced: 12,
    winRate: 0.67
  }
}

Market

{
  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"
}

Bet

{
  betId: "BET_789012",
  userId: "2347043163283",
  marketId: "MKT_123456",
  outcomeIndex: 0,
  stake: 50,
  potentialPayout: 87.5,
  status: "active",
  placedAt: "2024-01-15T10:30:00Z"
}

Treasury

{
  treasuryId: "TREASURY_MAIN",
  type: "platform",
  publicKey: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
  balance: 10000,
  totalReceived: 50000,
  totalPaid: 40000,
  transactions: []
}

๐Ÿ”ง API Endpoints

Core Endpoints

  • GET /webhook - WhatsApp webhook verification
  • POST /webhook - Message processing and routing
  • GET /health - System health check and status

Health Check Response

{
  "status": "ok",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "service": "OYA Prediction Market",
  "components": {
    "database": "connected",
    "treasury": "initialized", 
    "resolution": "active",
    "whatsapp": "verified"
  }
}

๐Ÿ› ๏ธ Customization

Adding New Market Types

  1. 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'
};
  1. 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
}

Custom WhatsApp Flows

// 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 Deployment

Environment Setup

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=50

Process Management

Using 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-market

Docker Deployment

FROM 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-market

Monitoring & Logging

Log Files (automatically created in logs/):

  • error.log - Error messages and exceptions
  • combined.log - All application logs
  • treasury.log - Treasury operations and transactions
  • resolution.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'

๐Ÿ” Security Features

WhatsApp Security

  • 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

Treasury Security

  • 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

Application Security

  • 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

Production Security Checklist

  • Environment variables secured
  • HTTPS/TLS enabled
  • Database access restricted
  • Private keys rotated regularly
  • Monitoring and alerting configured
  • Backup and recovery procedures tested

๐Ÿงช Testing

Running Tests

# 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 -- --coverage

Manual Testing

Webhook 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/health

WhatsApp Integration Test:

  1. Send "Hi" to your WhatsApp Business number
  2. Complete onboarding flow
  3. Create a test market
  4. Place a bet
  5. Verify treasury balances

Test Data

Seed Test Markets:

npm run seed:markets

This creates sample markets for testing:

  • Arsenal vs Chelsea (Football)
  • Lakers vs Warriors (Basketball)
  • Bitcoin Price Prediction (Crypto)

๐Ÿ”ง Troubleshooting

Common Issues

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

Debug Mode

Enable Verbose Logging:

LOG_LEVEL=debug npm run dev

Component-Specific Debugging:

# Treasury operations
DEBUG=treasury npm run dev

# WhatsApp webhook
DEBUG=webhook npm run dev

# Market resolution
DEBUG=resolution npm run dev

Log Analysis

Key Log Files:

  • logs/error.log - Application errors
  • logs/treasury.log - Treasury operations
  • logs/resolution.log - Market resolution
  • logs/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

๐Ÿ“ˆ Performance & Scalability

Current Capacity

  • 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

Scaling Considerations

  • 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

๐Ÿค Contributing

We welcome contributions to make OYA even better!

Development Setup

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Install dependencies: npm install
  4. Set up test environment: cp .env.example .env.test
  5. Run tests: npm test

Contribution Guidelines

  • 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

Areas for Contribution

  • ๐ŸŽฎ New market types (politics, entertainment, etc.)
  • ๐Ÿ”— Additional blockchain integrations
  • ๐Ÿ“ฑ Mobile app companion
  • ๐Ÿ“Š Advanced analytics and reporting
  • ๐ŸŒ Multi-language support

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ†˜ Support

Community Support

Enterprise Support

For production deployments and enterprise features:

  • ๐Ÿ“ง Email: enterprise@oya-markets.com
  • ๐Ÿ’ผ Custom integrations and white-label solutions
  • ๐Ÿ”ง Priority support and SLA agreements

Documentation


๐ŸŽฏ What Makes OYA Special

๐Ÿš€ 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.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors