0
0
Blockchain / Solidityprogramming~30 mins

Checks-Effects-Interactions pattern in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Checks-Effects-Interactions Pattern in Solidity
📖 Scenario: You are building a simple Ethereum smart contract for a wallet that allows users to withdraw their funds safely.In blockchain programming, it is important to follow the Checks-Effects-Interactions pattern to avoid security issues like reentrancy attacks.
🎯 Goal: Learn how to implement the Checks-Effects-Interactions pattern in Solidity by creating a withdraw function that first checks conditions, then updates state, and finally interacts with external contracts.
📋 What You'll Learn
Create a mapping called balances to store user balances
Add a function deposit to allow users to add funds
Add a function withdraw that uses the Checks-Effects-Interactions pattern
Print the remaining balance after withdrawal
💡 Why This Matters
🌍 Real World
Smart contracts on Ethereum must be secure to protect users' funds. The Checks-Effects-Interactions pattern is a key security practice.
💼 Career
Blockchain developers use this pattern daily to write safe contracts that handle money and interact with other contracts.
Progress0 / 4 steps
1
Create the balances mapping and deposit function
Create a public mapping called balances that maps address to uint. Then write a public deposit function that increases the sender's balance by msg.value.
Blockchain / Solidity
Need a hint?

Use mapping(address => uint) public balances; to store balances.

The deposit function should be payable and add msg.value to balances[msg.sender].

2
Add a withdraw function with a check for sufficient balance
Add a public function called withdraw that takes a uint amount parameter. Inside, first check that balances[msg.sender] is at least amount using require.
Blockchain / Solidity
Need a hint?

Use require to check if the sender has enough balance before proceeding.

3
Apply the Effects step by updating the balance before interaction
Inside the withdraw function, after the require check, subtract amount from balances[msg.sender]. This is the Effects step.
Blockchain / Solidity
Need a hint?

Update the user's balance by subtracting the withdrawal amount before sending funds.

4
Complete the withdraw function with the interaction and print remaining balance
In the withdraw function, after updating the balance, send amount to msg.sender using payable(msg.sender).transfer(amount). Then add a print statement to output the remaining balance of msg.sender.
Blockchain / Solidity
Need a hint?

Use payable(msg.sender).transfer(amount) to send Ether.

Solidity cannot print to console, so use an event to show the remaining balance.