Skip to content

Raffle with VRF

A fair on-chain raffle closes entries first, then asks for one random seed and maps it to a ticket, so nobody can enter, leave or pick the winner once the outcome is knowable. The contract below does that with one Randoo request per draw: players buy weighted tickets until a deadline, anyone can start the draw after it, the oracle's callback picks the winning ticket in a later block, and the winner withdraws the pot. It runs unchanged on Ronin, Base and Robinhood with the coordinator 0xC66eB2e7EE91145875000Ad46B55600000000001, its callback stays under 120,000 gas up to 16 million entries, and it is tested, including a failed callback and a winner that cannot receive ETH.

How raffles get gamed

Four ways a raffle contract gets gamed or stuck:

  • The winner comes from block data. keccak256(block.timestamp, block.prevrandao, msg.sender) can be predicted by anyone who sends the last transaction and chosen by whoever builds the block. On Robinhood prevrandao is constant, and on Ronin and Base anyone can read it on Ethereum before the block is built (Is block.prevrandao random?). A VRF seed is bound to the request block's hash, the request ID, your contract and the oracle's key hash, and its proof admits one output per input. The coordinator checks the proof before it calls your contract.
  • Entries are open while the seed is public. Anyone can compute the seed from the oracle's fulfillment transaction while it waits to be mined. If entering is still possible then, a buyer adds tickets only when the seed favors them. Entries have to close before the request is sent. The contract below refuses draw() until the deadline and refuses enter() after it.
  • The prize is sent inside the callback. Many raffle examples transfer the pot to the winner in the VRF callback. If the winner is a contract that rejects ETH or burns gas, the callback reverts and the draw never completes. Here the callback only records the winner, and the winner calls claim().
  • The operator decides when to draw. If only the owner can start the draw, the owner can wait, or never draw. Here anyone can call draw() once entries close.

The contract

Put the two files from the quickstart at src/RandooConsumerRonin.sol and src/interfaces/IRoninVRFCoordinatorForConsumers.sol, then add this one. Deploy it with 0xC66eB2e7EE91145875000Ad46B55600000000001, the ticket price in wei and the Unix time entries close. It needs no other library.

src/Raffle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {RandooConsumerRonin} from "./RandooConsumerRonin.sol";
import {IRoninVRFCoordinatorForConsumers} from "./interfaces/IRoninVRFCoordinatorForConsumers.sol";

interface IRandooSeeds {
    function seedOf(bytes32 reqHash) external view returns (uint256 seed, bool fulfilled, bool callbackOk);
}

contract Raffle is RandooConsumerRonin {
    uint256 public constant CALLBACK_GAS = 120_000;

    struct Entry {
        address player;
        // Running ticket total after this entry: entry i holds tickets [entries[i-1].end, end).
        uint96 end;
    }

    uint256 public immutable ticketPrice;
    uint256 public immutable entryEnd;

    Entry[] public entries;
    bytes32 public drawRequest;
    // One storage slot: the callback writes it once.
    address public winner;
    uint96 public winningTicket;
    bool public claimed;

    event Entered(address indexed player, uint256 firstTicket, uint256 tickets);
    event DrawRequested(bytes32 indexed reqHash);
    event Drawn(bytes32 indexed reqHash, uint256 ticket, address indexed winner);
    event Claimed(address indexed winner, address to, uint256 amount);

    constructor(address coordinator, uint256 ticketPrice_, uint256 entryEnd_) RandooConsumerRonin(coordinator) {
        require(ticketPrice_ > 0, "price");
        ticketPrice = ticketPrice_;
        entryEnd = entryEnd_;
    }

    function enter(uint256 tickets) external payable {
        require(block.timestamp < entryEnd, "closed");
        require(tickets > 0 && msg.value == tickets * ticketPrice, "price");
        uint256 first = totalTickets();
        entries.push(Entry(msg.sender, uint96(first + tickets)));
        emit Entered(msg.sender, first, tickets);
    }

    function totalTickets() public view returns (uint256) {
        uint256 n = entries.length;
        return n == 0 ? 0 : entries[n - 1].end;
    }

    function entryCount() external view returns (uint256) {
        return entries.length;
    }

    /// Anyone can start the draw once entries are closed, sending at least
    /// estimateRequestRandomFee(CALLBACK_GAS, gasPrice). The unused part goes back to the caller.
    function draw() external payable returns (bytes32 reqHash) {
        require(block.timestamp >= entryEnd, "open");
        require(entries.length > 0, "empty");
        require(drawRequest == bytes32(0), "requested");
        uint256 gasPrice = _declaredGasPrice();
        uint256 fee = IRoninVRFCoordinatorForConsumers(vrfCoordinator).estimateRequestRandomFee(CALLBACK_GAS, gasPrice);
        require(msg.value >= fee, "fee");
        reqHash = _requestRandomness(msg.value, CALLBACK_GAS, gasPrice, msg.sender);
        drawRequest = reqHash;
        emit DrawRequested(reqHash);
    }

    /// Finishes the draw if the callback failed, from the seed the coordinator stored.
    function settle() external {
        (uint256 seed, bool fulfilled,) = IRandooSeeds(vrfCoordinator).seedOf(drawRequest);
        require(fulfilled, "pending");
        _draw(drawRequest, seed);
    }

    /// The winner takes the pot, to any address. The callback never sends value.
    function claim(address payable to) external {
        require(msg.sender == winner && !claimed, "not yours");
        claimed = true;
        uint256 amount = totalTickets() * ticketPrice;
        (bool ok,) = to.call{value: amount}("");
        require(ok, "transfer");
        emit Claimed(msg.sender, to, amount);
    }

    /// The entry that holds `ticket`: the first one whose running total is above it.
    function entryOf(uint256 ticket) public view returns (uint256 lo) {
        uint256 hi = entries.length - 1;
        while (lo < hi) {
            uint256 mid = (lo + hi) / 2;
            if (entries[mid].end > ticket) hi = mid;
            else lo = mid + 1;
        }
    }

    function _fulfillRandomSeed(bytes32 reqHash, uint256 seed) internal override {
        _draw(reqHash, seed);
    }

    function _draw(bytes32 reqHash, uint256 seed) private {
        require(reqHash == drawRequest && winner == address(0), "drawn");
        uint256 ticket = seed % totalTickets();
        address w = entries[entryOf(ticket)].player;
        winner = w;
        winningTicket = uint96(ticket);
        emit Drawn(reqHash, ticket, w);
    }

    /// Ronin and Saigon: 23 gwei. Base and Robinhood: the transaction's gas price.
    function _declaredGasPrice() private view returns (uint256) {
        if (block.chainid == 2020 || block.chainid == 202601) return 23 gwei;
        return tx.gasprice;
    }
}
  • One request per draw. The seed picks one ticket out of all tickets sold. A player with three tickets out of ten wins three times in ten.
  • Entries close before the draw can start. enter() reverts at entryEnd and draw() reverts before it, so the seed is never public while anyone can still buy.
  • Anyone can draw. No owner key is needed, so the draw cannot be held back. The caller pays the request and is the refund address, so what the fulfillment does not use goes back to them. The draw fee never touches the pot.
  • It draws once. drawRequest blocks a second request, and winner blocks a second pick. There is no function to change the ticket price, the deadline or the winner.
  • The winner pulls the pot. claim(to) pays the whole pot to any address the winner names, once. A winner contract without a receive function still wins and can claim to another address.
  • settle covers a failed callback. If the callback reverts or runs out of gas, the request still counts as fulfilled and the coordinator stores the seed (callbacks). Anyone can then call settle(), which reads seedOf(drawRequest) and picks the winner from that seed.
  • The gas price to declare is 23 gwei on Ronin and Saigon and the transaction's gas price on Base and Robinhood. Fees and failures explains why.
  • Add what your raffle needs. A house cut, a cap on tickets per wallet, an ERC-20 or NFT prize instead of the ticket money, or a refund if nobody enters. A free raffle with tickets anyone can claim is not fair, which is why the constructor refuses a zero price; for a free draw, give out one entry per wallet from an allowlist instead.

Weighted tickets without a loop over players

Each enter() call appends one entry that stores the player and the running ticket total after it. With Alice buying 1 ticket, Bob 3 and Carol 6, the entries end at 1, 4 and 10, so Alice holds ticket 0, Bob tickets 1 to 3 and Carol tickets 4 to 9. The callback takes seed % totalTickets() and finds the first entry whose running total is above that ticket by binary search. For seed 123,456,783 the winning ticket is 3, which is Bob's.

Binary search reads about log2(entries) storage slots, so the callback costs the same order of gas for 100 entries as for a million. A loop over every ticket or every player would make the callback grow with the raffle until it no longer fits in any gas limit. A player who enters twice has two entries; that changes nothing about the odds.

Callback gas

We searched for the smallest callback gas limit at which the coordinator's call still succeeds, from cold storage, for 50 to 100 seeds at each raffle size:

EntriesWorst case, Solidity 0.8.38, via-IR, 200 runsWorst case, 0.8.30, no optimizer
133,62935,468
10051,02156,342
10,00068,33776,866
100,00075,84586,062
1,000,00083,27794,908
16,000,00093,199106,761

CALLBACK_GAS = 120_000 covers every row with room to spare. If you add work to the callback, such as minting a prize NFT, measure again and raise it to match (the limit is 50,000 to 2,500,000). Keep winner and winningTicket next to each other: they share one storage slot, and a separate slot would add another 22,100 gas write.

What a draw costs

A draw costs one request, whatever the number of tickets. estimateRequestRandomFee(120000, gasPrice) on each mainnet on 2026-11-19:

NetworkBlockDeclared gas pricePrepaid by the callerService fee in that
Ronin Mainnet63,802,08923 gwei0.1482 RON (≈ $0.0056)0.1325 RON ($0.005)
Base59,412,9670.006 gwei0.00000576 ETH (≈ $0.010)0.0000011 ETH ($0.002)
Robinhood118,047,6240.020 gwei0.0000351 ETH (≈ $0.063)0.0000194 ETH ($0.035)

The rest of the prepayment is gas for the callback and the fulfillment at the declared price with the coordinator's buffer, plus the L1 data fee on Base and Robinhood. The coordinator bills the gas the fulfillment actually used and refunds the rest to the caller. Dollar amounts convert at the coordinator's own price feed, which sets each service fee from the list price on Pricing.

Let players check the draw

A player needs three checks, and each one uses public data:

  1. The seed. DrawRequested and Drawn carry the request hash. Open /verify?q= followed by that hash: /verify finds the request on its network, re-derives the seed in the browser and checks the proof.
  2. The ticket. winningTicket must equal the seed modulo totalTickets().
  3. The winner. The Entered events list every entry's first ticket and count. The winner is the player whose range holds the winning ticket, and entryOf(winningTicket) returns the same entry on-chain.

The seed only became knowable after entryEnd, which a player checks by comparing the block time of the DrawRequested transaction with entryEnd().

More than one winner

The contract above draws one winner. For several prizes, keep the callback the same size: store the seed in the callback, and compute winner k afterwards from keccak256(abi.encode(seed, k)) % totalTickets() in a separate function anyone can call. If the same entry comes up twice and each player may win only once, move on to k + 1. This is not part of the tested contract above, so test it the same way before you ship it.

A raffle on Chainlink VRF v2.5 direct funding (VRFV2PlusWrapperConsumerBase) runs on Randoo by changing the wrapper address to 0xC66eB2e7EE91145875000Ad46B55600000000001 and paying in native token (Migrate from Chainlink VRF v2.5). Randoo has no subscriptions, so a subscription consumer moves to the wrapper interface or to the contract above. D20DAO's SDK ships a RaffleConsumer example, and a D20VRFConsumer contract runs on Randoo with 0xC66eB2e7EE91145875000Ad46B55600000000001 as its coordinator (Migrate from D20DAO).

Tests we ran

The contract compiles with Solidity 0.8.30 and 0.8.38. Against the mock coordinator from the integration playbook, extended with seedOf and a fulfillment with a chosen gas limit, these 17 tests pass with both compilers:

  • With 1, 3 and 6 tickets, tickets 0, 1, 3, 4 and 9 map to the right entries, and seed 123,456,783 picks ticket 3 and Bob.
  • For 300 entries of 1 to 50 tickets, entryOf returns the same entry as a linear scan for every ticket.
  • Over 30,000 seeds the three players win 2,979, 9,069 and 17,952 times, within 5% of 10%, 30% and 60%.
  • enter() with the wrong amount or zero tickets reverts with price, after entryEnd with closed. draw() before entryEnd reverts with open, with no entries with empty, and a second time with requested. A zero ticket price reverts at deployment.
  • draw() with one wei less than the quote reverts with fee, and the pot is untouched by the draw fee.
  • On chain ID 2020 (Ronin) the contract declares 23 gwei even when the transaction's gas price is zero.
  • Only the coordinator can call rawFulfillRandomSeed.
  • After a callback starved of gas, settle picks the winner once and a second settle reverts. settle on a pending request reverts with pending, and after a successful callback with drawn.
  • Only the winner can claim, only once, and the pot arrives in full.
  • A winner contract that rejects ETH still wins in a successful callback, cannot claim to itself, and can claim to another address.
  • The callback gas table above, for 1 to 16,000,000 entries.

Try it on a testnet

Roll a free seed on Base Sepolia in the playground without a wallet and check it on /verify. Then deploy Raffle there with the quickstart's forge create command, with src/Raffle.sol:Raffle in place of the template and the three constructor arguments, enter with a few tickets, wait for entryEnd and call draw() with at least the quoted fee. For an item roll per player instead of one draw, see Loot box with VRF; for one draw that reveals a whole NFT collection, see NFT reveal with VRF; for a bet settled by each roll, see Dice game with VRF.

Updated 2026-11-25.