Introduction
Welcome to my 30 Days of Solidity Challenge hosted by Web3 Compass! ๐
Today, weโre starting simple but powerful: building a digital click counter smart contract. This beginner-friendly exercise will teach you how to store and modify data on-chain, the foundation of interactive blockchain applications.
By the end of this tutorial, youโll know how to:
- Declare and use state variables (
uint
) - Write functions to increment and decrement numbers
- Emit events for off-chain tracking
- Build your first interactive smart contract
Challenge: Build a Click Counter
Imagine a digital clicker: each time someone clicks a button (calls a function), the counter increases. Weโll create:
- A variable to store the number of clicks
- A function
click()
to increase the counter - A function
unclick()
to decrease the counter - An optional
reset()
function to set the counter back to zero
ClickCounter.sol
Hereโs a clean, professional implementation:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract ClickCounter {
uint256 private _count;
event Clicked(address indexed caller, uint256 newCount);
event Unclicked(address indexed caller, uint256 newCount);
event Reset(address indexed caller);
function getCount() external view returns (uint256) {
return _count;
}
function click() external {
_count += 1;
emit Clicked(msg.sender, _count);
}
function unclick() external {
require(_count > 0, "ClickCounter: count already zero");
_count -= 1;
emit Unclicked(msg.sender, _count);
}
function reset() external {
_count = 0;
emit Reset(msg.sender);
}
}
How It Works
-
_count
stores the current number of clicks -
click()
increments the counter -
unclick()
decrements the counter (but never below zero) -
reset()
sets the counter to 0 - Events allow front-end apps or dApps to track clicks in real-time
Next Steps
- Deploy on Ethereum testnets like Goerli or Sepolia
- Build a web interface using React + ethers.js to call
click()
- Add ownership control so only you can reset the counter
- Experiment with more interactive functions in Solidity
Learning Outcomes
- Master Solidity state variables (
uint
) - Write functions to modify state on-chain
- Understand events and their role in dApps
- Learn basic smart contract structure
๐ก This is your first step into building interactive blockchain apps. Each click on this contract is a step toward mastering Solidity!
Stay tuned for Day 2 of the challenge, where weโll explore more advanced interactive patterns in smart contracts.
Top comments (0)