Accurately estimate gas costs for transactions to ensure reliable execution without overpaying.
Wagmi is not available on React Native. Use Ethers.js or Viem for EVM operations.
Estimate Gas for a Transaction
import { ethers } from "ethers";
async function estimateGas(
provider: ethers.Provider,
to: string,
value: string,
data?: string,
maxFeePerGas?: string,
maxPriorityFeePerGas?: string
) {
const tx = {
to,
value: ethers.parseEther(value),
data: data || "0x",
...(maxFeePerGas ? { maxFeePerGas: ethers.parseUnits(maxFeePerGas, "gwei") } : {}),
...(maxPriorityFeePerGas ? { maxPriorityFeePerGas: ethers.parseUnits(maxPriorityFeePerGas, "gwei") } : {})
};
const gasEstimate = await provider.estimateGas(tx);
return gasEstimate;
}
import { parseEther, parseGwei } from "viem";
async function estimateGas(
publicClient: PublicClient,
account: Account | `0x${string}`,
to: `0x${string}`,
value: string,
data?: `0x${string}`,
maxFeePerGas?: string,
maxPriorityFeePerGas?: string
) {
const gasEstimate = await publicClient.estimateGas({
account,
to,
value: parseEther(value),
data: data || "0x",
...(maxFeePerGas ? { maxFeePerGas: parseGwei(maxFeePerGas) } : {}),
...(maxPriorityFeePerGas ? { maxPriorityFeePerGas: parseGwei(maxPriorityFeePerGas) } : {})
});
return gasEstimate;
}
Next Steps