-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathElection.sol
More file actions
66 lines (54 loc) · 1.99 KB
/
Election.sol
File metadata and controls
66 lines (54 loc) · 1.99 KB
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
60
61
62
63
64
65
66
pragma solidity 0.5.16;
contract Election {
// Model a Candidate
struct Candidate {
uint id;
string name;
uint voteCount;
}
// Store accounts that have voted
mapping(address => bool) public voters;
// Store Candidates
mapping(uint => Candidate) public candidates;
/*Solidity tip: mapping is like an array or hashmap
it has a key value pair, here uint is the datatype of the key
and Candidate is the data type of the value which is a Candidate struct
candidates is the name of the mapping */
// Store Candidates Count
uint public candidatesCount;
/*Solidity tip: local variables which are NOT instance variables
begin with an '_' */
// voted event
event votedEvent (
uint indexed _candidateId
);
constructor () public {
addCandidate("Superman");
addCandidate("Batman");
}
function addCandidate (string memory _name) private {
candidatesCount ++;
candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
}
function getCandidate(uint256 _candidateId) public view returns(string memory) {
require(_candidateId > 0 && _candidateId <= candidatesCount, "Invalid Candidate ID");
return candidates[_candidateId].name;
}
function getVoteCount(uint256 _candidateId) external view returns (uint256 voteCount)
{
require(_candidateId > 0 && _candidateId <= candidatesCount, "Invalid Candidate ID");
return candidates[_candidateId].voteCount;
}
function vote (uint _candidateId) public {
// require that they haven't voted before
require(!voters[msg.sender]);
// require a valid candidate
require(_candidateId > 0 && _candidateId <= candidatesCount);
// record that voter has voted
voters[msg.sender] = true;
// update candidate vote Count
candidates[_candidateId].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId);
}
}