Getting Started with Gas Profiling
Begin by creating a smart contract named Inventory
with the following configuration:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
contract Inventory {
address public manager;
uint256 public totalProducts;
struct Product {
uint256 id;
string description;
uint256 price;
}
mapping(uint256 => Product) public products;
constructor() {
manager = msg.sender;
}
function addProduct(string memory description, uint256 price) external {
require(msg.sender == manager, "invalid manager");
totalProducts++;
products[totalProducts] = Product(
totalProducts,
description,
price
);
}
}
Add a test file named Inventory.js
to evaluate the gas reporter plugin. This file should include the following content:
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe.only("Inventory tests", function () {
let instance;
let owner;
before(async () => {
const Inventory = await ethers.getContractFactory("Inventory");
instance = await Inventory.deploy();
await instance.waitForDeployment();
const signers = await ethers.getSigners();
owner = signers[0];
});
it("should add a product", async () => {
const description = "Laptop";
const price = ethers.parseEther("1.5");
await instance.addProduct(description, price);
expect(await instance.totalProducts()).to.equal(1);
});
it("should store product details correctly", async () => {
const description = "Mouse";
const price = ethers.parseEther("0.05");
await instance.addProduct(description, price);
const product = await instance.products(2);
expect(product.id).to.equal(2);
expect(product.description).to.equal(description);
expect(product.price).to.equal(price);
});
it("should only allow manager to add products", async () => {
const signers = await ethers.getSigners();
const nonManager = signers[1];
const description = "Keyboard";
const price = ethers.parseEther("0.1");
await expect(
instance.connect(nonManager).addProduct(description, price)
).to.be.revertedWith("invalid manager");
});
it("should verify manager is set correctly", async () => {
expect(await instance.manager()).to.equal(owner.address);
});
});
Run npx hardhat test
to execute the tests. A gas usage report will be generated as shown below:

PreviousConfiguring the Hardhat Gas Reporter PluginNextTypical Approaches to Reduce Contract Size and Gas Costs
Last updated