1

I'm using Chainlink VRF and its function to get an array 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;
}

In my case, I want random numbers in [0, 99], so randomValue is gonna be 100, always. As far as I know, in order to use this function, firstly, I have to call:

function getRandomNumber() public returns (bytes32 requestId) {
    require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
    return requestRandomness(keyHash, fee);
}

Perfect. But... When I execute getRandomNumber() for the second time, I expect to get a different array, right? So why I'm getting the same array even after the second execution of getRandomNumber()? Perhaps that expand() function is not using the result of getRandomNumber()? Is that's the case, what's the logic of expand() function? Am I missing something?

SOLVED: this code is working perfectly:

    function getRandomNumber() public returns (bytes32 requestId) {
        require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
        return requestRandomness(keyHash, fee);
    }

    function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
        randomResult = randomness;
    }

    function expand() internal view returns (uint256[] memory expandedValues) {
        expandedValues = new uint256[](maxRandonNumbers);
        for (uint256 i = 0; i < maxRandonNumbers; i++) {
            expandedValues[i] = uint256(keccak256(abi.encode(randomResult, i))) % 100;
        }
        return expandedValues;
    }

1 Answer 1

0

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.

If you need to generate a random number within a given range, you should use modulo to define the limits of your range, %100 in your case for [0,99]

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))) % 100;
    }
    return expandedValues;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.