Skip to content

Instantly share code, notes, and snippets.

@silviopaganini
Created November 10, 2017 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silviopaganini/90d935b326f33c7b06087ebf40f3d137 to your computer and use it in GitHub Desktop.
Save silviopaganini/90d935b326f33c7b06087ebf40f3d137 to your computer and use it in GitHub Desktop.
Full stack Hello World - Contract updated to use require instead of throw
// Full Tutorial here https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2
pragma solidity ^0.4.11;
// We have to specify what version of compiler this code will compile with
contract Voting {
/* mapping field below is equivalent to an associative array or hash.
The key of the mapping is candidate name stored as type bytes32 and value is
an unsigned integer to store the vote count
*/
mapping (bytes32 => uint8) public votesReceived;
/* Solidity doesn't let you pass in an array of strings in the constructor (yet).
We will use an array of bytes32 instead to store the list of candidates
*/
bytes32[] public candidateList;
/* This is the constructor which will be called once when you
deploy the contract to the blockchain. When we deploy the contract,
we will pass an array of candidates who will be contesting in the election
*/
function Voting(bytes32[] candidateNames) public {
candidateList = candidateNames;
}
// This function returns the total votes a candidate has received so far
function totalVotesFor(bytes32 candidate) public view returns (uint8) {
require(validCandidate(candidate)); // updated to use require instead of throw
return votesReceived[candidate];
}
// This function increments the vote count for the specified candidate. This
// is equivalent to casting a vote
function voteForCandidate(bytes32 candidate) public {
require(validCandidate(candidate)); // updated to use require instead of throw
votesReceived[candidate] += 1;
}
function validCandidate(bytes32 candidate) internal view returns (bool response) {
for(uint i = 0; i < candidateList.length; i++) {
if (candidateList[i] == candidate) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment