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:

Setup

import { FC } from 'react';

import { parseEther, toHex } from 'viem';

import { useDynamicContext } from '@dynamic-labs/sdk-react-core';
import { isEthereumWallet } from '@dynamic-labs/ethereum-core';

export const EVMEstimateGas: FC = () => {
  const toAddress = '0x0000000000000000000000000000000000000000';
  const amount = '0.001';

  const { primaryWallet } = useDynamicContext();

  if (!primaryWallet || !isEthereumWallet(primaryWallet)) {
    return (
      <div>EVM Wallet not found</div>
    );
  }
  
  const estimateGas = async () => {
    // See [Estimate Gas Function]
  }

  return (
    <div>
      <button onClick={estimateGas}>Estimate Gas</button>
    </div>
  )
};

Estimate Gas Function

const estimateGas = async () => {
  const client = await primaryWallet.getPublicClient();

  if (!client) {
    console.error('Failed to get wallet client');
    return;
  }

  const estimate = await client.transport.request({
    method: 'eth_estimateGas',
    params: [
      {
        from: primaryWallet.address as `0x${string}`,
        to: toAddress as `0x${string}`,
        value: toHex(parseEther(amount)),
      },
    ],
  });

  // On success, the estimate will be a hex string
  console.log(estimate);
}