NEW

Introducing Transporter, a new bridging app powered by CCIP. Go cross-chain.

Back

Get a Random Number

This guide explains how to get random values using a simple contract to request and receive random values from Chainlink VRF v2 without managing a subscription. To explore more applications of VRF, refer to our blog.

Requirements

This guide assumes that you know how to create and deploy smart contracts on Ethereum testnets using the following tools:

If you are new to developing smart contracts on Ethereum, see the Getting Started guide to learn the basics.

Create and deploy a VRF v2 compatible contract

For this example, use the VRFv2DirectFundingConsumer.sol sample contract. This contract imports the following dependencies:

  • VRFV2WrapperConsumerBase.sol(link)
  • ConfirmedOwner.sol(link)

The contract also includes pre-configured values for the necessary request parameters such as callbackGasLimit, requestConfirmations, the number of random words numWords, the VRF v2 Wrapper address wrapperAddress, and the LINK token address linkAddress. You can change these parameters if you want to experiment on different testnets.

Build and deploy the contract on Sepolia.

  1. Open the VRFv2DirectFundingConsumer.sol contract in Remix.

  2. On the Compile tab in Remix, compile the VRFv2DirectFundingConsumer contract.

  3. Configure your deployment. On the Deploy tab in Remix, select the Injected Web3 Environment and select the VRFv2DirectFundingConsumer contract from the contract list.

  4. Click the Deploy button to deploy your contract onchain. MetaMask opens and asks you to confirm the transaction.

  5. After you deploy your contract, copy the address from the Deployed Contracts list in Remix. Before you can request randomness from VRF v2, you must fund your consuming contract with enough LINK tokens in order to request for randomness. Next, fund your contract.

Fund Your Contract

Requests for randomness will fail unless your consuming contract has enough LINK.

  1. Acquire testnet LINK.
  2. Fund your contract with testnet LINK. For this example, funding your contract with 2 LINK should be sufficient.

Request random values

The deployed contract requests random values from Chainlink VRF, receives those values, builds a struct RequestStatus containing them, and stores the struct in a mapping s_requests. Run the requestRandomWords() function on your contract to start the request.

  1. Return to Remix and view your deployed contract functions in the Deployed Contracts list.

  2. Click the requestRandomWords() function to send the request for random values to Chainlink VRF. MetaMask opens and asks you to confirm the transaction.

    After you approve the transaction, Chainlink VRF processes your request. Chainlink VRF fulfills the request and returns the random values to your contract in a callback to the fulfillRandomWords() function. At this point, a new key requestId is added to the mapping s_requests. Depending on current testnet conditions, it might take a few minutes for the callback to return the requested random values to your contract.

  3. To fetch the request ID of your request, call lastRequestId().

  4. After the oracle returns the random values to your contract, the mapping s_requests is updated. The received random values are stored in s_requests[_requestId].randomWords.

  5. Call getRequestStatus() and specify the requestId to display the random words.

Analyzing the contract

In this example, the consuming contract uses static configuration parameters.

// SPDX-License-Identifier: MIT
// An example of a consumer contract that directly pays for each request.
pragma solidity ^0.8.7;

import {ConfirmedOwner} from "@chainlink/contracts/src/v0.8/shared/access/ConfirmedOwner.sol";
import {VRFV2WrapperConsumerBase} from "@chainlink/contracts/src/v0.8/vrf/VRFV2WrapperConsumerBase.sol";
import {LinkTokenInterface} from "@chainlink/contracts/src/v0.8/shared/interfaces/LinkTokenInterface.sol";

/**
 * Request testnet LINK and ETH here: https://faucets.chain.link/
 * Find information on LINK Token Contracts and get the latest ETH and LINK faucets here: https://docs.chain.link/docs/link-token-contracts/
 */

/**
 * THIS IS AN EXAMPLE CONTRACT THAT USES HARDCODED VALUES FOR CLARITY.
 * THIS IS AN EXAMPLE CONTRACT THAT USES UN-AUDITED CODE.
 * DO NOT USE THIS CODE IN PRODUCTION.
 */

contract VRFv2DirectFundingConsumer is
    VRFV2WrapperConsumerBase,
    ConfirmedOwner
{
    event RequestSent(uint256 requestId, uint32 numWords);
    event RequestFulfilled(
        uint256 requestId,
        uint256[] randomWords,
        uint256 payment
    );

    struct RequestStatus {
        uint256 paid; // amount paid in link
        bool fulfilled; // whether the request has been successfully fulfilled
        uint256[] randomWords;
    }
    mapping(uint256 => RequestStatus)
        public s_requests; /* requestId --> requestStatus */

    // past requests Id.
    uint256[] public requestIds;
    uint256 public lastRequestId;

    // Depends on the number of requested values that you want sent to the
    // fulfillRandomWords() function. Test and adjust
    // this limit based on the network that you select, the size of the request,
    // and the processing of the callback request in the fulfillRandomWords()
    // function.
    uint32 callbackGasLimit = 100000;

    // The default is 3, but you can set this higher.
    uint16 requestConfirmations = 3;

    // For this example, retrieve 2 random values in one request.
    // Cannot exceed VRFV2Wrapper.getConfig().maxNumWords.
    uint32 numWords = 2;

    // Address LINK - hardcoded for Sepolia
    address linkAddress = 0x779877A7B0D9E8603169DdbD7836e478b4624789;

    // address WRAPPER - hardcoded for Sepolia
    address wrapperAddress = 0xab18414CD93297B0d12ac29E63Ca20f515b3DB46;

    constructor()
        ConfirmedOwner(msg.sender)
        VRFV2WrapperConsumerBase(linkAddress, wrapperAddress)
    {}

    function requestRandomWords()
        external
        onlyOwner
        returns (uint256 requestId)
    {
        requestId = requestRandomness(
            callbackGasLimit,
            requestConfirmations,
            numWords
        );
        s_requests[requestId] = RequestStatus({
            paid: VRF_V2_WRAPPER.calculateRequestPrice(callbackGasLimit),
            randomWords: new uint256[](0),
            fulfilled: false
        });
        requestIds.push(requestId);
        lastRequestId = requestId;
        emit RequestSent(requestId, numWords);
        return requestId;
    }

    function fulfillRandomWords(
        uint256 _requestId,
        uint256[] memory _randomWords
    ) internal override {
        require(s_requests[_requestId].paid > 0, "request not found");
        s_requests[_requestId].fulfilled = true;
        s_requests[_requestId].randomWords = _randomWords;
        emit RequestFulfilled(
            _requestId,
            _randomWords,
            s_requests[_requestId].paid
        );
    }

    function getRequestStatus(
        uint256 _requestId
    )
        external
        view
        returns (uint256 paid, bool fulfilled, uint256[] memory randomWords)
    {
        require(s_requests[_requestId].paid > 0, "request not found");
        RequestStatus memory request = s_requests[_requestId];
        return (request.paid, request.fulfilled, request.randomWords);
    }

    /**
     * Allow withdraw of Link tokens from the contract
     */
    function withdrawLink() public onlyOwner {
        LinkTokenInterface link = LinkTokenInterface(linkAddress);
        require(
            link.transfer(msg.sender, link.balanceOf(address(this))),
            "Unable to transfer"
        );
    }
}

The parameters define how your requests will be processed. You can find the values for your network in the Supported networks page.

  • uint32 callbackGasLimit: The limit for how much gas to use for the callback request to your contract's fulfillRandomWords() function. It must be less than the maxGasLimit limit on the coordinator contract minus the wrapperGasOverhead. See the VRF v2 Direct funding limits for more details. Adjust this value for larger requests depending on how your fulfillRandomWords() function processes and stores the received random values. If your callbackGasLimit is not sufficient, the callback will fail and your consuming contract is still charged for the work done to generate your requested random values.

  • uint16 requestConfirmations: How many confirmations the Chainlink node should wait before responding. The longer the node waits, the more secure the random value is. It must be greater than the minimumRequestBlockConfirmations limit on the coordinator contract.

  • uint32 numWords: How many random values to request. If you can use several random values in a single callback, you can reduce the amount of gas that you spend per random value. The total cost of the callback request depends on how your fulfillRandomWords() function processes and stores the received random values, so adjust your callbackGasLimit accordingly.

The contract includes the following functions:

  • requestRandomWords(): Takes your specified parameters and submits the request to the VRF v2 Wrapper contract.

  • fulfillRandomWords(): Receives random values and stores them with your contract.

  • getRequestStatus(): Retrive request details for a given _requestId.

  • withdrawLink(): At any time, the owner of the contract can withdraw outstanding LINK balance from it.

Clean up

After you are done with this contract, you can retrieve the remaining testnet LINK to use with other examples.

  1. Call withdrawLink() function. MetaMask opens and asks you to confirm the transaction. After you approve the transaction, the remaining LINK will be transferred from your consuming contract to your wallet address.

What's next

Stay updated on the latest Chainlink news