-
Notifications
You must be signed in to change notification settings - Fork 0
/
SmartContract.sol
59 lines (44 loc) · 1.82 KB
/
SmartContract.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// SPDX-License-Identifier: Unlicansed
pragma solidity ^0.8.7;
contract Lottery{
// declaring the state variables
address payable[] public players; //dynamic array of type address payable
address public manager;
// declaring the constructor
constructor(){
// initializing the owner to the address that deploys the contract
manager = msg.sender;
}
// declaring the receive() function that is necessary to receive ETH
receive () payable external{
// each player sends exactly 0.1 ETH
require(msg.value == 0.1 ether);
// appending the player to the players array
players.push(payable(msg.sender));
}
// returning the contract's balance in wei
function getBalance() public view returns(uint){
// only the manager is allowed to call it
require(msg.sender == manager);
return address(this).balance;
}
// helper function that returns a big random integer
function random() internal view returns(uint){
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, players.length)));
}
// selecting the winner
function pickWinner() public{
// only the manager can pick a winner if there are at least 3 players in the lottery
require(msg.sender == manager);
require (players.length >= 3);
uint r = random();
address payable winner;
// computing a random index of the array
uint index = r % players.length;
winner = players[index]; // this is the winner
// transferring the entire contract's balance to the winner
winner.transfer(getBalance());
// resetting the lottery for the next round
players = new address payable[](0);
}
}