/** Author: Ravi Kumar purpose: Coding Assignment: 1 description: solidity Programming - Voter Application */ pragma solidity ^0.4.10; contract Voting { //Owner of the contract, address which deploys the contract address owner; //Contract level variables, to capture the state of the contract uint256 canidatesCount; uint256 votersCount; uint256 votesCount; //Complex DataType //Contract level object to store Voter Information struct Voter { uint256 candidateIdVote; bool hasVoted; bool isAuthorized; } //Complex Data Type //Construct level object to store candidate information struct Candidate { string name; string party; uint256 votesCount; bool doesExists; } //Stores list of candidates & voters //Could have used array as well here mapping(uint256 => Candidate) candidates; mapping(address => Voter) voters; //constructor to initialize owner as the address which creates the contract constructor () public { owner = msg.sender; } //Pre execution Function/Validation check - Executes before the actual function call //This is usually added to other function definition as prerequisite modifier onlyOwner() { require(msg.sender == owner); //This step will ensure that next function call happens } //Add candidate //Only owner of the contract can add candidates function addCandidate(string memory name, string memory party) public onlyOwner { uint256 candidateId = canidatesCount++; candidates[candidateId] = Candidate(name, party, 0, true); } //Vote for candidate //Anyone can vote as long as they are authorized & have not voted earlier function vote(uint256 candidateId) public { require(!voters[msg.sender].hasVoted); //Check if candidate has voted earlier?? require(voters[msg.sender].isAuthorized); //Check if voter is authorized); if (candidates[candidateId].doesExists) { voters[msg.sender] = Voter(candidateId, true, true); candidates[candidateId].votesCount++; votesCount++; votersCount++; } } function totalVotes(uint256 candidateId) public view returns (uint256) { return candidates[candidateId].votesCount; } function getCandidateCount() public view returns (uint256) { return canidatesCount; } function getVotersCount() public view returns (uint256) { return votersCount; } function getCandidate(unit candidateId) public view returns ( uint256, string memory, string memory, uint256 ) { return ( candidateId, candidates[candidateId].name, candidates[candidateId].party, candidates[candidateId].votesCount ); } //Returns the owner and Sender address //Used only for debugging function getOwnerAndSender() public view returns (address, address) { return (owner, msg.sender); } //funtion to authorzied voters //only owner of the contract can authorized other voters function authorize(address voterId) public onlyOwner { //Authorize a particular address, enables them to vote voters[voterId].isAuthorized = true; } }
0.4.18