eth_estimateGas | Ethereum

Recipes
📄
How to encode callData parameters to programmatically interact with a smart contract
Open Recipe
💻
How to convert decimal numbers to hexadecimals strings using web3.js and ethers.js
Open Recipe
⚖️
How to transfer the entire account balance using web3.js
Open Recipe

Ethereum API method that returns an estimate of gas units needed for a given transaction.

It provides an estimate of the maximum amount of gas units required to complete the transaction based on the network's current state and the transaction's parameters. A client or wallet can use this estimate to determine the appropriate amount of gas to include in a transaction to ensure that the network processes it.

👍

Get you own node endpoint today

Start for free and get your app to production levels immediately. No credit card required.

You can sign up with your GitHub, X, Google, or Microsoft account.

Parameters

  • object — the transaction call object, same as in eth_call; the from field is optional, and the nonce field is omitted:

    • from — (optional) the string of the address used to send the transaction.
    • to — the string of the address to which the transaction is directed, a wallet, or a smart contract.
    • gas — (optional) the maximum amount of gas that can be used by the transaction.
    • gasprice — (optional) the amount of gas price the sender is willing to pay for each gas unit in Wei.
    • value — (optional) the value sent with this transaction, encoded as hexadecimal.
    • data — (optional) additional data to be sent with the call, usually used to invoke functions from smart contracts as a string of the hash of the method signature and encoded parameters; see the Ethereum Contract ABI.
  • quantity or tag — the integer of a block encoded as hexadecimal or the string with:

    • latest — the most recent block in the blockchain and the current state of the blockchain at the most recent block. A chain reorganization is to be expected.

    • safe — the block that received justification from the beacon chain. Although this block could be involved in a chain reorganization, it would necessitate either a coordinated attack by the majority of validators or an instance of severe propagation latency.

    • finalized — the block accepted as canonical by more than 2/3 of the validators. A chain reorganization is extremely unlikely, and it would require at least 1/3 of the staked ETH to be burned.

    • earliest — the earliest available or genesis block

    • pending — the pending state and transactions block. The current state of transactions that have been broadcast to the network but have not yet been included in a block.

      📘

      See the default block parameter and How The Merge Impacts Ethereum’s Application Layer.

Response

  • quantity — the estimated amount of gas units needed, represented as a hexadecimal string.

eth_estimateGas code examples

📘

Learn more about the ChainstackProvider in ethers.js: ethers ChainstackProvider Documentation.

const ethers = require("ethers");

// Create a ChainstackProvider instance for Ethereum mainnet
const chainstack = new ethers.ChainstackProvider("mainnet");

const estimateGas = async () => {
  // The transaction to estimate is a simple transfer in this example.
  const transactionObj = {
    from: "0xCb6Ed7E78d27FDff28127F9CbD61d861F09a2324",
    to: "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8",
  };

  const gasUnits = await chainstack.estimateGas(transactionObj);
  console.log(`Estimated gas units required: ${gasUnits}`);
};

estimateGas();

const { Web3 } = require("web3");
const NODE_URL = "CHAINSTACK_NODE_URL";
const web3 = new Web3(NODE_URL);

async function estimateGas() {
	// The transaction to estimate is a simple transfer in this example.
  const transactionObj = {
    from: "0xCb6Ed7E78d27FDff28127F9CbD61d861F09a2324",
    to: "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8",
  }

  const gasUnits = await web3.eth.estimateGas(transactionObj);
  console.log(`Estimated gas units required: ${gasUnits}`);
}

estimateGas()
from web3 import Web3  
node_url = "CHAINSTACK_NODE_URL"

web3 = Web3(Web3.HTTPProvider(node_url)) 
print(web3.eth.estimate_gas({"from":"0xCb6Ed7E78d27FDff28127F9CbD61d861F09a2324","to":"0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"}, "latest" ))  

Use case

A practical use case for eth_estimateGas is to calculate the gas cost required for a transaction that transfers a value from one Ethereum address (fromAddress) to another (toAddress). The gas cost is an important factor in transactions, as it determines the amount of fees that need to be paid by the sender to the network for processing the transaction.

const { Web3 } = require("web3");
const NODE_URL = "CHAINSTACK_NODE_URL";
const web3 = new Web3(NODE_URL);

async function estimateGasCost(from, to, value) {
    try {
      const gasEstimate = await web3.eth.estimateGas({ from: from, to: to, value: value });
      return gasEstimate
    } catch (error) {
      console.error(`Error estimating gas cost: ${error}`);
    }
  }
  
  async function main() {
  
    const fromAddress = '0xae2Fc483527B8EF99EB5D9B44875F005ba1FaE13';
    const toAddress = '0x81ab6Fd4A68d0aDDFAD65F9F97Bc1427dCd40C8E';
    const value = web3.utils.toWei("25", "ether" )

    const estimatedGas= await estimateGasCost(fromAddress, toAddress, value)
    if (estimatedGas) {
      console.log(`Estimated gas cost: ${estimatedGas}`);
    }
  }
  
  main()

The estimateGasCost function wraps the call to eth.estimateGas in a try-catch block so that any errors that occur during the estimation process can be handled gracefully. If an error occurs, the error message is logged to the console. If the estimate is successful, the estimated gas cost is returned.

The main function is the entry point of the code. It sets the fromAddress, toAddress, and value for the transaction, and then calls the estimateGasCost function to get the estimated gas cost. The estimated gas cost is logged to the console if the estimate is successful, but it is available to be used for further processing in the estimatedGas constant.

Try the eth_estimateGas RPC method yourself

Language
Click Try It! to start a request and see the response here!