# VRF security considerations, tested

A VRF consumer is safe when five things hold. Only the coordinator can call the callback. Each seed is matched to the request that asked for it. Nothing a player does after the request can change the outcome. The game has no retry, cancel or refund that someone can use to throw a seed away. And no player can make the callback revert. Below, each rule is a Foundry test: an attack that works on a contract that breaks the rule, and a check that the fix stops it.

The numbers are from those tests. Take a coin flip where a stuck bet can ask for a new seed. An oracle that holds back losing seeds wins 1,505 of 2,000 flips for its player with one retry, and 2,000 of 2,000 when retries are unlimited. Against an honest oracle, a player contract that reverts the callback when it loses wins 1,000 of 1,000. The same player on the fixed contract won 472 of 1,000.

Chainlink's [VRF security considerations](https://docs.chain.link/vrf/v2-5/security) state most of these rules in prose. The tests below make them concrete and apply them to every interface Randoo serves. The [table at the end](#what-each-provider-s-base-contract-enforces) shows which rule a provider's base contract enforces for you. It is only the first.

## The checklist

| Rule | Broken by | What the test measured | Enforced by the provider? |
| --- | --- | --- | --- |
| [Only the coordinator calls the callback](#1-only-the-coordinator-calls-the-callback) | A hand-written `rawFulfill…` with no sender check | The attacker delivered seed 1 and won; the real seed changed nothing | Yes, if you inherit the base contract and do not override it |
| [Match each seed to its request](#2-match-each-seed-to-its-request) | One storage slot for "the current player" | Alice's winning seed was credited to Bob | No |
| [No inputs after the request](#3-no-inputs-after-the-request) | Bets open until the seed lands | A bet placed with the seed in hand won | No |
| [No retry, cancel or refund that depends on the seed](#4-no-retry-cancel-or-refund-that-depends-on-the-seed) | `retry()` or `cancel()` after a timeout | 1,505 / 2,000 wins with one retry, 2,000 / 2,000 with no limit; with a refund, 968 losses became 968 refunds | No |
| [A player cannot make the callback revert](#5-a-player-cannot-make-the-callback-revert) | The callback calls the player's contract | 1,000 / 1,000 wins with 944 reverted callbacks | No. Providers only decide whether the same seed is delivered again |
| Enough confirmations | A reorg that moves the request to another block | Not tested here: see [How many confirmations](/docs/request-confirmations) | You choose the count on Chainlink's interfaces |
| One decision per derived number | Two outcomes from one word | See [VRF seed to a number in a range](/docs/random-range#one-value-per-decision) | No |

## The game

Every test uses a coin flip: the player wins when the seed is odd. This is the version that passes all five rules. It is built on Randoo's Ronin-VRF-shaped base contract, so it also runs on native Ronin VRF. On Chainlink's or D20DAO's base contract the shape is the same.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

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

/// Coin flip, odd seed wins. The safe version: the base contract checks the
/// caller, each request maps to its own bet, the callback only stores the
/// seed, and there is no retry or cancel.
contract Flip is RandooConsumerRonin {
    uint256 public constant CALLBACK_GAS = 60_000;
    uint256 public constant GAS_PRICE = 23 gwei;

    struct Bet {
        address player;
        bool seeded;
        bool settled;
        uint256 seed;
    }

    mapping(bytes32 => Bet) public bets;
    mapping(address => uint256) public wins;

    constructor(address coordinator) payable RandooConsumerRonin(coordinator) {}

    function flip() external returns (bytes32 reqHash) {
        uint256 fee = IRoninVRFCoordinatorForConsumers(vrfCoordinator)
            .estimateRequestRandomFee(CALLBACK_GAS, GAS_PRICE);
        reqHash = _requestRandomness(fee, CALLBACK_GAS, GAS_PRICE, address(this));
        bets[reqHash].player = msg.sender;
    }

    function _fulfillRandomSeed(bytes32 reqHash, uint256 seed) internal override {
        Bet storage bet = bets[reqHash];
        bet.seed = seed;
        bet.seeded = true;
    }

    /// Anyone can settle; no player code runs here either.
    function settle(bytes32 reqHash) external {
        Bet storage bet = bets[reqHash];
        require(bet.seeded && !bet.settled, "not ready");
        bet.settled = true;
        if (bet.seed % 2 == 1) wins[bet.player]++;
    }

    receive() external payable {}
}
```

The tests run against `MockRandooCoordinator`, the test coordinator from [Integrate](/docs/integrate). It delivers each request once, with exactly the callback gas limit, and reports a reverted callback instead of reverting, as the live coordinator does. The callback above used 52,546 gas, including the call into the contract, so the 60,000 limit holds. [How to set a VRF callback gas limit](/docs/callback-gas) explains how to measure your own.

In the tests, the oracle's seed for a request is `keccak256(abi.encode(ORACLE_KEY, reqHash))`. Like a real VRF output, it is fixed by the oracle's key and the request, and the oracle knows it before anyone else does. With honest delivery, the player won 970 of 2,000 flips.

## 1. Only the coordinator calls the callback

If the callback does not check `msg.sender`, anyone can call it first with the seed they want:

```solidity
// Bug: anyone can call this, with any seed.
function rawFulfillRandomSeed(bytes32 reqHash, uint256 seed) external {
    address player = playerOf[reqHash];
    delete playerOf[reqHash];
    if (seed % 2 == 1) wins[player]++;
}
```

```solidity
vm.prank(mallory);
game.rawFulfillRandomSeed(reqHash, 1); // odd: a win
assertEq(game.wins(mallory), 1);

// The real seed arrives later and finds nothing to settle.
assertTrue(coordinator.fulfil(reqHash, 2));
assertEq(game.wins(mallory), 1);
```

The fix is to inherit the base contract and implement only the internal function. Every provider's base contract checks the caller. `Flip` reverts with `OnlyCoordinatorCanFulfill` when Mallory tries the same call. This bug appears when a contract implements the callback itself instead of inheriting, or overrides the external function. Chainlink's page says not to override `rawFulfillRandomness`.

Who can change the coordinator address matters as much as the check. Chainlink's `VRFConsumerBaseV2Plus` has `setCoordinator`, which the consumer's owner can call. The owner can point it at a contract of their own and deliver any seed, and the base contract's check then passes. Randoo's `RandooConsumerRonin` and the `VRFConsumer` in Ronin's docs set the coordinator in the constructor and include no setter. If your game keeps a setter for migrations, put it behind a timelock that players can watch. The `CoordinatorSet` events show every change.

## 2. Match each seed to its request

Requests can be fulfilled in any order. Chainlink's page and [Several VRF requests at once](/docs/concurrent-requests) both say so, and the second shows Randoo seeds arriving out of order. A contract that keeps the player in one slot credits every seed to whoever asked last:

```solidity
address public currentPlayer; // Bug: one slot for every request in flight

function _fulfillRandomSeed(bytes32, uint256 seed) internal override {
    if (seed % 2 == 1) wins[currentPlayer]++;
}
```

In the test, Alice flips, then Bob flips, and both seeds are odd. Bob gets 2 wins and Alice 0. `Flip` keys the bet by `reqHash`. When Bob's seed lands first and Alice's second, each player gets their own result.

## 3. No inputs after the request

Close every choice that the seed decides before you ask for the seed. A round that takes bets until the seed arrives lets in anyone who sees the fulfilment before it is mined: the oracle, the sequencer, or any node that relays the transaction. Chainlink gives a second reason: a validator that can rewrite a block can move a request to get a fresh seed.

```solidity
// Bug: bets stay open until the seed arrives, not until it is requested.
function bet(uint256 side) external override {
    require(!done, "round over");
    _bet(side);
}
```

```solidity
round.draw();
uint256 seed = oracleSeed(round.reqHash()); // read from the pending fulfilment
vm.prank(mallory);
round.bet(2 - (seed % 2));
coordinator.fulfil(round.reqHash(), seed);
assertTrue(round.won(mallory));
```

The fix is one condition. `Round.bet` requires `reqHash == 0`, and `draw()` sets `reqHash` in the same transaction that sends the request. After that, a bet reverts with `bets closed`. The same applies to every input the outcome depends on: entries in a [raffle](/docs/raffle), the mint in an [NFT reveal](/docs/nft-reveal), and the stake on a [dice roll](/docs/dice).

## 4. No retry, cancel or refund that depends on the seed

The [VRF proof](/docs/vrf-proof) stops the oracle from choosing a seed. It does not stop the oracle from staying silent. Any VRF oracle, Randoo's included, computes the output before it publishes it. Every exit your game offers for an unanswered request is therefore an option for whoever sees the seed first, and the tests measured what the option is worth:

| Game exit after 100 blocks without a seed | Oracle withholds the player's losing seeds | Result over 2,000 flips |
| --- | --- | --- |
| None (`Flip`) | The bet stays open | 970 wins, as with an honest oracle. A withheld seed never becomes a loss or a win |
| `retry()` once: the same bet asks for a new seed | Once per bet | 1,505 wins, 495 losses |
| `retry()` without a limit | Until the seed wins | 2,000 wins, 0 losses, 3,915 requests |
| `cancel()`: the bet is called off and the stake returned | Every losing bet | 1,032 wins, 0 losses, 968 refunds |

With a refund, the oracle never takes the colluding player's stake. At a 2× payout, that player gains about half a stake per flip, and the house pays for it. The player does not need the oracle when the seed shows up somewhere public before it is used, and that is the next rule.

```solidity
/// Bug 1: the same bet gets a fresh seed.
function retry(bytes32 reqHash) external returns (bytes32) {
    Bet memory bet = bets[reqHash];
    require(bet.player == msg.sender, "not yours");
    require(block.number > bet.requestedAt + TIMEOUT, "too early");
    delete bets[reqHash];
    return _open(msg.sender);
}
```

Chainlink's rule is plain: "Do not allow re-requesting or cancellation of randomness." If your game needs a way out of a provider outage, the way out should give the same result whether the withheld seed was good or bad for the player. Some ways to do that:

- Leave the bet open. Randoo, Chainlink and native Ronin VRF set no deadline on chain, so a late seed can still arrive. [What happens when a VRF request is never fulfilled](/docs/request-not-fulfilled) lists each provider's deadline and who else can answer.
- Let only the house void open bets, and void all of them at once, never one player's bet.
- Make the timeout hours long, not blocks, and count voids. A void rate above your provider's usual miss rate is the signal to look at.

On D20DAO, anyone can refund a request that is not answered within 60 seconds, and the coordinator then calls your contract's `_onRefund`. According to the SDK README, its `RaffleConsumer` example allows a new draw there. A new draw after a refund is the `retry()` row in the table above, so check what your `_onRefund` does.

## 5. A player cannot make the callback revert

If the callback runs player code, the player decides whether it succeeds. Here `RetryFlip` tells the player the result:

```solidity
bool won = seed % 2 == 1;
if (won) wins[player]++;
else losses[player]++;
// Bug 2: if this reverts, the whole callback reverts and the bet stays open.
if (player.code.length > 0) IFlipPlayer(player).onFlip(won);
```

The player is a contract whose `onFlip` reverts on a loss: `require(won, "lost")`. The revert rolls back the loss. The coordinator still marks the request fulfilled, and the bet looks as if no seed has arrived. After the timeout, `retry()` gives the bet a new seed. With an honest oracle that delivered every seed at once, the player won 1,000 of 1,000 bets, with 944 reverted callbacks along the way.

The same player against `Flip` won 472 of 1,000, with no failed callbacks. `Flip`'s callback stores the seed and returns, and `settle` makes no external call. A payout that is a transfer belongs in a separate withdraw function, not in the callback or in `settle`. Otherwise, a winner whose contract rejects ETH blocks the round for everyone, as on the [raffle](/docs/raffle).

Without the retry, the revert gains the player nothing. On Chainlink and native Ronin VRF the bet is stuck and the seed sits in an event log. On Pyth Entropy, D20DAO, and Randoo's D20DAO interface, anyone can deliver the same seed again, and it hits the same revert. [When a VRF callback reverts](/docs/failed-callback) covers recovery for each provider. On Randoo, a contract can read the stored seed with `seedOf(reqHash)` and settle without the callback.

## What each provider's base contract enforces

| Provider | Base contract | Caller check | Who can change the coordinator | After a reverted callback |
| --- | --- | --- | --- | --- |
| Chainlink VRF v2.5, subscription | `VRFConsumerBaseV2Plus` | `OnlyCoordinatorCanFulfill(have, want)` | The owner, or the coordinator, via `setCoordinator` | Not called again |
| Chainlink VRF v2.5, direct funding | `VRFV2PlusWrapperConsumerBase` | `OnlyVRFWrapperCanFulfill(have, want)` | Nobody: the wrapper address is fixed at deployment | Not called again; the wrapper emits `WrapperFulfillmentFailed` |
| Native Ronin VRF | `VRFConsumer` (Ronin docs) | `OnlyCoordinatorCanFulfill()` | Nobody, in the base contract | Not called again |
| Pyth Entropy | `IEntropyConsumer` | `require(msg.sender == entropy, "Only Entropy can call this function")` | Your `getEntropy()` decides | Anyone can call `revealWithCallback` again with the same number |
| D20DAO | `D20VRFConsumer` | `OnlyCoordinator` | Passed to the constructor in D20DAO's examples | Anyone can call `retryCallback` with the same word |
| Randoo | Whichever of the three interfaces you use (`RandooConsumerRonin`, Chainlink's wrapper base, `D20VRFConsumer`) | As in that base | As in that base | Not called again on the Ronin and Chainlink interfaces, with the seed readable through `seedOf`; `retryCallback` on the D20DAO interface |

Rules 2 to 5 are your contract's job on every provider. A provider can refuse to deliver a seed twice, and every one above does. It cannot know which of your bets a seed belongs to, when your bets close, or what your timeout does.

## Tests we ran

With forge 1.10.0, Solidity 0.8.30 and forge-std, these 13 tests pass against `MockRandooCoordinator`:

- Caller: `UncheckedFlip` credits a seed of 1 delivered by Mallory, and the coordinator's later fulfil succeeds and changes nothing. `Flip` reverts with `OnlyCoordinatorCanFulfill`.
- Matching: `LastPlayerFlip` gives Bob 2 wins and Alice 0 from two odd seeds. In `Flip`, with Bob's seed delivered first, Alice gets 0 wins and Bob 1.
- Late inputs: on `LeakyRound`, Mallory bets after `draw()` with the seed in hand and wins. `Round` reverts the bet with `bets closed`.
- Withholding oracle, 2,000 flips each: `RetryFlip` with one retry 1,505 wins and 495 losses; without a limit 2,000 wins from 3,915 requests; `VoidFlip` 1,032 wins, 0 losses, 968 voids; `Flip` with honest delivery 970 wins.
- Reverting player, 1,000 flips each: against `RetryFlip`, 1,000 wins and 0 losses from 1,944 requests, 944 of them with a failed callback. Against `Flip`, 472 wins and 0 failed callbacks.
- Gas: `Flip`'s callback used 52,546 gas, under its 60,000 limit.

## 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). To build a consumer that follows these rules, start from the [quickstart](/docs/quickstart). Then pick the guide closest to your game: [loot box](/docs/loot-box), [raffle](/docs/raffle), [dice](/docs/dice) or [NFT reveal](/docs/nft-reveal). Each closes its inputs before the request and keeps the callback to storing the seed. If you are deciding whether a game needs a VRF at all, read [Commit-reveal or VRF?](/docs/commit-reveal)

Sources (read 2026-12-05): Chainlink's [VRF security considerations](https://docs.chain.link/vrf/v2-5/security); `VRFConsumerBaseV2Plus.sol` and `VRFV2PlusWrapperConsumerBase.sol` in `@chainlink/contracts` 1.5.0 from npm; the `VRFConsumer` contract in Ronin's [VRF docs](https://docs.roninchain.com/developers/tools/vrf); Pyth's `IEntropyConsumer.sol` (pyth-crosschain, main branch); the `@d20dao/vrf-sdk` 0.6.2 README; Randoo's `RandooConsumerRonin.sol`.

_Updated 2026-12-06._
