0
0
Blockchain / Solidityprogramming~5 mins

Gas usage testing in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Gas usage testing helps you see how much work your blockchain code needs. It shows how much it costs to run your code.

When you want to check if your smart contract is efficient.
Before deploying a contract to avoid high fees.
To compare different ways of writing the same function.
When optimizing your code to save money on transactions.
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
This example calls a function that sets a value and prints the gas used.
Blockchain / Solidity
const tx = await contract.setValue(42);
const receipt = await tx.wait();
console.log('Gas used:', receipt.gasUsed.toString());
This example measures gas for a token transfer function.
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;
});
OutputSuccess
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.