# Commit-reveal or VRF for an on-chain game?

Commit-reveal is enough for a game with exactly two players who stake the same amount, as long as a player who does not reveal in time loses the whole pot: then not revealing is never better than revealing. In every other shape, such as one player against the contract, a draw among three or more tickets, or one person holding several entries, the last player to reveal sees the result first and can change it by not revealing, and on Ronin, Base and Robinhood a future block hash cannot stand in for the missing party. Below are a tested two-player duel that is safe with commit-reveal, a commit-reveal raffle in which a player holding 3 of 10 tickets won 79% of 2,000 draws, the same duel on a VRF, and what each costs per game on the three mainnets.

## Which one fits your game

| Game | Commit-reveal between players | VRF |
| --- | --- | --- |
| Two players, equal stakes: coin flip, duel, rock-paper-scissors | Works, with a reveal deadline and a full forfeit | Works, with two transactions instead of four and no deadline |
| One player against the contract: dice, loot box, mint, gacha | Only if the house commits too and a missed house reveal pays the player, so the house has to answer every bet in time | Works ([Dice game](/docs/dice), [Loot box](/docs/loot-box)) |
| Three or more entries: raffle, lottery, tournament seeding | The last revealer chooses among outcomes (measured below) | Works ([Raffle](/docs/raffle)) |
| Hidden information: a hand of cards, fog of war | Needed: each player keeps their own secret | Not alone: a public seed makes every card public ([card shuffle](/docs/dice#several-dice-and-a-card-shuffle-from-one-seed)) |
| Moves that stay hidden until both are in: sealed bids, simultaneous turns | Needed: that is what commit-reveal is for | Does not apply |

## Two players: commit-reveal that holds

Each player sends a hash of a fresh random 32-byte secret with their stake. Once both are in, each reveals the secret, and the hash of the two secrets picks the winner. Neither player knows the other's secret when committing, so neither can steer the result. The second player to reveal does know the result before revealing, and that is why the forfeit rule matters: a player who sees they lost and does not reveal loses the pot to the other player when the deadline passes, exactly as if they had revealed. The most a loser can do is make the winner wait until the deadline.

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

/// Two players stake the same amount and each commits to a secret. When both have revealed,
/// the two secrets decide the winner. A player who does not reveal before the deadline loses
/// the whole pot to the one who did, which is no worse for them than revealing and losing.
contract CoinFlipDuel {
    uint256 public constant REVEAL_WINDOW = 1 hours;

    struct Duel {
        address a;
        uint64 deadline;
        bool revealedA;
        bool revealedB;
        address b;
        uint96 stake;
        bytes32 commitA;
        bytes32 commitB;
        bytes32 secretA;
        bytes32 secretB;
    }

    mapping(uint256 => Duel) public duels;
    uint256 public nextId = 1;
    mapping(address => uint256) public credit;

    event Opened(uint256 indexed id, address indexed a, uint256 stake);
    event Joined(uint256 indexed id, address indexed b, uint256 deadline);
    event Revealed(uint256 indexed id, address indexed player);
    event Won(uint256 indexed id, address indexed winner, uint256 pot, bool byForfeit);

    /// What a player commits to: hash this off-chain with a fresh random 32-byte secret for every duel.
    function commitmentOf(address player, bytes32 secret) public view returns (bytes32) {
        return keccak256(abi.encode(block.chainid, address(this), player, secret));
    }

    function open(bytes32 commitment) external payable returns (uint256 id) {
        require(msg.value > 0 && msg.value <= type(uint96).max, "stake");
        id = nextId++;
        Duel storage d = duels[id];
        d.a = msg.sender;
        d.stake = uint96(msg.value);
        d.commitA = commitment;
        emit Opened(id, msg.sender, msg.value);
    }

    function join(uint256 id, bytes32 commitment) external payable {
        Duel storage d = duels[id];
        require(d.a != address(0) && d.b == address(0), "not open");
        require(msg.sender != d.a, "same player");
        require(msg.value == d.stake, "stake");
        d.b = msg.sender;
        d.commitB = commitment;
        d.deadline = uint64(block.timestamp + REVEAL_WINDOW);
        emit Joined(id, msg.sender, d.deadline);
    }

    /// The opener takes the stake back while nobody has joined.
    function cancel(uint256 id) external {
        Duel storage d = duels[id];
        require(msg.sender == d.a && d.b == address(0), "cannot cancel");
        credit[d.a] += d.stake;
        delete duels[id];
    }

    function reveal(uint256 id, bytes32 secret) external {
        Duel storage d = duels[id];
        require(d.b != address(0) && block.timestamp < d.deadline, "not revealing");
        if (msg.sender == d.a && !d.revealedA) {
            require(commitmentOf(msg.sender, secret) == d.commitA, "commitment");
            d.secretA = secret;
            d.revealedA = true;
        } else if (msg.sender == d.b && !d.revealedB) {
            require(commitmentOf(msg.sender, secret) == d.commitB, "commitment");
            d.secretB = secret;
            d.revealedB = true;
        } else {
            revert("not yours");
        }
        emit Revealed(id, msg.sender);
        if (d.revealedA && d.revealedB) {
            bool aWins = uint256(keccak256(abi.encode(id, d.secretA, d.secretB))) % 2 == 0;
            _pay(id, aWins ? d.a : d.b, false);
        }
    }

    /// After the deadline: the only player who revealed takes the pot; if neither did, both get their stake back.
    function claim(uint256 id) external {
        Duel storage d = duels[id];
        require(d.b != address(0) && block.timestamp >= d.deadline, "not over");
        if (d.revealedA) {
            _pay(id, d.a, true);
        } else if (d.revealedB) {
            _pay(id, d.b, true);
        } else {
            credit[d.a] += d.stake;
            credit[d.b] += d.stake;
            delete duels[id];
        }
    }

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

    function _pay(uint256 id, address winner, bool byForfeit) private {
        uint256 pot = uint256(duels[id].stake) * 2;
        delete duels[id];
        credit[winner] += pot;
        emit Won(id, winner, pot, byForfeit);
    }
}
```

- **The commitment binds the chain, the contract and the player.** `commitmentOf` hashes `block.chainid`, the contract's address and `msg.sender` with the secret. A player who copies the opponent's commitment cannot reveal it, because the hash includes their own address, and loses by forfeit. Without the address, a copied commitment would make the opponent's reveal valid for both players.
- **The whole stake is forfeited.** If a player who does not reveal got their stake back, a loser would always withhold and turn every loss into a refund. Here only the player who revealed is paid, and the pot goes to them at `claim()` after the deadline.
- **If neither reveals, both are refunded.** Neither gains from that: both had to wait an hour for their own money.
- **A fresh secret every duel.** A revealed secret is public. Reusing it lets the next opponent pick a secret that wins against it. The outcome also hashes the duel ID, so two duels with the same pair of secrets do not repeat.
- **`REVEAL_WINDOW` is your liveness trade.** One hour gives players time to come back and reveal; it is also how long a sore loser can keep the winner waiting.

## Three or more entries: the last revealer chooses

In a raffle that draws from its players' secrets, whoever reveals last can compute the winner before revealing, and anyone holding more than one ticket can choose which of them to reveal. Each choice gives a different combined secret and a different number of revealed tickets, so a different winner. This raffle charges a bond per ticket and gives the bonds of unrevealed tickets to the winner. Do not ship it; it is here to measure the attack.

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

/// A raffle that draws from its players' secrets. Every ticket pays an entry fee and a bond;
/// revealing returns the bond, and the bonds of unrevealed tickets go into the prize.
/// Do not ship this: the last player to reveal can withhold tickets to choose the winner.
contract CommitRevealRaffle {
    struct Ticket {
        address player;
        bytes32 commitment;
        bool revealed;
    }

    uint256 public immutable entryFee;
    uint256 public immutable bond;
    uint256 public immutable commitEnd;
    uint256 public immutable revealEnd;

    Ticket[] public tickets;
    uint256[] public revealedTickets;
    uint256 public mix;
    address public winner;
    mapping(address => uint256) public credit;

    constructor(uint256 entryFee_, uint256 bond_, uint256 commitWindow, uint256 revealWindow) {
        entryFee = entryFee_;
        bond = bond_;
        commitEnd = block.timestamp + commitWindow;
        revealEnd = commitEnd + revealWindow;
    }

    function commitmentOf(address player, bytes32 secret) public view returns (bytes32) {
        return keccak256(abi.encode(block.chainid, address(this), player, secret));
    }

    function enter(bytes32 commitment) external payable returns (uint256 ticket) {
        require(block.timestamp < commitEnd, "closed");
        require(msg.value == entryFee + bond, "price");
        ticket = tickets.length;
        tickets.push(Ticket(msg.sender, commitment, false));
    }

    function reveal(uint256 ticket, bytes32 secret) external {
        require(block.timestamp >= commitEnd && block.timestamp < revealEnd, "not revealing");
        Ticket storage t = tickets[ticket];
        require(t.player == msg.sender && !t.revealed, "not yours");
        require(commitmentOf(msg.sender, secret) == t.commitment, "commitment");
        t.revealed = true;
        mix ^= uint256(secret);
        revealedTickets.push(ticket);
        credit[msg.sender] += bond;
    }

    function draw() external {
        require(block.timestamp >= revealEnd && winner == address(0), "not drawing");
        uint256 n = revealedTickets.length;
        require(n > 0, "no tickets");
        winner = tickets[revealedTickets[mix % n]].player;
        uint256 forfeited = (tickets.length - n) * bond;
        credit[winner] += tickets.length * entryFee + forfeited;
    }

    function revealedCount() external view returns (uint256) {
        return revealedTickets.length;
    }

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

We ran 2,000 raffles of 10 tickets each on fresh contracts for each case. The attacker held the last `k` tickets, waited until the other players had revealed, computed the winner for every non-empty subset of its own tickets, and revealed the subset with the fewest tickets withheld that made it win. When no subset won, it revealed every ticket. Every draw matched the attacker's prediction.

| Attacker's tickets (of 10) | Wins revealing every ticket | Wins choosing which to reveal | Tickets withheld in 2,000 raffles |
| --- | --- | --- | --- |
| 1 | 186 (9.3%) | 186 (9.3%) | 0 |
| 2 | 405 (20.3%) | 744 (37.2%) | 339 |
| 3 | 605 (30.3%) | 1,584 (79.2%) | 1,202 |

With one ticket there is nothing to choose: not revealing only takes the ticket out of the draw. With `k` tickets the attacker gets `2^k − 1` draws instead of one, which predicts 36.8% for two tickets and 77.9% for three, close to what we measured. Tickets cost nothing extra to split across addresses, so a one-ticket-per-address rule does not help.

**The bond did not cost the attacker anything.** It withheld tickets only in raffles it then won, and the forfeited bonds went into the prize it collected. Burning the bonds instead makes each withheld ticket cost its bond. On these numbers, the bond would have to be 10 entry fees per ticket against a 2-ticket attacker and 8.1 against a 3-ticket attacker before withholding stops paying: about the whole prize, per ticket. No raffle can ask that, so a raffle needs a random number that no player sees first ([Raffle with VRF](/docs/raffle)).

## Commit-reveal with a future block hash

The usual fix for a single player is to commit to a bet now and settle it from `blockhash` of a later block, so that no other party has to reveal. On these three chains:

- **One sequencer builds the block.** Ronin, Base and Robinhood each have a single sequencer that chooses which transactions go into a block and in what order, so it can influence the hash of the block your bet settles from.
- **`blockhash` returns 0 after 256 blocks.** On Ronin, with 2-second blocks, that is 512 seconds. On Base we measured 1,000 blocks in 200 seconds on 2026-12-01, so 256 blocks last 51 seconds. On Robinhood, `blockhash` takes Ethereum block numbers and some of its answers are hashes that had been public for 51 minutes ([block.number on Robinhood](/docs/block-number)). If an expired hash refunds the bet, a player who sees a losing hash waits out the window and gets the stake back; if it counts as a loss, every player has to settle within 51 seconds on Base.
- **`block.prevrandao` is no better.** It is the constant 1 on Robinhood and a value already public on Ethereum on Ronin and Base ([Is block.prevrandao random?](/docs/prevrandao)).

## The same duel with a VRF

With a VRF the duel needs no secrets, no reveals and no deadline. The second player's `join` requests a seed, and the coordinator's callback names the winner in a later transaction. Put the two files from the [quickstart](/docs/quickstart) at `src/RandooConsumerRonin.sol` and `src/interfaces/IRoninVRFCoordinatorForConsumers.sol`, add this one and deploy it with `0xC66eB2e7EE91145875000Ad46B55600000000001` on any of the three networks.

```solidity src/CoinFlipDuelVRF.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);
}

/// The same duel with a VRF seed: no secrets, no reveal, no deadline. The second player's
/// join requests the seed, and the callback names the winner.
contract CoinFlipDuelVRF is RandooConsumerRonin {
    uint256 public constant CALLBACK_GAS = 60_000;

    struct Duel {
        address a;
        address b;
        uint96 stake;
    }

    mapping(uint256 => Duel) public duels;
    mapping(bytes32 => uint256) public duelOf;
    uint256 public nextId = 1;
    mapping(address => uint256) public credit;

    event Opened(uint256 indexed id, address indexed a, uint256 stake);
    event Joined(uint256 indexed id, address indexed b, bytes32 reqHash);
    event Won(uint256 indexed id, address indexed winner, uint256 pot);

    constructor(address coordinator) RandooConsumerRonin(coordinator) {}

    function open() external payable returns (uint256 id) {
        require(msg.value > 0 && msg.value <= type(uint96).max, "stake");
        id = nextId++;
        duels[id] = Duel(msg.sender, address(0), uint96(msg.value));
        emit Opened(id, msg.sender, msg.value);
    }

    /// Send the stake plus at least estimateRequestRandomFee(CALLBACK_GAS, gasPrice);
    /// what the fulfillment does not use goes back to the joiner.
    function join(uint256 id) external payable returns (bytes32 reqHash) {
        Duel storage d = duels[id];
        require(d.a != address(0) && d.b == address(0), "not open");
        require(msg.sender != d.a, "same player");
        require(msg.value > d.stake, "stake");
        uint256 gasPrice = _declaredGasPrice();
        uint256 fee = msg.value - d.stake;
        require(fee >= IRoninVRFCoordinatorForConsumers(vrfCoordinator).estimateRequestRandomFee(CALLBACK_GAS, gasPrice), "fee");
        d.b = msg.sender;
        reqHash = _requestRandomness(fee, CALLBACK_GAS, gasPrice, msg.sender);
        duelOf[reqHash] = id;
        emit Joined(id, msg.sender, reqHash);
    }

    function cancel(uint256 id) external {
        Duel storage d = duels[id];
        require(msg.sender == d.a && d.b == address(0), "cannot cancel");
        credit[d.a] += d.stake;
        delete duels[id];
    }

    /// Settles a duel 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;
        (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 {
        uint256 id = duelOf[reqHash];
        require(id != 0, "settled");
        delete duelOf[reqHash];
        Duel memory d = duels[id];
        delete duels[id];
        address winner = seed % 2 == 0 ? d.a : d.b;
        credit[winner] += uint256(d.stake) * 2;
        emit Won(id, winner, uint256(d.stake) * 2);
    }

    /// 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;
    }
}
```

- **The joiner pays the request.** `join(id)` takes the stake plus at least `estimateRequestRandomFee(60000, gasPrice)`, and the unused part of the fee goes back to the joiner. Split it between the players by charging half of it in `open` if your game needs that.
- **The callback is small.** It used at most 44,327 gas in our tests (cold storage, Solidity 0.8.39, no optimizer), so `CALLBACK_GAS` is 60,000. The coordinator accepts 50,000 to 2,500,000.
- **`settle` covers a failed callback.** If the callback reverts or runs out of gas, the coordinator still stores the seed, and anyone can call `settle(reqHash)` to finish the duel from `seedOf` ([callbacks](/docs/gas#callbacks)).
- **The gas price to declare** is 23 gwei on Ronin and Saigon and the transaction's gas price on Base and Robinhood ([which gas price to declare](/docs/gas#which-gas-price-to-declare)).

## What a game costs

We deployed both duels on forks of Base (block 64,594,017) and Ronin (block 64,320,225) on 2026-12-01, played them with two accounts against the live coordinator `0xC66eB2e7EE91145875000Ad46B55600000000001`, and read the gas used from each receipt:

| Transaction | Commit-reveal duel | VRF duel |
| --- | --- | --- |
| `open` | 95,983 | 73,500 |
| `join` | 57,917 | 266,015 on Base, 212,847 on Ronin, including the coordinator's request |
| First `reveal` | 57,285 | none |
| Second `reveal`, which pays the winner | 81,060 | none |
| Per game | 292,245 gas in 4 transactions | 339,515 gas on Base and 286,347 on Ronin in 2 transactions, plus the request fee |

Both duels pay the winner through `withdraw`, which the table leaves out. Priced at each mainnet's gas price and the coordinator's own quote on 2026-12-01:

| Network | Gas price | Commit-reveal, 4 transactions | VRF duel, 2 transactions | Request fee prepaid by the joiner |
| --- | --- | --- | --- | --- |
| Ronin Mainnet | 21 gwei | 0.0061 RON ($0.0002) | 0.0060 RON ($0.0002) | 0.155 RON ($0.0055), of which the service fee is $0.005 |
| Base | 0.006 gwei | 0.0000018 ETH ($0.0030) | 0.0000020 ETH ($0.0035) | 0.0000054 ETH ($0.0092), of which the service fee is $0.002 |
| Robinhood | 0.020 gwei | 0.0000059 ETH ($0.0100) | not measured | 0.0000347 ETH ($0.059), of which the service fee is $0.035 |

Dollar amounts convert at the coordinator's price feed (RON $0.0355, ETH $1,703 on Base and $1,697 on Robinhood). The gas columns are execution gas only: Base and Robinhood add an L1 data fee to every transaction, which the commit-reveal duel pays four times and the VRF duel twice. The request fee is a prepayment for the fulfillment's gas at the declared price plus the service fee; the coordinator bills the gas the fulfillment used and refunds the rest to the joiner ([fees](/docs/gas#fee)). We did not measure the VRF duel's gas on Robinhood because a local fork cannot run its quote: Robinhood's coordinator reads Arbitrum precompiles that the fork does not provide.

So commit-reveal is the cheaper duel by about the request fee: half a cent on Ronin, about a cent on Base, about six cents on Robinhood. What it costs instead is two more transactions, both players coming back before the deadline, and a design that only holds for two players.

## Tests we ran

The three contracts compile with Solidity 0.8.24 and 0.8.39. With forge 1.10.0 and forge-std, against the mock coordinator from the [integration playbook](/docs/integrate) extended with `seedOf` and a fulfillment with a chosen gas limit, these 18 tests pass:

- Duel: when both reveal, the winner the hash picks gets twice the stake and the duel is deleted. A loser who does not reveal cannot reveal after the deadline, and the opponent's `claim` pays them the pot; `claim` before the deadline reverts. A player who joins with a copy of the opponent's commitment cannot reveal it and loses by forfeit. With no reveals both stakes are refunded. Only the opener can cancel, and a cancelled duel cannot be joined; `join` rejects the opener and a different stake.
- Over 10,000 duels with secrets `keccak256("a", i)` and `keccak256("b", i)`, the opener won 4,983.
- Raffle: the attack table above, 6,000 raffles on fresh contracts, every draw equal to the attacker's prediction; reveals before the commit phase ends or after the reveal phase revert; the bond of an unrevealed ticket goes to the winner.
- VRF duel: an odd seed pays the joiner and an even seed the opener; `join` rejects the opener, a fee one wei below the quote and a missing fee; only the coordinator can call `rawFulfillRandomSeed`; after a callback starved of gas, `settle` pays once, reverts with `pending` before the seed and `settled` after; on chain ID 2020 (Ronin) it declares 23 gwei with a zero transaction gas price; the callback's worst case over 20 duels is 44,327 gas.

## Try it on a testnet

Roll a free seed on Base Sepolia in the [playground](/playground?network=base-sepolia) without a wallet, and check it on [/verify](/verify). Then deploy `CoinFlipDuelVRF` there with the [quickstart's](/docs/quickstart) `forge create` command, with `src/CoinFlipDuelVRF.sol:CoinFlipDuelVRF` in place of the template, `open()` from one account and `join(1)` from another with the stake plus the quoted fee. For a weighted roll, see [Loot box with VRF](/docs/loot-box); for one winner from many tickets, see [Raffle with VRF](/docs/raffle).

_Updated 2026-12-01._
