New to blockchain software development? Read my beginners guide here

How to get random numbers in your Ethereum smart contracts

Created on August 2022 β€’ Tags: ethereumsolidityguides

A guide to getting randomness in Solidity/smart contracts on the EVM


Table of Contents for How to get random numbers in your Ethereum smart contracts


Solidity contracts are deterministic, so working with randomness is not straightforward in Solidity.

One of the most popular ways is to use randomness generated off-chain with Chainlink VRF (Verifiable Random Function).

For each request, Chainlink VRF generates one or more random values and cryptographic proof of how those values were determined. The proof is published and verified on-chain before any consuming applications can use it. This process ensures that results cannot be tampered with or manipulated by any single entity including oracle operators, miners, users, or smart contract developers.

Use Chainlink VRF to build reliable smart contracts for any applications that rely on unpredictable outcomes:

  • Building blockchain games and NFTs.
  • Random assignment of duties and resources. For example, randomly assigning judges to cases.
  • Choosing a representative sample for consensus mechanisms.

Pseudo random number generator in Solidity

If you need pseudo-randomness then sometimes you see people use block.timestamp, now or block.difficulty as seeds for a random number generator. But this can be influenced by miners, so it is not suitable as a source for random number generating.

copy
function randomNumberFrom0To100() private view returns (uint) {
// note: this has many issues and is deterministic.
// do not use this on production without understanding the issues
uint hash = uint(keccak256(block.difficulty, now));
return hash % 100;
}

This post is incomplete and a work-in-progress
I'll update it soon and flesh it out with more info!

Spotted a typo or have a suggestion to make this crypto dev article better? Please let me know!

See all posts (70+ more)

See all posts (70+ more)

Was this post helpful? πŸ“§

If you liked this content and want to receive emails about future posts like this, enter your email. I'll never spam you.

Or follow me on @CryptoGuide_Dev on twitter

By using this site, you agree that you have read and understand its Privacy Policy and Terms of Use.
Use any information on this site at your own risk, I take no responsibility for the accuracy of safety of the information on this site.