Imagine: a player bets 0.1 ETH on red in a blockchain roulette on Polygon. Without verifiable randomness, they can't be sure the number wasn't predetermined by a miner or operator. Chainlink VRF (Verifiable Random Function) is a decentralized random number generator that provides cryptographic proof of each result's correctness. We have completed over 15 VRF integrations into projects on Ethereum, Polygon, and BNB Chain for DeFi casinos, slots, and lotteries. Each time, we confirmed that correct parameter configuration — subscriptionId, keyHash, callbackGasLimit — is critical for reliability and protection against delays.
Main Problems in VRF Integration
The main issues when integrating VRF are choosing the payment mode, setting requestConfirmations, and calculating callbackGasLimit. An error in any of these parameters leads to lost requests or excessive gas consumption. Below we break down each setting using a real code example.
Why Chainlink VRF is the Standard for Fair Randomness
The generation process consists of three steps:
- The game contract calls
requestRandomWordson the Chainlink Coordinator. - Chainlink collects a seed from blocks and signs it with its key, forming a proof.
- The Coordinator calls
fulfillRandomWordswith the result; the contract verifies the proof and computes the final number.
VRF generates a random number with cryptographic proof of its correctness. On-chain verification of the proof occurs before the number is used in the game logic. Manipulation is excluded — neither the casino operator nor players can influence the outcome. According to Chainlink VRF v2.5 Documentation, each request contains a proof that is verified on-chain.
VRF v2.5: Subscription vs Direct Funding
The current version is VRF v2.5. Two payment modes: Subscription and Direct Funding. Subscription mode is 25% cheaper for high-volume requests, while Direct Funding offers simpler deployment for low-frequency calls. For a casino processing 1000 bets per day, Subscription reduces annual LINK costs by ~$300.
Integrating into the Casino Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
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 RouletteGame is VRFConsumerBaseV2Plus {
uint256 public immutable subscriptionId;
bytes32 public immutable keyHash;
struct Bet {
address player;
uint256 amount;
uint8 betType; // 0=red, 1=black, 2=number
uint8 number;
}
mapping(uint256 requestId => Bet) public pendingBets;
event BetPlaced(uint256 indexed requestId, address indexed player);
event GameResult(uint256 indexed requestId, uint8 result, bool won);
function placeBet(uint8 betType, uint8 number) external payable {
require(msg.value >= 0.01 ether, "Below minimum");
require(msg.value <= 10 ether, "Above maximum");
uint256 requestId = s_vrfCoordinator.requestRandomWords(
VRFV2PlusClient.RandomWordsRequest({
keyHash: keyHash,
subId: subscriptionId,
requestConfirmations: 3,
callbackGasLimit: 150_000,
numWords: 1,
extraArgs: VRFV2PlusClient._argsToBytes(
VRFV2PlusClient.ExtraArgsV1({nativePayment: false})
)
})
);
pendingBets[requestId] = Bet({
player: msg.sender,
amount: msg.value,
betType: betType,
number: number
});
emit BetPlaced(requestId, msg.sender);
}
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords)
internal override {
Bet memory bet = pendingBets[requestId];
delete pendingBets[requestId];
uint8 result = uint8(randomWords[0] % 37); // 0-36
bool won = _checkWin(bet, result);
if (won) {
uint256 payout = _calculatePayout(bet);
payable(bet.player).transfer(payout);
}
emit GameResult(requestId, result, won);
}
}
Critical Configuration Details
- callbackGasLimit must be set with a buffer. If gas is insufficient in fulfillRandomWords, Chainlink does not automatically retry — the request is lost. Calculate actual gas using forge test --gas-report. For a roulette with payout, 150K gas is enough; for complex logic, increase to 250K.
- requestConfirmations: 3 is the minimum. On Ethereum with a 2-block reorg, Chainlink might get a different seed. For jackpot bets >1 ETH, set 5–10 confirmations.
- Store bets in a mapping from requestId to Bet. An array of bets with lookup is O(n) in the callback, leading to gas griefing.
How to Avoid Lost VRF Requests
Chainlink provides several keyHashes for the same network—they differ by the maximum gas price Chainlink is willing to spend on delivery. On Ethereum mainnet:
| Lane | Max gas price | Delay | Cost per request |
|---|---|---|---|
| 200 gwei | 200 gwei | Possible delay at peaks | ~0.0001 LINK |
| 500 gwei | 500 gwei | Minimal | ~0.00015 LINK |
For casinos with instant games, use the 500 gwei lane—players should not wait hours during network congestion. The extra 0.00005 LINK per request is worth the reliability.
Protection Against Abuse and Timeout
Once a bet is placed, cancellation is impossible. This is correct because the random request has already been made. However, if the random doesn't arrive within 24 hours (issues with the Coordinator or depleted subscription balance), a refund function is necessary:
function refundExpiredBet(uint256 requestId) external {
Bet memory bet = pendingBets[requestId];
require(bet.player == msg.sender, "Not your bet");
require(block.timestamp > betTimestamps[requestId] + 24 hours, "Not expired");
delete pendingBets[requestId];
payable(msg.sender).transfer(bet.amount);
}
Testing with Foundry
Chainlink provides the VRFCoordinatorV2_5Mock for local tests. Manually call fulfillRandomWords with a chosen random value:
vrfCoordinator.fulfillRandomWords(requestId, address(game));
A fuzz test checks payouts for all values of randomWords[0] from 0 to 2^256-1. Edge case: randomWords[0] % 37 == 0 — roulette zero. Your contract must correctly handle this edge case. We also use forge fuzz with over 10,000 iterations to uncover hidden bugs.
What's Included in the VRF Integration Work
- Audit of the current contract and analysis of game mechanics.
- Architecture design: choosing Subscription or Direct Funding, with cost savings up to 25%.
- Implementation of VRF v2.5 integration (Solidity, Foundry).
- Development of safeguards: timeout refund, requestConfirmations.
- Testing on Sepolia with real VRF, including fuzz tests.
- Code documentation and deployment instructions.
- Repository access and one month of support.
Work Process and Timeline
- Analytics (1 day) — discuss game mechanics, request frequency, fairness requirements.
- Design (0.5 day) — choose VRF mode, keyHash, requestConfirmations.
- Implementation (1–2 days) — write the contract with integration, attach tests.
- Testing (1 day) — on testnet (Sepolia) verify operation with real VRF, including 10,000+ fuzz iterations.
- Deployment (0.5 day) — deploy to mainnet with subscription or wrapper configuration.
Cost: Basic integration from $2,500; new contract from $5,000. For an exact quote, write to us.
Typical Mistakes in VRF Integration (and How to Avoid)
- Insufficient callbackGasLimit (under 100K) — use 150K as baseline.
- Too few requestConfirmations (less than 3) — use 3–5 for standard bets.
- Lack of a timeout function — implement refund after 24h.
- Using an array of bets instead of a mapping — mapping is 10x cheaper in gas.
Implement verifiable randomness in your casino — contact us for a consultation. Order smart contract development with VRF turnkey.







