Created
April 23, 2020 08:46
-
-
Save ogwurujohnson/77312ebeb51866ff1fb51c4c99824817 to your computer and use it in GitHub Desktop.
An ethereum voting smart contract
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.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