Last active
May 22, 2021 19:32
-
-
Save parv3213/993607cf660806773f5467989617b0b8 to your computer and use it in GitHub Desktop.
Voting smart contract with candidate information
This file contains 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
//SPDX-License-Identifier: UNLICENSED | |
pragma solidity 0.8.0; | |
// 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 => uint256) public votesReceived; | |
/* struct for a candidate infromation */ | |
struct CandidateData { | |
string candidateName; | |
string constituency; | |
string party; | |
bytes32 candidateHash; | |
} | |
/* mapping for candidates information */ | |
CandidateData[] public candidatesData; | |
/* 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 details who will be contesting in the election | |
*/ | |
constructor(string[] memory candidateNames, string[] memory constituencies, string[] memory parties, bytes32[] memory _candidatesHash) { | |
for (uint256 i = 0; i < candidateNames.length ; i++){ | |
candidatesData.push(CandidateData(candidateNames[i], constituencies[i], parties[i], _candidatesHash[i])); | |
} | |
} | |
// This function returns the total votes a candidate has received so far | |
function totalVotesFor(bytes32 candidate) view public returns (uint256) { | |
require(validCandidate(candidate)); | |
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)); | |
votesReceived[candidate] += 1; | |
} | |
function validCandidate(bytes32 candidate) view public returns (bool) { | |
for(uint i = 0; i < candidatesData.length; i++) { | |
if (candidatesData[i].candidateHash == candidate) { | |
return true; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment