Build a Verifiably Random Lottery Smart Contract on Ethereum
How to create an Ethereum lottery

Editor’s note: This article is provided for entertainment and educational purposes only and does not constitute or contain financial advice. Any actions you take from the content of this article are solely your own.
True randomness has been near impossible on Ethereum. This is because transactions need to be verified by multiple nodes on the network to be confirmed. If a smart contract function were truly random, each node that verified a transaction using that function would come to a different result, meaning the transaction would never be confirmed.
A recent announcement by one of the biggest players in the Ethereum ecosystem has caused excitement around this very problem. Using a system called a Verifiable Random Function (VRF), Ethereum smart contracts can now generate random numbers.
This means concepts that seemed a perfect fit with smart contracts but couldn’t be brought to life because they required random numbers now can be.
One such concept is that of a lottery.
Building a Lottery Smart Contract
Our lottery is going to have three phases. The first is open, where new numbers can be submitted by anyone for a small fee. The second is closed, where no new numbers can be submitted and the random number is being generated. The third is finished, where the number has been generated and the winner has been paid.
If no one wins, the lottery contract can be rolled over, increasing the jackpot.
Defining the phases
Phases should restrict actions so only permitted operations can be performed. For example, the only phase that should allow new submissions is the open phase. If the lottery is closed or finished, the contract should forbid new submissions.
Using enum, we can define as many phases as we want. Let’s call it LotteryState. In our state variables, we define the following:
enum LotteryState { Open, Closed, Finished }
LotteryState public state;Now that the enumeration is defined, we can set rules (require statements) in the functions, ensuring the current state of the contract is what we expect it to be.
Given that these require statements are likely to look similar throughout the contract, let’s minimise it. We can define a modifier that performs the require statement, and we can assign it to any function we wish.
modifier isState(LotteryState _state) {
require(state == _state, "Wrong state for this action");
_;
}Now when we define functions, we can add this modifier to ensure the current state of the lottery is what we expect it to be.
Submitting numbers
Anyone should be allowed to submit a number so long as the minimum entry fee is paid. However, each entrant can’t submit the same number more than once. The only state that should allow new submissions is the open state.
Here’s our submitNumber function:





