-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVoting-system
87 lines (69 loc) · 2.45 KB
/
Voting-system
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
83
84
85
86
87
pragma solidity ^0.4.24;
contract Ballot{
address public chairperson;
struct Voter{
uint weight;
bool voted;
address delegate;
uint vote;
}
struct Proposal{
bytes32 name;
uint votesCount;
}
mapping (address => Voter) public voters;
Proposal[] public proposals;
constructor (bytes32[] _proposalNames) public{
chairperson = msg.sender;
voters[chairperson].weight = 1;
for (uint i = 0; i < _proposalNames.length; i++){
proposals.push(Proposal({
name:_proposalNames[i],
votesCount: 0
}));
}
}
function giveRightToVote (address _voter) public{
require(chairperson == msg.sender,"Only chairperson can give right to vote");
require(!voters[_voter].voted, "Already voted.");
require(voters[_voter].weight==0,"Weight issue.");
voters[_voter].weight = 1;
}
function delegate (address _to) public{
Voter storage sender = voters[msg.sender];
require(!sender.voted,"Already voted.");
require(_to != msg.sender,"Self-delegation not possible.");
while (voters[_to].delegate != address(0)){
_to = voters[_to].delegate;
require(_to != msg.sender, "Self-delegation not possible - while loop");
}
sender.voted = true;
sender.delegate = _to;
Voter storage delegate_ = voters[_to];
if (delegate_.voted){
proposals[delegate_.vote].votesCount += sender.weight;
}
else{
delegate_.weight += sender.weight;
}
}
function vote (uint _proposal) public{
Voter storage sender = voters[msg.sender];
require(!sender.voted, "Already voted.");
sender.voted = true;
sender.vote = _proposal;
proposals[_proposal].votesCount += sender.weight;
}
function winningProposal () public view returns (uint _winningProposal){
uint winningVotesCount=0;
for (uint i=0;i<proposals.length;i++){
if (proposals[i].votesCount > winningVotesCount){
winningVotesCount = proposals[i].votesCount;
_winningProposal = i;
}
}
}
function winnerName() public view returns (bytes32 _winnerName){
_winnerName = proposals[winningProposal()].name;
}
}