Estimate Contract Gas
Estimate gas for a contract write or deployment
Loading...
Estimate gas for a contract write or deployment
EstimateContractGas returns the estimated gas needed to execute a contract function call. Uses eth_estimateGas with ABI-encoded calldata. Use before sending a write transaction to set a gas limit or detect reverts.
import ( "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ChefBingbong/viem-go/actions/public")parsedABI, _ := abi.Parse(erc20ABI)
gas, err := public.EstimateContractGas(ctx, publicClient, public.EstimateContractGasParameters{ Account: &senderAddr, Address: common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), ABI: parsedABI, FunctionName: "transfer", Args: []any{recipient, amount}, Value: big.NewInt(0),})if err != nil { log.Fatal(err) // e.g. execution would revert}fmt.Printf("Estimated gas: %d", gas)*common.Addressnilcommon.Address*abi.ABIstring"transfer").[]anynil*big.Intnil*uint64 or BlockTag(uint64, error) — estimated gas units. On revert, returns an error.