Traditional voting systems often face challenges related to centralized authority, voter suppression, manual errors, and a lack of auditability. By moving the voting process to an Ethereum-compatible blockchain, we can build a system characterized by immutability, transparency, and verifiable integrity.
In this tutorial, we will design and deploy a complete, functional Decentralized Voting Smart Contract using Solidity. By the end of this guide, you will understand how to manage voter state, store candidates securely on-chain, prevent double-voting, and compute election winners deterministically.
System Architecture and Rules
Before writing code, let’s define the operational rules of our voting system:
- Chairperson (Owner): Deploys the contract, registers candidates, and grants voting rights to eligible wallet addresses.
- Voters: Addresses authorized by the chairperson. Each voter can vote exactly once.
- Candidates: Represented by an ID, name, and a vote counter.
- Transparency: Any user can query the election results and determine the winner in real-time.
Prerequisites
To follow along effectively, make sure you have:
- A basic understanding of Solidity, data types, and modifiers.
- Access to the Remix Ethereum IDE (no local installation required).
- A Web3 wallet (such as MetaMask) configured to a testnet (e.g., Sepolia) if you choose to deploy beyond the simulated environment.
Step 1: Setting Up Data Structures
We start by defining the structure of our contract. We need two custom structures (struct): one for the Voter and another for the Candidate.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract DecentralizedVoting {
// Structure to represent a Candidate
struct Candidate {
uint256 id;
string name;
uint256 voteCount;
}
// Structure to represent a Voter
struct Voter {
bool isAuthorized;
bool hasVoted;
uint256 votedCandidateId;
}
// State Variables
address public chairperson;
mapping(address => Voter) public voters;
Candidate[] public candidates;
uint256 public totalVotes;
bool public votingEnded;
// Events
event VoterAuthorized(address indexed voter);
event VoteCasted(address indexed voter, uint256 indexed candidateId);
event VotingEnded(uint256 winningCandidateId, string candidateName);
}
Breakdown:
mapping(address => Voter)allows $O(1)$ lookups to check if an address has permission to vote or has already voted.Candidate[] public candidatesis a dynamic array storing every contestant.Eventsallow front-end applications (e.g., React or Ethers.js) to listen for actions happening on-chain.
Step 2: Constructor and Modifiers
Next, we add the constructor to set the deployment creator as the chairperson and initialize candidate names. We also create modifiers to enforce access control.
modifier onlyChairperson() {
require(msg.sender == chairperson, "Only chairperson can perform this action");
_;
}
modifier ongoingVoting() {
require(!votingEnded, "Voting period has closed");
_;
}
constructor(string[] memory _candidateNames) {
chairperson = msg.sender;
// Add candidates supplied during deployment
for (uint256 i = 0; i < _candidateNames.length; i++) {
candidates.push(Candidate({
id: i,
name: _candidateNames[i],
voteCount: 0
}));
}
}
Step 3: Voter Registration
In a private or regulated election, not just any wallet address should vote. The chairperson must explicitly authorize addresses:
function authorizeVoter(address _voter) external onlyChairperson ongoingVoting {
require(!voters[_voter].isAuthorized, "Voter is already authorized");
require(!voters[_voter].hasVoted, "Voter has already voted");
voters[_voter].isAuthorized = true;
emit VoterAuthorized(_voter);
}
Step 4: Casting Votes
The core voting logic must prevent double-voting, ensure the target candidate is valid, and update the global vote counts correctly.
function vote(uint256 _candidateId) external ongoingVoting {
Voter storage sender = voters[msg.sender];
require(sender.isAuthorized, "You are not authorized to vote");
require(!sender.hasVoted, "You have already voted");
require(_candidateId < candidates.length, "Invalid candidate ID");
sender.hasVoted = true;
sender.votedCandidateId = _candidateId;
candidates[_candidateId].voteCount++;
totalVotes++;
emit VoteCasted(msg.sender, _candidateId);
}
Step 5: Querying and Closing the Election
Finally, we need functions to end the voting session and compute the winner based on the highest accumulated tally.
function endVoting() external onlyChairperson ongoingVoting {
votingEnded = true;
(uint256 winnerId, string memory winnerName) = getWinner();
emit VotingEnded(winnerId, winnerName);
}
function getWinner() public view returns (uint256 winnerId_, string memory winnerName_) {
uint256 highestVotes = 0;
uint256 winningIndex = 0;
for (uint256 i = 0; i < candidates.length; i++) {
if (candidates[i].voteCount > highestVotes) {
highestVotes = candidates[i].voteCount;
winningIndex = i;
}
}
return (candidates[winningIndex].id, candidates[winningIndex].name);
}
function getCandidates() external view returns (Candidate[] memory) {
return candidates;
}
Complete Smart Contract Code
Here is the entire contract assembled and ready to compile:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract DecentralizedVoting {
struct Candidate {
uint256 id;
string name;
uint256 voteCount;
}
struct Voter {
bool isAuthorized;
bool hasVoted;
uint256 votedCandidateId;
}
address public chairperson;
bool public votingEnded;
uint256 public totalVotes;
mapping(address => Voter) public voters;
Candidate[] public candidates;
event VoterAuthorized(address indexed voter);
event VoteCasted(address indexed voter, uint256 indexed candidateId);
event VotingEnded(uint256 winningCandidateId, string candidateName);
modifier onlyChairperson() {
require(msg.sender == chairperson, "Only chairperson can perform this action");
_;
}
modifier ongoingVoting() {
require(!votingEnded, "Voting period has closed");
_;
}
constructor(string[] memory _candidateNames) {
chairperson = msg.sender;
for (uint256 i = 0; i < _candidateNames.length; i++) {
candidates.push(Candidate({
id: i,
name: _candidateNames[i],
voteCount: 0
}));
}
}
function authorizeVoter(address _voter) external onlyChairperson ongoingVoting {
require(!voters[_voter].isAuthorized, "Voter is already authorized");
require(!voters[_voter].hasVoted, "Voter has already voted");
voters[_voter].isAuthorized = true;
emit VoterAuthorized(_voter);
}
function vote(uint256 _candidateId) external ongoingVoting {
Voter storage sender = voters[msg.sender];
require(sender.isAuthorized, "You are not authorized to vote");
require(!sender.hasVoted, "You have already voted");
require(_candidateId < candidates.length, "Invalid candidate ID");
sender.hasVoted = true;
sender.votedCandidateId = _candidateId;
candidates[_candidateId].voteCount++;
totalVotes++;
emit VoteCasted(msg.sender, _candidateId);
}
function endVoting() external onlyChairperson ongoingVoting {
votingEnded = true;
(uint256 winnerId, string memory winnerName) = getWinner();
emit VotingEnded(winnerId, winnerName);
}
function getWinner() public view returns (uint256 winnerId_, string memory winnerName_) {
uint256 highestVotes = 0;
uint256 winningIndex = 0;
for (uint256 i = 0; i < candidates.length; i++) {
if (candidates[i].voteCount > highestVotes) {
highestVotes = candidates[i].voteCount;
winningIndex = i;
}
}
return (candidates[winningIndex].id, candidates[winningIndex].name);
}
function getCandidates() external view returns (Candidate[] memory) {
return candidates;
}
}
Testing and Deployment in Remix
- Open Remix: Navigate to Remix IDE.
- Create File: In the File Explorer, create a new file named
Voting.soland paste the complete contract code above. - Compile: Go to the Solidity Compiler tab, select compiler version
0.8.20or higher, and click Compile Voting.sol. - Deploy:
- Go to the Deploy & Run Transactions tab.
- Set the environment to Remix VM (Cancun) or your local test environment.
- In the Deploy field, pass an array of names as the parameter:
["Alice", "Bob", "Charlie"]. - Click Deploy.
- Interact:
- Copy another account address from the Account dropdown.
- Under the deployed contract, call
authorizeVoterusing the copied address while acting as the chairperson account. - Switch to the newly authorized account, enter a candidate ID (e.g.,
0), and clickvote. - Verify the candidate’s score updates using the
candidatesgetter function.
Real-World Security & Architectural Considerations
While this contract demonstrates core functionality, production-grade voting systems must account for edge cases:
- Voter Anonymity: Public blockchains store all transactions publicly. A user’s vote can easily be linked to their address. To ensure secret ballots, production systems use Commit-Reveal schemes or Zero-Knowledge Proofs (ZK-SNARKs).
- Sybil Resistance: Authorizing voters manually by a single chairperson re-introduces centralization. Integrating decentralized identity (DID) frameworks (like WorldID or Gitcoin Passport) can automate validation trustlessly.
- Gas Delegation: Forcing voters to hold native cryptocurrency (like ETH) to pay gas introduces friction. Using meta-transactions (ERC-2771 / Account Abstraction via ERC-4337) allows the contract owner to sponsor gas costs for voters.