Created
June 4, 2018 15:37
-
-
Save jigar23/fbd3bf8700037d5a7cd558259307754e to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.4.23+commit.124ca40d.js&optimize=false&gist=
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.4.22; | |
contract Ballot { | |
struct Voter { | |
uint weight; | |
bool voted; | |
address delegate; | |
uint vote; | |
} | |
address private chairperson; | |
struct Proposal { | |
bytes32 name; | |
uint voteCount; | |
} | |
mapping (address => Voter) private voters; | |
Proposal[] private proposals; | |
modifier checkOwner { | |
require( | |
msg.sender == chairperson, | |
"Only chairperson can give right to vote." | |
); | |
_; | |
} | |
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], | |
voteCount: 0 | |
})); | |
} | |
} | |
function giveRightToVote(address voter) checkOwner public { | |
require( | |
!voters[voter].voted, | |
"Voter has already voted" | |
); | |
require(voters[voter].weight == 0); | |
voters[voter].weight = 1; | |
} | |
function delegateVote(address to) public { | |
Voter storage sender = voters[msg.sender]; | |
require(!sender.voted, "Sender has already voted"); | |
require(to != msg.sender, "Self delegate not allowed"); | |
while(voters[to].delegate != address(0)) { | |
to = voters[to].delegate; | |
require(to != msg.sender, "Loop not allowed"); | |
} | |
sender.voted = true; | |
sender.delegate = to; | |
if (voters[to].voted) { | |
proposals[voters[to].vote].voteCount += sender.weight; | |
} | |
else { | |
voters[to].weight += sender.weight; | |
} | |
} | |
function Vote(uint proposal) public { | |
Voter storage sender = voters[msg.sender]; | |
require(!sender.voted, "Sender has already voted"); | |
sender.voted = true; | |
sender.vote = proposal; | |
proposals[proposal].voteCount += sender.weight; | |
} | |
function winningProposal() public view | |
returns (uint winningProposal_) { | |
uint winnerCount = 0; | |
for(uint i = 0; i < proposals.length; i++) { | |
if (proposals[i].voteCount > winnerCount) { | |
winnerCount = proposals[i].voteCount; | |
winningProposal_ = i; | |
} | |
} | |
} | |
function winnerName() public view | |
returns (bytes32 winnerName_) { | |
winnerName_ = proposals[winningProposal()].name; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment