Add padding to gas estimations

Adds a 20% buffer to gas estimations to reduce out-of-gas errors.
This commit is contained in:
Shane Bammel 2023-03-24 22:53:42 -05:00
parent 2d3f7c679e
commit 63fde364a1
3 changed files with 23 additions and 10 deletions

View File

@ -542,7 +542,7 @@ func testCallContractAtHash(t *testing.T, client *rpc.Client) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if gas != 21000 {
if gas != 25200 {
t.Fatalf("unexpected gas price: %v", gas)
}
block, err := ec.HeaderByNumber(context.Background(), big.NewInt(1))
@ -569,7 +569,7 @@ func testCallContract(t *testing.T, client *rpc.Client) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if gas != 21000 {
if gas != 25200 {
t.Fatalf("unexpected gas price: %v", gas)
}
// CallContract

View File

@ -141,7 +141,7 @@ func TestGraphQLBlockSerialization(t *testing.T) {
// should return `estimateGas` as decimal
{
body: `{"query": "{block{ estimateGas(data:{}) }}"}`,
want: `{"data":{"block":{"estimateGas":53000}}}`,
want: `{"data":{"block":{"estimateGas":63600}}}`,
code: 200,
},
// should return `status` as decimal

View File

@ -1094,6 +1094,8 @@ func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNr
} else {
feeCap = common.Big0
}
// Track the maximum gas based on the account's available funds and the txn feeCap.
var accountGasLimit uint64
// Recap the highest gas limit with account's available balance.
if feeCap.BitLen() != 0 {
state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
@ -1111,14 +1113,17 @@ func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNr
allowance := new(big.Int).Div(available, feeCap)
// If the allowance is larger than maximum uint64, skip checking
if allowance.IsUint64() && hi > allowance.Uint64() {
transfer := args.Value
if transfer == nil {
transfer = new(hexutil.Big)
if allowance.IsUint64() {
accountGasLimit = allowance.Uint64()
if hi > allowance.Uint64() {
transfer := args.Value
if transfer == nil {
transfer = new(hexutil.Big)
}
log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
"sent", transfer.ToInt(), "maxFeePerGas", feeCap, "fundable", allowance)
hi = allowance.Uint64()
}
log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
"sent", transfer.ToInt(), "maxFeePerGas", feeCap, "fundable", allowance)
hi = allowance.Uint64()
}
}
// Recap the highest gas allowance with specified gascap.
@ -1175,6 +1180,14 @@ func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNr
return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
}
}
// Adds a 20% pad to the estimated gas usage, not exceeding account gas limit
// to help mitigate gas underestimations
hi = hi + hi/5
if accountGasLimit != 0 && hi > accountGasLimit {
hi = accountGasLimit
}
return hexutil.Uint64(hi), nil
}