Correct way of using Random() Function while using Loops in solidity

randomremixsolidity

I want to generate a random number several times using a loop. I am currently using block.timestamp logic but it is giving the same number on every iteration. Which is correct I think because the timestamp is same.
But I dont want that. I want the number to be different in every iteration. I am using the following logic:

// Random no b/w 0-20
    uint randomnumber = uint(keccak256(abi.encodePacked( block.timestamp, msg.sender, Owner))) % 20;

Any better way to achieve this???

Best Answer

Attention!

Solidity contracts are deterministic. Anyone who figures out how your contract produces randomness can anticipate its results and use this information to exploit your application.

The valid option is to use a Chainlink Verifiable Random Function to generate random number. More information here.

For your smart contract security, change your implementation and use this Chainlink oracle.

You can see this thread that explain better the block.timestamp vulnerability when try to generate random numbers.

Related Topic