Lottery Tutorial

In this guide, we will explore the process of leveraging Nerif Network to automate the mechanism for picking a winner in a lottery.

By following the step-by-step instructions provided, developers will gain the knowledge and practical skills to seamlessly automate smart contract functions execution using Nerif Network and unlock the power of automation for these operations.

To ensure a seamless flow of lottery winner-picking mechanism, Nerif Network will be calling 2 functions from the below Lottery smart contract:

  1. playersExist checks if there are at least two participants taking part in a lottery (doesn’t change state);

  2. pickWinner selects the winners among the participants (changes state so the transactions should be sent to execute it).

contract Lottery {
  uint public jackpot;
  address[] public players;
  // enter the given amount to the lottery pool
  function enter() public payable {
    require(msg.value > 0, "You must enter with a positive value");
    jackpot += msg.value;
  // playersExist checks if there are some player in the list
  function playersExist() public view returns (bool exist) {
    exist = players.length >= 2;
  // random choses a random winner
  function random() private view returns (uint) {
    return uint(keccak256(abi.encodePacked(block.timestamp, block.difficulty, players.length))) % players.length;
  // pickWinner picks a random winner and transfer funds to them
  function pickWinner() public {
    require(players.length >= 2, "Not enough players entered the lottery");
    uint randomIndex = random();
    address payable winner = payable(players[randomIndex]);
    delete players;
    jackpot = 0;

Let’s go!

Last updated