Skip to content

Instantly share code, notes, and snippets.

@adeleke5140
Created April 21, 2022 23:50
Show Gist options
  • Save adeleke5140/014b5d7b5e41401bbe056652f31e7132 to your computer and use it in GitHub Desktop.
Save adeleke5140/014b5d7b5e41401bbe056652f31e7132 to your computer and use it in GitHub Desktop.
Revert Ballot once the 5min Ballot time is exceeded
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
contract Ballot {
struct Voter {
uint weight;
bool voted;
address delegate;
uint vote;
}
struct Proposal {
bytes32 name;
uint voteCount;
}
address public chairperson;
uint256 startTime;
modifier voteEnded(){
require(block.timestamp <= startTime + 5 minutes);
_;
}
mapping(address => Voter) public voters;
//array named proposals that would contain various Proposal structs
Proposal[] public proposals;
constructor(bytes32[] memory proposalNames){
chairperson = msg.sender;
voters[chairperson].weight = 1;
startTime = block.timestamp;
for(uint i = 0; i < proposalNames.length; i++){
proposals.push(Proposal({
name: proposalNames[i],
voteCount: 0
}));
}
}
function giveRightToVote(address voter) external {
require(msg.sender == chairperson);
require(!voters[voter].voted);
require(voters[voter].weight == 0);
voters[voter].weight = 1;
}
function delegate(address to) external {
Voter storage sender = voters[msg.sender];
require(!sender.voted, "You already voted");
require(to != msg.sender, "Self delegation is disallowed");
while (voters[to].delegate != address(0)) {
to = voters[to].delegate;
require(to != msg.sender, "Found loop in delegation");
}
sender.voted = true;
sender.delegate = to;
Voter storage delegate_ = voters[to];
if(delegate_.voted){
proposals[delegate_.vote].voteCount += sender.weight;
} else {
delegate_.weight += sender.weight;
}
}
function vote(uint proposal) external voteEnded {
Voter storage sender = voters[msg.sender];
require(sender.weight != 0, "Has no right to vote");
require(!sender.voted, "Already voted");
sender.voted = true;
sender.vote = proposal;
proposals[proposal].voteCount += sender.weight;
}
function winningProposal() public view returns (uint winningProposal_){
uint winningVoteCount = 0;
for(uint p = 0; p < proposals.length; p++){
if(proposals[p].voteCount > winningVoteCount){
winningVoteCount = proposals[p].voteCount;
winningProposal_ = p;
}
}
}
function winnerName() external 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