How to get random numbers in your Ethereum smart contracts
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.
Using Chainlink VRF to get randomness 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.
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!
Next post
Previous post
π Solidity Auditing online quiz
Learn how to audit smart contracts by looking at some example code and trying to find the bugs
β½ Solidity Gas Optimizations Guide
How to optimize and reduce gas usage in your smart contracts in Solidity
π§ͺ Guide to testing with Foundry
Guide to adding testing for your Solidity contracts, using the Foundry and Forge tools
π Guide to UTXO
UTXO and the UTXO set (used by blockchains such as Bitcoin) explained
π Solidity Assembly Guide
Introduction guide to using assembly in your Solidity smart contracts
π¦ Ethereum EOF format explained
Information explaining what the upcoming Ethereum EOF format is all about