DEV Community

Rushank Savant
Rushank Savant

Posted on

Using eth-gas-reporter

A good smart contract is the one which is gas-optimized and not-vulnerable to attacks.
And there are some tools which help us analyze these aspects before deploying contract to production.
(I have made a series of blogs on Gas Optimization techniques and Security Vulnerabilities if you are interested)

In this blog, we will see how to use eth-gas-provider to get report of gas-consumption and gas-price for deployment and function calls of the contract.
If reading bores you, head over to my GitHub repo and follow along the steps.

So let's begin:

  • Install hardhat if you haven't done already:

npm install --save-dev hardhat

  • Create a sample hardhat project:

npx hardhat

This will create a Greeter.sol in contracts directory along with some other files and directories.

  • Installing dependencies:

npm i hardhat-gas-reporter

npm i dotenv

  • create a .env file(in main directory) as follows:
coinMarketCap_API= //get your api-key at https://coinmarketcap.com/api/pricing/
REPORT_GAS= true // set to false when you don't want gas-report
Enter fullscreen mode Exit fullscreen mode
  • Now goto hardhat.config.js file, and replace the content in it with the following:
require("@nomiclabs/hardhat-waffle");
require("hardhat-gas-reporter");
const dotenv = require("dotenv");
dotenv.config();

module.exports = {
  solidity: "0.8.4",
  gasReporter: {
    enabled: (process.env.REPORT_GAS) ? true : false, // will give report if REPORT_GAS environment variable is true
    currency: 'USD', // can be set to ETH and other currencies (see coinmarketcap api documentation)
    coinmarketcap: process.env.coinMarketCap_API // to fetch prices from coinmarketcap api
  }
};
Enter fullscreen mode Exit fullscreen mode
  • And finally, use the following command to compile, test, and get gas-report for the sample contract:

npx hardhat test

Output:

You can expect a similar output as follows:

Output

The usd (avg) might vary, based on price of ETH and current gas price. The Avg shows the gas consumption for function call and contract deployment.

Top comments (1)

Collapse
 
oscarjons456 profile image
Oscar James

XNX by Honeywell Analytics is a flagship gas detection solution renowned for its reliability, versatility, and innovation in safeguarding industrial environments. Offering a comprehensive array of gas detection options, XNX stands as a pinnacle in ensuring safety across various industries. Its modular design allows for seamless integration with a wide range of sensor types, catering to diverse gas detection needs. xnxxnxhoneywellanalytics.com/