Gas usage testing helps you see how much work your blockchain code needs. It shows how much it costs to run your code.
Gas usage testing in Blockchain / Solidity
Introduction
Syntax
Blockchain / Solidity
Use a testing framework like Hardhat or Truffle. Call the function and check the gas used from the transaction receipt. Example in JavaScript: const tx = await contract.someFunction(); const receipt = await tx.wait(); console.log('Gas used:', receipt.gasUsed.toString());
You need to run tests on a local blockchain or testnet.
Gas used is shown as a number representing units of gas.
Examples
Blockchain / Solidity
const tx = await contract.setValue(42); const receipt = await tx.wait(); console.log('Gas used:', receipt.gasUsed.toString());
Blockchain / Solidity
const tx = await contract.transfer(receiver, amount); const receipt = await tx.wait(); console.log(`Transfer gas: ${receipt.gasUsed.toString()}`);
Sample Program
This program deploys a simple contract and calls a function to set a value. It then prints how much gas was used.
Blockchain / Solidity
// Sample Hardhat test for gas usage const { ethers } = require('hardhat'); async function main() { const Contract = await ethers.getContractFactory('SimpleStorage'); const contract = await Contract.deploy(); await contract.deployed(); const tx = await contract.setValue(123); const receipt = await tx.wait(); console.log('Gas used for setValue:', receipt.gasUsed.toString()); } main().catch((error) => { console.error(error); process.exitCode = 1; });
Important Notes
Gas usage depends on the complexity of the function and blockchain state.
Always test on a local or test network to avoid real costs.
Summary
Gas usage testing shows how much it costs to run smart contract functions.
It helps find cheaper and faster ways to write blockchain code.
Use transaction receipts to get gas used after calling functions.
Practice
1. What is the main purpose of gas usage testing in blockchain smart contracts?
easy
Solution
Step 1: Understand gas usage testing
Gas usage testing measures the amount of gas consumed by smart contract functions during execution.Step 2: Differentiate from other tests
It is not about syntax errors, logic correctness, or changing gas prices but about cost measurement.Final Answer:
To measure how much gas a function consumes when executed -> Option DQuick Check:
Gas usage testing = measure gas cost [OK]
Hint: Gas testing measures cost, not correctness or syntax [OK]
Common Mistakes:
- Confusing gas usage testing with syntax or logic testing
- Thinking gas usage testing changes gas prices
- Assuming gas usage testing verifies contract correctness
2. Which of the following is the correct way to get gas used from a transaction receipt in Solidity testing frameworks?
easy
Solution
Step 1: Identify the correct property for gas used
Transaction receipts have a property calledgasUsedthat shows the gas consumed.Step 2: Eliminate incorrect properties
gas_priceis gas price per unit,gasLimitis max gas allowed, andgasCostis not a standard property.Final Answer:
const gasUsed = receipt.gasUsed; -> Option AQuick Check:
Gas used = receipt.gasUsed [OK]
Hint: Gas used is in receipt.gasUsed property [OK]
Common Mistakes:
- Using gas_price instead of gasUsed
- Confusing gasLimit with gas used
- Trying to access non-existent gasCost property
3. Consider this JavaScript test snippet for a smart contract function:
What will this code output?
const receipt = await contract.methods.myFunction().send({ from: user });
console.log(receipt.gasUsed);What will this code output?
medium
Solution
Step 1: Understand what receipt.gasUsed represents
Thereceipt.gasUsedproperty contains the gas consumed by the transaction.Step 2: Confirm the code logs gas used
The code logsreceipt.gasUsed, so it outputs the gas used bymyFunction.Final Answer:
The amount of gas used by myFunction execution -> Option CQuick Check:
receipt.gasUsed logs gas used [OK]
Hint: receipt.gasUsed shows gas consumed by function call [OK]
Common Mistakes:
- Thinking gasUsed is gas price or block gas limit
- Expecting gasUsed to be undefined or cause error
- Confusing gasUsed with transaction cost in ether
4. You wrote this test code to measure gas usage:
What is the error here?
const receipt = await contract.methods.transfer(to, amount).send({ from: sender });
const gasUsed = receipt.gasPrice;
console.log(gasUsed);What is the error here?
medium
Solution
Step 1: Check property used for gas consumption
The code usesreceipt.gasPrice, which is gas price per unit, not gas used.Step 2: Identify correct property for gas used
The correct property to get gas consumed isreceipt.gasUsed.Final Answer:
Using receipt.gasPrice instead of receipt.gasUsed to get gas consumed -> Option AQuick Check:
Gas used = receipt.gasUsed, not gasPrice [OK]
Hint: Use receipt.gasUsed, not gasPrice, for gas consumption [OK]
Common Mistakes:
- Confusing gasPrice with gasUsed
- Omitting await causing promise issues
- Assuming send() returns something other than receipt
5. You want to compare gas usage of two smart contract functions,
What is a potential issue with this approach?
funcA and funcB, to find which is cheaper. You run:const receiptA = await contract.methods.funcA().send({ from: user });
const receiptB = await contract.methods.funcB().send({ from: user });
console.log(receiptA.gasUsed < receiptB.gasUsed ? 'funcA cheaper' : 'funcB cheaper');What is a potential issue with this approach?
hard
Solution
Step 1: Understand gas usage variability
Gas used depends on blockchain state and inputs; single runs may not reflect average cost.Step 2: Identify why single comparison can mislead
Different states or conditions can cause gas usage to fluctuate, so multiple tests or averaging is better.Final Answer:
Gas usage can vary due to blockchain state; single runs may mislead -> Option BQuick Check:
Gas varies by state; test multiple times [OK]
Hint: Gas varies; test multiple times for accurate comparison [OK]
Common Mistakes:
- Assuming gasUsed is fixed for all runs
- Adding gasPrice to gasUsed incorrectly
- Thinking gasUsed must convert to ether for comparison
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
