How I built a simple counter Dapp: Coding the smart contract + Building the front end (for the first time…)
Note: I’ve also made a Youtube video explaining how I built the Dapp. Feel free to check it out!
In a world where contracts were paper and lawyers were, well, mostly human, a brave soul decided it was time to mix things up.
Nick Szabo, in 1994, swapped ink for pixels and turned legalese (lawyer-language) into code.
Enter, SMART CONTRACTS!
Smarts contracts are, basically, ‘law written in code’.
Before we jump into how I built my own smart contract, let’s dig deep into the details of what they really are!
❗SPOILER ALERT: No lawyers were harmed in the making of my smart contract.❗
What is a smart contract?
A smart contract is a computer program that executes itself automatically on a blockchain network when certain predefined conditions/criteria are met, without the involvement of third parties.
They are IRREVERSIBLE once deployed. This is arguably one of the most 🔑 features of smart contracts since it eliminates almost all possibilities of a breach in contract.
Billions of dollars are lost each year due to breaches in contract (its faced by everyone — farmers, mom-and-pop shop owners, mid-market companies, corporate giants)
If transactions involved in these contracts were written in code as a self-executing smart contract, such events would have been highly improbable.
Those billions of $ could have been saved.
This. Is. The. Power. Of. Smart. Contracts.
They allow for trusted transactions/agreements to be carried out among anonymous parties without the need for a central authority or legal system.
How do smart contracts work?
Smart contracts function on an ‘if/when-then’ basis:
“If/when event x happens, then execute action y.”
There can be multiple conditions to be met within one contract, and multiple contracts can be embedded into an application to support an interconnected set of processes.
An example of how smart contracts would work in a borrowing-lending scenario is:
- Term 1: If the user deposits collateral into the smart contract, then they can receive a loan that’s ≤50% of the value of their collateral.
- Term 2: If the user’s collateralization ratio (collateral/remaining loan value) drops below 200%, then the user’s collateral is automatically transferred to the lender.
Possible limitations of smart contracts?
- Immutability - This is one of the biggest advantages yet drawbacks of smart contracts. The fact that they are unalterable also means that they cannot be upgraded for new features, functionality, bug fixes, or expansions.
- Reliability - While smart contracts do not rely on any third party or legal authority after it has been deployed and integrated into an application, it of course has to rely on its programmer to ensure the code addresses the terms of the contract.
- Attacks - Yes, unfortunately, in spite of being deemed ‘trustless’, smart contracts do stand a risk of being attacked. Common forms are through reentrancy attacks (withdrawal of resources repeatedly without waiting for verification), Denial of Service or DoS, force-feeding attacks etc.
Okay, so you know what smart contracts are and how they work. Now, I’ll show you what i built😎
My simple Counter Dapp💱
Essentially, the whole process of building a counter Dapp involves 3 steps:
1. Creating the counter smart contract📑
2. Deploying the smart contract🚀
3. Building the front end to interact with the blockchain💻
Okay, so lets get to the technical-not-technical* part now
*technical concepts explained not-so-technically
Step 1: Creating the counter smart contract
There are multiple languages that can be used to code smart contracts such as Solidity, Vyper, Rust, C++, Golang etc, and I’ve used Solidity for mine.
I wrote my code on VS Code and used Forge as the development environment.
As you can see above, I first opened my Windows Terminal and ran `npx thirdweb create contract`, which created the the smart contract.
I named my contract ‘SimpleCounter’.
Then, I opened VS Code, added the project to my workspace, and began coding my actual contract.
Let me now explain what each part of my contract looks like and means👩💻
First, I set two simple variables ‘uint256’ and ‘address’ and kept them both as ‘public’.
Next, I wrote the ‘constructor’ function. This function gets called only once at the time of the deployment of the contract. Under it, I set:
counter = 0 (The value of the counter at the start will be zero)
owner = msg.sender (Whoever deploys the contract, i.e msg.sender, will be the owner)
Then, I wrote the ‘modifier’ function, which requires that the ‘msg.sender’ should be equal to the ‘owner’, or else, “Only owner can call this function” will be displayed.
Now, lets come to the parts of the contract which are callable publicly👨👨👧👧
I’ve added 2 functions that are callable publicly:
- increment - The value of the counter can be increased to > 0.
- decrement - The value of the counter can be decreased, however the value after decreasing cannot be negative, i.e. <0.
I’ve also added the ‘reset’ function (the value of the counter can be reset back to 0), but it is callable only by the owner.
Finally, I added the function ‘getCounter’ which makes the counter visible/viewable publicly.
So, in short, what does my contract do?
It is a basic Ethereum contract written in Solidity called “SimpleCounter.” It features a counter, which a Web3 wallet can be connected to, and it can be incremented, decremented (with a check to prevent negative values), and reset to zero (only callable by owner).
Wohoo, thats all for Part 1! 🎉
Step 2: Deploying the smart contract
I deployed my contract on the Mumbai network (other networks include Ethereum Mainnet, Goerli, Polygon Mainnet etc.)
To do so, once I made the contract, I opened a new terminal in VS Code and ran ‘npx thirdweb deploy mumbai’.
I connected it to my wallet, and that successfully deployed my contract!
Step 3: Building the front end to interact with the blockchain
Now, that I’d built and deployed my contract, I had to built something through which I could interact with the contract.
That’s what a front end does.
To build the Dapp, I ran ‘npx thirdweb create app’ my Windows Terminal and named my project ‘counterapp’.
After this, a set of files are /installedcreated, and a ‘CLIENT ID’ is required in the file .env.example (later renamed to .env):-
For this, I created a new API key (an identifier to connect to or perform an API call) on my smart contract’s thirdweb dashboard, under ‘Settings’.
Every API key has a unique client ID attached to it.
Next, I added some styling to make the front end look nicer (“aesthetics ya see”😎)
*some snippets from my Home.module.css file under the ‘Styles’ folder*
Now, lets get to the core piece of code behind the Dapp: The index.tsx file
Importing statements and constants:
I imported Web3Button
, ConnectWallet
,CONTRACT_ADDRESS
and a couple of other statements from different libraries.
Then, I defined constants like Home, address and contract.
Heading and Counter Display:
Under the main container, I had added the ConnectWallet
button.
As my h1 or main heading, I had ‘Counter Dapp’.
According to the code, if isCounterLoading
is true, it shows "0"; otherwise, it displays the actual counter value obtained from counter.toNumber()
.
Buttons to increment and decrement:
These buttons use the Web3Button
component, and they increase or decrease the value of the counter when clicked (The value of the counter will only decrease if it already >0, or else it will show “error”.
Button to reset:
A “Reset” button is displayed if there is an address (i.e. the user is connected) and the address matches the owner’s address.
The last part of the code checks if the connected wallet address matches the owner’s wallet address and displays different messages accordingly.
AND ITS DONE!
THAT, IS HOW I MADE A SIMPLE COUNTER DAPP.
*My personal remarks: What it was like to learn Solidity👩💻 and build a Dapp💱 for the first time*
Okay, diving into Solidity for the first time was both challenging and exhilarating.
From going into myriad internet rabbit holes🐰 on smart contracts to sitting for hours trying to debug my code — it was tough, but undeniably rewarding💪.
This was just, of course, my stepping stone.
I will keep expanding my horizons and building in the realm of blockchain and web3, until I achieve my ultimate goal —
impacting billions🌎 with revolutionary tech.