A Step-by-Step Guide to Building and Deploying a Voting Smart Contract on the Blockchain
This article was originally published at Building a Decentralized nft Marketplace
In this tutorial, we will guide you through the process of developing a voting smart contract using the Solidity programming language. We will then deploy the contract on a blockchain network and test it to ensure its functionality. By the end of this tutorial, you will have a good understanding of how to create and deploy a smart contract for voting purposes.
Step 1: Cloning the Tutorial Repo
1.1 Forking the Tutorial Repository:
- Head over to our Tutorial Repository and click on the “Fork” button to create a copy of the repository on your own account. Wait for the forking process to finish before proceeding.
1.2 Cloning the repository locally:
- Go to your forked repository on GitHub.
- Click the “Code” button and copy the HTTPS or SSH URL.
- Open your terminal or Git Bash.
- Navigate to the directory where you want to clone the repository.
- Run the below command to clone the Repo.
git clone <paste the URL you copied>
- Wait for the cloning process to complete. Once it’s done, you should see a new directory with the name of the repository in the directory.
- To move into the cloned repository, use this command
cd <Name of the cloned Repo>
, then move to the voting folder use this commandcd Voting
.
Step 2: Developing Election Smart Contract
Below is the code for our smart contract. You can get it from here Election. sol.
Let’s run through our smart contract real quick 🏃
- Basic details about the election — This block of code would be storing basic details of each
Election
contract. Details includename
anddescription
.
- Storing candidate details — Candidate details would be stored in a mapping between an unsigned integer to the
Candidate
structure.Candidate
the structure would consist of data likeid
,name
(candidate's name), andvoteCount
(number of times they are voted).
- Storing details of voters who have already voted and the number of candidates —
voters
is a mapping between the address of the voter and a boolean. In Solidity, the default boolean value isfalse
, so if the returned value ofvoters(address)
isfalse
we can understand that the voters are voting for the first time in this election, and vice-versa fortrue
.
- Constructor call and adding candidates to the election — When a smart contract is deployed on a network, the first thing to be called is a
constructor()
function. Whatever we want to initialize in a smart contract, we do it inside theconstructor()
function. Like here, we will be adding a name, description, and candidates to the election. Here,addCandidate()
is a private function, so that, it cannot be called publicly. This function takesname
anddescription
as a single array named_nda
in the first argument and candidates' names as an array in the second argument.
- Voting candidates in an election — We made a
vote()
function. It takescandidateId
as an argument and increments the vote of the respective candidate. It requires two things, viz. voters should not have voted in the particular election by checking the boolean across thevoters
mapping andcandidateId
should be a valid one, i.e.0 <= candidateId < candiatesCount
.
MainContract.sol
MainContract.sol
is the main entry point of our e-voting DApp. It will maintain the number of election contracts deployed, and their address on the network and will also help in deploying them. We have also imported Election.sol
a contract, for using it in the MainContract.sol
.
- Here
electionId
is used for assigning IDs to each election that a user creates and is incremented for using it while creating the next election. Also,Elections
is a public mapping betweenelectionId
and the address of the deployed election contract.
- We have made a
createElection()
the function which will be used to deploy ourElection
smart contract. This function takesname
anddescription
as a single array named_nda
in the first argument and candidates’ names as an array in the second argument.
Here you can see that a new Election
contract is deployed on the network using the new
keyword. And the address for the deployed smart contract is stored in the Elections
mapping. Once the election contract is deployed successfully, electionId
is incremented.
Step 3: Getting up the infra needed to deploy and test our smart contract
3.1. Visit the BuildBear App (why BuildBear: Read article here).
3.2. Create your Private Testnet forking from the Ethereum Mainnet, feel free to fork any Chain.
3.3. Add your Private Testnet to your MetaMask wallet by using the “Add to Metamask” button:
3.4. Click on Open Faucet you will be redirected to Faucet Pages, and then Mint native Tokens to pay for gas for the transactions.
Step 4: Deploying the Smart Contract
For installing the necessary packages, please execute the following command: npm install
.
4.1 Update thehardhat.config.js
.
- Head to your Dashboard and click on “verify contract”.
- Copy the BuildBear and Etherscan objects, and update the
hardhat.config.js
file. - To deploy the
maincontract.sol
the smart contract runs the deploy command. This will run the deployment script indeploy/00_deploy_mainContract.js
and save the deployment details along with ABI and Contract address.
npx hardhat deploy
Click on the link provided in the terminal to see the Contract on Explore page.
WOOT WOOT 🎉 🎉
4.2. Creating an Election
The scripts for invoking the createElection function and verifying the Election contract have already been configured in the scripts/deployElectionContract.js
file, as demonstrated above. To execute the scripts, please run the following command.
npx hardhat run scripts/deployElectionContract.js
Our new election has been successfully deployed, and the contract has been verified. To view the contract on Explore, simply click on the link provided in the terminal. This will take you directly to the Contract page, where we can read and write directly from the contract.
4.3 Casting our Vote
Enter the candidate id to see the there name and Total votes cast to them.
Let’s move to the write the contract section and cast our vote.
Now if we go back to the read and check the total votes received by Candidate 1 it will be increased by 1.
We have successfully built an Election smart contract, deployed it, created an election, and cast our vote !!! 🎉🎉🎉
Share your project on Twitter and LinkedIn and tag BuildBear.
If you appreciate what we are doing, please follow us on Twitter, and LinkedIn and Join the Telegram group if you haven’t done yet.
And please give us a clap 👏 if you like our work.
About BuildBear:
BuildBear is a platform for testing dApps at scale, for teams. It provides users with their own private Testnet to test their smart contracts and dApps, which can be forked from any EVM chain. It also provides a Faucet, Explorer, and RPC for testing purposes.
BuildBear aims to build an ecosystem of tools for testing dApps at scale for the teams.
Read our past articles and keep learning :
- Learn how to Create, Deploy an NFT Smart Contract and Develop a Front End App in 15mins
- Learn how to create, Deploy a Soul Bound Token(SBT)
- Generate NFT with AI and Deploy the NFT smart contract, and the Front End App
- Learn, code, and deploy your own MultiSig Wallet
- Let’s understand Subscription NFTs and mint a few