0
0
Blockchain / Solidityprogramming~30 mins

Function modifiers in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Function Modifiers in Solidity
📖 Scenario: You are creating a simple smart contract for a shared piggy bank. Only the owner can add money or withdraw it. To keep things safe, you will use function modifiers to check who is calling the functions.
🎯 Goal: Build a Solidity contract that uses a modifier to restrict access to certain functions so only the owner can call them.
📋 What You'll Learn
Create a contract named PiggyBank
Add a state variable owner to store the address of the contract creator
Create a modifier named onlyOwner that allows function execution only if the caller is the owner
Use the onlyOwner modifier on deposit and withdraw functions
Add a balance state variable to track the piggy bank balance
Implement deposit and withdraw functions that update the balance
💡 Why This Matters
🌍 Real World
Function modifiers are used in smart contracts to control who can call certain functions, protecting assets and enforcing rules automatically.
💼 Career
Understanding function modifiers is essential for blockchain developers to write secure and maintainable smart contracts.
Progress0 / 4 steps
1
Create the PiggyBank contract and owner variable
Create a contract named PiggyBank and inside it, declare a public address variable called owner. Set owner to msg.sender inside the constructor.
Blockchain / Solidity
Need a hint?

The constructor runs once when the contract is created. Use msg.sender to get the creator's address.

2
Add the onlyOwner modifier
Inside the PiggyBank contract, create a modifier named onlyOwner that uses require(msg.sender == owner) to allow function execution only if the caller is the owner. Use _; to continue function execution.
Blockchain / Solidity
Need a hint?

A modifier lets you add checks before running a function. Use require to stop if the caller is not the owner.

3
Add balance variable and deposit function with onlyOwner modifier
Add a public unsigned integer variable called balance to track the piggy bank balance. Then create a public function deposit that takes a uint amount parameter. Use the onlyOwner modifier on deposit. Inside the function, add amount to balance.
Blockchain / Solidity
Need a hint?

Use uint for numbers without decimals. The onlyOwner modifier goes after the function visibility.

4
Add withdraw function with onlyOwner modifier and print balance
Add a public function withdraw that takes a uint amount parameter. Use the onlyOwner modifier on withdraw. Inside the function, subtract amount from balance only if balance is greater or equal to amount using require. Then add a public view function getBalance that returns the current balance.
Blockchain / Solidity
Need a hint?

Use require to check if there is enough balance before withdrawing. The view keyword means the function does not change state.