The cheapest way to keep gas costs down is a test that fails when a function uses more gas than you allow. This post shows that test, then measures a real optimization with it so you can see how big the saving actually is. The numbers come from the example contracts here, run on Hardhat 2.29 with Solidity 0.8.28.
A function that costs too much gas
Here is a bonus payout that reads storage for every employee:
contract BonusOnChain {
mapping(address => uint256) public salary;
uint256 public bonusBps = 500; // 5%
function calculateBonus(address employee) public view returns (uint256) {
return (salary[employee] * bonusBps) / 10_000;
}
function distributeBonuses(address[] memory employees) external payable {
for (uint256 i = 0; i < employees.length; i++) {
(bool ok, ) = employees[i].call{value: calculateBonus(employees[i])}("");
require(ok, "transfer failed");
}
}
}
Every iteration reads two storage slots and then sends ETH. The loop grows with the number of employees, and so does the bill.
The change: pass the bonuses in
The caller computes the bonuses off-chain and passes them in, so the contract skips the storage reads:
contract BonusPrecomputed {
function distributeBonuses(
address[] calldata employees,
uint256[] calldata bonuses
) external payable {
require(employees.length == bonuses.length, "length mismatch");
for (uint256 i = 0; i < employees.length; i++) {
(bool ok, ) = employees[i].call{value: bonuses[i]}("");
require(ok, "transfer failed");
}
}
}
Two details matter here. First, this is not batching. It still makes one ETH transfer per employee, and that transfer is most of the cost. Second, I use call instead of Solidity’s transfer. transfer forwards a fixed 2300 gas, which breaks when the recipient is a contract wallet, and ConsenSys Diligence has advised against it since the 2019 gas repricing. call needs a reentrancy guard or the checks-effects-interactions pattern around it.
The change also shifts trust. The caller now supplies the amounts, so the function needs access control, which I left out to keep the example short.
If the number of recipients is unbounded, consider a pull payment instead: record what each person is owed and let them claim it. One recipient that reverts then can’t block everyone else’s payout. It costs more gas for the funder, since each credit writes a storage slot, but it removes the risk of a loop that can never finish.
How to test gas usage
The test sends one transaction and asserts that the gas used stays under a ceiling. In ethers v6, receipt.gasUsed is a bigint, so compare it with a bigint literal:
const { expect } = require('chai');
const { ethers } = require('hardhat');
describe('BonusPrecomputed', function () {
it('stays under the gas ceiling for 3 employees', async function () {
const [, a, b, c] = await ethers.getSigners();
const distributor = await ethers.deployContract('BonusPrecomputed');
const employees = [a.address, b.address, c.address];
const bonuses = [100n, 200n, 300n];
const tx = await distributor.distributeBonuses(employees, bonuses, {
value: 600n,
});
const receipt = await tx.wait();
expect(receipt.gasUsed).to.be.lessThan(70_000n); // measured plus headroom
});
});
Pick the ceiling from a measured run plus some headroom, not from a guess. My run of this test used about 54,000 gas, so 70,000 leaves room for small changes and still catches a large regression. When a later change pushes the function over the ceiling, the build goes red before deploy and you look at the diff while it’s still small.
Results
I ran both versions with 10 and 100 recipients, each paying fresh addresses so neither side got a discount from existing accounts:
| Scenario | Before (reads storage) | After (amounts passed in) | Savings |
|---|---|---|---|
| 10 employees | 405,878 gas | 378,486 gas | 6.7% |
| 100 employees | 3,840,125 gas | 3,583,620 gas | 6.6% |
The saving is real and small. About 25,000 gas of every payout goes to creating a new account, and none of the change touches that. This is why I measure before I rewrite. A change that looks like a big win in the code can move the bill by a few percent. The same applies to any gas claim you read, including a headline percentage with no measurement behind it.
Tools that help
- hardhat-gas-reporter, included in the Hardhat toolbox, prints gas per function after a test run when you set
gasReporter: { enabled: true }inhardhat.config.js. See the plugin repository. - Foundry has
forge test --gas-reportfor per-function gas andforge snapshotfor committing gas numbers to the repository, so a pull request diff shows the change. See getfoundry.sh.
Habits that keep gas under control
- Put gas assertions for your most-called functions in CI. The automated testing setup shows the workflow.
- Run a gas reporter regularly. It shows which functions are expensive before users do.
- Move calculations off-chain when the contract only needs the result, and measure the saving.
- Look at loops first. Anything that scales with user count is where the bill grows.
- Re-check gas after every upgrade. A new implementation can cost more than the old one, which I cover in testing smart contract upgrades.
Gas is also a budget line for the project, though a smaller one than most teams expect. See how much web3 testing costs. If you want help setting up gas checks on your contracts, see how I work with teams.