Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Glossary

VRF Consumer

A VRF Consumer is a smart contract that requests and receives cryptographically verifiable random numbers from a Verifiable Random Function (VRF) oracle service.
Chainscore © 2026
definition
BLOCKCHAIN ORACLE

What is a VRF Consumer?

A VRF Consumer is a smart contract that requests and receives cryptographically verifiable random numbers from a Verifiable Random Function (VRF) oracle service.

In blockchain applications, a VRF Consumer is the endpoint smart contract that initiates a request for randomness and subsequently processes the random value provided by an oracle. The consumer defines the logic for how the random number will be used, such as selecting a winner in a lottery, assigning traits to an NFT, or determining matchmaking in a game. Its primary role is to integrate provable randomness into its core application logic in a secure and trust-minimized way.

The interaction follows a request-and-receive pattern. First, the consumer contract calls a function on the VRF coordinator, submitting a request and paying any required LINK tokens. This request includes a seed and the consumer's contract address. The oracle network then generates the random number and a cryptographic proof. Finally, the oracle calls a predefined function (e.g., fulfillRandomWords) on the consumer contract, delivering the verifiable random result for on-chain use.

Key design considerations for a VRF Consumer include managing gas costs for the callback, ensuring the contract can only be called by the authorized VRF coordinator (to prevent spoofing), and handling potential request idempotency. Developers must also account for the asynchronous nature of the response; the contract state should be designed to handle the delay between the initial request and the callback fulfillment.

Prominent examples include Chainlink VRF, which provides this service on multiple blockchains. A typical consumer contract imports and inherits from libraries like VRFConsumerBase to implement the necessary interface. This architecture decouples the complex task of generating verifiable randomness from the application's business logic, providing developers with a reliable and auditable source of randomness for their decentralized applications.

how-it-works
CHAINLINK VRF

How a VRF Consumer Works

A VRF Consumer is a smart contract that requests and receives cryptographically secure random numbers from a Verifiable Random Function (VRF) oracle, such as Chainlink VRF.

A VRF Consumer is a smart contract that implements the logic to request a random number from a VRF provider and defines how to use the generated random value. The core interaction is a two-step process: first, the consumer contract submits a request, which includes a seed and a fee, to the VRF coordinator. The VRF oracle then generates a random number and a cryptographic proof, delivering this result back to the consumer's predefined callback function, typically named fulfillRandomWords. This mechanism ensures the consumer only proceeds with a verified, tamper-proof random input.

The security model is paramount. The VRF Consumer must be designed to only accept a response from the authorized VRF coordinator contract. Upon receiving the random words, the consumer's fulfillRandomWords function executes, applying the randomness to its core logic—such as selecting a winner in a lottery, minting an NFT with random traits, or determining gameplay outcomes. The contract must also manage request IDs to match responses to specific requests and handle potential failures or revert scenarios to maintain system integrity.

Key implementation details include funding the consumer with LINK tokens to pay for VRF requests, inheriting from a provider's consumer base contract (like VRFConsumerBaseV2 for Chainlink), and carefully managing gas limits for the callback function. Developers must also consider the asynchronous nature of the request-fulfillment cycle and design their application state accordingly. Properly implemented, a VRF Consumer enables blockchain applications to leverage verifiable randomness in a trust-minimized way, which is critical for fairness and security in decentralized systems.

key-features
BLOCKCHAIN INFRASTRUCTURE

Key Features of a VRF Consumer

A VRF (Verifiable Random Function) Consumer is a smart contract that requests and receives cryptographically secure random numbers from a VRF Provider. These are its core architectural and operational characteristics.

01

Request-Response Pattern

A VRF Consumer operates on a two-step, asynchronous request-response pattern. The consumer contract first calls the VRF Provider's requestRandomness function, which returns a unique requestId. The provider later fulfills the request by calling the consumer's fulfillRandomWords callback function with the generated random numbers, identified by the same requestId.

  • Key Flow: Request → Wait for Fulfillment → Receive Result.
  • Asynchronous: The consumer must be designed to handle the delay between request and fulfillment.
02

Callback Function Implementation

The core logic of a VRF Consumer resides in its fulfillRandomWords function, which is a callback that the VRF Provider invokes. This function must:

  • Be external and virtual/override.
  • Accept the requestId and an array of random numbers (uint256[] memory randomWords) as parameters.
  • Contain the application logic that uses the verified random numbers (e.g., selecting a winner, minting an NFT with random traits).
  • Implement access control, often using the onlyVRFCoordinator modifier to ensure only the authorized provider can call it.
03

Request ID Tracking

To manage multiple concurrent or sequential randomness requests, a VRF Consumer must track requestIds. This is critical because the fulfillment callback is asynchronous and the consumer may have multiple pending requests.

  • Mapping Storage: Consumers typically use a mapping (e.g., mapping(uint256 => RequestStatus)) to store the state of each request.
  • State Management: The mapping tracks if a request is PENDING, FULFILLED, or contains the resulting random words.
  • Prevents Replay Attacks: The requestId ensures that a fulfillment can only be applied to the specific, original request.
04

Subscription & Prepayment Model

Modern VRF systems (e.g., Chainlink VRF v2) use a subscription model. The consumer contract does not pay per request. Instead, it must be funded via a subscription account managed off-chain.

  • Consumer Registration: The consumer's address is added to a subscription that holds LINK tokens.
  • Gas Payment: The subscription owner pays for the gas used by the provider to fulfill the request.
  • Consumer Responsibility: The consumer contract must ensure the subscription has sufficient balance, or the request will fail.
05

Security & Verifiability

A key feature is that the consumer receives cryptographically verifiable randomness. The random numbers are generated off-chain with a secret key and delivered with a cryptographic proof.

  • On-Chain Verification: The VRF Provider's coordinator contract verifies this proof on-chain before calling the consumer's callback.
  • Tamper-Proof: The randomness is provably unpredictable and cannot be manipulated by the provider, miners/validators, or users.
  • Consumer Trust: The consumer's logic executes only after the proof is verified, guaranteeing the integrity of the input.
06

Common Implementation Patterns

VRF Consumers are built for specific use cases, leading to common patterns:

  • NFT Random Minting: Request randomness upon mint to determine rarity traits or attributes for a new token.
  • Lottery & Gaming: Select a random winner from a pool of participants or determine game outcomes.
  • DAO Governance: Randomly select contributors for rewards or committee members in a verifiably fair way.
  • Dynamic Asset Generation: Create in-game items, artwork, or metadata with random properties.
code-example
IMPLEMENTATION

VRF Consumer Code Example

A practical demonstration of a smart contract that requests and receives verifiable random numbers from a VRF service.

A VRF Consumer is a smart contract that implements the logic to request a random number from a Verifiable Random Function (VRF) provider, such as Chainlink VRF, and defines a callback function to receive and utilize the generated random value. The core of this implementation is the requestRandomWords function, which sends a transaction to the VRF coordinator, and the fulfillRandomWords function, which is automatically executed by the oracle network to deliver the provably random result. This pattern separates the request and fulfillment phases, ensuring the consumer's logic is only executed once a tamper-proof random number is securely on-chain.

A typical VRF consumer contract inherits from a provider-specific base contract, like VRFConsumerBaseV2 for Chainlink, which handles the underlying communication. Key parameters must be configured, including the Subscription ID for billing, the VRF Coordinator contract address, and the key hash identifying the specific oracle job. The consumer must also manage a request ID to correlate incoming fulfillments with the original request, especially when handling multiple concurrent random number requests. Security is paramount; the fulfillRandomWords function should include access control, often restricting execution to the VRF coordinator contract itself.

Developers implement custom logic within the fulfillRandomWords callback. Common use cases include selecting a random winner in a lottery, assigning random traits to an NFT, or determining pseudo-random gameplay outcomes. The code must be gas-efficient and should not revert, as this could cause the fulfillment to fail. It is also critical to account for the block confirmation delay; the random number is generated based on the block hash of a future block, meaning there is a short, predictable wait between the request and its fulfillment.

examples
APPLICATIONS

VRF Consumer Use Cases & Examples

A VRF Consumer is a smart contract that requests and receives verifiable random numbers from a VRF provider. These are the primary real-world applications where on-chain randomness is critical.

04

Dynamic NFT & Metaverse Systems

Powers evolving digital assets and environments where changes are triggered by unpredictable events.

  • Procedural Generation: Creating unique, random landscapes or items in virtual worlds.
  • NFT Evolution: Triggering state changes (e.g., leveling up) based on random external events.
  • Event-Driven Updates: Modifying an asset's metadata or appearance after a random time period or oracle-reported event.
05

Lotteries & Prize Draws

The canonical use case for creating transparent, on-chain lotteries where the winning ticket is selected verifiably at random.

  • Smart Contract Lotteries: Decentralized applications where the prize pool and winner selection are fully automated and trustless.
  • Airdrop Eligibility: Randomly selecting wallet addresses from a snapshot to receive tokens or NFTs.
  • Contest Winners: Fairly picking winners for promotional campaigns or community events.
ecosystem-usage
ECOSYSTEM & PROTOCOL USAGE

VRF Consumer

A VRF Consumer is a smart contract that requests and receives verifiably random numbers from a Verifiable Random Function (VRF) provider, such as Chainlink VRF, for on-chain applications.

01

Core Request-Response Flow

A VRF Consumer initiates the process by calling the requestRandomness function, which emits an event. An off-chain oracle node detects this event, generates the random number and a cryptographic proof, and delivers it back on-chain via the fulfillRandomness callback function. This two-step process ensures the consumer's logic only executes after provable randomness is securely received.

02

Key Contract Requirements

To function, a consumer contract must:

  • Inherit from the VRF provider's base consumer contract (e.g., VRFConsumerBase).
  • Define a fulfillRandomness function to handle the received random number.
  • Fund its subscription or pay the oracle gas fee to cover the request cost.
  • Manage the request ID to correctly match responses to specific on-chain actions, preventing mix-ups.
03

Primary Use Cases

VRF Consumers are essential for any on-chain application requiring tamper-proof randomness:

  • NFT Minting & Traits: Determining rare attributes for generative art collections.
  • Play-to-Earn Gaming: Selecting random in-game loot, matchmaking, or critical hits.
  • Lotteries & Raffles: Picking verifiably fair winners without a trusted third party.
  • DAO Governance: Randomizing committee selection or proposal ordering to prevent manipulation.
04

Security & Provenance

The security model relies on the cryptographic proof submitted by the oracle. The VRF provider's on-chain contract verifies this proof before delivering the number to the consumer, guaranteeing it was generated unpredictably and tamper-proof. Consumers must also implement safeguards against reentrancy attacks within the fulfillRandomness callback and ensure adequate gas for the callback execution.

05

Gas & Cost Considerations

Consumers incur two main costs: the oracle gas fee paid to the VRF service and the gas for their own fulfillRandomness execution. Modern systems like Chainlink VRF use a subscription model, where the consumer contract pre-funds a balance used to pay for requests, simplifying cost management. Failed callbacks due to insufficient gas can leave requests unfulfilled.

06

Example: Basic NFT Mint

solidity
function mintNFT() public {
    bytes32 requestId = requestRandomness(keyHash, fee);
    requestToSender[requestId] = msg.sender;
}

function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
    address sender = requestToSender[requestId];
    uint256 newTokenId = uint256(keccak256(abi.encode(randomness, sender)));
    _safeMint(sender, newTokenId);
}

This shows a consumer storing the requester's address with the requestId and using the delivered randomness to mint a unique NFT.

security-considerations
VRF CONSUMER

Security Considerations & Best Practices

A VRF Consumer is a smart contract that requests and receives verifiable random numbers from a VRF service. Its security is paramount as it directly controls the randomness used in applications like gaming, lotteries, and NFT minting.

01

Preventing Reentrancy on Fulfillment

The fulfillRandomWords callback executes after the VRF service responds. Critical logic must be protected against reentrancy attacks. Use the Checks-Effects-Interactions pattern and consider non-reentrant modifiers. Ensure state changes (like marking a request as fulfilled) occur before any external calls or transfers triggered by the random result.

02

Managing Request Gas Limits

The VRF Coordinator will only call back your consumer if the gas limit for fulfillRandomWords is sufficient. Underestimating this limit is a common failure mode. Calculate gas based on your callback's worst-case logic. Use the estimateGas method during testing and include a significant safety margin (e.g., 100k-200k gas) to account for future contract updates and blockchain state changes.

03

Validating Request Provenance

Always verify that the callback originates from the trusted VRF Coordinator contract. Implement access control in fulfillRandomWords using require(msg.sender == vrfCoordinator). This prevents malicious contracts from injecting fake randomness. Also, validate the requestId matches one your contract emitted to ensure idempotency.

04

Handling Request Failures & Idempotency

VRF requests can fail due to insufficient subscription balance or gas. Design your consumer to handle this gracefully. Implement idempotent fulfillment: track request IDs and ensure the same random result cannot be applied twice. Consider allowing users to manually trigger a re-request after a timeout if a request appears stalled.

05

Securing the Randomness Application

The security chain extends to how randomness is used. Avoid predictable input seeds from block data. For multi-step processes, commit to user choices before the request is made. Be aware that while the random number is provably fair, your application's logic (e.g., modulo bias in ranges) can introduce predictability. Use established libraries for fair distribution.

06

Subscription & Funding Management

If using a subscription model, ensure your contract's subscription has an adequate LINK balance or that the sponsoring account is funded. Monitor subscription balances off-chain to prevent service disruption. For direct funding, ensure the consumer contract itself holds enough LINK to pay for requests, and protect the withdraw function with appropriate access controls.

COMPARISON

VRF Consumer vs. Alternative Randomness Sources

A technical comparison of on-chain verifiable randomness sources for smart contracts.

Feature / MetricChainlink VRF ConsumerBlock Hash RandomnessRANDAO / VDF

Verifiability & Proof

Partial (RANDAO)

Pre-commit / Reveal Scheme

Yes (Request-Response)

No

Yes (Commit-Reveal)

Resistance to Miner/Validator Manipulation

High

Low

Medium (RANDAO), High (VDF)

Latency (Request to Receipt)

~2-5 blocks

1 block

1+ epoch (RANDAO)

On-Chain Gas Cost

~200k-500k gas + LINK

< 50k gas

~50k-100k gas

Required Trust Assumptions

Decentralized Oracle Network

Current Block Proposer

Committee of Validators

Suitable for High-Value Applications

Context Dependent

VRF CONSUMER

Frequently Asked Questions (FAQ)

Common questions about VRF Consumers, the smart contracts that request and receive verifiable random numbers from a decentralized oracle.

A VRF Consumer is a smart contract that requests and securely receives verifiable random numbers from a Verifiable Random Function (VRF) oracle service, such as Chainlink VRF. It works by first calling a requestRandomWords function, which emits an event that oracle nodes detect. The nodes then generate the random number and a cryptographic proof, delivering it back to the consumer's fulfillRandomWords callback function, where the verified random value can be used on-chain. This two-step request-fulfill pattern ensures the randomness is tamper-proof and cannot be manipulated by the oracle, the user, or the contract itself.

ENQUIRY

Get In Touch
today.

Our experts will offer a free quote and a 30min call to discuss your project.

NDA Protected
24h Response
Directly to Engineering Team
10+
Protocols Shipped
$20M+
TVL Overall
NDA Protected Directly to Engineering Team
VRF Consumer: On-Chain Randomness Smart Contract | ChainScore Glossary