diff options
author | Péter Szilágyi <peterke@gmail.com> | 2017-01-21 06:39:16 +0800 |
---|---|---|
committer | Felix Lange <fjl@users.noreply.github.com> | 2017-01-21 06:39:16 +0800 |
commit | 682875adff760a29a2bb0024190883e4b4dd5d72 (patch) | |
tree | 36507842d38b82731d222878cda7e977b2b82a3e /internal/ethapi/api.go | |
parent | 0126d014351bc4f58e2d7e6564a054fb80f87153 (diff) | |
download | go-tangerine-682875adff760a29a2bb0024190883e4b4dd5d72.tar.gz go-tangerine-682875adff760a29a2bb0024190883e4b4dd5d72.tar.zst go-tangerine-682875adff760a29a2bb0024190883e4b4dd5d72.zip |
accounts/abi/bind, internal/ethapi: binary search gas estimation (#3587)
Gas estimation currently mostly works, but can underestimate for more funky
refunds. This is because various ops (e.g. CALL) need more gas to run than they
actually consume (e.g. 2300 stipend that is refunded if not used). With more
intricate contract interplays, it becomes almost impossible to return a proper
value to the user.
This commit swaps out the simplistic gas estimation to a binary search approach,
honing in on the correct gas use. This does mean that gas estimation needs to
rerun the transaction log(max-price) times to measure whether it fails or not,
but it's a price paid by the transaction issuer, and it should be worth it to
support proper estimates.
Diffstat (limited to 'internal/ethapi/api.go')
-rw-r--r-- | internal/ethapi/api.go | 30 |
1 files changed, 28 insertions, 2 deletions
diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 4359181c8..925f547b6 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -559,8 +559,34 @@ func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr r // EstimateGas returns an estimate of the amount of gas needed to execute the given transaction. func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (*hexutil.Big, error) { - _, gas, err := s.doCall(ctx, args, rpc.PendingBlockNumber) - return (*hexutil.Big)(gas), err + // Binary search the gas requirement, as it may be higher than the amount used + var lo, hi uint64 + if (*big.Int)(&args.Gas).BitLen() > 0 { + hi = (*big.Int)(&args.Gas).Uint64() + } else { + // Retrieve the current pending block to act as the gas ceiling + block, err := s.b.BlockByNumber(ctx, rpc.PendingBlockNumber) + if err != nil { + return nil, err + } + hi = block.GasLimit().Uint64() + } + for lo+1 < hi { + // Take a guess at the gas, and check transaction validity + mid := (hi + lo) / 2 + (*big.Int)(&args.Gas).SetUint64(mid) + + _, gas, err := s.doCall(ctx, args, rpc.PendingBlockNumber) + + // If the transaction became invalid or used all the gas (failed), raise the gas limit + if err != nil || gas.Cmp((*big.Int)(&args.Gas)) == 0 { + lo = mid + continue + } + // Otherwise assume the transaction succeeded, lower the gas limit + hi = mid + } + return (*hexutil.Big)(new(big.Int).SetUint64(hi)), nil } // ExecutionResult groups all structured logs emitted by the EVM |