Skip to content

Gas Estimation

This guide demonstrates how to estimate gas using the wagmi library in a React component. Gas estimation is crucial for ensuring that a transaction has enough gas to be processed on the Celo network without running out of gas, which would result in a failed transaction.

Example Code

Below is a simple example of how to estimate gas:

tsx
import { useEstimateGas } from "wagmi";
import { formatUnits } from 'viem'

const Example = () => {
  const result = useEstimateGas();

  // If the gas estimation data is available,
  // format it to a readable unit; otherwise, default to "0".
  const gas = result.data ? formatUnits(result.data, 18) : "0";
  return <p>{gas}</p>;
};

Notes:

  • Ensure wagmi is correctly configured. Follow our quickstart guide to know how.
  • useEstimateGas: This is a hook provided by the wagmi library that helps in estimating the gas required for a transaction. It returns an object that includes the estimated gas amount.
  • formatUnits: This function is used to convert the gas amount from its raw format to a more human-readable format, typically in Ether units.
  • Error Handling: In a production environment, consider adding error handling to manage cases where gas estimation might fail or return unexpected results.

For a full example, visit the Wagmi documentation.