solidity – How to Request Multiple Random Numbers at Once Using Chainlink VRF

chainlinkmainnetsolidity

Would it be possible to require more than one random number on the chainlink VRF with only one call to requestRandomness or any other function ?

Thank you

Best Answer

If you want to get multiple random numbers from a single VRF response, you should create an array where the randomValue is your original returned VRF number and n is the desired number of random numbers.

function expand(uint256 randomValue, uint256 n) public pure returns (uint256[] memory expandedValues) {
    expandedValues = new uint256[](n);
    for (uint256 i = 0; i < n; i++) {
        expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i)));
    }
    return expandedValues;
}

This code snippet takes the initial random value, puts it inside a for loop, combines it with an incrementing number by ABI encoding the random number and incremented number, hashes that encoding using Keccak256, and finally type casts the hash to a type uint to be used as that now expanded random number. The loop then continues for as many random numbers needed, which were set with the n parameter of the function.

Reference: VRF Best Practices

Related Topic