Skip to main content
Before sending a transaction, you can use the public client to estimate the gas fees. Some chains also support custom gas estimation methods. Here are examples of how to get a gas estimate using viem:

Estimate Gas Function

import { mainnet } from 'viem/chains';
import { toHex, parseEther } from 'viem';
import { dynamicClient } from './dynamicClient';

const estimateGas = async () => {
  const publicClient = await dynamicClient.viem.createPublicClient({
    chain: mainnet,
  });

  const estimate = await publicClient.estimateGas({
    from: dynamicClient.wallets.primary.address as `0x${string}`,
    to: '0x123' as `0x${string}`,
    value: toHex(parseEther('0.001')),
  })

  console.log(estimate);
}