DEV Community

Abdullah Sheikh
Abdullah Sheikh

Posted on

How to Build a Blockchain-Based Voting System from Scratch: A Beginner’s Guide

Step‑by‑step you’ll design, code, and launch a secure, transparent voting app using blockchain technology

Before We Start: What You'll Walk Away With

When you finish this guide you’ll see the whole blockchain voting system layout, from the ledger’s blocks to the user’s screen.

You’ll code a tiny smart contract, push it to a public testnet, and hook up a basic web page that lets voters cast and verify their choices.

A ready‑to‑use checklist will show you how to lock down the prototype and stretch it for real elections.

Think of the architecture like a restaurant kitchen: the blockchain is the pantry where ingredients (votes) are stored safely, the smart contract is the chef’s recipe, and the front‑end is the waiter taking orders.

  • Understand the three‑layer layout – network, contract, UI.

  • Write and test a vote() function that records a choice.

  • Deploy on goerli (or any testnet) and connect via Web3.js.

  • Run the front‑end, submit a ballot, and watch the transaction appear in the block explorer.

Tools you’ll need are simple:

  • Node.js – runs JavaScript scripts.

  • Hardhat – compiles and deploys contracts.

  • MetaMask – injects a wallet into the browser.

  • Vite – quick dev server for the UI.

Here’s a quick cheat sheet to keep on your desk:

  • Contract address: copy from the deployment log.

  • ABI file: artifacts/contracts/Vote.sol/Vote.json.

  • Network RPC: https://goerli.infura.io/v3/….

  • Gas limit: start with 200000 and adjust if needed.

With these pieces in place you’ll have a functional blockchain voting system you can demo tomorrow.

What Blockchain Voting Actually Is (No Jargon)

Blockchain voting records each ballot as a permanent entry on a shared ledger that lives on many computers at once. Once a vote is written, the network checks it against the existing chain and then locks it in place, so nobody can alter or erase it later. The result is a transparent, tamper‑resistant list that anyone can audit without trusting a single authority.

Imagine a public Google Sheet where every voter gets a unique link to add a new row. The sheet is view‑only for everyone else, and once a row appears it’s frozen—no one can go back and change the numbers. That’s essentially how a blockchain voting system works, except the “sheet” is distributed across dozens or hundreds of nodes, and the freezing happens automatically through cryptographic rules rather than a manual lock.

The 3 Mistakes Everyone Makes With Blockchain Voting

Most first attempts stumble over the same three traps.

  • Over‑engineering: You’ll see folks launch a full public blockchain for a small poll, then wonder why it’s crawling. Think of it like ordering a 12‑course dinner when you only wanted a sandwich. A permissioned testnet or even a simple sidechain gives you speed, lower costs, and the control you need without the unnecessary baggage.

  • Ignoring UX: Voters quickly bail if the interface feels like a crypto wallet instead of a ballot box. Imagine trying to navigate Google Maps with only voice commands—confusing and frustrating. Keep the flow to a few clicks: login, select candidate, confirm. Simplicity trumps flash.

  • Skipping security basics: Some skip hashing voter IDs or fail to safeguard private keys. That’s akin to packing a suitcase and leaving the lock off; anyone can peek inside. Use a standard hash function for IDs and store keys in a hardware security module or a vault service. Even a modest security layer stops the obvious attacks.

Avoid these pitfalls and your blockchain voting system will stay functional, friendly, and safe.

How to Build a Blockchain Voting System: Step‑by‑Step

  • Pick a blockchain playground. The easiest start is Ethereum’s Goerli testnet paired with Solidity contracts—think of it as a sandbox where you can experiment without real money.

  • Get your tools ready. Install Node.js, then pull in Hardhat (npm install --save-dev hardhat) and add the Metamask extension to your browser. This setup is like assembling a kitchen before you start cooking.

  • Write the smart contract. Create a .sol file that includes three core functions: registerVoter(), castVote(), and tally(). Each function should check permissions, record a vote, or sum results, respectively.

  • Run local tests. Use Hardhat’s built‑in network to simulate a full voting round: register a few dummy addresses, cast votes, then call tally() and assert the expected outcome.

  • Deploy to Goerli. Fund a test wallet via a faucet, then execute npx hardhat run scripts/deploy.js --network goerli. After deployment, paste the contract address into Etherscan’s verification page so anyone can read the source.

  • Build the front‑end. Scaffold a React app, install ethers.js, and write components that call the contract’s methods. Keep the UI simple—just a registration form, a list of candidates, and a “Submit Vote” button.

  • Hook up Metamask. When a user clicks “Submit Vote,” prompt Metamask to sign the transaction. This step is the digital equivalent of signing a ballot in person.

  • Show the results. Query tally() from the UI, then render a chart (e.g., using Chart.js) so every voter can see a transparent, real‑time count.

Cheat Sheet

  • npm i -g hardhat

  • npx hardhat node – local testnet

  • npx hardhat run scripts/deploy.js --network goerli

  • Metamask → Goerli test network

A Real Example: Campus Student Council Election

Maya, the IT coordinator at Greenfield University, needs a cheap, tamper‑proof vote for 250 students.

She boots up Hardhat and creates a new project folder called student‑council‑vote. Just like setting up a new playlist, the command

npx hardhat init
Enter fullscreen mode Exit fullscreen mode

gives her a clean workspace.

  • Using the template from the guide, Maya names the Solidity contract StudentCouncilVote. The contract mirrors a simple menu: each student picks one dish (candidate) and the kitchen (blockchain) records the order.

  • She registers every voter by hashing their university email. The script looks like this:

const crypto = require('crypto');
function hashEmail(email) {
  return crypto.createHash('sha256').update(email).digest('hex');
}
Enter fullscreen mode Exit fullscreen mode
  • She runs the script for the 250 emails, stores the hashes in voters.json, and calls registerVoter(hash) on the contract.

  • Each student receives a unique link like https://vote.greenfield.edu/2024. Think of it as a QR code on a cafeteria tray, pointing them straight to their voting seat.

  • On voting day, students open the React app, connect their MetaMask wallet, and see a list of candidates. When they click “Vote”, the app sends a transaction to vote(candidateId). The blockchain acts like a digital receipt printer – immutable and instantly visible.

  • Results update in real time on a bar chart. It’s like watching a live poll on a sports scoreboard; every new vote nudges the bars up.

  • Tip: Set the contract’s onlyOnce modifier to block double‑voting, just as a turnstile lets each person through only once.

  • Cheat sheet: Deploy with npx hardhat run scripts/deploy.js --network localhost, then start the UI with npm start.

That’s Maya’s end‑to‑end blockchain voting system, ready for the next student council election.

The Tools That Make This Easier

Grab the right gear and the rest feels like ordering a coffee—straightforward and quick.

  • Hardhat – Think of it as a local kitchen where you can bake, taste, and fix recipes before serving anyone. It spins up a private Ethereum node, runs tests, and lets you debug contracts without waiting for a public network.

  • Alchemy – This is the reliable delivery service for your dishes. Their Goerli RPC endpoint works like a Google Maps lane: fast, stable, and with a dashboard that shows traffic (request latency) at a glance.

  • Ethers.js – The Swiss‑army knife for wallet chores. It lets you sign, send, and read transactions with just a few lines, much like using a single app to pay for a ride, a meal, and a movie.

  • React + Vite – Picture a pre‑packed suitcase for your front‑end. Vite whips up a dev server in seconds, and React gives you modular compartments to drop UI pieces into without clutter.

  • MetaMask – Your personal ID badge at the voting booth. The browser extension stores keys, prompts signatures, and shows balances, so users can vote with a single click.

Putting them together looks like this:

  • Initialize a Hardhat project, add @openzeppelin/contracts, and write the ballot contract.

  • Deploy to Alchemy’s Goerli endpoint using npx hardhat run scripts/deploy.js --network goerli.

  • In your React app, import ethers and connect to MetaMask to read/write votes.

Cheat sheet

  • Hardhat: npx hardhat node

  • Alchemy dashboard: copy the Goerli API key, paste into hardhat.config.js

  • Ethers: const provider = new ethers.providers.Web3Provider(window.ethereum)

  • Vite start: npm run dev

  • MetaMask: ensure network set to “Goerli Testnet”

With these tools in hand, building a blockchain voting system becomes a matter of assembling, not inventing.

Quick Reference: Blockchain Voting Cheat Sheet

Grab this cheat sheet and keep it open while you code – it’s the quick‑order menu for your blockchain voting system.

  • Pick a permissioned testnet – think of Goerli as a sandbox playground where you can experiment without paying real gas fees.

  • Set up the toolbox – install Node.js, Hardhat, and add the MetaMask extension. It’s like assembling a kitchen before you start cooking.

Smart contract skeleton – implement three core functions:

- `registerVoter(address)` – like signing up a new user on a website.

- `castVote(uint256 candidateId)` – similar to clicking “order” in a food‑delivery app.

- `tallyVotes()` – the final receipt that adds up every order.
Enter fullscreen mode Exit fullscreen mode
  • Run local tests – use Hardhat scripts to simulate registrations and votes before any live deployment. It’s the “dry‑run” before the real show.

  • Deploy and verify – push the contract to Goerli, then verify it on Etherscan. For example, when Alice deployed her community poll, the verification link let every participant inspect the exact code they were trusting.

  • Build the front‑end – combine React, ethers.js, and MetaMask. Think of it as a Google Maps UI that guides voters to the right address.

Security checklist

- Hash voter IDs before storing them.

- Never expose private keys; keep them in environment variables.

- Enforce one‑vote‑per‑address logic in the contract.
Enter fullscreen mode Exit fullscreen mode
  • Plan for scale – once the prototype works, migrate to Polygon or a private consortium chain. It’s like moving from a small café to a larger restaurant when the crowd grows.

Keep this list handy; it’s your shortcut from idea to a working blockchain voting system.

What to Do Next

Grab the repo, spin it up, and see the voting flow in action.

  • Easy: Fork the GitHub repo linked below and run npm start (or python -m http.server) on your laptop. It’s like ordering a ready‑made pizza – you just heat it up and start eating.

  • Medium: Swap the hard‑coded voter list for a CSV import. Read the file, hash each email with keccak256, and feed the hashes into the contract. Think of it as packing a suitcase: you replace loose items with neatly folded ones that fit the space.

  • Hard: Deploy the contract on a permissioned Hyperledger Besu network. Set up the consortium nodes, configure privacy groups, and point your front‑end to the new RPC endpoint. This step is the “Google Maps” of the guide – you’re building your own road network instead of using the default streets.

  • Tools: truffle or hardhat for migrations, csv‑parser (JS) or pandas (Python) for CSV handling, and Docker for Besu.

  • Tip: Keep the private key for the admin account in a .env file and never commit it.

Got stuck or have a cool use case? Drop a comment or DM me – I’d love to hear how you’re using a blockchain voting system!



About the Author

Abdullah Sheikh is the Founder & CEO at Exteed, where he leads a team of skilled developers specializing in Web2 and Web3 applications, Custom Smart Contracts, and Blockchain solutions.

With 6+ years of experience, Abdullah has built CRMs, Crypto Wallets, DeFi Exchanges, E-Commerce Stores, HIPAA Compliant EMR Systems, and AI-powered systems that drive business efficiency and innovation.

His expertise spans Blockchain, Crypto & Tokenomics, Artificial Intelligence, and Web Applications; building reliable and smooth web apps that fit the client’s goals and requirements.

📧 info@abdullah-sheikh.com · 🔗 LinkedIn · 🌐 abdullah-sheikh.com

Top comments (0)