0

Is there a way to generate several random numbers in a single transaction? Let's suppose I have this code:

function example(uint _prop) public{
    while(random(100) < _prob){
      // Do something  
    }
}

The condition of the while loop depends on the random number chosen in each iteration. Is it possible to do this with VRF (Chainlink)? Or can only one random number be generated for each transaction?

For now I'm using this solution:

function random(uint _interval) internal returns (uint) {
    nonce++;
    return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, nonce))) % _interval;
}

but I know this is not a random number... This serves my purpose, but it is not formal. I want to improve it.

Joncarre
  • 129
  • 7
  • See [this question](https://stackoverflow.com/questions/48848948/how-to-generate-a-random-number-in-solidity) or [this one](https://stackoverflow.com/questions/52467248/how-can-we-generate-multiple-random-number-in-ethereum). – pgSystemTester Nov 25 '21 at 00:42

1 Answers1

2

What you'd want to do, is make a Chainlink Random number request and then use than number to "expand" to more random numbers, like so:

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;
}

Since we get the random number from a verifiably random location, we can then drop the number in this and get any number of random numbers after.

Patrick Collins
  • 5,621
  • 3
  • 26
  • 64