๐Ÿš€ QuizCraftArena | Decentralized Quiz Gaming on Conflux eSpace Testnet ๐ŸŽฎ๐Ÿ’ก

Building QuizCraftArena: A Decentralized Quiz Gaming Platform on Conflux eSpace

Revolutionizing online quiz gaming through blockchain technology, smart contracts, and transparent prize distribution


:dart: Introduction

In the rapidly evolving world of blockchain gaming, QuizCraftArena stands out as an innovative decentralized quiz gaming platform built on Conflux eSpace. This project combines the excitement of competitive quiz gaming with the transparency and security of blockchain technology, creating a fair and trustless environment where players can compete for real prizes.

:star2: What is QuizCraftArena?

QuizCraftArena is a smart contract-powered quiz platform that enables users to:

  • Create competitive quiz lobbies with customizable parameters
  • Join lobbies by paying entry fees that contribute to prize pools
  • Compete in a secure, transparent environment
  • Receive automatic prize distribution through smart contracts

The platform eliminates the need for centralized authorities to manage funds or determine winners, making the entire gaming experience trustless and transparent.

:building_construction: Technical Architecture

Smart Contract Foundation

Built on Solidity ^0.8.10, QuizCraftArena leverages OpenZeppelinโ€™s battle-tested security standards:

contract QuizCraftArena is ReentrancyGuard, Ownable {
    uint256 public constant LOBBY_TIMEOUT = 5 minutes;
    
    enum LobbyStatus { OPEN, STARTED, IN_PROGRESS, COMPLETED, CANCELLED }
    enum DistributionStatus { NOT_DISTRIBUTED, DISTRIBUTED }
    
    struct Lobby {
        uint256 id;
        string name;
        string category;
        uint256 entryFee;
        uint256 playerCount;
        uint256 maxPlayers;
        uint256 prizePool;
        uint256 createdAt;
        LobbyStatus status;
        DistributionStatus distribution;
        address[] players;
        address winner;
        address creator;
    }
}

Core Features Implementation

1. Lobby Creation System

The platform allows users to create customized quiz lobbies with specific parameters:

function createLobby(
    string memory _name,
    string memory _category,
    uint256 _entryFee,
    uint256 _maxPlayers
) external returns (uint256) {
    require(bytes(_name).length > 0, "Lobby name cannot be empty");
    require(bytes(_category).length > 0, "Category cannot be empty");
    require(_entryFee > 0, "Entry fee must be greater than 0");
    require(_maxPlayers > 1 && _maxPlayers <= 10, "Invalid max players");
    
    uint256 lobbyId = nextLobbyId++;
    Lobby storage newLobby = lobbies[lobbyId];
    
    // Initialize lobby parameters
    newLobby.id = lobbyId;
    newLobby.name = _name;
    newLobby.category = _category;
    newLobby.entryFee = _entryFee;
    newLobby.maxPlayers = _maxPlayers;
    newLobby.createdAt = block.timestamp;
    newLobby.status = LobbyStatus.OPEN;
    newLobby.creator = msg.sender;
    
    emit LobbyCreated(lobbyId, _name, _category, _entryFee, _maxPlayers, msg.sender);
    return lobbyId;
}

2. Secure Player Joining Mechanism

Players can join lobbies by paying the exact entry fee, with comprehensive validation:

function joinLobby(uint256 _lobbyId) external payable nonReentrant validLobby(_lobbyId) {
    Lobby storage lobby = lobbies[_lobbyId];
    require(msg.value == lobby.entryFee, "Incorrect entry fee");
    require(lobby.players.length < lobby.maxPlayers, "Lobby full");
    require(lobby.status == LobbyStatus.OPEN || lobby.status == LobbyStatus.STARTED, "Lobby not open");
    require(block.timestamp <= lobby.createdAt + LOBBY_TIMEOUT, "Lobby expired");
    require(msg.sender != lobby.creator, "Creator cannot join this lobby");
    
    lobby.players.push(msg.sender);
    lobby.playerCount++;
    lobby.prizePool += msg.value;
    
    emit PlayerJoined(_lobbyId, msg.sender);
}

3. Transparent Prize Distribution

Only lobby creators can execute winner payouts, ensuring controlled and secure prize distribution:

function executeWinnerPayout(uint256 _lobbyId, address _winner)
    external
    nonReentrant
    validLobby(_lobbyId)
    onlyLobbyCreator(_lobbyId)
{
    Lobby storage lobby = lobbies[_lobbyId];
    require(lobby.distribution == DistributionStatus.NOT_DISTRIBUTED, "Already distributed");
    require(isPlayerInLobby(_lobbyId, _winner), "Winner not in this lobby");
    
    lobby.status = LobbyStatus.COMPLETED;
    lobby.winner = _winner;
    lobby.distribution = DistributionStatus.DISTRIBUTED;
    
    uint256 prize = lobby.prizePool;
    lobby.prizePool = 0; // Prevent reentrancy
    
    (bool success, ) = payable(_winner).call{value: prize}("");
    require(success, "Prize transfer failed");
    
    emit LobbyCompleted(_lobbyId, _winner, prize);
}

:shield: Security Features

QuizCraftArena implements multiple layers of security:

1. Reentrancy Protection

Using OpenZeppelinโ€™s ReentrancyGuard to prevent reentrancy attacks:

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

2. Access Control

Implementing Ownable pattern for administrative functions:

import "@openzeppelin/contracts/access/Ownable.sol";

3. Input Validation

Comprehensive parameter validation across all functions:

  • Entry fee validation
  • Player count limits (2-10 players)
  • Lobby timeout enforcement (5 minutes)
  • Winner verification

4. Direct ETH Protection

Preventing accidental fund loss:

receive() external payable {
    revert("Do not send ETH directly");
}

:test_tube: Comprehensive Testing Suite

The project includes 26 comprehensive test cases covering:

describe("QuizCraftArena", function () {
  let quizCraftArena;
  let owner, player1, player2, player3, player4, player5;

  beforeEach(async function () {
    [owner, player1, player2, player3, player4, player5] = await ethers.getSigners();
    const QuizCraftArena = await ethers.getContractFactory("QuizCraftArena");
    quizCraftArena = await QuizCraftArena.deploy();
    await quizCraftArena.deployed();
  });

  // Test categories include:
  // โœ… Deployment and initialization
  // โœ… Lobby creation and validation  
  // โœ… Player joining and status updates
  // โœ… Winner payout execution
  // โœ… View function accuracy
  // โœ… Security and access control
  // โœ… Edge cases and error handling
});

Test Results: All 26 tests passing in 666ms, demonstrating robust contract functionality.

:rocket: Development Stack

Dependencies

{
  "dependencies": {
    "@openzeppelin/contracts": "^4.9.3"
  },
  "devDependencies": {
    "@nomiclabs/hardhat-ethers": "^2.2.3",
    "@nomiclabs/hardhat-waffle": "^2.0.6",
    "chai": "^4.3.8",
    "ethereum-waffle": "^4.0.10",
    "ethers": "5.7.2",
    "hardhat": "^2.17.3"
  }
}

Build & Deployment Scripts

{
  "scripts": {
    "test": "npx hardhat test",
    "test:demo": "npx hardhat run test/TestRunner.js",
    "compile": "npx hardhat compile",
    "deploy": "npx hardhat run scripts/deploy.js --network eSpace",
    "deploy:local": "npx hardhat run scripts/deploy.js --network hardhat"
  }
}

:bar_chart: Usage Examples

Creating a Quiz Lobby

const tx = await quizCraftArena.createLobby(
    "Crypto Knowledge Quiz",
    "Blockchain",
    ethers.utils.parseEther("0.1"), // 0.1 CFX entry fee
    4 // Maximum 4 players
);

Joining a Lobby

const tx = await quizCraftArena.connect(player1).joinLobby(0, {
    value: ethers.utils.parseEther("0.1") // Entry fee
});

Executing Winner Payout

const tx = await quizCraftArena.executeWinnerPayout(
    0, // Lobby ID
    player1.address // Winner's address
);

:video_game: Platform Features

Lobby Management

  • Dynamic Status Tracking: OPEN โ†’ STARTED โ†’ IN_PROGRESS โ†’ COMPLETED
  • Flexible Player Limits: Support for 2-10 players per lobby
  • Category System: Organize quizzes by topics
  • Timeout Protection: 5-minute lobby expiration

Prize System

  • Automatic Pool Accumulation: Entry fees automatically build prize pools
  • Secure Distribution: Smart contract-managed payouts
  • Transparent Tracking: All transactions recorded on-chain
  • Winner Verification: Only verified lobby participants can win

Event Transparency

The contract emits comprehensive events for full transparency:

event LobbyCreated(uint256 indexed lobbyId, string name, string category, uint256 entryFee, uint256 maxPlayers, address creator);
event PlayerJoined(uint256 indexed lobbyId, address player);
event LobbyCompleted(uint256 indexed lobbyId, address winner, uint256 prize);
event LobbyCancelled(uint256 indexed lobbyId);

:link: Repository & Demo

GitHub Repository

https://github.com/[your-username]/QuizDapp

Live Demo

[Include link to deployed contract on Conflux eSpace explorer]

Video Demonstration

[Include link to video demo showing the platform in action]

:hammer_and_wrench: Getting Started

Prerequisites

  • Node.js (v14 or higher)
  • npm or yarn
  • Hardhat development environment
  • Conflux eSpace wallet

Quick Setup

# Clone the repository
git clone https://github.com/Vikash-8090-Yadav/QuizDapp
cd QuizDapp/SamrtContract

# Install dependencies
npm install

# Compile contracts
npx hardhat compile

# Run tests
npm test

# Deploy to Conflux eSpace
npm run deploy

:star2: Key Innovations

1. Trustless Gaming

No central authority controls funds or determines winners - everything is handled by smart contracts.

2. Fair Competition

Lobby creators cannot participate in their own lobbies, ensuring fair competition.

3. Transparent Operations

All lobby activities, prize distributions, and player interactions are recorded on-chain.

4. Flexible Architecture

Support for various quiz categories and player counts makes the platform versatile.

5. Security-First Design

Built with OpenZeppelin standards and comprehensive testing ensures robust security.

:rocket: Future Enhancements

The platform is designed for extensibility with planned features including:

  • Leaderboard System: Track top performers across lobbies
  • Score Submission: Automated score tracking and verification
  • Tournament Mode: Multi-round competitions with elimination
  • NFT Rewards: Special achievements and collectible prizes
  • Cross-chain Support: Expansion to other blockchain networks

:bulb: Technical Highlights

Gas Optimization

  • Efficient struct packing
  • Minimal storage operations
  • Optimized loop iterations

Error Handling

  • Comprehensive require statements
  • Meaningful error messages
  • Graceful failure modes

Code Quality

  • Extensive documentation
  • Clear variable naming
  • Modular function design
  • Comprehensive test coverage

:dart: Conclusion

QuizCraftArena represents a significant step forward in decentralized gaming, combining the excitement of competitive quizzes with the security and transparency of blockchain technology. By eliminating intermediaries and ensuring fair play through smart contracts, the platform creates a truly trustless gaming environment.

The project demonstrates how blockchain technology can enhance traditional gaming experiences while providing new opportunities for transparent, secure, and fair competition. With its robust architecture, comprehensive security measures, and extensible design, QuizCraftArena is positioned to become a leading platform in the decentralized gaming space.

Whether youโ€™re a developer interested in blockchain gaming, a quiz enthusiast looking for fair competition, or an investor exploring the GameFi space, QuizCraftArena offers valuable insights into the future of decentralized entertainment platforms.


:telephone_receiver: Connect & Contribute

Built with :heart: for the Conflux ecosystem and the future of decentralized gaming.