0
0
Blockchain / Solidityprogramming~30 mins

Why gas efficiency saves money in Blockchain / Solidity - See It in Action

Choose your learning style9 modes available
Why Gas Efficiency Saves Money
📖 Scenario: You are building a simple smart contract to understand how gas efficiency affects the cost of running blockchain transactions. Gas is the fee paid to execute operations on the blockchain. The less gas your contract uses, the less money you spend.
🎯 Goal: Create a smart contract that stores and updates a number. Then, calculate the gas used for updating the number and see how reducing operations saves gas and money.
📋 What You'll Learn
Create a smart contract with a state variable called storedNumber initialized to 0
Add a function called updateNumber that sets storedNumber to a new value
Add a helper variable called gasUsed to simulate gas consumption
Implement two versions of updateNumber: one with extra unnecessary steps and one optimized
Print the gas used by both versions to compare savings
💡 Why This Matters
🌍 Real World
Blockchain developers must write efficient smart contracts to save users money on transaction fees.
💼 Career
Understanding gas efficiency is essential for blockchain engineers, smart contract developers, and anyone working with decentralized applications.
Progress0 / 4 steps
1
Create the smart contract with a state variable
Create a Solidity contract called GasDemo with a public uint state variable named storedNumber initialized to 0.
Blockchain / Solidity
Need a hint?

Use uint public storedNumber = 0; inside the contract.

2
Add a helper variable to track gas used
Inside the GasDemo contract, add a public uint variable called gasUsed initialized to 0.
Blockchain / Solidity
Need a hint?

Declare uint public gasUsed = 0; inside the contract.

3
Add two versions of updateNumber function
Add two public functions inside GasDemo: updateNumberInefficient(uint newValue) and updateNumberEfficient(uint newValue). In updateNumberInefficient, set storedNumber to newValue and increment gasUsed by 15 units to simulate inefficiency. In updateNumberEfficient, set storedNumber to newValue and increment gasUsed by 5 units to simulate efficiency.
Blockchain / Solidity
Need a hint?

Define both functions with the exact names and update storedNumber and gasUsed as described.

4
Print gas used after calling both functions
Write a public view function called getGasUsedDifference that returns the difference in gas used between calling updateNumberInefficient and updateNumberEfficient. For simplicity, simulate calling both functions with newValue 10 and 20 respectively inside the function and return the difference 10 (which is 15 - 5). Then, write a print statement in comments showing the output 10.
Blockchain / Solidity
Need a hint?

Return the fixed difference 10 in the function as a simple simulation.