From db50cdd311fb6d6dace4ce2097f94a22dc3fdb09 Mon Sep 17 00:00:00 2001 From: Daniel Liu <139250065@qq.com> Date: Thu, 28 Aug 2025 19:00:44 +0800 Subject: [PATCH] ethclient: add EstimateGasAt[Hash] functions #27508 (#1396) --- ethclient/ethclient.go | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/ethclient/ethclient.go b/ethclient/ethclient.go index e12c05c552..6ac93065aa 100644 --- a/ethclient/ethclient.go +++ b/ethclient/ethclient.go @@ -646,9 +646,13 @@ func (ec *Client) FeeHistory(ctx context.Context, blockCount uint64, lastBlock * } // EstimateGas tries to estimate the gas needed to execute a specific transaction based on -// the current pending state of the backend blockchain. There is no guarantee that this is -// the true gas limit requirement as other transactions may be added or removed by miners, -// but it should provide a basis for setting a reasonable default. +// the current state of the backend blockchain. There is no guarantee that this is the +// true gas limit requirement as other transactions may be added or removed by miners, but +// it should provide a basis for setting a reasonable default. +// +// Note that the state used by this method is implementation-defined by the remote RPC +// server, but it's reasonable to assume that it will either be the pending or latest +// state. func (ec *Client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error) { var hex hexutil.Uint64 err := ec.c.CallContext(ctx, &hex, "eth_estimateGas", toCallArg(msg)) @@ -658,6 +662,28 @@ func (ec *Client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64 return uint64(hex), nil } +// EstimateGasAtBlock is almost the same as EstimateGas except that it selects the block height +// instead of using the remote RPC's default state for gas estimation. +func (ec *Client) EstimateGasAtBlock(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) (uint64, error) { + var hex hexutil.Uint64 + err := ec.c.CallContext(ctx, &hex, "eth_estimateGas", toCallArg(msg), toBlockNumArg(blockNumber)) + if err != nil { + return 0, err + } + return uint64(hex), nil +} + +// EstimateGasAtBlockHash is almost the same as EstimateGas except that it selects the block +// hash instead of using the remote RPC's default state for gas estimation. +func (ec *Client) EstimateGasAtBlockHash(ctx context.Context, msg ethereum.CallMsg, blockHash common.Hash) (uint64, error) { + var hex hexutil.Uint64 + err := ec.c.CallContext(ctx, &hex, "eth_estimateGas", toCallArg(msg), rpc.BlockNumberOrHashWithHash(blockHash, false)) + if err != nil { + return 0, err + } + return uint64(hex), nil +} + // SendTransaction injects a signed transaction into the pending pool for execution. // // If the transaction was a contract creation use the TransactionReceipt method to get the