PUBLISHED

CryptoTux: Web3 Raffle Solution

CryptoTux: Web3 Raffle Solution
2025-02-1212 min
FR

Fair and transparent raffle organization is a recurring need in blockchain projects. During the organization of the CryptoXR conference, a seemingly simple challenge - organizing a draw among a list of participants who claimed an NFT at the event - highlighted a glaring lack of suitable tools.

Explore the project and contribute on our GitHub repository. Check out our complete documentation to guide you through the implementation.

The Assessment: A Gap to Fill

Analysis of available solutions reveals three main approaches, each with its limitations:

  • Web2 Centralized Solutions: Costly subscriptions, dependency on third-party services, and complete opacity in the drawing process
  • Oracle Solutions (Chainlink VRF): Robust but expensive, their usage fees are prohibitive for small projects
  • Custom Implementations: Often poorly documented and difficult to audit

In a Web3 environment where transparency, verifiability, and decentralization are fundamental principles, the absence of a simple and accessible solution was surprising.

The CryptoTux Raffle Approach

CryptoTux Raffle brings a pragmatic response to these challenges. The system relies on a fully on-chain verifiable process, eliminating any "black box". This transparency comes with economic accessibility, made possible by intelligent deployment on test networks and the absence of oracle fees.

Although born from a specific need related to NFTs, CryptoTux Raffle is designed to be universal. The only requirement is having a defined list of participants - whether they are NFT holders, event attendees, or any other community requiring fair random selection.

Vision and Philosophy

The creation of CryptoTux Raffle follows an approach where trust is based on code transparency and verifiability rather than intermediaries. This philosophy manifests through two essential aspects:

Democratization and Accessibility

  • Elimination of traditional financial barriers
  • Clear and comprehensive documentation
  • Intuitive user interface

Technical Innovation The project balances security and simplicity needs through carefully designed architecture. The open-source approach facilitates continuous system auditing and encourages community contribution, establishing the foundation for a sustainable and evolving solution.

What started as an internal solution has become a versatile open-source tool, perfectly illustrating the Web3 spirit: creating transparent, accessible, and verifiable solutions to solve concrete problems.

An Innovative and Accessible Solution

CryptoTux Raffle is built around a smart contract that combines security and transparency. Its architecture revolves around a commit-reveal mechanism associated with multiple blockchain entropy sources, reinforced by a configurable waiting period that can extend over several hours depending on security requirements.

The Local VRF Mechanism: A Technical Innovation

The core of the system lies in its three-phase drawing process, each phase playing a crucial role in ensuring a fair and verifiable outcome.

The first phase begins during contract deployment with the generation and securing of a secret value:

tsx
// Generate a secret value during deployment
const reveal = ethers.randomBytes(32);
const commitHash = ethers.keccak256(reveal);

This is followed by a waiting period, which is configurable by the user. The longer this period, the more difficult it becomes to predict or manipulate the future entropy sources that will be used during the drawing. This flexibility allows adapting the security level to each drawing's specific needs.

The final execution phase cleverly combines six distinct entropy sources:

solidity
bytes32 randomSeed = keccak256(
    abi.encodePacked(
        blockhash(block.number - 1),  // Previous block hash
        block.timestamp,               // Precise timestamp
        block.prevrandao,             // Blockchain entropy
        participantIds,               // Participants list
        reveal,                       // Initial secret
        msg.sender                    // Executor address
    )
);

This combination through keccak256 ensures that even if some sources are predictable or known, manipulating the final result remains practically impossible.

Security and Transparency by Design

The system's security isn't solely based on cryptographic complexity. Every aspect of the contract has been designed to ensure transparency and verifiability. The code is open source, each important action emits an on-chain traceable event, and the entire process can be audited end-to-end.

solidity
event DrawingInitiated(uint256 targetBlock, uint256 participantCount);
event WinnersSelected(uint256[3] winnerIds, bytes32 randomSeed, bytes32 commitReveal);

The system's robustness relies on the practical impossibility of simultaneously manipulating all entropy sources, even if some are known in advance. This approach achieves a high security level while maintaining system simplicity and efficiency.

A Cost-Effective Alternative

Compared to traditional solutions, CryptoTux Raffle offers significant advantages:

Economic Aspects

  • No external oracle fees
  • Only network transaction fees
  • No subscription or recurring costs

Technical Benefits

  • Simple and quick deployment
  • Minimal maintenance
  • Fully automated process
  • Complete result verifiability

This balanced approach between technical innovation and accessibility makes CryptoTux Raffle a unique solution in the Web3 ecosystem, proving that it's possible to create a secure, transparent, and economical raffle system.

From Theory to Practice

Concrete Use Cases

CryptoTux Raffle, while born from a specific NFT-related need, adapts to a variety of scenarios where fairness and transparency are essential. The only prerequisite is having a defined list of participants.

In the NFT Ecosystem

  • Winner selection during mint events
  • Fair distribution of whitelist spots
  • Community rewards attribution

For Physical Events Our initial use case perfectly illustrates this application: during the CryptoXR conference, visitors who claimed an NFT were automatically entered into a transparent raffle to win prizes.

Quick Start Guide

Thanks to Workspaces, getting started with CryptoTux Raffle is straightforward:

bash
# Clone the repository
git clone <https://github.com/cyphertux/cryptotux-raffle>
cd cryptotux-raffle

# Install all dependencies (both smart contract and interface)
npm install

# Start local development on Moonbase Alpha
npm run dev:moonbase

The interface will be available at http://localhost:3000

Project Structure

The repository uses npm workspaces to manage both the smart contract and interface:

typescript
cryptotux-raffle/
├── moonbeam-raffle/    # Smart contract implementation
│   └── contracts/      # Solidity contracts
└── raffle-interface/   # Next.js frontend
    └── components/     # React components

Test Environment Requirements

To interact with the test environment, you'll need:

  • DEV tokens from the Moonbase Alpha faucet
  • A Web3 wallet (e.g., MetaMask) configured for Moonbase Alpha
  • Node.js >= 18

Configure Environment

Copy the example environment files and configure them:

bash
cp moonbeam-raffle/.env.example moonbeam-raffle/.env
cp raffle-interface/.env.example raffle-interface/.env.local

Essential environment variables:

typescript
# API Authentication
API_SECRET=your_secret_key
NEXT_PUBLIC_API_SECRET=same_as_above

# Blockchain Configuration
PRIVATE_KEY=your_private_key
NEXT_PUBLIC_DEFAULT_NETWORK=moonbase

Want to customize the Raffle? Check out our Customization Guide for detailed instructions on adapting the system to your needs.

How's this addition to the documentation? It provides a clearer path for developers to get started while maintaining the technical accuracy of the project.

Integration Examples

Integration into an existing project can be done in several ways:

tsx
// Custom configuration
interface RaffleConfig {
    participants: number[];    // List of participant IDs
    drawDelay: number;        // Delay in blocks before drawing
    network: "moonbase" | "westend";
}

// Initialization example
const config: RaffleConfig = {
    participants: Array.from({length: 148}, (_, i) => i + 1),
    drawDelay: 6000,  // ~10 hours on Moonbase
    network: "moonbase"
};

Customization and Adaptation

The system offers several customization points:

Participant Configuration

tsx
// Customizable participant format
export const participants = [
    { id: 1, code: "CUSTOM-1" },
    { id: 2, code: "CUSTOM-2" }
    // ...
];

Security Management

bash
# Essential environment variables
API_SECRET=your_secret_key
NEXT_PUBLIC_API_SECRET=your_api_secret
PRIVATE_KEY=your_private_key

The system's flexibility allows its adaptation to various needs while maintaining a high security level. Projects can easily:

  • Modify identifier formats
  • Adjust the waiting period
  • Customize the user interface
  • Integrate the system into their existing workflows

This adaptability, combined with comprehensive documentation and concrete examples, facilitates the adoption and integration of CryptoTux Raffle into a variety of projects, whether they're NFT-focused, event-based, or community-oriented.

Under the Hood: For Developers

Detailed Technical Architecture

CryptoTux Raffle Architecture

CryptoTux Raffle adopts a three-layer architecture, each with specific responsibilities:

Smart Contract Layer

solidity
contract LocalVRFRaffle is ReentrancyGuard, Pausable, Ownable {
    struct DrawingResult {
        uint256[3] winnerIds;
        bytes32 randomSeed;
        uint256 drawBlock;
        bytes32 commitReveal;
    }

    // Contract state
    uint256[] public participantIds;
    uint256 public targetBlock;
    DrawingResult public result;
    bool public isDrawingComplete;
}

The contract incorporates several essential security features:

  • Reentrancy protection via
    typescript
    ReentrancyGuard
  • Emergency pause mechanism with
    typescript
    Pausable
  • Access rights management via
    typescript
    Ownable

API Interface

tsx
export async function executeDrawing(networkName: string) {
    const network = NETWORKS[networkName];
    const wsProvider = await createProvider(network.wsUrl);
    const wallet = new Wallet(process.env.PRIVATE_KEY || '', wsProvider);
    const raffle = new Contract(network.contractAddress, RAFFLE_ABI, wallet);

    // Security checks
    const isAuthorized = await raffle.authorizedDrawers(wallet.address);
    const isComplete = await raffle.isDrawingComplete();

    // Drawing execution
    const reveal = getRevealValue();
    const tx = await raffle.requestDrawing(reveal);
}

Frontend React Layer The interface layer uses custom hooks to manage the raffle state and real-time updates:

tsx
const {
    currentBlock,
    targetBlock,
    isComplete,
    winners,
    smoothProgress
} = useRaffle(network);

Security and Verifiability

CryptoTux Raffle Résultat

The system implements multiple verification levels:

On-chain Verification

solidity
function requestDrawing(bytes32 reveal) external
    whenNotPaused
    onlyAuthorizedDrawer
    nonReentrant
{
    require(block.number >= targetBlock, "Too early for drawing");
    require(!isDrawingComplete, "Drawing already complete");
    require(keccak256(abi.encodePacked(reveal)) == commitHash,
        "Invalid reveal value");
    // ...
}

Verification Interface

tsx
// VerifyButton component for result verification
function VerifyButton({ winners, network }: VerifyButtonProps) {
    const verifyWinners = async () => {
        const provider = new JsonRpcProvider(network.rpcUrl);
        const contract = new Contract(network.contractAddress!, RAFFLE_ABI, provider);
        const onChainWinners = await contract.getWinnerIds();
        // Match verification
    };
}

Code Key Points

Winner Selection

solidity
function selectWinners(bytes32 seed) private view returns (uint256[3] memory) {
    uint256[3] memory selectedWinners;
    uint256[] memory indexes = new uint256[](participantIds.length);

    // Fisher-Yates implementation for fair selection
    for(uint i = 0; i < participantIds.length; i++) {
        indexes[i] = i;
    }
    for(uint i = 0; i < 3; i++) {
        uint256 remainingParticipants = participantIds.length - i;
        uint256 randomIndex = uint256(
            keccak256(
                abi.encodePacked(seed, i)
            )
        ) % remainingParticipants;
        selectedWinners[i] = participantIds[indexes[randomIndex]];
        indexes[randomIndex] = indexes[remainingParticipants - 1];
    }
    return selectedWinners;
}

Contribution Guide

Developers wishing to contribute can focus on several areas:

Possible Improvements

  • Enhanced deployment process automation
  • Additional network support
  • User interface improvements
  • Gas cost optimization

Code Standards

  • Unit tests for each new feature
  • Comprehensive code documentation
  • Adherence to Solidity and TypeScript standards
  • Security verification through static analysis tools

The complete technical documentation and modular project structure facilitate the integration of new contributions while maintaining quality and security standards.

The Future of the Project

CryptoTux Raffle, initially designed as a solution for a specific need, is naturally evolving into a complete decentralized raffle management platform. This evolution revolves around simplifying the user experience while maintaining the fundamental principles of transparency and security that have guided the project since its inception.

A Unified Administration Interface

The next major step for the project is the development of a comprehensive dashboard that will allow administrators to manage the entire raffle process directly from the web interface. This evolution will be made possible through the implementation of a Factory system:

solidity
contract RaffleFactory is Ownable {
    mapping(address => bytes32) public reveals;
    mapping(uint256 => address) public latestRaffle;

    event RaffleCreated(address indexed raffle, address indexed creator);

    function deployRaffle(
        uint256[] memory participants,
        uint256 blocksUntilDraw
    ) external returns (address) {
        LocalVRFRaffle newRaffle = new LocalVRFRaffle(
            participants,
            blocksUntilDraw
        );
        emit RaffleCreated(address(newRaffle), msg.sender);
        return address(newRaffle);
    }
}

This architecture will enable essential new features:

  • One-click raffle deployment
  • Centralized management of different raffles
  • Real-time tracking of raffle status
  • Intuitive administration interface

A Multi-Raffle Platform

The evolution towards multi-raffle management will open new possibilities for organizers. The dashboard will allow:

Managing Multiple Types of Raffles

  • Immediate or scheduled drawings
  • Single or multiple winner selection
  • Custom delay configuration
  • Adaptation to different use cases

The platform will also integrate analysis and reporting tools to help organizers better understand and optimize their raffles.

Long-Term Technical Vision

Future development is structured around three main axes:

Automation and Simplicity

  • Intuitive deployment interface
  • Automated reveal management via Factory
  • Simplified verification processes
  • Optimized user experience

Extensibility The new Factory architecture will allow easy addition of new features:

tsx
interface RaffleConfig {
    type: "standard" | "delayed" | "custom";
    participants: number[];
    winners: number;
    drawDelay?: number;
    customParams?: object;
}

Interoperability The system will be designed to integrate easily with other Web3 projects, paving the way for innovative use cases.

Community Call

The long-term success of CryptoTux Raffle relies on its community. We encourage contributors from all backgrounds to participate in the project's development:

  • Developers can explore the code, propose improvements, and contribute to new features
  • Users are invited to share their feedback and suggest new functionalities
  • Content creators can help document and promote the solution

Together, we can make CryptoTux Raffle the reference in decentralized raffles, proving that it's possible to combine ease of use with Web3 fundamental principles.

This article has provided you with an overview of CryptoTux Raffle, but there's more to come! I'm preparing a series of technical articles that will dive deep into every aspect of the system, from architecture to implementation details. Meanwhile, I encourage you to explore the GitHub repository, especially the detailed README files for each component: the user interface and smart contracts. You'll find a wealth of technical information to get you started.

blockchainweb3raffle
CypherTux OS v1.30.2
© 2025 CYPHERTUX SYSTEMS