forked from KCLBlockchain/Backend-Voting-System
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVotingSystem.sol
More file actions
82 lines (54 loc) · 2.02 KB
/
VotingSystem.sol
File metadata and controls
82 lines (54 loc) · 2.02 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
pragma solidity ^0.4.20;
contract VotingSystem {
// This sctructure holds info about the person who votes
struct Voter {
bool voted;
uint8 vote;
}
// This sctructure holds info about the person who you can vote for
struct Candidate {
bytes32 name;
uint8 numberOfVotes;
}
// Contract owner's address
address contractOwner;
// Mapping adresse's to voter info
mapping(address => Voter) voters;
Candidate[] candidates;
mapping(string => Candidate) results;
// Our constructor assigns names of candidates to the Candidate
// array we stor on block chain.
// Also stors the contractOwner address on the block chain
function VotingSystem (bytes32[] candidateNames) {
contractOwner = msg.sender;
for (uint8 i = 0; i < candidateNames.length; i++) {
candidates.push(Candidate({
name : candidateNames[i],
numberOfVotes : 0
}));
}
}
// Voting function:
// Check wheter the voter has voted, if not:
// Mark the fact that he voted, also store the person he voted for
// Finally increment candidate's numberOfVotes
function vote (uint8 voteFor) {
Voter storage sender = voters[msg.sender];
if(sender.voted) return;
sender.voted = true;
sender.vote = voteFor;
candidates[voteFor].numberOfVotes += 1;
}
// This function returns the candidate with most votes.
function winningCandidate () constant returns(uint8 winnerName) {
uint8 tempWinnerName;
uint maxVote = 0;
for (uint8 i = 0; i < candidates.length; i++) {
if (candidates[i].numberOfVotes > maxVote) {
maxVote = candidates[i].numberOfVotes;
tempWinnerName = i;
}
}
return tempWinnerName;
}
}