Chainlink VRF for Casino: Integration and Setup

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Chainlink VRF for Casino: Integration and Setup
Simple
from 1 day to 3 days
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1360
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

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:

  1. The game contract calls requestRandomWords on the Chainlink Coordinator.
  2. Chainlink collects a seed from blocks and signs it with its key, forming a proof.
  3. The Coordinator calls fulfillRandomWords with 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

  1. Analytics (1 day) — discuss game mechanics, request frequency, fairness requirements.
  2. Design (0.5 day) — choose VRF mode, keyHash, requestConfirmations.
  3. Implementation (1–2 days) — write the contract with integration, attach tests.
  4. Testing (1 day) — on testnet (Sepolia) verify operation with real VRF, including 10,000+ fuzz iterations.
  5. 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.

Smart Contract Development

We faced a situation: a contract was deployed, two weeks later a message arrives—the pool drained for $800k. Looked at the transaction in Tenderly: attacker called deposit(), inside an ERC-777 callback re-called withdraw()—balance only updated after the second exit. Classic reentrancy, but not via ETH transfer—through an ERC-777 hook. ReentrancyGuard was only on withdraw().

Such cases are not rare. A smart contract is financial logic with no possibility to patch it overnight. Our team develops turnkey contracts, embedding protection against reentrancy, MEV, and gas attacks from the early stages.

How We Develop Smart Contracts Turnkey

We start with business logic audit and stack selection. Solidity 0.8.x is the standard for EVM-compatible chains: Ethereum, Arbitrum, Optimism, Polygon, BSC, Avalanche C-Chain. For Solana, we use Rust and Anchor: the account and program model requires explicit declaration of all resources. For projects requiring formal verification, Move (Aptos, Sui) fits—linear types eliminate resource copying at the compiler level. Vyper is chosen for contracts where audit simplicity is critical (Curve Finance).

Language Execution Model Typical Domain Risks
Solidity 0.8.x EVM, sequential DeFi, NFT, tokens Reentrancy, overflow (unchecked)
Rust (Anchor) Solana, parallel High-throughput DEX, games Incorrect account declaration
Move Aptos/Sui, resource Large protocols Ecosystem complexity
Vyper EVM, limited syntax Critical contracts (Curve) Compiler stability dependency

Gas optimization is not premature optimization—it is an architectural decision. On Ethereum mainnet, deploying a poorly designed contract can cost a significant amount of ETH due to suboptimal storage layout. Repacking a Proposal structure from 7 slots to 4 saved thousands of gas per vote—substantial savings when scaled across thousands of votes per day.

Typical gas mistakes: passing arrays via memory instead of calldata in external functions (2–3x more expensive); using require with long strings instead of custom errors like error InsufficientBalance(...). Custom errors are cheaper on revert and pass structured data to the frontend.

Why Smart Contract Audit Is Critical for Security

Audit is not a one-time check—it is a built-in development stage. We use three levels:

  1. Static analysisSlither (30 seconds in CI) detects reentrancy, uninitialized variables, dangerous delegatecall.
  2. Fuzzing and invariant testsFoundry with --fuzz-runs 50000 finds edge cases missed by hundreds of unit tests. Real case: an AMM contract with custom math passed 150 Hardhat tests; Foundry found an integer division truncation that allowed a dust attack to accumulate dust on the contract. Echidna checks invariants ("sum of all balances ≤ totalSupply").
  3. Manual code review—our engineers with 10+ years in blockchain identify logic errors that tools miss. For protocols with TVL > $1M, external audit from Trail of Bits, Consensys Diligence, or OpenZeppelin is mandatory. Timeline: 2–4 weeks.

Any upgradeable protocol must have a timelock. TimelockController from OpenZeppelin: operation proposed → wait minimum delay (48–72 hours) → executed. Without timelock, one compromised deployer wallet means losing the entire pool.

What Upgrade Patterns Do We Choose?

Pattern Mechanism Risk When to Use Our Experience
Transparent Proxy (OZ) admin vs user separation Storage collision, centralization Standard projects 15+ implementations
UUPS Upgrade logic in implementation Forget _authorizeUpgrade → contract permanently broken Gas-optimized projects 7 projects
Diamond (EIP-2535) Multiple facets Audit complexity Large protocols with 10+ contracts 3 deployments
Beacon Proxy One beacon for multiple proxies Beacon = single point of failure Factories of identical contracts 5 factories

Storage collision is the main danger of proxies. Implementation v2 must not add variables before existing ones. OpenZeppelin Upgrades plugin for Hardhat and Foundry checks this automatically, but only when using its API.

How to Protect a Contract from MEV and Front-Running

On Ethereum mainnet, transactions in the mempool are visible to all. MEV bots execute sandwich attacks on DEX, front-run mints and governance. Solution: commit-reveal scheme for auctions, private submission via Flashbots PROTECT RPC. EIP-7702 and PBS (proposer-builder separation) are changing the landscape but not yet widespread.

What Is the Development Process?

  1. Analysis—functional specification, call diagram, edge case analysis. Without this, coding starts in vain.
  2. Development—Solidity/Rust with tests in parallel. Test → code → refactoring. Use Foundry for fuzz and invariant tests.
  3. Internal audit—Slither + Echidna + manual code review. Foundry invariant tests for protocol invariants.
  4. External audit—for projects with real money. Timeline: 2–4 weeks.
  5. Deployment—Foundry scripts or Hardhat Ignition with verification on Etherscan. Gnosis Safe for ownership transfer immediately after deployment.
  6. Monitoring—Tenderly alerts, OpenZeppelin Defender, Forta Network.

What Is Included

  • Architecture documentation and contract specification (NatSpec).
  • Source code with repository and CI (Slither, Foundry, coverage).
  • Deployed contract with verification on blockchain explorer.
  • Audit results (internal and external upon request).
  • Access to monitoring and management (Gnosis Safe).
  • Code warranty: critical bug fixes within one month after deployment.
  • Consultation on web integration (wagmi, RainbowKit).

Estimated Timelines

  • ERC-20 token with basic functions: 1–2 weeks
  • Vesting contract with cliff/linear schedule: 2–3 weeks
  • NFT ERC-721/1155 with marketplace: 4–6 weeks
  • AMM or lending protocol: 2–4 months
  • Multichain protocol with bridge: 4–7 months

Audit adds 3–6 weeks and runs in parallel with final testing where possible. Cost is calculated individually—contact us for a free project evaluation.

Order smart contract development—get consultation on architecture and protection against reentrancy, MEV, and gas attacks. Want to discuss details? Write to us—we will select the optimal stack for your task.