Skip to content

Instantly share code, notes, and snippets.

@vis-kid
Created March 20, 2022 21:52
Show Gist options
  • Save vis-kid/56d3c27e390003e78239416af67e62cf to your computer and use it in GitHub Desktop.
Save vis-kid/56d3c27e390003e78239416af67e62cf 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.8.7+commit.e28d00a7.js&optimize=false&runs=200&gist=
pragma solidity >=0.7.0 <0.9.0;
contract Ballot {
// Variables
struct vote {
address voterAddress;
bool choice;
}
struct voter {
string voterName;
bool voted;
}
uint private countResult = 0;
uint public finalResult = 0;
uint public totalVoter = 0;
uint public totalVote = 0;
address public ballotOfficialAddress;
string public ballotOfficialName;
string public proposal;
mapping(uint => vote) private votes;
mapping(address => voter) public voterRegister;
enum State { CREATED, VOTING, ENDED }
State public state;
// Modifiers
modifier condition(bool _condition) {
require(_condition);
_;
}
modifier onlyOfficial() {
require(msg.sender == ballotOfficialAddress, "Not authorized!");
_;
}
modifier inState(State _state) {
require(state == _state, "Not authorized!");
_;
}
// Events
// Functions
constructor(string memory _ballotOfficialName, string memory _proposal) {
ballotOfficialAddress = msg.sender;
ballotOfficialName = _ballotOfficialName;
proposal = _proposal;
state = State.CREATED;
}
function addVoter(address _voterAddress, string memory _voterName)
public
inState(State.CREATED)
onlyOfficial
{
voter memory newVoter;
newVoter.voterName = _voterName;
newVoter.voted = false;
voterRegister[_voterAddress] = newVoter;
totalVoter ++;
}
function startVote()
public
onlyOfficial
inState(State.CREATED)
{
state = State.VOTING;
}
function dovote(bool _choice)
public
inState(State.VOTING)
returns (bool voted)
{
bool found = false;
if (bytes(voterRegister[msg.sender].voterName).length != 0
&& !voterRegister[msg.sender].voted) {
voterRegister[msg.sender].voted = true;
vote memory newVote;
newVote.voterAddress = msg.sender;
newVote.choice = _choice;
if(_choice) {
countResult ++;
}
votes[totalVote] = newVote;
totalVote ++;
found = true;
}
return found;
}
function endVote() public onlyOfficial inState(State.VOTING) {
state = State.ENDED;
finalResult = countResult;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment