How do I get secure on-chain randomness with Chainlink VRF?
Inherit VRFConsumerBaseV2Plus and call requestRandomWords; the coordinator verifies the oracle's proof before calling fulfillRandomWords. Freeze inputs first, match requestId, never re-request and never revert in the callback.
Use Chainlink VRF v2.5: your contract inherits VRFConsumerBaseV2Plus and calls requestRandomWords on the VRF Coordinator; a few blocks later an oracle node returns random numbers together with a cryptographic proof, the coordinator verifies the proof on chain, and only then calls your fulfillRandomWords. The node can't choose or predict the output, and neither can validators or users. The randomness is only secure if your contract is too: match each fulfilment by requestId, stop accepting inputs once a request is made, never allow re-requesting, choose enough requestConfirmations for the chain's reorg risk, and make sure fulfillRandomWords never reverts.
Why can't I use block.prevrandao or blockhash?
Everything inside a block is either public or chosen by someone with an incentive.
Users can preview and revert. If a contract computes uint256(keccak256(abi.encode(block.prevrandao, msg.sender))) % 100 in the same transaction as the bet, an attacker's contract can compute the same value first and revert whenever it would lose.
Validators have influence. On Ethereum, PREVRANDAO mixes in each proposer's RANDAO reveal. A proposer can't pick the value, but it can choose not to propose, which gives one bit of influence per slot it controls. That's enough to tilt a large prize.
blockhash is worse. It's known to everyone once the block exists, and only the last 256 block hashes are available at all.
Rollups differ. On many L2s PREVRANDAO is a constant or set by the sequencer. The zkEVM compatibility guide lists it among fields that don't carry over from L1.
Commit-reveal schemes avoid an oracle, but the last participant to reveal can refuse when the outcome is bad, so they need deposits and timeouts. A verifiable random function moves the problem to someone who provably can't cheat.
How does Chainlink VRF work?
VRF is a different Chainlink service from the : it's request-and-response, and every answer is checked on chain. A takes a secret key and an input and produces an output plus a proof. Anyone with the public key can check the proof, and for a given key and input there is exactly one valid output. The flow:
Use latestRoundData, reject non-positive or stale answers based on the feed's heartbeat, normalize with decimals(), and on L2s check the Sequencer Uptime Feed with a grace period.
Your contract calls requestRandomWords. The coordinator records the request, derives a pre-seed from your consumer address, subscription and nonce, and emits a RandomWordsRequested event.
The VRF node for your key hash waits requestConfirmations blocks.
The node computes the seed from the pre-seed and the hash of the block containing the request, then the VRF output and proof with its secret key.
It sends the proof to the coordinator, which verifies it against the node's registered public key, expands the output into numWords values, charges your subscription and calls rawFulfillRandomWords on your contract.
VRFConsumerBaseV2Plus checks that msg.sender is the coordinator and passes the words to your fulfillRandomWords.
The node can't pick a favourable result because the proof only verifies for the one correct output. The block hash wasn't known when you sent the request, so the node can't precompute it either. Its remaining power is to not respond, which is a liveness problem, not a manipulation one. The remaining manipulation risk is a reorg: a validator who could rewrite the request's block would change the block hash and therefore the result. That's what requestConfirmations protects against.
Subscription or direct funding?
Subscription
Direct funding
Base contract
VRFConsumerBaseV2Plus
VRFV2PlusWrapperConsumerBase
Who pays
A prepaid subscription shared by your consumer contracts
The consumer contract pays per request
Payment
LINK or native token (nativePayment flag)
LINK or native token
Cost
Lower per request
Higher, includes wrapper overhead
Fits
Apps making regular requests
One-off requests, or passing the cost to the end user
You create and fund a subscription in the VRF subscription manager, then add each consumer contract's address to it. Chainlink has deprecated VRF v1 and v2 in favour of v2.5, so new code should use the v2.5 contracts shown here; see the VRF v2.5 docs for current coordinator addresses and key hashes per network.
A secure consumer contract
A one-round raffle that applies the security rules:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";
contract Raffle is VRFConsumerBaseV2Plus {
enum State { Open, Drawing, Closed }
uint256 public constant TICKET_PRICE = 0.01 ether;
uint32 public constant CALLBACK_GAS_LIMIT = 150_000;
uint16 public constant REQUEST_CONFIRMATIONS = 3;
uint256 public immutable subscriptionId;
bytes32 public immutable keyHash;
State public state;
address[] public players;
uint256 public pot;
uint256 public pendingRequestId;
address public winner;
mapping(address => uint256) public prizes;
event DrawRequested(uint256 indexed requestId);
event WinnerPicked(address indexed winner, uint256 prize);
constructor(address coordinator, uint256 subId, bytes32 _keyHash)
VRFConsumerBaseV2Plus(coordinator)
{
subscriptionId = subId;
keyHash = _keyHash;
}
function enter() external payable {
require(state == State.Open, "not open");
require(msg.value == TICKET_PRICE, "wrong price");
players.push(msg.sender);
pot += msg.value;
}
function draw() external onlyOwner {
require(state == State.Open && players.length > 0, "cannot draw");
state = State.Drawing; // freeze entries before the request exists
pendingRequestId = s_vrfCoordinator.requestRandomWords(
VRFV2PlusClient.RandomWordsRequest({
keyHash: keyHash,
subId: subscriptionId,
requestConfirmations: REQUEST_CONFIRMATIONS,
callbackGasLimit: CALLBACK_GAS_LIMIT,
numWords: 1,
extraArgs: VRFV2PlusClient._argsToBytes(
VRFV2PlusClient.ExtraArgsV1({nativePayment: false})
)
})
);
emit DrawRequested(pendingRequestId);
}
// Must not revert: VRF does not retry a failed callback.
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal override {
if (requestId != pendingRequestId || state != State.Drawing) return;
address w = players[randomWords[0] % players.length];
winner = w;
prizes[w] = pot;
state = State.Closed;
emit WinnerPicked(w, pot);
}
// Pull payment: the winner withdraws, so a reverting receiver can't block the draw.
function claim() external {
uint256 amount = prizes[msg.sender];
require(amount > 0, "nothing to claim");
prizes[msg.sender] = 0;
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "transfer failed");
}
}
What each choice prevents:
State flips to Drawing before the request. Nobody can enter after the outcome could be known. The fulfilment transaction is visible in the mempool before it executes, so any input accepted after the request is a front-running opportunity, the same dynamic described in how MEV and sandwich attacks work.
There's no "redraw" or cancel function. If the owner could request again, they could keep discarding results they dislike.
The callback ignores unknown IDs instead of reverting, and does only cheap bookkeeping. Paying the winner inside the callback could revert (a contract winner that rejects ETH) and leave the raffle stuck forever. Pull payments with state updated before the transfer also follow the pattern in preventing reentrancy.
randomWords[0] % players.length has negligible bias because a 256-bit value is vastly larger than any player count. For other ranges, the same holds as long as the range is tiny compared with 2^256.
How do I choose the request parameters?
requestConfirmations: at least the coordinator's minimum (commonly 3) and at most 200. Raise it for high-value draws or chains with deeper reorgs; how to handle reorgs in a backend explains why depth matters.
callbackGasLimit: enough for your callback with a margin, below the coordinator's maximum. If it's too low, the callback runs out of gas, the request is still charged and there's no retry. Measure with a test, don't guess.
numWords: request several words in one go if you need them, up to the coordinator's MAX_NUM_WORDS (500 in the v2.5 coordinator), or derive more from one word with uint256(keccak256(abi.encode(word, i))).
keyHash: selects the gas lane, the maximum gas price you're willing to pay for fulfilment. A cheap lane can delay fulfilment when gas prices spike.
How do I test it locally?
Chainlink ships VRFCoordinatorV2_5Mock, which lets you fulfil requests with any words you choose. That turns randomness into a fuzz input:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Test} from "forge-std/Test.sol";
import {VRFCoordinatorV2_5Mock} from "@chainlink/contracts/src/v0.8/vrf/mocks/VRFCoordinatorV2_5Mock.sol";
import {Raffle} from "../src/Raffle.sol";
contract RaffleTest is Test {
VRFCoordinatorV2_5Mock coordinator;
Raffle raffle;
function setUp() public {
coordinator = new VRFCoordinatorV2_5Mock(0.1 ether, 1e9, 4e15);
uint256 subId = coordinator.createSubscription();
coordinator.fundSubscription(subId, 100 ether);
raffle = new Raffle(address(coordinator), subId, bytes32(0));
coordinator.addConsumer(subId, address(raffle));
}
function testFuzz_WinnerIsAPlayerAndEntriesAreFrozen(uint256 word) public {
for (uint256 i; i < 5; i++) {
address p = address(uint160(0x1000 + i));
vm.deal(p, 1 ether);
vm.prank(p);
raffle.enter{value: 0.01 ether}();
}
raffle.draw();
vm.expectRevert("not open");
raffle.enter{value: 0.01 ether}();
uint256[] memory words = new uint256[](1);
words[0] = word;
coordinator.fulfillRandomWordsWithOverride(raffle.pendingRequestId(), address(raffle), words);
assertEq(raffle.winner(), address(uint160(0x1000 + (word % 5))));
assertEq(raffle.prizes(raffle.winner()), 0.05 ether);
}
}
Fuzz and invariant testing in Foundry covers how to extend this into invariants such as "the pot is always paid to exactly one player". Then test on a real testnet coordinator, because the mock doesn't model confirmation delays or gas lanes.
Checklist
Never use block.prevrandao, blockhash or timestamps for anything worth money.
Inherit VRFConsumerBaseV2Plus and don't override rawFulfillRandomWords.
Freeze all inputs (entries, bets, parameters) before calling requestRandomWords.
Store the requestId and match it in fulfillRandomWords.
Provide no way to re-request or cancel a pending request.
Keep the callback cheap and non-reverting; move payouts and heavy logic to separate calls.
Set requestConfirmations for the value at risk and the chain's reorg depth.
Measure callbackGasLimit, keep the subscription funded and manage it from a plain EOA or multisig rather than an ERC-4337 smart account, which Chainlink warns can delay subscription changes.