0
0
Blockchain / Solidityprogramming~30 mins

Gas usage testing in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Gas usage testing
📖 Scenario: You are developing a simple smart contract on the Ethereum blockchain. You want to measure how much gas your contract uses when calling a function that stores a number.
🎯 Goal: Build a smart contract and write a test script that measures the gas used when calling a storeNumber function.
📋 What You'll Learn
Create a smart contract with a storeNumber function that saves a number.
Write a test script that calls storeNumber and measures gas used.
Print the gas used in the test output.
💡 Why This Matters
🌍 Real World
Measuring gas usage helps developers optimize smart contracts to save money and improve performance on blockchains like Ethereum.
💼 Career
Blockchain developers must understand gas costs to write efficient contracts and manage deployment and transaction expenses.
Progress0 / 4 steps
1
Create the smart contract
Create a Solidity contract named GasTest with a public uint256 variable called storedNumber and a function storeNumber that takes a uint256 parameter called num and sets storedNumber to num.
Blockchain / Solidity
Need a hint?

Define a contract with a public variable and a function that updates it.

2
Set up the test environment
In a JavaScript test file, import ethers from hardhat and declare a variable gasTest to hold the deployed contract instance.
Blockchain / Solidity
Need a hint?

Use require("hardhat") to import ethers and declare a variable for the contract.

3
Deploy the contract and call the function
Write an async function main that deploys GasTest using ethers.getContractFactory, assigns it to gasTest, then calls storeNumber(42) and waits for the transaction receipt.
Blockchain / Solidity
Need a hint?

Deploy the contract, then call the function and wait for the transaction receipt.

4
Print the gas used
Add a line in main to print the gas used by accessing receipt.gasUsed.toString() with console.log. Then call main() and catch errors to print them.
Blockchain / Solidity
Need a hint?

Use console.log to print the gas used from the receipt, then run main() with error handling.