Socket
Socket
Sign inDemoInstall

hardhat-gas-optimizer

Package Overview
Dependencies
4
Maintainers
1
Versions
21
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    hardhat-gas-optimizer

Hardhat plugin for eth-gas-optimizer, a mocha optimizer for Ethereum test suites


Version published
Weekly downloads
0
decreased by-100%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

npm version Build Status Codechecks buidler

hardhat-gas-reporter

eth-gas-reporter plugin for hardhat.

What

A Mocha reporter for Ethereum test suites:

  • Gas usage per unit test.
  • Metrics for method calls and deployments.
  • National currency costs of deploying and using your contract system.

Example report

Screen Shot 2019-06-23 at 2 10 19 PM

Installation

npm install hardhat-gas-reporter --save-dev

And add the following to your hardhat.config.js:

require("hardhat-gas-reporter");

Or, if you are using TypeScript, add this to your hardhat.config.ts:

import "hardhat-gas-reporter"

Looking for buidler-gas-reporter docs? They moved here...

Configuration

Configuration is optional.

module.exports = {
  gasReporter: {
    currency: 'CHF',
    gasPrice: 21
  }
}

:bulb: Pro Tips

Turning the plugin on/off

The options include an enabled key that lets you toggle gas reporting on and off using shell environment variables. When enabled is false, mocha's (faster) default spec reporter is used. Example:

module.exports = {
  gasReporter: {
    enabled: (process.env.REPORT_GAS) ? true : false
  }
}

Migrating from Truffle

If you already have eth-gas-reporter installed in your project, make sure you uninstall it before adding this plugin. hardhat-gas-reporter manages eth-gas-reporter as a dependency and having multiple versions in your lockfile can stop the reporter from working correctly.

Usage

This plugin overrides the built-in test task. Gas reports are generated by default with:

npx hardhat test

Options

:warning: CoinMarketCap API change :warning:

Beginning March 2020, CoinMarketCap requires an API key to access currency market price data. The reporter uses an unprotected free tier key by default (10k reqs/mo). You can get your own API key here and set it with the coinmarketcap option.

In order to retrieve the gas price of a particular blockchain, you can configure the token and gasPriceApi (API key rate limit may apply).

NOTE: HardhatEVM and ganache-cli implement the Ethereum blockchain. To get accurate gas measurements for other chains you may need to run your tests against development clients developed specifically for those networks.

OptionTypeDefaultDescription
enabledBooleantrueAlways generate gas reports when running the hardhat test command.
currencyString'EUR'National currency to represent gas costs in. Exchange rates loaded at runtime from the coinmarketcap api. Available currency codes can be found here.
coinmarketcapString(unprotected API key)API key to use when fetching current market price data. (Use this if you stop seeing price data)
gasPriceNumber(varies)Denominated in gwei. Default is loaded at runtime from the eth gas station api
tokenString'ETH'The reference token for gas price
gasPriceApiStringEtherscanThe API endpoint to retrieve the gas price. Find below other networks.
outputFileStringstdoutFile path to write report output to
noColorsBooleanfalseSuppress report color. Useful if you are printing to file b/c terminal colorization corrupts the text.
onlyCalledMethodsBooleantrueOmit methods that are never called from report.
rstBooleanfalseOutput with a reStructured text code-block directive. Useful if you want to include report in RTD
rstTitleString""Title for reStructured text header (See Travis for example output)
showTimeSpentBooleanfalseShow the amount of time spent as well as the gas consumed
excludeContractsString[][]Contracts (or folders) to exclude from report. Ex: ['Migrations.sol', 'Wallets/']. (See v1.0.3 release notes for additional usage help)
srcString"contracts"Folder in root directory to begin search for .sol files. This can also be a path to a subfolder relative to the root, e.g. "planets/annares/contracts"
urlStringweb3.currentProvider.hostRPC client url (ex: "http://localhost:8545")
proxyResolverFunctionnoneCustom method to resolve identity of methods managed by a proxy contract.
artifactTypeFunction or String"truffle-v5"Compilation artifact format to consume. (See advanced use.)
showMethodSigBooleanfalseDisplay complete method signatures. Useful when you have overloaded methods you can't tell apart.
maxMethodDiffNumberundefinedCodechecks failure threshold, triggered when the % diff for any method is greater than number (integer)
maxDeploymentDiffNumberundefinedCodechecks failure threshold, triggered when the % diff for any deployment is greater than number (integer)
remoteContractsRemoteContract[][]Contracts pre-deployed to a (forked) network which the reporter should collect gas usage data for. (See RemoteContract type and usage example)
token and gasPriceApi options example
NetworktokengasPriceApi
Ethereum (default)ETHhttps://api.etherscan.io/api?module=proxy&action=eth_gasPrice
BinanceBNBhttps://api.bscscan.com/api?module=proxy&action=eth_gasPrice
PolygonMATIChttps://api.polygonscan.com/api?module=proxy&action=eth_gasPrice
AvalancheAVAXhttps://api.snowtrace.io/api?module=proxy&action=eth_gasPrice
HecoHThttps://api.hecoinfo.com/api?module=proxy&action=eth_gasPrice
MoonriverMOVRhttps://api-moonriver.moonscan.io/api?module=proxy&action=eth_gasPrice

These APIs have rate limits. Depending on the usage, it might require an API Key.

NB: Any gas price API call which returns a JSON-RPC response formatted like this is supported: {"jsonrpc":"2.0","id":73,"result":"0x6fc23ac00"}.

Documentation

Other useful documentation can be found at eth-gas-reporter

Parallelization

This plugin also adds a Hardhat Task for merging several gasReporterOutput.json files, which are generated by eth-gas-reporter when running your tests with in parallelized jobs in CI.

To use the task you just have to give it the filepaths or a glob pattern pointing to all of the reports:

npx hardhat gas-reporter:merge 'gasReporterOutput-*.json'

Here is an example config.yml file used by CircleCI to run the tests on parallel first, and then merge the reports

version: 2.1

jobs:
  test:
    docker:
      - image: circleci/node:14.15.1-stretch
    parallelism: 8
    steps:
      - attach_workspace:
          at: .
      - run:
          name: Run tests
          command: |
            circleci tests glob 'test/**/*.spec.ts' |
            circleci tests split |
            xargs npx hardhat test
      - run:
          name: Save gas report
          command: |
            mv gasReporterOutput.json ./gasReporterOutput-$CIRCLE_NODE_INDEX.json
      - persist_to_workspace:
          root: .
          paths:
            - gasReporterOutput-*.json
  test-gas-report:
    docker:
      - image: circleci/node:14.15.1-stretch
    steps:
      - checkout
      - attach_workspace:
          at: .
      - run:
          name: Upload gas reports
          command: |
            npx hardhat gas-reporter:merge gasReporterOutput-*.json
            npx codechecks codechecks.unit.yml
      - store_artifacts:
          path: gasReporterOutput.json

workflows:
  workflow-all:
    jobs:
      - test
      - test-gas-report:
          requires:
            - test

Keywords

FAQs

Last updated on 22 Dec 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc