Skip to content

Instantly share code, notes, and snippets.

@satyambnsal
Created July 15, 2024 08:40
Show Gist options
  • Save satyambnsal/5e8165392e21b3d50d8da1ffad5b906c to your computer and use it in GitHub Desktop.
Save satyambnsal/5e8165392e21b3d50d8da1ffad5b906c to your computer and use it in GitHub Desktop.
Voting Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Voting {
struct Candidate {
string name;
uint256 voteCount;
}
Candidate[] public candidates;
mapping(address => bool) public voters;
address public owner;
constructor(string[] memory candidateNames) {
owner = msg.sender;
for (uint i = 0; i < candidateNames.length; i++) {
candidates.push(Candidate({
name: candidateNames[i],
voteCount: 0
}));
}
}
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can call this function");
_;
}
function vote(uint256 candidateIndex) public {
require(!voters[msg.sender], "You have already voted");
require(candidateIndex < candidates.length, "Invalid candidate index");
voters[msg.sender] = true;
candidates[candidateIndex].voteCount++;
}
function getCandidateCount() public view returns (uint256) {
return candidates.length;
}
function getCandidate(uint256 index) public view returns (string memory, uint256) {
require(index < candidates.length, "Invalid candidate index");
Candidate memory candidate = candidates[index];
return (candidate.name, candidate.voteCount);
}
function getCandidates(uint256[] memory indices) public view returns (string[] memory names, uint256[] memory voteCounts) {
names = new string[](indices.length);
voteCounts = new uint256[](indices.length);
for (uint256 i = 0; i < indices.length; i++) {
require(indices[i] < candidates.length, "Invalid candidate index");
Candidate memory candidate = candidates[indices[i]];
names[i] = candidate.name;
voteCounts[i] = candidate.voteCount;
}
return (names, voteCounts);
}
function getWinner() public view returns (string memory, uint256) {
require(candidates.length > 0, "No candidates available");
uint256 winningVoteCount = 0;
uint256 winningCandidateIndex = 0;
for (uint256 i = 0; i < candidates.length; i++) {
if (candidates[i].voteCount > winningVoteCount) {
winningVoteCount = candidates[i].voteCount;
winningCandidateIndex = i;
}
}
return (candidates[winningCandidateIndex].name, winningVoteCount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment