# VRF

## Introduction to Chainlink VRF

<mark style="color:red;">**Chainlink VRF (Verifiable Random Function)**</mark> is a provably fair and verifiable random number generator (RNG) that enables smart contracts to access random values without compromising security or usability. For each request, Chainlink VRF generates one or more random values and cryptographic proof of how those values were determined. The proof is published and verified on-chain before any consuming applications can use it. This process ensures that results cannot be tampered with or manipulated by any single entity including oracle operators, miners, users, or smart contract developers.

Use Chainlink VRF to build reliable smart contracts for any applications that rely on unpredictable outcomes:

* Building blockchain games and NFTs.
* Random assignment of duties and resources. For example, randomly assigning judges to cases.
* Choosing a representative sample for consensus mechanisms.

To learn more about the benefits of Chainlink VRF v2, see our blog post [Chainlink VRF v2 Is Now Live on Mainnet](https://blog.chain.link/vrf-v2-mainnet-launch/). For help with your specific use case, [contact us](https://chain.link/contact) to connect with one of our Solutions Architects. You can also ask questions about Chainlink VRF on [Stack Overflow](https://stackoverflow.com/questions/ask?tags=chainlink).

### Two methods to request randomness <a href="#two-methods-to-request-randomness" id="two-methods-to-request-randomness"></a>

Chainlink VRF v2 offers two methods for requesting randomness:

* [Subscription](https://docs.chain.link/vrf/v2/subscription/): Create a subscription account and fund its balance with LINK tokens. Users can then connect multiple consuming contracts to the subscription account. When the consuming contracts request randomness, the transaction costs are calculated after the randomness requests are fulfilled and the subscription balance is deducted accordingly. This method allows you to fund requests for multiple consumer contracts from a single subscription.
* [Direct funding](https://docs.chain.link/vrf/v2/direct-funding/): Consuming contracts directly pay with LINK when they request random values. You must directly fund your consumer contracts and ensure that there are enough LINK tokens to pay for randomness requests.

## Security Considerations

{% hint style="danger" %}
This section is the most important thing in Chainlink doc. Make sure you read it multiple times.
{% endhint %}

Gaining access to high quality randomness on-chain requires a solution like Chainlink’s VRF, but it also requires you to understand some of the ways that miners or validators can potentially manipulate randomness generation. Here are some of the top security considerations you should review in your project.

* [ ] [Use `requestId` to match randomness requests with their fulfillment in order](https://docs.chain.link/vrf/v2/security#use-requestid-to-match-randomness-requests-with-their-fulfillment-in-order)
* [ ] [Choose a safe block confirmation time, which will vary between blockchains](https://docs.chain.link/vrf/v2/security#choose-a-safe-block-confirmation-time-which-will-vary-between-blockchains)
* [ ] [Do not re-request randomness](https://docs.chain.link/vrf/v2/security#do-not-re-request-randomness)
* [ ] [Don’t accept bids/bets/inputs after you have made a randomness request](https://docs.chain.link/vrf/v2/security#dont-accept-bidsbetsinputs-after-you-have-made-a-randomness-request)
* [ ] [The `fulfillRandomWords` function must not revert](https://docs.chain.link/vrf/v2/security#fulfillrandomwords-must-not-revert)
* [ ] [Use `VRFConsumerBaseV2` in your contract to interact with the VRF service](https://docs.chain.link/vrf/v2/security#use-vrfconsumerbasev2-in-your-contract-to-interact-with-the-vrf-service)

### Use `requestId` to match randomness requests with their fulfillment in order <a href="#use-requestid-to-match-randomness-requests-with-their-fulfillment-in-order" id="use-requestid-to-match-randomness-requests-with-their-fulfillment-in-order"></a>

{% hint style="info" %}
**My comment**\
Requests without ID could come back in a different order. For example, requests sequence sent out as \[A, B, C] might return as \[C, A, B].\
\
Use `requestId` to avoid requests race condition
{% endhint %}

<mark style="color:red;">**If your contract could have multiple VRF requests in flight simultaneously, you must ensure that the order in which the VRF fulfillments arrive cannot be used to manipulate your contract’s user-significant behavior.**</mark>

Blockchain miners/validators can control the order in which your requests appear on-chain, and hence the order in which your contract responds to them.

For example, if you made randomness requests `A`, `B`, `C` in short succession, there is no guarantee that the associated randomness fulfillments will also be in order `A`, `B`, `C`. The randomness fulfillments might just as well arrive at your contract in order `C`, `A`, `B` or any other order.

We recommend using the `requestID` to match randomness requests with their corresponding fulfillments.

### Choose a safe block confirmation time, which will vary between blockchains <a href="#choose-a-safe-block-confirmation-time-which-will-vary-between-blockchains" id="choose-a-safe-block-confirmation-time-which-will-vary-between-blockchains"></a>

{% hint style="info" %}
**My comment**\
Miners/validators can "re-roll the dice" by rewriting the blockchain history to put a randomness request from your contract into a different block.\
\
Chhose a safe block confirmation time to avoid this.
{% endhint %}

<mark style="color:red;">**In principle, miners/validators of your underlying blockchain could rewrite the chain's history to put a randomness request from your contract into a different block, which would result in a different VRF output.**</mark> Note that this does not enable a miner to determine the random value in advance. It only enables them to get a fresh random value that might or might not be to their advantage. By way of analogy, they can only re-roll the dice, not predetermine or predict which side it will land on.

You must choose an appropriate confirmation time for the randomness requests you make. <mark style="color:red;">**Confirmation time is how many blocks the VRF service waits before writing a fulfillment to the chain to make potential rewrite attacks unprofitable in the context of your application and its value-at-risk.**</mark>

### Do not re-request randomness <a href="#do-not-re-request-randomness" id="do-not-re-request-randomness"></a>

{% hint style="info" %}
**My comment**\
"Re-request" pattern will give VRF service provider the power to "re-roll the dice" until they got a favorable outcome.\
\
Avoid using "re-request" pattern.
{% endhint %}

<mark style="color:red;">**Any re-request of randomness is an incorrect use of VRFv2.**</mark> Doing so would give the VRF service provider the option to withhold a VRF fulfillment if the outcome is not favorable to them and wait for the re-request in the hopes that they get a better outcome, similar to the considerations with block confirmation time.

Re-requesting randomness is easily detectable on-chain and should be avoided for use cases that want to be considered as using VRFv2 correctly.

### Don’t accept bids/bets/inputs after you have made a randomness request <a href="#dont-accept-bidsbetsinputs-after-you-have-made-a-randomness-request" id="dont-accept-bidsbetsinputs-after-you-have-made-a-randomness-request"></a>

{% hint style="info" %}
**My comment**\
User input accepted after sending out randomness requests and before fulfillment could mess up the contract logic.\
\
Stop accepting further user actions in this time window.
{% endhint %}

Consider the example of a contract that mints a random NFT in response to a user’s actions.

The contract should:

1. Record whatever actions of the user may affect the generated NFT.
2. <mark style="color:red;">**Stop accepting further user actions that might affect the generated NFT**</mark> and issue a randomness request.
3. On randomness fulfillment, mint the NFT.

Generally speaking, whenever an outcome in your contract depends on some user-supplied inputs and randomness, the contract should not accept any additional user-supplied inputs after it submits the randomness request.

Otherwise, the cryptoeconomic security properties may be violated by an attacker that can rewrite the chain.

### `fulfillRandomWords` must not revert <a href="#fulfillrandomwords-must-not-revert" id="fulfillrandomwords-must-not-revert"></a>

{% hint style="info" %}
**My comment**\
VRF service will not call a reverted `fulfillRandomWords()` implementation a second time. This is similar to a DoS scenario.\
\
Make sure `fulfillRandomWords()` never reverts.
{% endhint %}

If your `fulfillRandomWords()` implementation reverts, the VRF service will not attempt to call it a second time. Make sure your contract logic does not revert. Consider simply storing the randomness and taking more complex follow-on actions in separate contract calls made by you, your users, or an [Automation Node](https://docs.chain.link/chainlink-automation/introduction/).

### Use `VRFConsumerBaseV2` in your contract, to interact with the VRF service <a href="#use-vrfconsumerbasev2-in-your-contract-to-interact-with-the-vrf-service" id="use-vrfconsumerbasev2-in-your-contract-to-interact-with-the-vrf-service"></a>

{% hint style="info" %}
**My comment**\
Use `VRFConsumerBaseV2` for subscription method.
{% endhint %}

If you implement the [subscription method](https://docs.chain.link/vrf/v2/subscription/), use `VRFConsumerBaseV2`. It includes a check to ensure the randomness is fulfilled by `VRFCoordinatorV2`. For this reason, it is a best practice to inherit from `VRFConsumerBaseV2`. Similarly, don’t override `rawFulfillRandomness`.

### Use `VRFv2WrapperConsumer.sol` in your contract, to interact with the VRF service <a href="#use-vrfv2wrapperconsumersol-in-your-contract-to-interact-with-the-vrf-service" id="use-vrfv2wrapperconsumersol-in-your-contract-to-interact-with-the-vrf-service"></a>

{% hint style="info" %}
**My comment**\
Use `VRFv2WrapperConsumer` for direct funding method.
{% endhint %}

If you implement the [direct funding method](https://docs.chain.link/vrf/v2/direct-funding/), use `VRFv2WrapperConsumer`. It includes a check to ensure the randomness is fulfilled by the `VRFV2Wrapper`. For this reason, it is a best practice to inherit from `VRFv2WrapperConsumer`. Similarly, don’t override `rawFulfillRandomWords`.

## Best Practices

These are example best practices for using Chainlink VRF. To explore more applications of VRF, refer to our [blog](https://blog.chain.link/).

### Getting a random number within a range <a href="#getting-a-random-number-within-a-range" id="getting-a-random-number-within-a-range"></a>

If you need to generate a random number within a given range, use [modulo](https://docs.soliditylang.org/en/v0.8.7/types.html#modulo) to define the limits of your range. Below you can see how to get a random number in a range from 1 to 50.

```solidity
function fulfillRandomWords(
    uint256, /* requestId */
    uint256[] memory randomWords
) internal override {
    // Assuming only one random word was requested.
    s_randomRange = (randomWords[0] % 50) + 1;
}
```

### Getting multiple random values <a href="#getting-multiple-random-values" id="getting-multiple-random-values"></a>

If you want to get multiple random values from a single VRF request, you can request this directly with the `numWords` argument:

* If you are using the VRF v2 subscription method, see the [Get a Random Number](https://docs.chain.link/vrf/v2/subscription/examples/get-a-random-number/) guide for an example where one request returns multiple random values.
* If you are using the VRF v2 direct funding method, see the [Get a Random Number](https://docs.chain.link/vrf/v2/direct-funding/examples/get-a-random-number/) guide for an example where one request returns multiple random values.

### Processing simultaneous VRF requests <a href="#processing-simultaneous-vrf-requests" id="processing-simultaneous-vrf-requests"></a>

<mark style="color:red;">**If you want to have multiple VRF requests processing simultaneously, create a mapping between**</mark> `requestId` <mark style="color:red;">**and the response.**</mark> You might also create a mapping between the `requestId` and the address of the requester to track which address made each request.

```solidity
mapping(uint256 => uint256[]) public s_requestIdToRandomWords;
mapping(uint256 => address) public s_requestIdToAddress;
uint256 public s_requestId;

function requestRandomWords() external onlyOwner returns (uint256) {
    uint256 requestId = COORDINATOR.requestRandomWords(
        keyHash,
        s_subscriptionId,
        requestConfirmations,
        callbackGasLimit,
        numWords
  );
    s_requestIdToAddress[requestId] = msg.sender;

    // Store the latest requestId for this example.
    s_requestId = requestId;

    // Return the requestId to the requester.
    return requestId;
}

function fulfillRandomWords(
    uint256 requestId,
    uint256[] memory randomWords
) internal override {
    // You can return the value to the requester,
    // but this example simply stores it.
    s_requestIdToRandomWords[requestId] = randomWords;
}
```

You could also map the `requestId` to an index to keep track of the order in which a request was made.

```solidity
mapping(uint256 => uint256) s_requestIdToRequestIndex;
mapping(uint256 => uint256[]) public s_requestIndexToRandomWords;
uint256 public requestCounter;

function requestRandomWords() external onlyOwner {
    uint256 requestId = COORDINATOR.requestRandomWords(
        keyHash,
        s_subscriptionId,
        requestConfirmations,
        callbackGasLimit,
        numWords
    );
    s_requestIdToRequestIndex[requestId] = requestCounter;
    requestCounter += 1;
}

function fulfillRandomWords(
    uint256 requestId,
    uint256[] memory randomWords
) internal override {
    uint256 requestNumber = s_requestIdToRequestIndex[requestId];
    s_requestIndexToRandomWords[requestNumber] = randomWords;
}
```

### Processing VRF responses through different execution paths <a href="#processing-vrf-responses-through-different-execution-paths" id="processing-vrf-responses-through-different-execution-paths"></a>

If you want to process VRF responses depending on predetermined conditions, you can create an `enum`. When requesting for randomness, map each `requestId` to an enum. This way, you can handle different execution paths in `fulfillRandomWords`. See the following example:

```solidity
// SPDX-License-Identifier: MIT
// An example of a consumer contract that relies on a subscription for funding.
// It shows how to setup multiple execution paths for handling a response.
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";

/**
 * 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 VRFv2MultiplePaths is VRFConsumerBaseV2 {
    VRFCoordinatorV2Interface COORDINATOR;

    // Your subscription ID.
    uint64 s_subscriptionId;

    // Sepolia coordinator. For other networks,
    // see https://docs.chain.link/docs/vrf/v2/supported-networks/#configurations
    address vrfCoordinator = 0x8103B0A8A00be2DDC778e6e7eaa21791Cd364625;

    // The gas lane to use, which specifies the maximum gas price to bump to.
    // For a list of available gas lanes on each network,
    // see https://docs.chain.link/docs/vrf/v2/supported-networks/#configurations
    bytes32 keyHash =
        0x474e34a077df58807dbe9c96d3c009b23b3c6d0cce433e59bbf5b34f823bc56c;

    uint32 callbackGasLimit = 100000;

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

    // For this example, retrieve 1 random value in one request.
    // Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS.
    uint32 numWords = 1;

    enum Variable {
        A,
        B,
        C
    }

    uint256 public variableA;
    uint256 public variableB;
    uint256 public variableC;

    mapping(uint256 => Variable) public requests;

    // events
    event FulfilledA(uint256 requestId, uint256 value);
    event FulfilledB(uint256 requestId, uint256 value);
    event FulfilledC(uint256 requestId, uint256 value);

    constructor(uint64 subscriptionId) VRFConsumerBaseV2(vrfCoordinator) {
        COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
        s_subscriptionId = subscriptionId;
    }

    function updateVariable(uint256 input) public {
        uint256 requestId = COORDINATOR.requestRandomWords(
            keyHash,
            s_subscriptionId,
            requestConfirmations,
            callbackGasLimit,
            numWords
        );

        if (input % 2 == 0) {
            requests[requestId] = Variable.A;
        } else if (input % 3 == 0) {
            requests[requestId] = Variable.B;
        } else {
            requests[requestId] = Variable.C;
        }
    }

    function fulfillRandomWords(
        uint256 requestId,
        uint256[] memory randomWords
    ) internal override {
        Variable variable = requests[requestId];
        if (variable == Variable.A) {
            fulfillA(requestId, randomWords[0]);
        } else if (variable == Variable.B) {
            fulfillB(requestId, randomWords[0]);
        } else if (variable == Variable.C) {
            fulfillC(requestId, randomWords[0]);
        }
    }

    function fulfillA(uint256 requestId, uint256 randomWord) private {
        // execution path A
        variableA = randomWord;
        emit FulfilledA(requestId, randomWord);
    }

    function fulfillB(uint256 requestId, uint256 randomWord) private {
        // execution path B
        variableB = randomWord;
        emit FulfilledB(requestId, randomWord);
    }

    function fulfillC(uint256 requestId, uint256 randomWord) private {
        // execution path C
        variableC = randomWord;
        emit FulfilledC(requestId, randomWord);
    }
}
```
