How to test a Chainlink VRF v2.5 consumer in Foundry
Deploy VRFCoordinatorV2_5Mock from @chainlink/contracts, request from your consumer, then call mock.fulfillRandomWords(requestId, address) yourself and assert on your contract's state. Do not assert on the call: a callback that reverts or runs out of gas does not make it revert. For a direct-funding consumer, deploy Chainlink's own VRFV2PlusWrapper on top of the mock and fulfil to the wrapper, not to your contract. Set vm.txGasPrice, because forge's default gas price of 0 makes the wrapper's quote 0. Everything on this page ran with forge 1.10.0 and @chainlink/contracts 1.5.0 on 2026-11-30: 16 tests, all passing, 13 local and 3 on a Base Sepolia fork.
Seven traps, each one tested
| What you do | What happens | Test |
|---|---|---|
| Fulfil a request whose callback runs out of gas | fulfillRandomWords succeeds; only RandomWordsFulfilled(…, success = false, …) says it failed, and the request is deleted | test_CallbackOutOfGasIsSilent |
Pass the wrong address to fulfillRandomWords | The mock calls whatever you pass. To an account without code the call "succeeds" and your game gets nothing | test_WrongConsumerAddressIsSilent |
Fund with fundSubscription, request with nativePayment: true | The request is accepted; the fulfilment reverts with InsufficientBalance. fundSubscription credits LINK only; native needs fundSubscriptionWithNative | test_NativeRequestNeedsNativeFunding |
Construct the mock with (0.25 ether, 1e9, 4e15) and read the first number as "0.25 LINK" | One fulfilment charges 62.5 LINK: the base fee is in wei of the native token, converted to LINK at 4e15 wei per LINK | test_LinkRoundTrip |
| Fulfil a direct-funding request to your contract instead of the wrapper | Your contract reverts with OnlyVRFWrapperCanFulfill inside the mock's call, the mock reports success = false, and the request is gone | test_FulfilToConsumerBurnsRequest |
Request through the wrapper without vm.txGasPrice | The quote is 0 wei and the request goes through unpaid | test_ZeroGasPriceQuotesZero |
Configure your local wrapper with a small wrapperGasOverhead | The wrapper itself runs out of gas: the mock reports success = false and the wrapper emits no WrapperFulfillmentFailed | test_LowWrapperOverheadIsSilent |
What the mock skips altogether, from its source: it accepts any requestConfirmations, any callbackGasLimit (we requested 30,000,000; the live coordinator on Base reverts above 2,500,000) and any numWords (live: at most 500). It numbers requests 1, 2, 3, while live request IDs are 256-bit hashes. It generates words as keccak256(abi.encode(requestId, i)), so they are the same on every run. pendingRequestExists reverts with NotImplemented.
Set up the project
Run npm i @chainlink/contracts@1.5.0 in the Foundry project. It also installs OpenZeppelin 4.9.6 as @openzeppelin/contracts-4.9.6, which SubscriptionAPI.sol imports under the path @openzeppelin/contracts@4.9.6/, so map that path too. VRFV2PlusWrapper.sol pins pragma solidity 0.8.19: any test that imports it must accept 0.8.19, and without the optimizer it fails to compile with Stack too deep.
[profile.default]
src = "src"
test = "test"
libs = ["lib", "node_modules"]
optimizer = true
optimizer_runs = 200
remappings = [
"@chainlink/contracts/=node_modules/@chainlink/contracts/",
"@openzeppelin/contracts@4.9.6/=node_modules/@openzeppelin/contracts-4.9.6/",
"forge-std/=lib/forge-std/src/",
]The game under test is a coin flip, written twice: once as a subscription consumer and once as a direct-funding consumer. Subscription or direct funding? compares what the two cost on Base. The callback keys each result by request ID, as Several VRF requests at once explains.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import {VRFV2PlusWrapperConsumerBase} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFV2PlusWrapperConsumerBase.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";
/// Subscription consumer: the coordinator calls back.
contract CoinFlipSub is VRFConsumerBaseV2Plus {
uint256 public immutable subId;
bytes32 public immutable keyHash;
bool public immutable payNative;
uint32 public callbackGasLimit = 100_000;
mapping(uint256 => address) public playerOf;
mapping(address => uint8) public outcome; // 0 pending, 1 heads, 2 tails
constructor(address coordinator, uint256 subId_, bytes32 keyHash_, bool payNative_)
VRFConsumerBaseV2Plus(coordinator)
{
subId = subId_;
keyHash = keyHash_;
payNative = payNative_;
}
function setCallbackGasLimit(uint32 gasLimit) external {
callbackGasLimit = gasLimit;
}
function flip() external returns (uint256 requestId) {
requestId = s_vrfCoordinator.requestRandomWords(
VRFV2PlusClient.RandomWordsRequest({
keyHash: keyHash,
subId: subId,
requestConfirmations: 3,
callbackGasLimit: callbackGasLimit,
numWords: 1,
extraArgs: VRFV2PlusClient._argsToBytes(VRFV2PlusClient.ExtraArgsV1({nativePayment: payNative}))
})
);
playerOf[requestId] = msg.sender;
}
function fulfillRandomWords(uint256 requestId, uint256[] calldata words) internal override {
address player = playerOf[requestId];
require(player != address(0), "unknown request");
delete playerOf[requestId];
outcome[player] = words[0] % 2 == 0 ? 1 : 2;
}
}
/// Direct-funding consumer: the wrapper calls back. Works with Chainlink's wrapper or Randoo's coordinator.
contract CoinFlipDirect is VRFV2PlusWrapperConsumerBase {
uint32 public callbackGasLimit = 100_000;
mapping(uint256 => address) public playerOf;
mapping(address => uint8) public outcome;
constructor(address wrapper) VRFV2PlusWrapperConsumerBase(wrapper) {}
receive() external payable {}
function setCallbackGasLimit(uint32 gasLimit) external {
callbackGasLimit = gasLimit;
}
function flip() external payable returns (uint256 requestId, uint256 price) {
(requestId, price) = requestRandomnessPayInNative(
callbackGasLimit, 3, 1, VRFV2PlusClient._argsToBytes(VRFV2PlusClient.ExtraArgsV1({nativePayment: true}))
);
playerOf[requestId] = msg.sender;
}
function fulfillRandomWords(uint256 requestId, uint256[] memory words) internal override {
address player = playerOf[requestId];
require(player != address(0), "unknown request");
delete playerOf[requestId];
outcome[player] = words[0] % 2 == 0 ? 1 : 2;
}
}Subscription consumers
Create a subscription on the mock, add the consumer, fund it in the currency the request pays in, request, fulfil. Read the outcome from the mock's RandomWordsFulfilled event or, better, from your contract.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {Test, Vm, console} from "forge-std/Test.sol";
import {VRFCoordinatorV2_5Mock} from "@chainlink/contracts/src/v0.8/vrf/mocks/VRFCoordinatorV2_5Mock.sol";
import {SubscriptionAPI} from "@chainlink/contracts/src/v0.8/vrf/dev/SubscriptionAPI.sol";
import {CoinFlipSub} from "../src/CoinFlip.sol";
contract SubscriptionMockTest is Test {
bytes32 constant KEY_HASH = bytes32(uint256(1)); // the mock does not check it
bytes32 constant FULFILLED_SIG =
keccak256("RandomWordsFulfilled(uint256,uint256,uint256,uint96,bool,bool,bool)");
VRFCoordinatorV2_5Mock mock;
address player = makeAddr("player");
function setUp() public {
// base fee in wei of the native token, gas price, wei per LINK
mock = new VRFCoordinatorV2_5Mock(0.25 ether, 1e9, 4e15);
}
function _game(bool payNative) internal returns (CoinFlipSub game, uint256 subId) {
subId = mock.createSubscription();
game = new CoinFlipSub(address(mock), subId, KEY_HASH, payNative);
mock.addConsumer(subId, address(game));
}
/// (payment, success) from the mock's RandomWordsFulfilled event.
function _fulfilled() internal returns (uint96 payment, bool success) {
Vm.Log[] memory logs = vm.getRecordedLogs();
for (uint256 i; i < logs.length; i++) {
if (logs[i].topics[0] == FULFILLED_SIG) {
(, payment,, success,) = abi.decode(logs[i].data, (uint256, uint96, bool, bool, bool));
}
}
}
function test_LinkRoundTrip() public {
(CoinFlipSub game, uint256 subId) = _game(false);
mock.fundSubscription(subId, 100 ether); // 100 LINK
vm.prank(player);
uint256 id = game.flip();
vm.recordLogs();
mock.fulfillRandomWords(id, address(game));
(uint96 payment,) = _fulfilled();
assertGt(game.outcome(player), 0);
console.log("LINK charged (wei):", payment);
}
function test_NativeRequestNeedsNativeFunding() public {
(CoinFlipSub game, uint256 subId) = _game(true);
mock.fundSubscription(subId, 100 ether); // credits LINK only
vm.prank(player);
uint256 id = game.flip(); // accepted
vm.expectRevert(SubscriptionAPI.InsufficientBalance.selector);
mock.fulfillRandomWords(id, address(game));
mock.fundSubscriptionWithNative{value: 1 ether}(subId);
vm.recordLogs();
mock.fulfillRandomWords(id, address(game));
(uint96 payment,) = _fulfilled();
assertGt(game.outcome(player), 0);
console.log("native charged (wei):", payment);
}
function test_CallbackOutOfGasIsSilent() public {
(CoinFlipSub game, uint256 subId) = _game(false);
mock.fundSubscription(subId, 100 ether);
game.setCallbackGasLimit(20_000);
vm.prank(player);
uint256 id = game.flip();
vm.recordLogs();
mock.fulfillRandomWords(id, address(game)); // does not revert
(, bool success) = _fulfilled();
assertFalse(success);
assertEq(game.outcome(player), 0, "the player never gets a result");
vm.expectRevert(VRFCoordinatorV2_5Mock.InvalidRequest.selector);
mock.fulfillRandomWords(id, address(game)); // and it cannot be retried
}
function test_WrongConsumerAddressIsSilent() public {
(CoinFlipSub game, uint256 subId) = _game(false);
mock.fundSubscription(subId, 100 ether);
vm.prank(player);
uint256 id = game.flip();
vm.recordLogs();
mock.fulfillRandomWords(id, player); // an account without code
(, bool success) = _fulfilled();
assertTrue(success, "reported as delivered");
assertEq(game.outcome(player), 0, "but the game got nothing");
}
function test_MockSkipsLiveLimits() public {
(CoinFlipSub game, uint256 subId) = _game(false);
mock.fundSubscription(subId, 1_000_000 ether);
game.setCallbackGasLimit(30_000_000); // the live coordinator on Base reverts above 2,500,000
vm.prank(player);
assertEq(game.flip(), 1); // and its request IDs are not 1, 2, 3
}
function test_OverrideWords() public {
(CoinFlipSub game, uint256 subId) = _game(false);
mock.fundSubscription(subId, 100 ether);
vm.prank(player);
uint256 id = game.flip();
uint256[] memory words = new uint256[](1);
words[0] = 7; // odd: tails
mock.fulfillRandomWordsWithOverride(id, address(game), words);
assertEq(game.outcome(player), 2);
}
/// Chainlink's guide: base fee 0.1, 1 gwei, 100 LINK, at 0.00396 ETH per LINK.
function test_ChainlinkGuideConstants() public {
VRFCoordinatorV2_5Mock m = new VRFCoordinatorV2_5Mock(0.1 ether, 1e9, 3_962_147_213_857_640);
uint256 subId = m.createSubscription();
CoinFlipSub game = new CoinFlipSub(address(m), subId, KEY_HASH, false);
m.addConsumer(subId, address(game));
m.fundSubscription(subId, 100 ether);
uint256 fulfilled;
while (true) {
vm.prank(player);
uint256 id = game.flip();
try m.fulfillRandomWords(id, address(game)) {
fulfilled++;
} catch (bytes memory err) {
assertEq(bytes4(err), SubscriptionAPI.InsufficientBalance.selector);
break;
}
}
(uint96 left,,,,) = m.getSubscription(subId);
assertEq(fulfilled, 3);
console.log("LINK left (wei):", left);
}
}Why the mock runs out of LINK
The mock charges baseFee + gasUsed × gasPrice in wei of the native token, then converts that to LINK at weiPerUnitLink. With 0.25 ether, 1e9 and 4e15, one fulfilment of this callback charged 0.250067 ETH when paid in native, and 62.52 LINK when paid in LINK. A test that funds 3 or 10 LINK fails with InsufficientBalance on the first fulfilment.
Chainlink's local testing guide uses a base fee of 100000000000000000, a gas price of 1000000000, the current LINK/ETH price, and funds 100 LINK. At 0.00396 ETH per LINK (the fallback price in Base's wrapper on 2026-11-30), each fulfilment charged 25.25 LINK, and the fourth one reverted with 24.24 LINK left (test_ChainlinkGuideConstants). If your tests fulfil more than a few requests, fund far more than you expect to use, or pass a smaller base fee to the constructor.
The callback limit you set in a test does not tell you what the callback needs on chain. How to set a VRF callback gas limit has a Foundry test that finds the least gas a callback needs from cold storage.
Direct-funding consumers (the wrapper)
Chainlink's v2.5 docs have no local testing guide for direct funding (/vrf/v2-5/direct-funding/test-locally returns 404 on 2026-11-30); the v2 guide is for Hardhat and Remix. The wrapper runs on the mock unchanged: create a subscription, deploy the wrapper with its ID, add the wrapper as a consumer, fund the subscription with native, and call setConfig. The values below are what getConfig() returned from Chainlink's wrapper on Base mainnet at block 64,160,872.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {Test, Vm, console} from "forge-std/Test.sol";
import {VRFCoordinatorV2_5Mock} from "@chainlink/contracts/src/v0.8/vrf/mocks/VRFCoordinatorV2_5Mock.sol";
import {VRFV2PlusWrapper} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFV2PlusWrapper.sol";
import {MockV3Aggregator} from "@chainlink/contracts/src/v0.8/shared/mocks/MockV3Aggregator.sol";
import {CoinFlipDirect} from "../src/CoinFlip.sol";
contract WrapperMockTest is Test {
bytes32 constant FULFILLED_SIG =
keccak256("RandomWordsFulfilled(uint256,uint256,uint256,uint96,bool,bool,bool)");
bytes32 constant WRAPPER_FAILED_SIG = keccak256("WrapperFulfillmentFailed(uint256,address)");
VRFCoordinatorV2_5Mock mock;
VRFV2PlusWrapper wrapper;
CoinFlipDirect game;
address player = makeAddr("player");
function setUp() public {
mock = new VRFCoordinatorV2_5Mock(0.002 ether, 1e9, 4e15);
MockV3Aggregator linkNativeFeed = new MockV3Aggregator(18, 4e15);
uint256 subId = mock.createSubscription();
wrapper = new VRFV2PlusWrapper(makeAddr("link"), address(linkNativeFeed), address(mock), subId);
mock.addConsumer(subId, address(wrapper));
mock.fundSubscriptionWithNative{value: 10 ether}(subId);
_configure(13_400);
game = new CoinFlipDirect(address(wrapper));
vm.deal(address(game), 1 ether); // the game pays for its requests
}
/// Base mainnet's wrapper config, with a chosen wrapper overhead.
function _configure(uint32 wrapperGasOverhead) internal {
wrapper.setConfig(
wrapperGasOverhead,
128_500, // coordinatorGasOverheadNative
150_400, // coordinatorGasOverheadLink
435, // coordinatorGasOverheadPerWord
60, // coordinatorNativePremiumPercentage
50, // coordinatorLinkPremiumPercentage
bytes32(uint256(1)), // keyHash
10, // maxNumWords
172_800, // stalenessSeconds
3_962_147_213_857_640, // fallbackWeiPerUnitLink
0, // fulfillmentFlatFeeNativePPM
0 // fulfillmentFlatFeeLinkDiscountPPM
);
}
function _results() internal returns (bool success, bool wrapperFailed) {
Vm.Log[] memory logs = vm.getRecordedLogs();
for (uint256 i; i < logs.length; i++) {
if (logs[i].topics[0] == WRAPPER_FAILED_SIG) wrapperFailed = true;
if (logs[i].topics[0] == FULFILLED_SIG) {
(,,, success,) = abi.decode(logs[i].data, (uint256, uint96, bool, bool, bool));
}
}
}
function test_RoundTrip() public {
vm.txGasPrice(0.01 gwei);
vm.prank(player);
(uint256 id, uint256 price) = game.flip();
console.log("price at 0.01 gwei (wei):", price);
vm.recordLogs();
mock.fulfillRandomWords(id, address(wrapper)); // the wrapper, not the game
(bool success, bool wrapperFailed) = _results();
assertTrue(success && !wrapperFailed);
assertGt(game.outcome(player), 0);
}
function test_ZeroGasPriceQuotesZero() public {
vm.prank(player);
(, uint256 price) = game.flip(); // no vm.txGasPrice
assertEq(price, 0);
}
function test_FulfilToConsumerBurnsRequest() public {
vm.txGasPrice(0.01 gwei);
vm.prank(player);
(uint256 id,) = game.flip();
vm.recordLogs();
mock.fulfillRandomWords(id, address(game)); // OnlyVRFWrapperCanFulfill, swallowed
(bool success,) = _results();
assertFalse(success);
vm.expectRevert(VRFCoordinatorV2_5Mock.InvalidRequest.selector);
mock.fulfillRandomWords(id, address(wrapper));
}
function test_CallbackOutOfGas() public {
vm.txGasPrice(0.01 gwei);
game.setCallbackGasLimit(20_000);
vm.prank(player);
(uint256 id,) = game.flip();
vm.recordLogs();
mock.fulfillRandomWords(id, address(wrapper));
(bool success, bool wrapperFailed) = _results();
assertTrue(success); // coordinator to wrapper: fine
assertTrue(wrapperFailed); // wrapper to game: out of gas
assertEq(game.outcome(player), 0);
}
function test_LowWrapperOverheadIsSilent() public {
_configure(1_000);
vm.txGasPrice(0.01 gwei);
vm.prank(player);
(uint256 id,) = game.flip();
vm.recordLogs();
mock.fulfillRandomWords(id, address(wrapper));
(bool success, bool wrapperFailed) = _results();
assertFalse(success); // the wrapper ran out of gas
assertFalse(wrapperFailed); // so it emitted nothing
assertEq(game.outcome(player), 0);
}
function test_FindMinWrapperOverhead() public {
vm.txGasPrice(0.01 gwei);
uint32 lo = 0;
uint32 hi = 13_400;
while (lo < hi) {
uint32 mid = (lo + hi) / 2;
if (_delivers(mid)) hi = mid;
else lo = mid + 1;
}
console.log("least wrapperGasOverhead that delivers:", lo);
}
function _delivers(uint32 overhead) internal returns (bool ok) {
uint256 snap = vm.snapshotState();
_configure(overhead);
vm.prank(player);
(uint256 id,) = game.flip();
mock.fulfillRandomWords(id, address(wrapper));
ok = game.outcome(player) != 0;
vm.revertToState(snap);
}
}At 0.01 gwei the wrapper quoted 3,796,960,000,000 wei for a 100,000 gas callback and one word: 0.01 gwei × 13,400 for the wrapper, plus 0.01 gwei × (100,000 + 128,500 + 435) × 1.6 for the coordinator with its 60% premium. That is the formula in _calculateRequestPriceNative. The package's Optimism and Arbitrum variants of the wrapper (VRFV2PlusWrapper_Optimism, VRFV2PlusWrapper_Arbitrum) add an L1 data fee to it.
Two layers report failure differently. When your callback fails, the mock reports success = true (its call to the wrapper worked) and the wrapper emits WrapperFulfillmentFailed(requestId, consumer). When the wrapper itself runs out of gas, the mock reports success = false and there is no wrapper event. With this build the wrapper needed a wrapperGasOverhead of at least 13,345 gas to deliver (binary search in test_FindMinWrapperOverhead); copy the live value instead of inventing a small one.
Run the same consumer against the live wrapper on a fork
A mock only checks your logic against Chainlink's contracts as you configured them. A fork test checks your request against the deployed contract: its config, its price and its reverts. Nobody fulfils on a fork, so the test then plays the wrapper with vm.prank and calls your contract's rawFulfillRandomWords.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import {Test} from "forge-std/Test.sol";
import {CoinFlipDirect} from "../src/CoinFlip.sol";
contract WrapperForkTest is Test {
address constant CHAINLINK_WRAPPER = 0x7a1BaC17Ccc5b313516C5E16fb24f7659aA5ebed;
address constant RANDOO = 0xC66eB2e7EE91145875000Ad46B55600000000001;
address player = makeAddr("player");
function setUp() public {
vm.createSelectFork("https://sepolia.base.org");
}
function _roundTrip(address wrapper) internal {
CoinFlipDirect game = new CoinFlipDirect(wrapper);
vm.deal(address(game), 1 ether);
vm.txGasPrice(block.basefee + 1); // a fork's tx.gasprice is 0 too
vm.prank(player);
(uint256 id, uint256 price) = game.flip();
assertGt(price, 0);
uint256[] memory words = new uint256[](1);
words[0] = uint256(keccak256("any seed"));
vm.prank(wrapper);
game.rawFulfillRandomWords(id, words);
assertGt(game.outcome(player), 0);
vm.expectRevert(abi.encodeWithSignature("OnlyVRFWrapperCanFulfill(address,address)", player, wrapper));
vm.prank(player);
game.rawFulfillRandomWords(id, words);
}
function test_ChainlinkWrapper() public {
_roundTrip(CHAINLINK_WRAPPER);
}
function test_Randoo() public {
_roundTrip(RANDOO);
}
function test_ZeroGasPrice() public {
CoinFlipDirect onChainlink = new CoinFlipDirect(CHAINLINK_WRAPPER);
CoinFlipDirect onRandoo = new CoinFlipDirect(RANDOO);
vm.deal(address(onChainlink), 1 ether);
vm.deal(address(onRandoo), 1 ether);
(, uint256 price) = onChainlink.flip(); // accepted at a gas price of 0
assertGt(price, 0);
vm.expectRevert(bytes4(keccak256("InvalidGasPrice()")));
onRandoo.flip(); // Randoo refuses a request priced at 0
}
}Both pass on Base Sepolia at block 65,504,065, and the request IDs show why a game must not assume their shape: the mock's first ID is 1, Chainlink's wrapper returned a 78-digit number, and Randoo returned 12, the next value of its per-network counter.
Without vm.txGasPrice the two differ (test_ZeroGasPrice). Chainlink's wrapper on Base Sepolia quoted 4,193,328,342,214 wei at a gas price of 0 and took the request. Randoo's coordinator prices every wrapper request at tx.gasprice and reverts with InvalidGasPrice when it is 0, so a fork test that forgets the gas price fails instead of passing with a request priced below what it costs on chain.
The same CoinFlipDirect runs against both because Randoo serves Chainlink's wrapper interface at 0xC66eB2e7EE91145875000Ad46B55600000000001: calculateRequestPriceNative, requestRandomWordsInNative and the rawFulfillRandomWords callback. Requests paid in LINK revert there, and link() returns the zero address. Chainlink VRF wrapper lists the limits.
What no local test shows
- Whether the oracle answers in time. Neither the mock nor a fork fulfils on its own. How many requestConfirmations? has measured times per chain, and When a VRF request is never fulfilled what happens when nobody answers.
- The real gas of a fulfilment. The mock calls your callback with
callbackGasLimitand skips the live coordinator's check that 63/64 of the remaining gas covers it. Measure your callback with How to set a VRF callback gas limit. - What your contract does after a failed callback. The live coordinator does not retry either. When a VRF callback reverts shows how to finish the outcome later.
Run one request on a testnet before mainnet. The playground sends a free Randoo request on Base Sepolia without a wallet, so you can see a real fulfilment and its proof first.
Updated 2026-12-04.