Skip to content

Dice game with VRF

A fair on-chain dice game takes the bet first and rolls in a later transaction from a VRF seed, so neither the player nor the block producer can see or choose the roll while the bet can still change. The contract below does that with one Randoo request per roll: the player bets on a roll under a number they pick, the oracle's callback rolls and pays in a later block, and the house can only withdraw what no open bet could win. It runs unchanged on Ronin, Base and Robinhood with the coordinator 0xC66eB2e7EE91145875000Ad46B55600000000001, its callback stays under 73,000 gas, and it is tested, including a failed callback and a winner whose wallet refuses the payout. Further down, the same seed deals a shuffled 52-card deck or several dice.

How dice games get gamed

Five ways a dice contract gets gamed, drained or stuck:

  • The roll comes from block data. keccak256(block.timestamp, block.prevrandao, msg.sender) % 100 can be predicted by anyone who sends the 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.
  • The bet and the roll share a transaction. If the roll happens while the bet is placed, a player's contract can check the result and revert when it loses, paying only gas for every loss. Here roll() only records the bet and requests a seed; the roll happens in the oracle's transaction, after the bet can no longer be withdrawn.
  • The house cannot pay. A contract that accepts a bet it could not cover if the player won either reverts on the payout or pays early winners from later players' stakes. Here every bet reserves its full payout in locked, and roll() reverts with bankroll when the balance cannot cover all reserved payouts.
  • A bet can be cancelled while the roll is pending. Anyone can compute the seed from the oracle's fulfillment transaction while it waits to be mined. A refund or cancel function that works until the callback lands lets a player cancel exactly the bets that are about to lose. The contract below has no such function: once a bet is placed it settles from the seed, through the callback or through settle().
  • The payout blocks the roll. If the callback sends the winnings and the player's wallet rejects them, the callback reverts and the bet never settles. Here the callback sends with a 2,300 gas stipend, and if that fails the winnings become credit the player withdraws to any address.

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, then send it the bankroll in native token. It needs no other library.

src/Dice.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);
}

/// Roll-under dice: a bet with `chance` wins when the roll (0 to 99) is below `chance`,
/// and pays amount * 99 / chance, so the house keeps 1% of every bet on average.
contract Dice is RandooConsumerRonin {
    uint256 public constant CALLBACK_GAS = 100_000;
    uint256 public constant MAX_CHANCE = 95;

    struct Bet {
        address player;
        uint88 amount;
        uint8 chance;
    }

    address public immutable owner;

    mapping(bytes32 => Bet) public bets;
    // Payouts reserved for bets still waiting for their seed.
    uint256 public locked;
    // Winnings the callback could not send; each player withdraws their own.
    mapping(address => uint256) public credit;
    uint256 public owed;

    event BetPlaced(bytes32 indexed reqHash, address indexed player, uint256 amount, uint256 chance);
    event Rolled(bytes32 indexed reqHash, address indexed player, uint256 roll, uint256 payout);

    constructor(address coordinator) RandooConsumerRonin(coordinator) {
        owner = msg.sender;
    }

    /// The house bankroll: anyone can add to it, only the owner takes out what no bet has reserved.
    receive() external payable {}

    function payoutFor(uint256 amount, uint256 chance) public pure returns (uint256) {
        return amount * 99 / chance;
    }

    /// Bankroll not reserved for open bets or unpaid winnings.
    function free() public view returns (uint256) {
        return address(this).balance - locked - owed;
    }

    /// Bets `amount` on a roll below `chance` (1 to 95). Send amount plus at least
    /// estimateRequestRandomFee(CALLBACK_GAS, gasPrice); the unused part goes back to the player.
    function roll(uint256 amount, uint256 chance) external payable returns (bytes32 reqHash) {
        require(chance >= 1 && chance <= MAX_CHANCE, "chance");
        require(amount > 0 && amount <= type(uint88).max && msg.value > amount, "amount");
        uint256 payout = payoutFor(amount, chance);
        uint256 gasPrice = _declaredGasPrice();
        uint256 fee = msg.value - amount;
        require(fee >= IRoninVRFCoordinatorForConsumers(vrfCoordinator).estimateRequestRandomFee(CALLBACK_GAS, gasPrice), "fee");
        reqHash = _requestRandomness(fee, CALLBACK_GAS, gasPrice, msg.sender);
        locked += payout;
        // The bet is already in the balance, so the house covers the rest of the payout.
        require(locked + owed <= address(this).balance, "bankroll");
        bets[reqHash] = Bet(msg.sender, uint88(amount), uint8(chance));
        emit BetPlaced(reqHash, msg.sender, amount, chance);
    }

    /// Settles a bet whose callback failed, from the seed the coordinator stored.
    function settle(bytes32 reqHash) external {
        (uint256 seed, bool fulfilled,) = IRandooSeeds(vrfCoordinator).seedOf(reqHash);
        require(fulfilled, "pending");
        _settle(reqHash, seed);
    }

    function withdraw(address payable to) external {
        uint256 amount = credit[msg.sender];
        credit[msg.sender] = 0;
        owed -= amount;
        (bool ok,) = to.call{value: amount}("");
        require(ok, "transfer");
    }

    function withdrawHouse(address payable to, uint256 amount) external {
        require(msg.sender == owner, "owner");
        require(amount <= free(), "reserved");
        (bool ok,) = to.call{value: amount}("");
        require(ok, "transfer");
    }

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

    function _settle(bytes32 reqHash, uint256 seed) private {
        Bet memory bet = bets[reqHash];
        require(bet.player != address(0), "settled");
        delete bets[reqHash];
        uint256 payout = payoutFor(bet.amount, bet.chance);
        locked -= payout;
        uint256 rolled = seed % 100;
        if (rolled >= bet.chance) payout = 0;
        emit Rolled(reqHash, bet.player, rolled, payout);
        if (payout == 0) return;
        // A wallet that needs more than the stipend to receive gets credit instead of blocking the bet.
        (bool ok,) = bet.player.call{value: payout, gas: 2300}("");
        if (!ok) {
            credit[bet.player] += payout;
            owed += payout;
        }
    }

    /// 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 roll. The player sends the bet plus the request fee in one transaction: roll(amount, chance) with msg.value of amount plus at least estimateRequestRandomFee(100000, gasPrice). The player is the refund address, so what the fulfillment does not use goes back to them. The fee never touches the bankroll.
  • The odds are the player's choice. A bet with chance 50 wins on rolls 0 to 49 and pays 1.98 times the stake; chance 10 pays 9.9 times; chance 1 pays 99 times. Every bet returns 99% of the stake on average, which is the house's 1% edge. MAX_CHANCE stops at 95 because a bet that almost always wins pays almost nothing.
  • The bankroll covers every open bet. locked holds the payout of every bet still waiting for its seed and owed holds credited winnings. A bet that would push them above the contract's balance reverts, and withdrawHouse can take only free(), so the owner cannot drain the bankroll while a roll is pending.
  • Nothing cancels a bet. The seed decides every bet, through the callback or settle. There is no function to change the odds, the edge or a placed bet.
  • Winners are paid in the callback when their wallet allows it. A plain address receives the payout in the oracle's transaction. A contract wallet that needs more than 2,300 gas to receive gets credit instead and calls withdraw(to), once, to any 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(reqHash), which reads seedOf(reqHash) and settles the bet 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 game needs. A cap on the profit of a single bet as a share of free() (common in dice games, so one lucky streak cannot empty the bankroll), a minimum bet, ERC-20 bets, or a referral cut. The roll itself needs no change.

seed % 100 is uniform for all practical purposes: the seed is a 256-bit number, so the bias toward low rolls is below one part in 10^74.

Callback gas

We searched for the smallest callback gas limit at which the coordinator's call still succeeds, from cold storage and a cold player account, for 100 bets on each path:

PathWorst case, Solidity 0.8.38, via-IR, 200 runsWorst case, 0.8.30, no optimizer
Lost bet15,11917,654
Won, paid to the player's address26,72729,437
Won, wallet refuses, winnings credited68,97072,020

CALLBACK_GAS = 100_000 covers every row with room to spare. The credit path is the most expensive because it writes two new storage values. If you add work to the callback, measure again and raise it to match (the limit is 50,000 to 2,500,000).

What a roll costs

A roll costs one request, whatever the bet. estimateRequestRandomFee(100000, gasPrice) on each mainnet on 2026-11-20:

NetworkBlockDeclared gas pricePrepaid by the playerService fee in that
Ronin Mainnet63,844,93823 gwei0.1523 RON (≈ $0.0056)0.1371 RON ($0.005)
Base59,841,4620.006 gwei0.00000567 ETH (≈ $0.0099)0.0000011 ETH ($0.002)
Robinhood118,870,4980.020 gwei0.0000351 ETH (≈ $0.061)0.00002 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 player. Dollar amounts convert at the coordinator's own price feed, which sets each service fee from the list price on Pricing. On small bets the request fee matters more than the house edge: a $1 bet at 1% edge costs the player $0.01 on average, about what one request costs on Base.

Several dice and a card shuffle from one seed

One seed is enough for any number of dice or a whole deck. Derive each value from the seed and its position with keccak256, so the values are independent of each other:

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

library Deck {
    /// Fisher-Yates shuffle of cards 0 to 51 from one seed. Card c is rank c % 13, suit c / 13.
    function shuffle(uint256 seed) internal pure returns (uint8[52] memory deck) {
        for (uint256 i = 0; i < 52; i++) {
            deck[i] = uint8(i);
        }
        for (uint256 i = 51; i > 0; i--) {
            uint256 j = uint256(keccak256(abi.encode(seed, i))) % (i + 1);
            (deck[i], deck[j]) = (deck[j], deck[i]);
        }
    }

    /// Die `i` (0, 1, 2, ...) of a roll of several six-sided dice from one seed.
    function die(uint256 seed, uint256 i) internal pure returns (uint256) {
        return uint256(keccak256(abi.encode(seed, i))) % 6 + 1;
    }
}
  • Store the seed in the callback, shuffle later. The shuffle costs 40,454 gas with 0.8.38 via-IR and 64,919 without the optimizer. Rather than raise the callback limit for it, save the seed in the callback and call Deck.shuffle(seed) in a view function, or in the move that needs the next card.
  • Fisher-Yates gives every one of the 52! orders the same chance as long as each swap index is uniform, which keccak256(seed, i) % (i + 1) is to within one part in 10^74. The common mistake, swapping each card with any of the 52 positions instead of one at or below its own, makes some orders more likely than others.
  • Several dice from one throw need one request, not several. Separate requests cost a service fee each and can be fulfilled in any order; Several VRF requests at once has a contract where players keep many rolls open at once.
  • For two dice, use die(seed, 0) and die(seed, 1), rather than slicing the seed with seed % 6, (seed / 6) % 6 and so on. Both are fair, but the hash needs no bookkeeping of how much of the seed earlier dice used.
  • A public seed means public cards. Once the seed is on-chain, anyone can compute the whole deck. That is right for games where every card is shown when dealt or where the deck order is the outcome, such as a shuffled draft, a solitaire run or a battle deck. It is wrong for hidden hands, such as poker: there each player's cards must stay secret from the others, which needs commit-reveal or encryption on top of the seed, not a VRF alone.

Let players check a roll

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

  1. The seed. BetPlaced and Rolled 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 roll. The roll in Rolled must equal the seed modulo 100.
  3. The payout. A roll below the bet's chance pays amount * 99 / chance, the value in Rolled; anything else pays 0. If the player's address shows no transfer, credit(player) holds the winnings.

A dice game 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. A D20VRFConsumer contract runs on Randoo with 0xC66eB2e7EE91145875000Ad46B55600000000001 as its coordinator (Migrate from D20DAO).

Tests we ran

The two files compile 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 18 tests pass with both compilers:

  • payoutFor pays 1.98 times at chance 50, 99 times at 1 and 1.0421 times at 95.
  • roll() with chance 0 or 96 reverts with chance, with a zero amount or no fee on top with amount, and with one wei less than the quote with fee.
  • With a 10,000-unit bankroll, a bet whose payout is 9,999 units is accepted and the next bet that the bankroll cannot cover reverts with bankroll.
  • A won bet pays the player's address in the callback, a lost bet leaves the stake with the house, and both release the reserved payout and delete the bet.
  • A player contract that rejects ETH, and one whose receive writes to storage, both win and get credit; the first cannot withdraw to itself and can withdraw to another address.
  • After a callback starved of gas, settle pays once and a second settle reverts with settled. settle on a pending request reverts with pending, and after a successful callback with settled.
  • Only the coordinator can call rawFulfillRandomSeed, and on chain ID 2020 (Ronin) the contract declares 23 gwei even when the transaction's gas price is zero.
  • Only the owner can call withdrawHouse, and not for more than free(): with a 99-unit payout reserved, those 99 units stay in the contract.
  • Over 20,000 bets at chance 50 with seeds keccak256(i), the player won 9,893 times (49.5%) and got back 97.9% of the stakes, against an expected 50% and 99%.
  • Deck.shuffle returns a permutation of 0 to 51 for 300 seeds; over 26,000 shuffles each of the 52 cards came out on top between 380 and 620 times (expected 500). Over 24,000 dice each face came up within 6% of 4,000.
  • The callback gas table above.

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 Dice there with the quickstart's forge create command, with src/Dice.sol:Dice in place of the template, send it a small bankroll, and call roll(amount, 50) with the amount plus at least the quoted fee. For a weighted item roll instead of a bet, see Loot box with VRF; for one winner drawn from many tickets, see Raffle with VRF.

Updated 2026-11-25.