Skip to content

Instantly share code, notes, and snippets.

@begmaroman
Created February 21, 2023 13:24
Show Gist options
  • Save begmaroman/c8c936bf8232dc3fc867edba4302a34c to your computer and use it in GitHub Desktop.
Save begmaroman/c8c936bf8232dc3fc867edba4302a34c to your computer and use it in GitHub Desktop.
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
// Lottery implements simple lottery contract.
// In this contract, the enter function allows players to enter the lottery
// by sending a positive value to the contract, which is added to the jackpot total.
// The random function generates a random index within the bounds of the players
// array length, using the current block timestamp, difficulty, and array length.
//
// The pickWinner function selects the winner by calling the random function and
// transferring the entire jackpot to the winner's address.
// Finally, the players array and the jackpot total are reset for the next lottery.
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");
players.push(msg.sender);
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]);
winner.transfer(jackpot);
delete players;
jackpot = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment