0
0
Blockchain / Solidityprogramming~30 mins

Gas optimization with storage in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Gas Optimization with Storage in Solidity
📖 Scenario: You are building a simple smart contract on the Ethereum blockchain that stores user balances. Since storing data on the blockchain costs gas (real money), you want to optimize how you store and update these balances to save gas fees.
🎯 Goal: Create a Solidity contract that stores user balances efficiently by minimizing storage writes, and then display the final balances.
📋 What You'll Learn
Create a mapping called balances to store user addresses and their uint balances.
Create a uint variable called increment to hold the amount to add to each balance.
Write a function that loops through a list of addresses and adds increment to each balance using a local variable to minimize storage writes.
Print the final balances of all users.
💡 Why This Matters
🌍 Real World
Smart contracts on blockchains like Ethereum charge gas fees for storage operations. Optimizing how you read and write data can save users money and make your contract more efficient.
💼 Career
Blockchain developers must write gas-efficient code to build scalable and cost-effective decentralized applications.
Progress0 / 4 steps
1
DATA SETUP: Create the balances mapping
Create a public mapping called balances that maps address to uint. Initialize balances for three addresses: 0x1111111111111111111111111111111111111111 with 100, 0x2222222222222222222222222222222222222222 with 200, and 0x3333333333333333333333333333333333333333 with 300.
Blockchain / Solidity
Need a hint?

Use mapping(address => uint) public balances; and set initial values in the constructor.

2
CONFIGURATION: Add the increment variable
Add a public uint variable called increment and set it to 50.
Blockchain / Solidity
Need a hint?

Declare uint public increment = 50; inside the contract but outside the constructor.

3
CORE LOGIC: Optimize balance updates using a local variable
Write a public function called addIncrement that takes an array of addresses called users. For each user, load their balance into a local uint variable, add increment to it, then update the mapping once with the new balance.
Blockchain / Solidity
Need a hint?

Use a for loop over users, read balance into currentBalance, add increment, then write back.

4
OUTPUT: Display final balances after increment
Write a public view function called getBalances that takes an array of addresses called users and returns an array of uints with their balances. Then, after calling addIncrement with the three addresses, call getBalances with the same addresses and print the returned balances.
Blockchain / Solidity
Need a hint?

Create a getBalances function that returns an array of balances for given addresses.