Guide 6: How to fetch gas prices & estimate gas costs

Use the Alchemy SDK to retrieve the current gas price and estimate gas costs on Ethereum.

The SDK Developer Challenge: What are we here for?

The SDK Developer Challenge is an opportunity to build and learn together, using daily guides to inspire and motivate you to supercharge your app with the SDK.

The SDK will be your secret weapon to help simplify your code so you can build faster.

As you build, submit your project to win prizes.

What could you win? Epic never-before seen Alchemy swag, and $500 in monthly Alchemy credit.

For all of the challenges, you will need to set up a free Alchemy account. This will give you access to the SDK, as well as a HUGE selection of web3 development tools.

Ok, let's go!

Guide 6: How to fetch gas prices & estimate gas costs

In this guide, we will assume that you already know how to:

  • Set up an Alchemy SDK instance in your local project and initialize it with your Alchemy API Key
  • Perform basic navigation of the command line
  • Make an API call to Alchemy
  • Show the results in your terminal

If you don't, head on back to Guide 2, How to get started on the Alchemy SDK.

Intro

As a web3 developer, there are two important gas-related functions you may need:

  1. Get the current gas price on Ethereum. You may need this if you are building an analytics dApp like ETH Gas Station or want to display current Ethereum gas prices.
  2. Estimate gas cost of an Ethereum transaction. You'll use this if you are looking to make transactions or contract deployments on mainnet and want to estimate how much you'll need to pay.

The Alchemy SDK allows you to easily fetch this gas-related data. Let's dive in! 🤿

Step 1: Import Code Snippet into Local Project

Assuming you have a local environment set up and an Alchemy API key ready, copy-paste the code snippets below:

Get the current gas price on Ethereum

Copy-paste the snippet below in order to get the current gas price on Ethereum in gwei units.

require('dotenv').config();
const { Alchemy, Network, Utils } = require('alchemy-sdk');

// Optional Config object, but defaults to demo api-key and eth-mainnet.
const settings = {
  apiKey: process.env.ALCHEMY_API_KEY,
  network: Network.ETH_MAINNET,
};

const alchemy = new Alchemy(settings);

async function getCurrentGas() {
  const currentGasInHex = await alchemy.core.getGasPrice();

  console.log(
    'The current gas cost on the network is: ' +
      Utils.formatUnits(currentGasInHex, 'gwei') +
      ' gwei'
  );
}

getCurrentGas();

Super simple - literally two lines of code!

Next up: estimating the gas cost of a transaction. ⬇️

Estimate gas cost of an Ethereum transaction

Copy-paste the snippet below in order to estimate gas cost of an Ethereum transaction in ether units.

require('dotenv').config();
const { Alchemy, Network, Utils } = require('alchemy-sdk');

// Optional Config object, but defaults to demo api-key and eth-mainnet.
const settings = {
  apiKey: process.env.ALCHEMY_API_KEY,
  network: Network.ETH_MAINNET,
};

const alchemy = new Alchemy(settings);

async function estimateGasOfTx() {
  const estimatedGasCostInHex = await alchemy.core.estimateGas({
    // Wrapped ETH address
    to: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
    // `function deposit() payable`
    data: '0xd0e30db0',
    // 1 ether
    value: Utils.parseEther('1.0'),
  });
  console.log(
    'The gas cost estimation for the above tx is: ' +
      Utils.formatUnits(estimatedGasCostInHex, 'ether') +
      ' ether'
  );
}

estimateGasOfTx();

The code snippet above does the following:

  1. It uses the alchemy.core namespace to access the estimateGas function, which is rigged to Alchemy's eth_estimateGas enhanced API.
  2. Estimates a simple transaction, by taking the to address to be the Wrapped Ether ERC-20 smart contract and passes in data. This data is simply the first 4 bytes of the hex encoding of what the calldata for the deposit() function on that contract would look like.
  3. The response is then shown in ether units by using Utils.formatEther from the Alchemy SDK.

Curious about learning how to manually calculate the calldata of a transaction? Sign up for Alchemy University to learn about these nitty-gritty details!

Step 2: Run Your Script!

Get the current gas price on Ethereum

  1. Run node getCurrentGas.js

Your terminal should output the following:

534

Gas price on Ethereum returned in gwei units.

Estimate gas cost of an Ethereum transaction

  1. Run node estimateGas.js

Your terminal should output the following:

658

The estimated gas cost of converting 1 ETH to 1 WETH in ether.

The response is then shown in ether units by using Utils.formatEther from the Alchemy SDK. All you need to do now is multiply this amount by the current cost of Ether in whatever fiat denomination you can think of. For example, using the amount above, 0.000000000000027938 ether multiplied by the current price of ETH in USD (as of 02/21) looks like this: 0.000000000000027938 x 1665 = $0.000000000046517.

Step 3: Customize Your Script!

There's not much to do to customize the script for getting the current gas price on Ethereum, unless you want to see the price in a different unit (ie, instead of gwei, check it out in wei).

There's quite a bit you can do to customize how you estimate transaction gas costs though! The code snippet above shows the estimated gas cost of a transaction that calls the Wrapped Ether smart contract's deposit() function - which in essence is the act of "wrapping" 1 ETH, since you simply get 1 WETH back by doing this!

But you for sure will have other transactions you'll need to estimate the gas cost of - go ahead and modify the script to account for those! As an extra challenge, can you estimate what the gas cost of a smart contract deployment would be by using the same base code above? You got this! 💪


ReadMe