How to “safely” generate random numbers in solidity contracts.

Image for post
Image for post

Don’t generate random numbers inside your contracts. It won’t work, you will get hacked.

Is it possible to generate random numbers inside a Solidity contract?

How do I get hacked if I generate a pseudo random inside a solidity contract?

wheelspin.io logo, give it a try if you feel lucky!
wheelspin.io logo, give it a try if you feel lucky!
Wheelspin.io Logo. Give it a try if you feel lucky! 😃
function random() private returns (uint) {
uint randomnumber = uint(keccak256(abi.encodePacked(now, msg.sender, nonce))) % 100;
randomnumber = randomnumber + 1;
nonce++;
return randomnumber;
}
Image for post
Image for post
My Ether… gone. Hopefully it wasn’t much. 😤

So… What is the best solution to safely generate random numbers inside a solidity contract?

uint randomNumber = uint(keccak256(abi.encodePacked(_result))) % ceiling;

Written by

Full Stack Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store