Skip to content

mooncitydev/jackpot-game-web3-onchain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🎰 Solana Jackpot Game

A fully decentralized, on-chain jackpot gambling game built on Solana blockchain. Players deposit SOL tokens into a shared pot, and a winner is randomly selected to claim the entire jackpot. Built with Anchor framework, featuring real-time updates via WebSocket and a modern Next.js frontend.

📋 Table of Contents

✨ Features

  • 🎲 Decentralized Game Logic: Fully on-chain smart contract ensures transparency and fairness
  • ⚡ Real-time Updates: WebSocket integration for live game state updates
  • 💰 Multi-player Support: Multiple players can join the same jackpot pool
  • 🔐 Secure Transactions: All transactions verified on Solana blockchain
  • 📱 Modern UI: Responsive Next.js frontend with Tailwind CSS
  • 💬 Live Chat: Integrated chat system for player interaction
  • 📊 Game Statistics: Track wagered amounts, player counts, and game history
  • 🎯 Provably Fair: Random winner selection based on on-chain data

🛠 Tech Stack

Frontend

  • Next.js 12 - React framework
  • TypeScript - Type-safe development
  • Tailwind CSS - Utility-first CSS framework
  • Socket.IO Client - Real-time communication
  • @solana/wallet-adapter - Solana wallet integration
  • React Query - Data fetching and caching

Backend

  • Node.js + Express - RESTful API server
  • TypeScript - Type-safe backend
  • Socket.IO - WebSocket server for real-time updates
  • MongoDB + Mongoose - Database for game state and messages
  • @solana/web3.js - Solana blockchain interaction
  • @project-serum/anchor - Anchor framework integration

Smart Contract

  • Anchor Framework - Solana program development
  • Rust - Smart contract language
  • Solana Program Library (SPL) - Token and system programs

🏗 Architecture

┌─────────────────┐
│   Frontend       │
│   (Next.js)      │
└────────┬─────────┘
         │ HTTP/WebSocket
         │
┌────────▼─────────┐
│   Backend        │
│   (Express)      │
└────────┬─────────┘
         │
    ┌────┴────┐
    │         │
┌───▼───┐ ┌──▼────┐
│MongoDB│ │Solana │
│       │ │Network│
└───────┘ └───────┘

Data Flow

  1. Player Action: User connects wallet and deposits SOL via frontend
  2. Transaction: Frontend creates and signs Solana transaction
  3. Blockchain: Transaction is submitted to Solana network
  4. Backend Monitoring: Backend monitors blockchain for new transactions
  5. Database Update: Game state is updated in MongoDB
  6. Real-time Broadcast: WebSocket broadcasts updates to all connected clients
  7. Winner Selection: After cooldown period, winner is randomly selected on-chain
  8. Reward Claim: Winner claims the jackpot via smart contract

📦 Prerequisites

  • Node.js >= 16.x
  • Yarn or npm
  • Rust >= 1.70.0 (for smart contract development)
  • Solana CLI >= 1.16.0
  • Anchor CLI >= 0.28.0
  • MongoDB >= 5.0 (local or cloud instance)
  • Solana Wallet (Phantom, Solflare, etc.)

🚀 Installation

1. Clone the Repository

git clone https://github.com/mooncitydev/solana-jackpot-game.git
cd solana-jackpot-game

2. Install Backend Dependencies

cd Jackpot_backend
yarn install
# or
npm install

3. Install Frontend Dependencies

cd ../Jackpot_frontend
yarn install
# or
npm install

4. Install Smart Contract Dependencies

cd ../Jackpot_program/jackpot
yarn install
anchor build

5. Set Up Environment Variables

Backend (.env)

Create Jackpot_backend/.env:

PORT=3002
CORS_ORIGIN=*

SOLANA_NETWORK=devnet
SOLANA_MAINNET=https://api.mainnet-beta.solana.com
SOLANA_DEVNET=https://api.devnet.solana.com
PROGRAM_ID=E13jNxzoQbUuyaZ9rYJUdRAirYZKU75NJNRV9CHdDhHE

DB_CONNECTION=mongodb://localhost:27017/jackpot

Frontend (.env.local)

Create Jackpot_frontend/.env.local:

NEXT_PUBLIC_API_URL=http://localhost:3002
NEXT_PUBLIC_SOCKET_URL=http://localhost:3002

NEXT_PUBLIC_NETWORK=devnet
NEXT_PUBLIC_RPC_URL=https://api.devnet.solana.com
NEXT_PUBLIC_PROGRAM_ID=E13jNxzoQbUuyaZ9rYJUdRAirYZKU75NJNRV9CHdDhHE
NEXT_PUBLIC_CREATOR_ADDRESS=A8rgsJecHutEamvb7e8p1a14LQH3vGRPr796CDaESMeu

NEXT_PUBLIC_SOL_PRICE_API=https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd

6. Set Up MongoDB

Make sure MongoDB is running locally or update DB_CONNECTION with your cloud MongoDB URI.

7. Deploy Smart Contract (Optional)

For development, you can use the existing program ID or deploy your own:

cd Jackpot_program/jackpot
anchor build
anchor deploy --provider.cluster devnet

⚙️ Configuration

Backend Configuration

  • PORT: Server port (default: 3002)
  • CORS_ORIGIN: Allowed CORS origins
  • SOLANA_NETWORK: devnet or mainnet
  • PROGRAM_ID: Your deployed program ID
  • DB_CONNECTION: MongoDB connection string

Frontend Configuration

  • NEXT_PUBLIC_API_URL: Backend API URL
  • NEXT_PUBLIC_SOCKET_URL: WebSocket server URL
  • NEXT_PUBLIC_NETWORK: Solana network (devnet or mainnet)
  • NEXT_PUBLIC_RPC_URL: Solana RPC endpoint
  • NEXT_PUBLIC_PROGRAM_ID: Smart contract program ID

🎮 Usage

Start Backend Server

cd Jackpot_backend
yarn dev
# or
npm run dev

Server will start on http://localhost:3002

Start Frontend Development Server

cd Jackpot_frontend
yarn dev
# or
npm run dev

Frontend will start on http://localhost:3000

Build for Production

Backend:

cd Jackpot_backend
yarn build
yarn start

Frontend:

cd Jackpot_frontend
yarn build
yarn start

📁 Project Structure

solana-jackpot-game/
├── Jackpot_backend/          # Backend server
│   ├── src/
│   │   ├── index.ts          # Express server & routes
│   │   ├── script.ts         # Solana transaction processing
│   │   ├── db.ts             # Database operations
│   │   ├── jackpot.ts        # Anchor IDL types
│   │   ├── model/            # Mongoose models
│   │   └── config.ts         # Configuration constants
│   ├── package.json
│   └── tsconfig.json
│
├── Jackpot_frontend/         # Next.js frontend
│   ├── src/
│   │   ├── pages/            # Next.js pages
│   │   ├── components/       # React components
│   │   ├── context/          # React context providers
│   │   ├── utils/            # Utility functions
│   │   └── styles/           # Global styles
│   ├── public/               # Static assets
│   ├── package.json
│   └── next.config.js
│
└── Jackpot_program/          # Solana smart contract
    └── jackpot/
        ├── programs/
        │   └── jackpot/
        │       └── src/
        │           └── lib.rs # Main program logic
        ├── tests/             # Anchor tests
        ├── Anchor.toml
        └── Cargo.toml

🔐 Smart Contract

Instructions

  1. initialize: Initialize the vault account
  2. playGame: Create a new game pool and deposit initial amount
  3. enterGame: Join an existing game pool
  4. claimReward: Winner claims the jackpot

Game Flow

  1. First player calls playGame to create a new game
  2. Additional players call enterGame to join
  3. After cooldown period, admin calls claimReward
  4. Winner is selected based on random number and deposit amounts
  5. Winner receives entire jackpot

Randomness

Winner selection uses a deterministic random number derived from:

  • On-chain timestamp
  • Program-derived address (PDA)
  • Character multiplication of address

Note: For production, consider using Switchboard or Chainlink VRF for more secure randomness.

📡 API Endpoints

REST API

  • GET /health - Health check
  • GET /getMessage - Get recent chat messages
  • POST /writeMessage - Send a chat message
  • GET /getRecentGame - Get current game state
  • POST /createGame - Process game creation transaction
  • POST /enterGame - Process game entry transaction

WebSocket Events

Client → Server:

  • Connection automatically established

Server → Client:

  • connectionUpdated - Active connection count
  • chatUpdated - New chat message
  • startGame - New game started
  • endTimeUpdated - Game end time updated
  • gameEnded - Game finished, winner announced
  • newGameReady - New game available

⚠️ Security Notes

This project is intended as a proof of concept. Before deploying to mainnet:

  • Use Secure Randomness: Implement Switchboard or Chainlink VRF
  • Smart Contract Audit: Get professional security audit
  • Rate Limiting: Add anti-bot and rate limiting protections
  • Input Validation: Validate all user inputs
  • Access Control: Implement proper admin controls
  • Error Handling: Comprehensive error handling and logging
  • Testing: Extensive unit and integration tests

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

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

📄 License

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

📞 Contact

Telegram: @moooncity

For questions, support, or collaboration opportunities, feel free to reach out via Telegram.


⚠️ Disclaimer: This software is provided "as is" without warranty. Gambling involves risk. Please gamble responsibly and only with funds you can afford to lose. This project is for educational purposes.

About

Solana Jackpot Game is a decentralized, on-chain gambling application on Solana. Players deposit SOL into a shared jackpot pool, and a randomly selected winner claims the pot. Features include real-time WebSocket updates, a Next.js frontend, and an Anchor-based smart contract.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors