Skip to content

Instantly share code, notes, and snippets.

@ogwurujohnson
Created April 23, 2020 08:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ogwurujohnson/77312ebeb51866ff1fb51c4c99824817 to your computer and use it in GitHub Desktop.
Save ogwurujohnson/77312ebeb51866ff1fb51c4c99824817 to your computer and use it in GitHub Desktop.
An ethereum voting smart contract
pragma solidity ^0.4.0;
pragma experimental ABIEncoderV2;
contract Voter {
struct OptionPos {
uint pos;
bool exists;
}
uint[] public votes;
string[] public options;
mapping(address => bool) hasVoted;
mapping(string => OptionPos) posOfOption;
constructor(string[] _options) public {
options = _options;
votes.length = options.length;
for (uint i = 0; i<options.length; i++) {
OptionPos memory optionPos = OptionPos(i, true);
string optionName = options[i];
posOfOption[optionName] = optionPos;
}
}
function vote(uint option) public {
require(0 <= option && option < options.length, "Invalid option");
require(!hasVoted[msg.sender], "user has voted previously");
votes[option] = votes[option] + 1;
hasVoted[msg.sender] = true;
}
function vote(string optionName) public {
require(!hasVoted[msg.sender], "user has voted previously");
OptionPos memory optionPos = posOfOption[optionName];
require(optionPos.exists, "Option does not exists");
votes[optionPos.pos] = votes[optionPos.pos] + 1;
hasVoted[msg.sender] = true;
}
function getOptions() view public returns (string[]) {
return options;
}
function getVotes() view public returns (uint[]) {
return votes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment