From c2611ebb2806ad6a6bdba1fd6ddd8e258bb8e265 Mon Sep 17 00:00:00 2001 From: Dimitris Date: Fri, 20 Nov 2026 16:06:35 +0200 Subject: [PATCH 1/5] Update Arbitrum estimator to enable PGA --- pkg/config/chaintype/chaintype.go | 3 +- pkg/gas/arbitrum_estimator.go | 71 ++++++-- pkg/gas/arbitrum_estimator_test.go | 240 ++++++++++++++++++++++++-- pkg/gas/fee_history_estimator.go | 20 ++- pkg/gas/fee_history_estimator_test.go | 99 +++++++---- pkg/gas/models.go | 38 ++-- 6 files changed, 388 insertions(+), 83 deletions(-) diff --git a/pkg/config/chaintype/chaintype.go b/pkg/config/chaintype/chaintype.go index a368103856..01ba20e0ff 100644 --- a/pkg/config/chaintype/chaintype.go +++ b/pkg/config/chaintype/chaintype.go @@ -32,7 +32,8 @@ const ( // IsL2 returns true if this chain is a Layer 2 chain. Notably: // - the block numbers used for log searching are different from calling block.number -// - gas bumping is not supported, since there is no tx mempool +// - L2-specific fee errors (fee too low, fee too high, sequencer queue full) are classified as +// FeeOutOfValidRange, so the transaction is re-estimated and resent instead of failing func (c ChainType) IsL2() bool { switch c { case ChainArbitrum, ChainMetis: diff --git a/pkg/gas/arbitrum_estimator.go b/pkg/gas/arbitrum_estimator.go index 526ca7c8e1..d522572411 100644 --- a/pkg/gas/arbitrum_estimator.go +++ b/pkg/gas/arbitrum_estimator.go @@ -3,6 +3,7 @@ package gas import ( "context" "fmt" + "math/big" "slices" "sync" "time" @@ -15,6 +16,7 @@ import ( "github.com/smartcontractkit/chainlink-framework/chains/fees" "github.com/smartcontractkit/chainlink-evm/pkg/assets" + evmconfig "github.com/smartcontractkit/chainlink-evm/pkg/config" "github.com/smartcontractkit/chainlink-evm/pkg/config/chaintype" "github.com/smartcontractkit/chainlink-evm/pkg/gas/rollups" ) @@ -23,14 +25,23 @@ type ArbConfig interface { LimitMax() uint64 BumpPercent() uint16 BumpMin() *assets.Wei + EIP1559DynamicFees() bool + FeeHistory() evmconfig.FeeHistory + BlockHistory() evmconfig.BlockHistory } -// arbitrumEstimator is an Estimator which extends SuggestedPriceEstimator to use getPricesInArbGas() for gas limit estimation. +// arbitrumEstimator wraps a price estimator and uses getPricesInArbGas() to add the L1 calldata cost to the gas limit. +// Prices are delegated to the wrapped estimator: +// - SuggestedPriceEstimator for legacy transactions, on chains that process transactions in FIFO order. +// - FeeHistoryEstimator for dynamic fee transactions, on chains that order transactions by priority fee. +// +// For legacy transactions the gas limit is adjusted in GetLegacyGas. For dynamic fee transactions GetDynamicFee doesn't +// return a gas limit, so evmFeeEstimator applies gasLimitWithL1Cost directly. type arbitrumEstimator struct { services.StateMachine cfg ArbConfig - EvmEstimator // *SuggestedPriceEstimator + EvmEstimator // *SuggestedPriceEstimator or *FeeHistoryEstimator pollPeriod time.Duration logger logger.Logger @@ -49,12 +60,29 @@ type arbitrumEstimator struct { const arbitrumPollPeriod = 2 * time.Second -func NewArbitrumEstimator(lggr logger.Logger, cfg ArbConfig, ethClient FeeEstimatorClient, l1Oracle rollups.ArbL1GasOracle) EvmEstimator { +// NewArbitrumEstimator returns an estimator that adds the L1 calldata cost to the gas limit. Pricing is delegated to +// FeeHistoryEstimator if EIP1559DynamicFees is enabled, or to SuggestedPriceEstimator otherwise. Both are created with +// the Arbitrum chain type, as the Arbitrum estimator implies Arbitrum's pricing semantics. +func NewArbitrumEstimator(lggr logger.Logger, cfg ArbConfig, ethClient FeeEstimatorClient, chainID *big.Int, l1Oracle rollups.ArbL1GasOracle) EvmEstimator { lggr = logger.Named(lggr, "ArbitrumEstimator") + var priceEstimator EvmEstimator + if cfg.EIP1559DynamicFees() { + fhCfg := FeeHistoryEstimatorConfig{ + BumpPercent: cfg.BumpPercent(), + CacheTimeout: cfg.FeeHistory().CacheTimeout(), + EIP1559: cfg.EIP1559DynamicFees(), + BlockHistorySize: uint64(cfg.BlockHistory().BlockHistorySize()), + RewardPercentile: float64(cfg.BlockHistory().TransactionPercentile()), + } + priceEstimator = NewFeeHistoryEstimator(lggr, ethClient, fhCfg, chainID, chaintype.ChainArbitrum, l1Oracle) + } else { + priceEstimator = NewSuggestedPriceEstimator(lggr, ethClient, cfg, chaintype.ChainArbitrum, l1Oracle) + } + return &arbitrumEstimator{ cfg: cfg, - EvmEstimator: NewSuggestedPriceEstimator(lggr, ethClient, cfg, chaintype.ChainArbitrum, l1Oracle), + EvmEstimator: priceEstimator, pollPeriod: arbitrumPollPeriod, logger: lggr, chForceRefetch: make(chan (chan struct{})), @@ -97,16 +125,23 @@ func (a *arbitrumEstimator) HealthReport() map[string]error { } // GetLegacyGas estimates both the gas price and the gas limit. -// - Price is delegated to the embedded SuggestedPriceEstimator. -// - Limit is computed from the dynamic values perL2Tx and perL1CalldataUnit, provided by the getPricesInArbGas() method -// of the precompile contract at ArbGasInfoAddress. perL2Tx is a constant amount of gas, and perL1CalldataUnit is -// multiplied by the length of the tx calldata. The sum of these two values plus the original l2GasLimit is returned. +// - Price is delegated to the wrapped estimator, with a buffer added on top (see gasPriceWithBuffer). +// - Limit is l2GasLimit plus the L1 calldata cost (see gasLimitWithL1Cost). func (a *arbitrumEstimator) GetLegacyGas(ctx context.Context, calldata []byte, l2GasLimit uint64, maxGasPriceWei *assets.Wei, opts ...fees.Opt) (gasPrice *assets.Wei, chainSpecificGasLimit uint64, err error) { gasPrice, _, err = a.EvmEstimator.GetLegacyGas(ctx, calldata, l2GasLimit, maxGasPriceWei, opts...) if err != nil { return } gasPrice = a.gasPriceWithBuffer(gasPrice, maxGasPriceWei) + chainSpecificGasLimit, err = a.gasLimitWithL1Cost(ctx, calldata, l2GasLimit, opts...) + return +} + +// gasLimitWithL1Cost adds the dynamic values perL2Tx and perL1CalldataUnit, provided by the getPricesInArbGas() method +// of the precompile contract at ArbGasInfoAddress, to l2GasLimit. perL2Tx is a constant amount of gas, and +// perL1CalldataUnit is multiplied by the length of the tx calldata. It returns an error if the estimator is not started +// or if the result exceeds LimitMax. +func (a *arbitrumEstimator) gasLimitWithL1Cost(ctx context.Context, calldata []byte, l2GasLimit uint64, opts ...fees.Opt) (chainSpecificGasLimit uint64, err error) { ok := a.IfStarted(func() { if slices.Contains(opts, fees.OptForceRefetch) { ch := make(chan struct{}) @@ -131,23 +166,23 @@ func (a *arbitrumEstimator) GetLegacyGas(ctx context.Context, calldata []byte, l } perL2Tx, perL1CalldataUnit := a.getPricesInArbGas() chainSpecificGasLimit = l2GasLimit + uint64(perL2Tx) + uint64(len(calldata))*uint64(perL1CalldataUnit) - a.logger.Debugw("GetLegacyGas", "l2GasLimit", l2GasLimit, "calldataLen", len(calldata), "perL2Tx", perL2Tx, + a.logger.Debugw("gasLimitWithL1Cost", "l2GasLimit", l2GasLimit, "calldataLen", len(calldata), "perL2Tx", perL2Tx, "perL1CalldataUnit", perL1CalldataUnit, "chainSpecificGasLimit", chainSpecificGasLimit) }) if !ok { - return nil, 0, pkgerrors.New("estimator is not started") - } else if err != nil { - return + return 0, pkgerrors.New("estimator is not started") } - if max := a.cfg.LimitMax(); chainSpecificGasLimit > max { - err = fmt.Errorf("estimated gas limit: %d is greater than the maximum gas limit configured: %d", chainSpecificGasLimit, max) - return + if err != nil { + return 0, err } - return + if limitMax := a.cfg.LimitMax(); chainSpecificGasLimit > limitMax { + return 0, fmt.Errorf("estimated gas limit: %d is greater than the maximum gas limit configured: %d", chainSpecificGasLimit, limitMax) + } + return chainSpecificGasLimit, nil } -// GetMaxLegacyGas returns the result of GetLegacyGas. Arbitrum doesn't have a mempool. That means transaction priority follows a FIFO model. -// Fetching a standard gas estimation will have the same effect for transaction inclusion. +// GetMaxLegacyGas returns the result of GetLegacyGas. Legacy pricing is used on chains that process transactions in +// FIFO order, so a higher price doesn't improve inclusion and a standard gas estimation has the same effect. func (a *arbitrumEstimator) GetMaxLegacyGas(ctx context.Context, calldata []byte, gasLimit uint64, maxGasPriceWei *assets.Wei, opts ...fees.Opt) (gasPrice *assets.Wei, chainSpecificGasLimit uint64, err error) { return a.GetLegacyGas(ctx, calldata, gasLimit, maxGasPriceWei, opts...) } diff --git a/pkg/gas/arbitrum_estimator_test.go b/pkg/gas/arbitrum_estimator_test.go index ba7b983396..3d9b3cf89d 100644 --- a/pkg/gas/arbitrum_estimator_test.go +++ b/pkg/gas/arbitrum_estimator_test.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "math/big" "testing" + "time" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" @@ -17,17 +18,33 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink-common/pkg/utils/tests" + "github.com/smartcontractkit/chainlink-framework/chains/fees" "github.com/smartcontractkit/chainlink-evm/pkg/assets" + evmconfig "github.com/smartcontractkit/chainlink-evm/pkg/config" "github.com/smartcontractkit/chainlink-evm/pkg/gas" "github.com/smartcontractkit/chainlink-evm/pkg/gas/mocks" "github.com/smartcontractkit/chainlink-evm/pkg/gas/rollups" + "github.com/smartcontractkit/chainlink-evm/pkg/testutils" + evmtypes "github.com/smartcontractkit/chainlink-evm/pkg/types" ) +type arbFeeHistoryConfig struct { + cacheTimeout time.Duration +} + +func (a *arbFeeHistoryConfig) CacheTimeout() time.Duration { + return a.cacheTimeout +} + type arbConfig struct { - v uint64 - bumpPercent uint16 - bumpMin *assets.Wei + v uint64 + bumpPercent uint16 + bumpMin *assets.Wei + eip1559 bool + feeHistory arbFeeHistoryConfig + blockHistory gas.MockBlockHistoryConfig + limitMultiplier float32 } func (a *arbConfig) LimitMax() uint64 { @@ -42,9 +59,37 @@ func (a *arbConfig) BumpMin() *assets.Wei { return a.bumpMin } +func (a *arbConfig) EIP1559DynamicFees() bool { + return a.eip1559 +} + +func (a *arbConfig) FeeHistory() evmconfig.FeeHistory { + return &a.feeHistory +} + +func (a *arbConfig) BlockHistory() evmconfig.BlockHistory { + return &a.blockHistory +} + +func (a *arbConfig) LimitMultiplier() float32 { + if a.limitMultiplier == 0 { + return 1.0 + } + return a.limitMultiplier +} + +func (a *arbConfig) EstimateLimit() bool { + return false +} + +func (a *arbConfig) SenderAddress() *evmtypes.EIP55Address { + return nil +} + func TestArbitrumEstimator(t *testing.T) { t.Parallel() + chainID := testutils.FixtureChainID maxGasPrice := assets.NewWeiI(100) const maxGasLimit uint64 = 500_000 calldata := []byte{0x00, 0x00, 0x01, 0x02, 0x03} @@ -58,7 +103,7 @@ func TestArbitrumEstimator(t *testing.T) { l1Oracle, err := rollups.NewArbitrumL1GasOracle(logger.Test(t), feeEstimatorClient) require.NoError(t, err) - o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, l1Oracle) + o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, chainID, l1Oracle) _, _, err = o.GetLegacyGas(tests.Context(t), calldata, gasLimit, maxGasPrice) assert.EqualError(t, err, "estimator is not started") }) @@ -84,7 +129,7 @@ func TestArbitrumEstimator(t *testing.T) { assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(zeros.Bytes(), nil) - o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{v: maxGasLimit, bumpPercent: bumpPercent, bumpMin: bumpMin}, feeEstimatorClient, l1Oracle) + o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{v: maxGasLimit, bumpPercent: bumpPercent, bumpMin: bumpMin}, feeEstimatorClient, chainID, l1Oracle) servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(tests.Context(t), calldata, gasLimit, maxGasPrice) require.NoError(t, err) @@ -98,7 +143,7 @@ func TestArbitrumEstimator(t *testing.T) { l1Oracle, err := rollups.NewArbitrumL1GasOracle(logger.Test(t), feeEstimatorClient) require.NoError(t, err) - o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, l1Oracle) + o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, chainID, l1Oracle) feeEstimatorClient.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(nil).Run(func(args mock.Arguments) { res := args.Get(1).(*hexutil.Big) @@ -125,7 +170,7 @@ func TestArbitrumEstimator(t *testing.T) { l1Oracle, err := rollups.NewArbitrumL1GasOracle(logger.Test(t), feeEstimatorClient) require.NoError(t, err) - o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, l1Oracle) + o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, chainID, l1Oracle) feeEstimatorClient.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(nil).Run(func(args mock.Arguments) { res := args.Get(1).(*hexutil.Big) @@ -151,7 +196,7 @@ func TestArbitrumEstimator(t *testing.T) { l1Oracle, err := rollups.NewArbitrumL1GasOracle(logger.Test(t), feeEstimatorClient) require.NoError(t, err) - o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, l1Oracle) + o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, chainID, l1Oracle) _, _, err = o.BumpLegacyGas(tests.Context(t), assets.NewWeiI(42), gasLimit, assets.NewWeiI(10), nil) assert.EqualError(t, err, "estimator is not started") }) @@ -161,7 +206,7 @@ func TestArbitrumEstimator(t *testing.T) { l1Oracle, err := rollups.NewArbitrumL1GasOracle(logger.Test(t), feeEstimatorClient) require.NoError(t, err) - o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, l1Oracle) + o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, chainID, l1Oracle) feeEstimatorClient.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(pkgerrors.New("kaboom")) feeEstimatorClient.On("CallContract", mock.Anything, mock.IsType(ethereum.CallMsg{}), mock.IsType(&big.Int{})).Run(func(args mock.Arguments) { @@ -183,7 +228,7 @@ func TestArbitrumEstimator(t *testing.T) { l1Oracle, err := rollups.NewArbitrumL1GasOracle(logger.Test(t), feeEstimatorClient) require.NoError(t, err) - o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, l1Oracle) + o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, chainID, l1Oracle) _, err = o.GetDynamicFee(tests.Context(t), maxGasPrice) assert.EqualError(t, err, "dynamic fees are not implemented for this estimator") }) @@ -193,7 +238,7 @@ func TestArbitrumEstimator(t *testing.T) { l1Oracle, err := rollups.NewArbitrumL1GasOracle(logger.Test(t), feeEstimatorClient) require.NoError(t, err) - o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, l1Oracle) + o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, feeEstimatorClient, chainID, l1Oracle) fee := gas.DynamicFee{ GasFeeCap: assets.NewWeiI(42), GasTipCap: assets.NewWeiI(5), @@ -229,7 +274,7 @@ func TestArbitrumEstimator(t *testing.T) { assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(b.Bytes(), nil) - o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{v: maxGasLimit, bumpPercent: bumpPercent, bumpMin: bumpMin}, feeEstimatorClient, l1Oracle) + o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{v: maxGasLimit, bumpPercent: bumpPercent, bumpMin: bumpMin}, feeEstimatorClient, chainID, l1Oracle) servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(tests.Context(t), calldata, gasLimit, maxGasPrice) require.NoError(t, err) @@ -265,9 +310,178 @@ func TestArbitrumEstimator(t *testing.T) { assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(b.Bytes(), nil) - o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{v: maxGasLimit, bumpPercent: bumpPercent, bumpMin: bumpMin}, feeEstimatorClient, l1Oracle) + o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{v: maxGasLimit, bumpPercent: bumpPercent, bumpMin: bumpMin}, feeEstimatorClient, chainID, l1Oracle) servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(tests.Context(t), calldata, gasLimit, maxGasPrice) require.Error(t, err, "expected error but got (%s, %d)", gasPrice, chainSpecificGasLimit) }) + + t.Run("EIP1559 dynamic fees use FeeHistoryEstimator and apply L1 gas limit", func(t *testing.T) { + feeEstimatorClient := mocks.NewFeeEstimatorClient(t) + l1Oracle, err := rollups.NewArbitrumL1GasOracle(logger.Test(t), feeEstimatorClient) + require.NoError(t, err) + + const ( + perL2Tx = 50_000 + perL1Calldata = 10_000 + ) + expLimit := gasLimit + perL2Tx + perL1Calldata*uint64(len(calldata)) + + var arbPrices bytes.Buffer + arbPrices.Write(common.BigToHash(big.NewInt(perL2Tx)).Bytes()) + arbPrices.Write(common.BigToHash(big.NewInt(perL1Calldata)).Bytes()) + arbPrices.Write(common.BigToHash(big.NewInt(0)).Bytes()) + + feeEstimatorClient.On("CallContract", mock.Anything, mock.IsType(ethereum.CallMsg{}), (*big.Int)(nil)). + Return(common.BigToHash(big.NewInt(1)).Bytes(), nil).Maybe() + feeEstimatorClient.On("CallContract", mock.Anything, mock.IsType(ethereum.CallMsg{}), big.NewInt(-1)). + Return(arbPrices.Bytes(), nil) + + baseFee := big.NewInt(100) + priorityFee := big.NewInt(10) + priorityThreshold := big.NewInt(25) + feeHistoryResult := ðereum.FeeHistory{ + OldestBlock: big.NewInt(1), + Reward: [][]*big.Int{{priorityFee, priorityThreshold}}, + BaseFee: []*big.Int{baseFee}, + } + feeEstimatorClient.On("FeeHistory", mock.Anything, uint64(5), (*big.Int)(nil), []float64{60, gas.ConnectivityPercentile}). + Return(feeHistoryResult, nil) + + cfg := &arbConfig{ + v: maxGasLimit, + bumpPercent: bumpPercent, + bumpMin: bumpMin, + eip1559: true, + feeHistory: arbFeeHistoryConfig{cacheTimeout: gas.MinimumCacheTimeout}, + blockHistory: gas.MockBlockHistoryConfig{BlockHistorySizeF: 5, TransactionPercentileF: 60}, + } + + arbEst := gas.NewArbitrumEstimator(logger.Test(t), cfg, feeEstimatorClient, chainID, l1Oracle) + wrapped := gas.NewEvmFeeEstimator(logger.Test(t), arbEst, true, cfg, feeEstimatorClient) + servicetest.RunHealthy(t, wrapped) + + maxFeePrice := assets.NewWeiI(1000) + var fee gas.EvmFee + var estLimit uint64 + require.Eventually(t, func() bool { + fee, estLimit, err = wrapped.GetFee(tests.Context(t), calldata, gasLimit, maxFeePrice, nil, nil) + return err == nil + }, 5*time.Second, 20*time.Millisecond) + + expectedFeeCap := assets.NewWei(baseFee).AddPercentage(gas.NoMempoolBaseFeeBufferPercentage).Add(assets.NewWei(priorityFee)) + assert.Equal(t, expectedFeeCap, fee.GasFeeCap) + assert.Equal(t, assets.NewWei(priorityFee), fee.GasTipCap) + assert.Nil(t, fee.GasPrice) + assert.Equal(t, expLimit, estLimit) + + maxFee, maxEstLimit, err := wrapped.GetMaxFee(tests.Context(t), calldata, gasLimit, maxFeePrice, nil, nil) + require.NoError(t, err) + expectedMaxFeeCap := assets.NewWei(baseFee).AddPercentage(gas.NoMempoolBaseFeeBufferPercentage).Add(assets.NewWei(priorityThreshold)) + assert.Equal(t, expectedMaxFeeCap, maxFee.GasFeeCap) + assert.Equal(t, assets.NewWei(priorityThreshold), maxFee.GasTipCap) + assert.Equal(t, expLimit, maxEstLimit) + }) + + t.Run("EIP1559 dynamic fees return error when L1-adjusted limit exceeds LimitMax", func(t *testing.T) { + feeEstimatorClient := mocks.NewFeeEstimatorClient(t) + l1Oracle, err := rollups.NewArbitrumL1GasOracle(logger.Test(t), feeEstimatorClient) + require.NoError(t, err) + + var arbPrices bytes.Buffer + arbPrices.Write(common.BigToHash(big.NewInt(500_000)).Bytes()) + arbPrices.Write(common.BigToHash(big.NewInt(100_000)).Bytes()) + arbPrices.Write(common.BigToHash(big.NewInt(0)).Bytes()) + + feeEstimatorClient.On("CallContract", mock.Anything, mock.IsType(ethereum.CallMsg{}), (*big.Int)(nil)). + Return(common.BigToHash(big.NewInt(1)).Bytes(), nil).Maybe() + feeEstimatorClient.On("CallContract", mock.Anything, mock.IsType(ethereum.CallMsg{}), big.NewInt(-1)). + Return(arbPrices.Bytes(), nil) + + feeHistoryResult := ðereum.FeeHistory{ + OldestBlock: big.NewInt(1), + Reward: [][]*big.Int{{big.NewInt(10), big.NewInt(25)}}, + BaseFee: []*big.Int{big.NewInt(100)}, + } + feeEstimatorClient.On("FeeHistory", mock.Anything, uint64(5), (*big.Int)(nil), []float64{60, gas.ConnectivityPercentile}). + Return(feeHistoryResult, nil) + + cfg := &arbConfig{ + v: maxGasLimit, + bumpPercent: bumpPercent, + bumpMin: bumpMin, + eip1559: true, + feeHistory: arbFeeHistoryConfig{cacheTimeout: gas.MinimumCacheTimeout}, + blockHistory: gas.MockBlockHistoryConfig{BlockHistorySizeF: 5, TransactionPercentileF: 60}, + } + + arbEst := gas.NewArbitrumEstimator(logger.Test(t), cfg, feeEstimatorClient, chainID, l1Oracle) + wrapped := gas.NewEvmFeeEstimator(logger.Test(t), arbEst, true, cfg, feeEstimatorClient) + servicetest.RunHealthy(t, wrapped) + + maxFeePrice := assets.NewWeiI(1000) + require.Eventually(t, func() bool { + _, _, err = wrapped.GetFee(tests.Context(t), calldata, gasLimit, maxFeePrice, nil, nil) + return err != nil && err.Error() != "dynamic fee not set" + }, 5*time.Second, 20*time.Millisecond) + assert.ErrorContains(t, err, "is greater than the maximum gas limit configured") + }) + + t.Run("EIP1559 dynamic fees support OptForceRefetch for L1 gas limit", func(t *testing.T) { + feeEstimatorClient := mocks.NewFeeEstimatorClient(t) + l1Oracle, err := rollups.NewArbitrumL1GasOracle(logger.Test(t), feeEstimatorClient) + require.NoError(t, err) + + var initialPrices bytes.Buffer + initialPrices.Write(common.BigToHash(big.NewInt(10_000)).Bytes()) + initialPrices.Write(common.BigToHash(big.NewInt(1_000)).Bytes()) + initialPrices.Write(common.BigToHash(big.NewInt(0)).Bytes()) + + var refreshedPrices bytes.Buffer + refreshedPrices.Write(common.BigToHash(big.NewInt(20_000)).Bytes()) + refreshedPrices.Write(common.BigToHash(big.NewInt(2_000)).Bytes()) + refreshedPrices.Write(common.BigToHash(big.NewInt(0)).Bytes()) + + // First call is from arbitrumL1Oracle.Start() (getL1BaseFeeEstimate, blockNumber == nil), + // subsequent calls with blockNumber == -1 are getPricesInArbGas(). + feeEstimatorClient.On("CallContract", mock.Anything, mock.IsType(ethereum.CallMsg{}), (*big.Int)(nil)). + Return(common.BigToHash(big.NewInt(1)).Bytes(), nil).Maybe() + feeEstimatorClient.On("CallContract", mock.Anything, mock.IsType(ethereum.CallMsg{}), big.NewInt(-1)). + Return(initialPrices.Bytes(), nil).Once() + feeEstimatorClient.On("CallContract", mock.Anything, mock.IsType(ethereum.CallMsg{}), big.NewInt(-1)). + Return(refreshedPrices.Bytes(), nil) + + feeHistoryResult := ðereum.FeeHistory{ + OldestBlock: big.NewInt(1), + Reward: [][]*big.Int{{big.NewInt(10), big.NewInt(25)}}, + BaseFee: []*big.Int{big.NewInt(100)}, + } + feeEstimatorClient.On("FeeHistory", mock.Anything, uint64(5), (*big.Int)(nil), []float64{60, gas.ConnectivityPercentile}). + Return(feeHistoryResult, nil) + + cfg := &arbConfig{ + v: maxGasLimit, + bumpPercent: bumpPercent, + bumpMin: bumpMin, + eip1559: true, + feeHistory: arbFeeHistoryConfig{cacheTimeout: gas.MinimumCacheTimeout}, + blockHistory: gas.MockBlockHistoryConfig{BlockHistorySizeF: 5, TransactionPercentileF: 60}, + } + + arbEst := gas.NewArbitrumEstimator(logger.Test(t), cfg, feeEstimatorClient, chainID, l1Oracle) + wrapped := gas.NewEvmFeeEstimator(logger.Test(t), arbEst, true, cfg, feeEstimatorClient) + servicetest.RunHealthy(t, wrapped) + + maxFeePrice := assets.NewWeiI(1000) + var estLimit uint64 + require.Eventually(t, func() bool { + _, estLimit, err = wrapped.GetFee(tests.Context(t), calldata, gasLimit, maxFeePrice, nil, nil) + return err == nil + }, 5*time.Second, 20*time.Millisecond) + assert.Equal(t, gasLimit+10_000+1_000*uint64(len(calldata)), estLimit) + + _, estLimit, err = wrapped.GetFee(tests.Context(t), calldata, gasLimit, maxFeePrice, nil, nil, fees.OptForceRefetch) + require.NoError(t, err) + assert.Equal(t, gasLimit+20_000+2_000*uint64(len(calldata)), estLimit) + }) } diff --git a/pkg/gas/fee_history_estimator.go b/pkg/gas/fee_history_estimator.go index fef4e98038..c71d7b6cfb 100644 --- a/pkg/gas/fee_history_estimator.go +++ b/pkg/gas/fee_history_estimator.go @@ -17,6 +17,7 @@ import ( "github.com/smartcontractkit/chainlink-evm/pkg/assets" "github.com/smartcontractkit/chainlink-evm/pkg/client" + "github.com/smartcontractkit/chainlink-evm/pkg/config/chaintype" "github.com/smartcontractkit/chainlink-evm/pkg/gas/rollups" evmtypes "github.com/smartcontractkit/chainlink-evm/pkg/types" "github.com/smartcontractkit/chainlink-framework/chains/fees" @@ -36,6 +37,8 @@ const ( // NoMempoolBaseFeeBufferPercentage covers potential cache staleness and delays from the time the prices are fetched until transmission. // Chains without a mempool sequence transactions almost immediately, so the exposure is the CacheTimeout window // (especially on super fast chains like Arbitrum) rather than the mempool wait. + // It is also used for Arbitrum regardless of BlockHistorySize: Arbitrum's base fee is priced by ArbOS based on the + // backlog rather than by EIP-1559, so it has no per-block cap and can increase sharply within the CacheTimeout window. // We avoid using an even larger buffer because even though the excess fee is refunded, it still increases the pre-transactional cost // and can cause the transaction to be rejected with an insufficient funds error. NoMempoolBaseFeeBufferPercentage = 90 @@ -82,10 +85,11 @@ type feeHistoryEstimatorClient interface { type FeeHistoryEstimator struct { services.StateMachine - client feeHistoryEstimatorClient - logger logger.Logger - config FeeHistoryEstimatorConfig - chainID *big.Int + client feeHistoryEstimatorClient + logger logger.Logger + config FeeHistoryEstimatorConfig + chainID *big.Int + chainType chaintype.ChainType gasPriceMu sync.RWMutex gasPrice *assets.Wei @@ -102,13 +106,14 @@ type FeeHistoryEstimator struct { refreshCh chan struct{} } -func NewFeeHistoryEstimator(lggr logger.Logger, client feeHistoryEstimatorClient, cfg FeeHistoryEstimatorConfig, chainID *big.Int, l1Oracle rollups.L1Oracle) *FeeHistoryEstimator { +func NewFeeHistoryEstimator(lggr logger.Logger, client feeHistoryEstimatorClient, cfg FeeHistoryEstimatorConfig, chainID *big.Int, chainType chaintype.ChainType, l1Oracle rollups.L1Oracle) *FeeHistoryEstimator { l := logger.Sugared(logger.Named(lggr, "FeeHistoryEstimator")) return &FeeHistoryEstimator{ client: client, logger: l, config: cfg, chainID: chainID, + chainType: chainType, l1Oracle: l1Oracle, metrics: newFeeHistoryEstimatorMetrics(l, chainID), wg: new(sync.WaitGroup), @@ -370,9 +375,10 @@ func calcPriorityFees(rewards [][]*big.Int) (avg *assets.Wei, threshold *assets. } // baseFeeBufferPercentage returns the safety buffer applied on top of the latest base fee. BlockHistorySize of 0 is used -// as the signal for a chain without a mempool. +// as the signal for a chain without a mempool. Arbitrum always gets the wider buffer, even when BlockHistorySize > 0 is +// set to price priority fees, because its base fee has no per-block cap (see NoMempoolBaseFeeBufferPercentage). func (f *FeeHistoryEstimator) baseFeeBufferPercentage() uint16 { - if f.config.BlockHistorySize == 0 { + if f.config.BlockHistorySize == 0 || f.chainType == chaintype.ChainArbitrum { return NoMempoolBaseFeeBufferPercentage } return BaseFeeBufferPercentage diff --git a/pkg/gas/fee_history_estimator_test.go b/pkg/gas/fee_history_estimator_test.go index 41c55ed195..a3443f3d83 100644 --- a/pkg/gas/fee_history_estimator_test.go +++ b/pkg/gas/fee_history_estimator_test.go @@ -15,6 +15,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink-evm/pkg/assets" + "github.com/smartcontractkit/chainlink-evm/pkg/config/chaintype" "github.com/smartcontractkit/chainlink-evm/pkg/gas" "github.com/smartcontractkit/chainlink-evm/pkg/gas/mocks" "github.com/smartcontractkit/chainlink-evm/pkg/testutils" @@ -34,7 +35,7 @@ func TestFeeHistoryEstimatorLifecycle(t *testing.T) { EIP1559: false, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) _, _, err := u.GetLegacyGas(t.Context(), nil, gasLimit, maxPrice) assert.ErrorContains(t, err, "gas price not set") }) @@ -42,7 +43,7 @@ func TestFeeHistoryEstimatorLifecycle(t *testing.T) { t.Run("fails to start if BumpPercent is lower than the minimum cap", func(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{BumpPercent: 9} - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) assert.ErrorContains(t, u.Start(t.Context()), "BumpPercent") }) @@ -53,7 +54,7 @@ func TestFeeHistoryEstimatorLifecycle(t *testing.T) { EIP1559: true, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) assert.ErrorContains(t, u.Start(t.Context()), "RewardPercentile") }) @@ -64,7 +65,7 @@ func TestFeeHistoryEstimatorLifecycle(t *testing.T) { CacheTimeout: 200 * time.Millisecond, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) assert.ErrorContains(t, u.Start(t.Context()), "CacheTimeout") }) @@ -78,7 +79,7 @@ func TestFeeHistoryEstimatorLifecycle(t *testing.T) { CacheTimeout: 10 * time.Second, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) err := u.Start(t.Context()) assert.NoError(t, err) err = u.Close() @@ -99,7 +100,7 @@ func TestFeeHistoryEstimatorGetLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) _, err := u.RefreshGasPrice() assert.NoError(t, err) gasPrice, _, err := u.GetLegacyGas(t.Context(), nil, gasLimit, maxPrice) @@ -114,7 +115,7 @@ func TestFeeHistoryEstimatorGetLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{} maxPrice := assets.NewWeiI(1) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) _, err := u.RefreshGasPrice() assert.NoError(t, err) gas1, _, err := u.GetLegacyGas(t.Context(), nil, gasLimit, maxPrice) @@ -126,7 +127,7 @@ func TestFeeHistoryEstimatorGetLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{} maxPrice := assets.NewWeiI(1) - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) _, _, err := u.GetLegacyGas(t.Context(), nil, gasLimit, maxPrice) assert.Error(t, err) assert.ErrorContains(t, err, "gas price not set") @@ -147,7 +148,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{BumpPercent: 50, CacheTimeout: 5 * time.Second} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) servicetest.RunHealthy(t, u) gasPrice, _, err := u.BumpLegacyGas(t.Context(), originalGasPrice, gasLimit, maxPrice, nil) assert.NoError(t, err) @@ -158,7 +159,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { client := mocks.NewFeeHistoryEstimatorClient(t) cfg := gas.FeeHistoryEstimatorConfig{} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) var originalPrice *assets.Wei _, _, err := u.BumpLegacyGas(t.Context(), originalPrice, gasLimit, maxPrice, nil) @@ -176,7 +177,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) gas, _, err := u.BumpLegacyGas(t.Context(), originalGasPrice, gasLimit, maxPrice, nil) assert.NoError(t, err) assert.Equal(t, assets.NewWeiI(80), gas) @@ -190,7 +191,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{BumpPercent: 50} maxPrice := assets.NewWeiI(14) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) gas, _, err := u.BumpLegacyGas(t.Context(), originalGasPrice, gasLimit, maxPrice, nil) assert.NoError(t, err) assert.Equal(t, maxPrice, gas) @@ -204,7 +205,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{BumpPercent: 50} maxPrice := assets.NewWeiI(14) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) gas, _, err := u.BumpLegacyGas(t.Context(), originalGasPrice, gasLimit, maxPrice, nil) assert.NoError(t, err) assert.Equal(t, maxPrice, gas) @@ -219,7 +220,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { // Price will be capped by the max price maxPrice := assets.NewWeiI(101) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) _, _, err := u.BumpLegacyGas(t.Context(), originalGasPrice, gasLimit, maxPrice, nil) assert.Error(t, err) }) @@ -260,7 +261,7 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { avrgPriorityFee.Add(maxPriorityFeePerGas1, maxPriorityFeePerGas2).Div(avrgPriorityFee, big.NewInt(int64(blockHistoryLength))) maxFee := (*assets.Wei)(baseFee).AddPercentage(gas.BaseFeeBufferPercentage).Add((*assets.Wei)(avrgPriorityFee)) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) err := u.RefreshDynamicFee() assert.NoError(t, err) dynamicFee, err := u.GetDynamicFee(t.Context(), maxPrice) @@ -273,7 +274,7 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{} maxPrice := assets.NewWeiI(1) - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) _, err := u.GetDynamicFee(t.Context(), maxPrice) assert.Error(t, err) assert.ErrorContains(t, err, "dynamic fee not set") @@ -295,7 +296,7 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{BlockHistorySize: 1} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) err := u.RefreshDynamicFee() assert.NoError(t, err) dynamicFee, err := u.GetDynamicFee(t.Context(), maxPrice) @@ -319,7 +320,7 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { // BlockHistorySize of 0 signals a chain without a mempool, so buffer is increased. cfg := gas.FeeHistoryEstimatorConfig{BlockHistorySize: 0, EIP1559: true} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) require.NoError(t, u.RefreshDynamicFee()) dynamicFee, err := u.GetDynamicFee(t.Context(), maxPrice) @@ -333,6 +334,38 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { require.NoError(t, err) assert.Equal(t, dynamicFee.GasFeeCap, maxFee.GasFeeCap) }) + + t.Run("applies the NoMempoolBaseFeeBufferPercentage for Arbitrum even with BlockHistorySize > 0", func(t *testing.T) { + client := mocks.NewFeeHistoryEstimatorClient(t) + baseFee := big.NewInt(100) + priorityFee := big.NewInt(10) + priorityThreshold := big.NewInt(25) + maxPrice := assets.NewWeiI(1000) + + feeHistoryResult := ðereum.FeeHistory{ + OldestBlock: big.NewInt(1), + Reward: [][]*big.Int{{priorityFee, priorityThreshold}}, + BaseFee: []*big.Int{baseFee}, + } + client.On("FeeHistory", mock.Anything, uint64(5), (*big.Int)(nil), []float64{60, gas.ConnectivityPercentile}).Return(feeHistoryResult, nil).Once() + + cfg := gas.FeeHistoryEstimatorConfig{BlockHistorySize: 5, RewardPercentile: 60, EIP1559: true} + + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, chaintype.ChainArbitrum, nil) + require.NoError(t, u.RefreshDynamicFee()) + + dynamicFee, err := u.GetDynamicFee(t.Context(), maxPrice) + require.NoError(t, err) + expectedFeeCap := assets.NewWei(baseFee).AddPercentage(gas.NoMempoolBaseFeeBufferPercentage).Add(assets.NewWei(priorityFee)) + assert.Equal(t, expectedFeeCap, dynamicFee.GasFeeCap) + assert.Equal(t, assets.NewWei(priorityFee), dynamicFee.GasTipCap) + + maxFee, err := u.GetMaxDynamicFee(maxPrice) + require.NoError(t, err) + expectedMaxFeeCap := assets.NewWei(baseFee).AddPercentage(gas.NoMempoolBaseFeeBufferPercentage).Add(assets.NewWei(priorityThreshold)) + assert.Equal(t, expectedMaxFeeCap, maxFee.GasFeeCap) + assert.Equal(t, assets.NewWei(priorityThreshold), maxFee.GasTipCap) + }) } func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { @@ -348,7 +381,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { EIP1559: true, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) fee, err := u.GetMaxDynamicFee(maxPrice) require.Error(t, err) assert.ErrorContains(t, err, "priorityFeeThreshold not set") @@ -376,7 +409,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { BlockHistorySize: 2, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) err := u.RefreshDynamicFee() require.NoError(t, err) @@ -400,7 +433,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { client.On("FeeHistory", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(feeHistoryResult, nil).Once() cfg := gas.FeeHistoryEstimatorConfig{BumpPercent: 20, RewardPercentile: 60, EIP1559: true, BlockHistorySize: 2} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) require.NoError(t, u.RefreshDynamicFee()) fee, err := u.GetMaxDynamicFee(maxPrice) @@ -436,7 +469,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { BlockHistorySize: 2, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) require.NoError(t, u.RefreshDynamicFee()) // The priority fees are still unset, but the base fee has been cached. _, err := u.GetMaxDynamicFee(maxPrice) @@ -478,7 +511,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { BlockHistorySize: 2, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) require.NoError(t, u.RefreshDynamicFee()) require.NoError(t, u.RefreshDynamicFee()) @@ -514,7 +547,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { BlockHistorySize: 2, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) require.NoError(t, u.RefreshDynamicFee()) maxFee, err := u.GetMaxDynamicFee(maxPrice) @@ -559,7 +592,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { expectedFeeCap := originalFee.GasFeeCap.AddPercentage(cfg.BumpPercent) expectedTipCap := originalFee.GasTipCap.AddPercentage(cfg.BumpPercent) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) err := u.RefreshDynamicFee() assert.NoError(t, err) dynamicFee, err := u.BumpDynamicFee(t.Context(), originalFee, globalMaxPrice, nil) @@ -573,7 +606,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { maxPrice := assets.NewWeiI(20) cfg := gas.FeeHistoryEstimatorConfig{BlockHistorySize: 1} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) // nil original fee var originalFee gas.DynamicFee _, err := u.BumpDynamicFee(t.Context(), originalFee, maxPrice, nil) @@ -621,7 +654,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { BumpPercent: 50, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) err := u.RefreshDynamicFee() assert.NoError(t, err) bumpedFee, err := u.BumpDynamicFee(t.Context(), originalFee, globalMaxPrice, nil) @@ -655,7 +688,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { BumpPercent: 50, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) err := u.RefreshDynamicFee() assert.NoError(t, err) _, err = u.BumpDynamicFee(t.Context(), originalFee, globalMaxPrice, nil) @@ -688,7 +721,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { BumpPercent: 50, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) err := u.RefreshDynamicFee() assert.NoError(t, err) bumpedFee, err := u.BumpDynamicFee(t.Context(), originalFee, maxPrice, nil) @@ -721,7 +754,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { BumpPercent: 50, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) err := u.RefreshDynamicFee() assert.NoError(t, err) _, err = u.BumpDynamicFee(t.Context(), originalFee, maxPrice, nil) @@ -755,7 +788,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { // No mempool means the wider staleness buffer applies. maxFeePerGas := assets.NewWei(baseFee).AddPercentage(gas.NoMempoolBaseFeeBufferPercentage) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) servicetest.RunHealthy(t, u) bumpedFee, err := u.BumpDynamicFee(t.Context(), originalFee, globalMaxPrice, nil) assert.NoError(t, err) @@ -772,7 +805,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { } // The client is never called because the estimator isn't started. - u := gas.NewFeeHistoryEstimator(logger.Test(t), mocks.NewFeeHistoryEstimatorClient(t), cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), mocks.NewFeeHistoryEstimatorClient(t), cfg, chainID, "", nil) _, err := u.BumpDynamicFee(t.Context(), gas.DynamicFee{GasFeeCap: assets.NewWeiI(40), GasTipCap: assets.NewWeiI(0)}, globalMaxPrice, nil) require.ErrorContains(t, err, "estimator not started") }) @@ -788,7 +821,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { EIP1559: true, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) servicetest.RunHealthy(t, u) _, err := u.BumpDynamicFee(t.Context(), gas.DynamicFee{GasFeeCap: assets.NewWeiI(40), GasTipCap: assets.NewWeiI(0)}, globalMaxPrice, nil) require.ErrorContains(t, err, "RPC unreachable") diff --git a/pkg/gas/models.go b/pkg/gas/models.go index d6f0c08800..4b9b9b8456 100644 --- a/pkg/gas/models.go +++ b/pkg/gas/models.go @@ -54,7 +54,7 @@ type FeeEstimatorClient interface { } // NewEstimator returns the estimator for a given config -func NewEstimator(lggr logger.Logger, ethClient FeeEstimatorClient, chaintype chaintype.ChainType, chainID *big.Int, geCfg evmconfig.GasEstimator, clientsByChainID map[string]rollups.DAClient) (EvmFeeEstimator, error) { +func NewEstimator(lggr logger.Logger, ethClient FeeEstimatorClient, chainType chaintype.ChainType, chainID *big.Int, geCfg evmconfig.GasEstimator, clientsByChainID map[string]rollups.DAClient) (EvmFeeEstimator, error) { bh := geCfg.BlockHistory() s := geCfg.Mode() lggr.Infow("Initializing EVM gas estimator in mode: "+s, @@ -82,7 +82,7 @@ func NewEstimator(lggr logger.Logger, ethClient FeeEstimatorClient, chaintype ch df := geCfg.EIP1559DynamicFees() // create l1Oracle only if it is supported for the chain - l1Oracle, err := rollups.NewL1GasOracle(lggr, ethClient, chaintype, geCfg.DAOracle(), clientsByChainID) + l1Oracle, err := rollups.NewL1GasOracle(lggr, ethClient, chainType, geCfg.DAOracle(), clientsByChainID) if err != nil { return nil, fmt.Errorf("failed to initialize L1 oracle: %w", err) } @@ -90,17 +90,20 @@ func NewEstimator(lggr logger.Logger, ethClient FeeEstimatorClient, chaintype ch var newEstimator EvmEstimator switch s { case "Arbitrum": - arbOracle, err := rollups.NewArbitrumL1GasOracle(lggr, ethClient) - if err != nil { - return nil, fmt.Errorf("failed to initialize Arbitrum L1 oracle: %w", err) + arbOracle, ok := l1Oracle.(rollups.ArbL1GasOracle) + if !ok { + arbOracle, err = rollups.NewArbitrumL1GasOracle(lggr, ethClient) + if err != nil { + return nil, fmt.Errorf("failed to initialize Arbitrum L1 oracle: %w", err) + } } - newEstimator = NewArbitrumEstimator(lggr, geCfg, ethClient, arbOracle) + newEstimator = NewArbitrumEstimator(lggr, geCfg, ethClient, chainID, arbOracle) case "BlockHistory": - newEstimator = NewBlockHistoryEstimator(lggr, ethClient, chaintype, geCfg, bh, chainID, l1Oracle) + newEstimator = NewBlockHistoryEstimator(lggr, ethClient, chainType, geCfg, bh, chainID, l1Oracle) case "FixedPrice": newEstimator = NewFixedPriceEstimator(geCfg, ethClient, bh.EIP1559FeeCapBufferBlocks(), lggr, l1Oracle) case "L2Suggested", "SuggestedPrice": - newEstimator = NewSuggestedPriceEstimator(lggr, ethClient, geCfg, chaintype, l1Oracle) + newEstimator = NewSuggestedPriceEstimator(lggr, ethClient, geCfg, chainType, l1Oracle) case "FeeHistory": ccfg := FeeHistoryEstimatorConfig{ BumpPercent: geCfg.BumpPercent(), @@ -109,7 +112,7 @@ func NewEstimator(lggr logger.Logger, ethClient FeeEstimatorClient, chaintype ch BlockHistorySize: uint64(geCfg.BlockHistory().BlockHistorySize()), RewardPercentile: float64(geCfg.BlockHistory().TransactionPercentile()), } - newEstimator = NewFeeHistoryEstimator(lggr, ethClient, ccfg, chainID, l1Oracle) + newEstimator = NewFeeHistoryEstimator(lggr, ethClient, ccfg, chainID, chainType, l1Oracle) default: lggr.Warnf("GasEstimator: unrecognised mode '%s', falling back to FixedPriceEstimator", s) newEstimator = NewFixedPriceEstimator(geCfg, ethClient, bh.EIP1559FeeCapBufferBlocks(), lggr, l1Oracle) @@ -282,7 +285,9 @@ func (e *evmFeeEstimator) GetFee(ctx context.Context, calldata []byte, feeLimit } fee.GasFeeCap = dynamicFee.GasFeeCap fee.GasTipCap = dynamicFee.GasTipCap - chainSpecificFeeLimit = feeLimit + if chainSpecificFeeLimit, err = e.dynamicFeeLimit(ctx, calldata, feeLimit, opts...); err != nil { + return + } } else { // get legacy fee fee.GasPrice, chainSpecificFeeLimit, err = e.EvmEstimator.GetLegacyGas(ctx, calldata, feeLimit, maxFeePrice, opts...) @@ -323,7 +328,9 @@ func (e *evmFeeEstimator) GetMaxFee(ctx context.Context, calldata []byte, feeLim } fee.GasFeeCap = dynamicFee.GasFeeCap fee.GasTipCap = dynamicFee.GasTipCap - chainSpecificFeeLimit = feeLimit + if chainSpecificFeeLimit, err = e.dynamicFeeLimit(ctx, calldata, feeLimit, opts...); err != nil { + return + } } else { fee.GasPrice, chainSpecificFeeLimit, err = e.EvmEstimator.GetMaxLegacyGas(ctx, calldata, feeLimit, maxFeePrice, opts...) if err != nil { @@ -369,6 +376,15 @@ func (e *evmFeeEstimator) BumpFee(ctx context.Context, originalFee EvmFee, feeLi return } +// dynamicFeeLimit returns the gas limit for a dynamic fee transaction. GetDynamicFee doesn't return a gas limit, so the +// Arbitrum L1 calldata cost is added here. Legacy transactions get the same adjustment from GetLegacyGas. +func (e *evmFeeEstimator) dynamicFeeLimit(ctx context.Context, calldata []byte, feeLimit uint64, opts ...fees.Opt) (uint64, error) { + if arb, ok := e.EvmEstimator.(*arbitrumEstimator); ok { + return arb.gasLimitWithL1Cost(ctx, calldata, feeLimit, opts...) + } + return feeLimit, nil +} + func (e *evmFeeEstimator) estimateFeeLimit(ctx context.Context, feeLimit uint64, calldata []byte, fromAddress, toAddress *common.Address) (estimatedFeeLimit uint64, err error) { // Use the feeLimit * LimitMultiplier as the provided gas limit since this multiplier is applied on top of the caller specified gas limit providedGasLimit, err := fees.ApplyMultiplier(feeLimit, e.geCfg.LimitMultiplier()) From bd6578ee219818b49af3eb65aa5a9c8f70b43bbe Mon Sep 17 00:00:00 2001 From: Dimitris Date: Mon, 23 Nov 2026 19:07:05 +0200 Subject: [PATCH 2/5] Update FeeHistory estimator --- pkg/gas/arbitrum_estimator.go | 14 +-- pkg/gas/fee_history_estimator.go | 46 +++++---- pkg/gas/fee_history_estimator_test.go | 128 +++++++++++++++++++------- pkg/gas/models.go | 14 +-- 4 files changed, 135 insertions(+), 67 deletions(-) diff --git a/pkg/gas/arbitrum_estimator.go b/pkg/gas/arbitrum_estimator.go index d522572411..6f87bed113 100644 --- a/pkg/gas/arbitrum_estimator.go +++ b/pkg/gas/arbitrum_estimator.go @@ -69,13 +69,15 @@ func NewArbitrumEstimator(lggr logger.Logger, cfg ArbConfig, ethClient FeeEstima var priceEstimator EvmEstimator if cfg.EIP1559DynamicFees() { fhCfg := FeeHistoryEstimatorConfig{ - BumpPercent: cfg.BumpPercent(), - CacheTimeout: cfg.FeeHistory().CacheTimeout(), - EIP1559: cfg.EIP1559DynamicFees(), - BlockHistorySize: uint64(cfg.BlockHistory().BlockHistorySize()), - RewardPercentile: float64(cfg.BlockHistory().TransactionPercentile()), + BumpPercent: cfg.BumpPercent(), + CacheTimeout: cfg.FeeHistory().CacheTimeout(), + EIP1559: cfg.EIP1559DynamicFees(), + BlockHistorySize: uint64(cfg.BlockHistory().BlockHistorySize()), + RewardPercentile: float64(cfg.BlockHistory().TransactionPercentile()), + ConnectivityPercentile: float64(cfg.BlockHistory().CheckInclusionPercentile()), + ChainType: chaintype.ChainArbitrum, } - priceEstimator = NewFeeHistoryEstimator(lggr, ethClient, fhCfg, chainID, chaintype.ChainArbitrum, l1Oracle) + priceEstimator = NewFeeHistoryEstimator(lggr, ethClient, fhCfg, chainID, l1Oracle) } else { priceEstimator = NewSuggestedPriceEstimator(lggr, ethClient, cfg, chaintype.ChainArbitrum, l1Oracle) } diff --git a/pkg/gas/fee_history_estimator.go b/pkg/gas/fee_history_estimator.go index c71d7b6cfb..7e43858861 100644 --- a/pkg/gas/fee_history_estimator.go +++ b/pkg/gas/fee_history_estimator.go @@ -35,8 +35,7 @@ const ( // 12.5% * (gasUsed - target) / target per block. This value covers ~8 blocks at u = 0.67, which is a demand spike rather than regular traffic. BaseFeeBufferPercentage = 40 // NoMempoolBaseFeeBufferPercentage covers potential cache staleness and delays from the time the prices are fetched until transmission. - // Chains without a mempool sequence transactions almost immediately, so the exposure is the CacheTimeout window - // (especially on super fast chains like Arbitrum) rather than the mempool wait. + // Chains without a mempool sequence transactions almost immediately, so the exposure is the CacheTimeout window rather than the mempool wait. // It is also used for Arbitrum regardless of BlockHistorySize: Arbitrum's base fee is priced by ArbOS based on the // backlog rather than by EIP-1559, so it has no per-block cap and can increase sharply within the CacheTimeout window. // We avoid using an even larger buffer because even though the excess fee is refunded, it still increases the pre-transactional cost @@ -49,9 +48,11 @@ type FeeHistoryEstimatorConfig struct { BumpPercent uint16 CacheTimeout time.Duration - EIP1559 bool - BlockHistorySize uint64 - RewardPercentile float64 + EIP1559 bool + BlockHistorySize uint64 + RewardPercentile float64 + ConnectivityPercentile float64 + ChainType chaintype.ChainType } // dynamicFeeCache holds the cached results of a single RefreshDynamicFee round. @@ -85,11 +86,10 @@ type feeHistoryEstimatorClient interface { type FeeHistoryEstimator struct { services.StateMachine - client feeHistoryEstimatorClient - logger logger.Logger - config FeeHistoryEstimatorConfig - chainID *big.Int - chainType chaintype.ChainType + client feeHistoryEstimatorClient + logger logger.Logger + config FeeHistoryEstimatorConfig + chainID *big.Int gasPriceMu sync.RWMutex gasPrice *assets.Wei @@ -106,14 +106,16 @@ type FeeHistoryEstimator struct { refreshCh chan struct{} } -func NewFeeHistoryEstimator(lggr logger.Logger, client feeHistoryEstimatorClient, cfg FeeHistoryEstimatorConfig, chainID *big.Int, chainType chaintype.ChainType, l1Oracle rollups.L1Oracle) *FeeHistoryEstimator { +func NewFeeHistoryEstimator(lggr logger.Logger, client feeHistoryEstimatorClient, cfg FeeHistoryEstimatorConfig, chainID *big.Int, l1Oracle rollups.L1Oracle) *FeeHistoryEstimator { + if cfg.ConnectivityPercentile == 0 { + cfg.ConnectivityPercentile = ConnectivityPercentile + } l := logger.Sugared(logger.Named(lggr, "FeeHistoryEstimator")) return &FeeHistoryEstimator{ client: client, logger: l, config: cfg, chainID: chainID, - chainType: chainType, l1Oracle: l1Oracle, metrics: newFeeHistoryEstimatorMetrics(l, chainID), wg: new(sync.WaitGroup), @@ -128,9 +130,13 @@ func (f *FeeHistoryEstimator) Start(context.Context) error { return fmt.Errorf("BumpPercent: %s is less than minimum allowed percentage: %s", strconv.FormatUint(uint64(f.config.BumpPercent), 10), strconv.Itoa(MinimumBumpPercentage)) } - if f.config.EIP1559 && f.config.RewardPercentile > ConnectivityPercentile { - return fmt.Errorf("RewardPercentile: %s is greater than maximum allowed percentile: %s", - strconv.FormatUint(uint64(f.config.RewardPercentile), 10), strconv.Itoa(ConnectivityPercentile)) + if f.config.EIP1559 && f.config.ConnectivityPercentile > 100 { + return fmt.Errorf("ConnectivityPercentile: %g is greater than maximum allowed percentile: 100", + f.config.ConnectivityPercentile) + } + if f.config.EIP1559 && f.config.RewardPercentile > f.config.ConnectivityPercentile { + return fmt.Errorf("RewardPercentile: %g is greater than maximum allowed percentile: %g", + f.config.RewardPercentile, f.config.ConnectivityPercentile) } if f.config.CacheTimeout < MinimumCacheTimeout { return fmt.Errorf("CacheTimeout: %s must be at least %s", f.config.CacheTimeout, MinimumCacheTimeout) @@ -270,8 +276,8 @@ func (f *FeeHistoryEstimator) RefreshDynamicFee() error { ctx, cancel := f.stopCh.CtxWithTimeout(client.QueryTimeout) defer cancel() - // RewardPercentile will be used for maxPriorityFeePerGas estimations and connectivityPercentile to set the highest threshold for bumping. - feeHistory, err := f.client.FeeHistory(ctx, max(f.config.BlockHistorySize, 1), nil, []float64{f.config.RewardPercentile, ConnectivityPercentile}) + // RewardPercentile will be used for maxPriorityFeePerGas estimations and ConnectivityPercentile to set the highest threshold for bumping. + feeHistory, err := f.client.FeeHistory(ctx, max(f.config.BlockHistorySize, 1), nil, []float64{f.config.RewardPercentile, f.config.ConnectivityPercentile}) if err != nil { return err } @@ -378,7 +384,7 @@ func calcPriorityFees(rewards [][]*big.Int) (avg *assets.Wei, threshold *assets. // as the signal for a chain without a mempool. Arbitrum always gets the wider buffer, even when BlockHistorySize > 0 is // set to price priority fees, because its base fee has no per-block cap (see NoMempoolBaseFeeBufferPercentage). func (f *FeeHistoryEstimator) baseFeeBufferPercentage() uint16 { - if f.config.BlockHistorySize == 0 || f.chainType == chaintype.ChainArbitrum { + if f.config.BlockHistorySize == 0 || f.config.ChainType == chaintype.ChainArbitrum { return NoMempoolBaseFeeBufferPercentage } return BaseFeeBufferPercentage @@ -464,8 +470,8 @@ func (f *FeeHistoryEstimator) BumpDynamicFee(ctx context.Context, originalFee Dy } if bumpedMaxPriorityFeePerGas.Cmp(priorityFeeThreshold) > 0 { - return bumped, fmt.Errorf("%w: bumpedMaxPriorityFeePerGas: %s is above market's %sth percentile: %s, bumping is halted", - fees.ErrConnectivity, bumpedMaxPriorityFeePerGas, strconv.Itoa(ConnectivityPercentile), priorityFeeThreshold) + return bumped, fmt.Errorf("%w: bumpedMaxPriorityFeePerGas: %s is above market's %gth percentile: %s, bumping is halted", + fees.ErrConnectivity, bumpedMaxPriorityFeePerGas, f.config.ConnectivityPercentile, priorityFeeThreshold) } bumpedMaxFeePerGas, err = LimitBumpedFee(originalFee.GasFeeCap, currentDynamicFee.GasFeeCap, bumpedMaxFeePerGas, maxPrice) diff --git a/pkg/gas/fee_history_estimator_test.go b/pkg/gas/fee_history_estimator_test.go index a3443f3d83..670e6dacb4 100644 --- a/pkg/gas/fee_history_estimator_test.go +++ b/pkg/gas/fee_history_estimator_test.go @@ -35,7 +35,7 @@ func TestFeeHistoryEstimatorLifecycle(t *testing.T) { EIP1559: false, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) _, _, err := u.GetLegacyGas(t.Context(), nil, gasLimit, maxPrice) assert.ErrorContains(t, err, "gas price not set") }) @@ -43,7 +43,7 @@ func TestFeeHistoryEstimatorLifecycle(t *testing.T) { t.Run("fails to start if BumpPercent is lower than the minimum cap", func(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{BumpPercent: 9} - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) assert.ErrorContains(t, u.Start(t.Context()), "BumpPercent") }) @@ -54,10 +54,44 @@ func TestFeeHistoryEstimatorLifecycle(t *testing.T) { EIP1559: true, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) assert.ErrorContains(t, u.Start(t.Context()), "RewardPercentile") }) + t.Run("fails to start if ConnectivityPercentile is greater than 100 in EIP-1559", func(t *testing.T) { + cfg := gas.FeeHistoryEstimatorConfig{ + BumpPercent: 20, + RewardPercentile: 60, + ConnectivityPercentile: 101, + EIP1559: true, + } + + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) + assert.ErrorContains(t, u.Start(t.Context()), "ConnectivityPercentile") + }) + + t.Run("allows RewardPercentile up to custom ConnectivityPercentile", func(t *testing.T) { + client := mocks.NewFeeHistoryEstimatorClient(t) + client.On("FeeHistory", mock.Anything, mock.Anything, mock.Anything, []float64{90, 95}).Return(ðereum.FeeHistory{ + OldestBlock: big.NewInt(1), + BaseFee: []*big.Int{big.NewInt(100)}, + Reward: [][]*big.Int{{big.NewInt(10), big.NewInt(20)}}, + }, nil).Maybe() + + cfg := gas.FeeHistoryEstimatorConfig{ + BumpPercent: 20, + RewardPercentile: 90, + ConnectivityPercentile: 95, + CacheTimeout: 10 * time.Second, + BlockHistorySize: 1, + EIP1559: true, + } + + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + require.NoError(t, u.Start(t.Context())) + require.NoError(t, u.Close()) + }) + t.Run("fails to start if CacheTimeout is less than MinimumCacheTimeout", func(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{ BumpPercent: 20, @@ -65,7 +99,7 @@ func TestFeeHistoryEstimatorLifecycle(t *testing.T) { CacheTimeout: 200 * time.Millisecond, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) assert.ErrorContains(t, u.Start(t.Context()), "CacheTimeout") }) @@ -79,7 +113,7 @@ func TestFeeHistoryEstimatorLifecycle(t *testing.T) { CacheTimeout: 10 * time.Second, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) err := u.Start(t.Context()) assert.NoError(t, err) err = u.Close() @@ -100,7 +134,7 @@ func TestFeeHistoryEstimatorGetLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) _, err := u.RefreshGasPrice() assert.NoError(t, err) gasPrice, _, err := u.GetLegacyGas(t.Context(), nil, gasLimit, maxPrice) @@ -115,7 +149,7 @@ func TestFeeHistoryEstimatorGetLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{} maxPrice := assets.NewWeiI(1) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) _, err := u.RefreshGasPrice() assert.NoError(t, err) gas1, _, err := u.GetLegacyGas(t.Context(), nil, gasLimit, maxPrice) @@ -127,7 +161,7 @@ func TestFeeHistoryEstimatorGetLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{} maxPrice := assets.NewWeiI(1) - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) _, _, err := u.GetLegacyGas(t.Context(), nil, gasLimit, maxPrice) assert.Error(t, err) assert.ErrorContains(t, err, "gas price not set") @@ -148,7 +182,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{BumpPercent: 50, CacheTimeout: 5 * time.Second} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) servicetest.RunHealthy(t, u) gasPrice, _, err := u.BumpLegacyGas(t.Context(), originalGasPrice, gasLimit, maxPrice, nil) assert.NoError(t, err) @@ -159,7 +193,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { client := mocks.NewFeeHistoryEstimatorClient(t) cfg := gas.FeeHistoryEstimatorConfig{} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) var originalPrice *assets.Wei _, _, err := u.BumpLegacyGas(t.Context(), originalPrice, gasLimit, maxPrice, nil) @@ -177,7 +211,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) gas, _, err := u.BumpLegacyGas(t.Context(), originalGasPrice, gasLimit, maxPrice, nil) assert.NoError(t, err) assert.Equal(t, assets.NewWeiI(80), gas) @@ -191,7 +225,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{BumpPercent: 50} maxPrice := assets.NewWeiI(14) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) gas, _, err := u.BumpLegacyGas(t.Context(), originalGasPrice, gasLimit, maxPrice, nil) assert.NoError(t, err) assert.Equal(t, maxPrice, gas) @@ -205,7 +239,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{BumpPercent: 50} maxPrice := assets.NewWeiI(14) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) gas, _, err := u.BumpLegacyGas(t.Context(), originalGasPrice, gasLimit, maxPrice, nil) assert.NoError(t, err) assert.Equal(t, maxPrice, gas) @@ -220,7 +254,7 @@ func TestFeeHistoryEstimatorBumpLegacyGas(t *testing.T) { // Price will be capped by the max price maxPrice := assets.NewWeiI(101) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) _, _, err := u.BumpLegacyGas(t.Context(), originalGasPrice, gasLimit, maxPrice, nil) assert.Error(t, err) }) @@ -261,7 +295,7 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { avrgPriorityFee.Add(maxPriorityFeePerGas1, maxPriorityFeePerGas2).Div(avrgPriorityFee, big.NewInt(int64(blockHistoryLength))) maxFee := (*assets.Wei)(baseFee).AddPercentage(gas.BaseFeeBufferPercentage).Add((*assets.Wei)(avrgPriorityFee)) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) err := u.RefreshDynamicFee() assert.NoError(t, err) dynamicFee, err := u.GetDynamicFee(t.Context(), maxPrice) @@ -274,7 +308,7 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{} maxPrice := assets.NewWeiI(1) - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) _, err := u.GetDynamicFee(t.Context(), maxPrice) assert.Error(t, err) assert.ErrorContains(t, err, "dynamic fee not set") @@ -296,7 +330,7 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { cfg := gas.FeeHistoryEstimatorConfig{BlockHistorySize: 1} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) err := u.RefreshDynamicFee() assert.NoError(t, err) dynamicFee, err := u.GetDynamicFee(t.Context(), maxPrice) @@ -320,7 +354,7 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { // BlockHistorySize of 0 signals a chain without a mempool, so buffer is increased. cfg := gas.FeeHistoryEstimatorConfig{BlockHistorySize: 0, EIP1559: true} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) require.NoError(t, u.RefreshDynamicFee()) dynamicFee, err := u.GetDynamicFee(t.Context(), maxPrice) @@ -349,9 +383,9 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { } client.On("FeeHistory", mock.Anything, uint64(5), (*big.Int)(nil), []float64{60, gas.ConnectivityPercentile}).Return(feeHistoryResult, nil).Once() - cfg := gas.FeeHistoryEstimatorConfig{BlockHistorySize: 5, RewardPercentile: 60, EIP1559: true} + cfg := gas.FeeHistoryEstimatorConfig{BlockHistorySize: 5, RewardPercentile: 60, EIP1559: true, ChainType: chaintype.ChainArbitrum} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, chaintype.ChainArbitrum, nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) require.NoError(t, u.RefreshDynamicFee()) dynamicFee, err := u.GetDynamicFee(t.Context(), maxPrice) @@ -366,6 +400,30 @@ func TestFeeHistoryEstimatorGetDynamicFee(t *testing.T) { assert.Equal(t, expectedMaxFeeCap, maxFee.GasFeeCap) assert.Equal(t, assets.NewWei(priorityThreshold), maxFee.GasTipCap) }) + + t.Run("uses custom ConnectivityPercentile when configured", func(t *testing.T) { + client := mocks.NewFeeHistoryEstimatorClient(t) + baseFee := big.NewInt(100) + feeHistoryResult := ðereum.FeeHistory{ + OldestBlock: big.NewInt(1), + Reward: [][]*big.Int{{big.NewInt(10), big.NewInt(30)}}, + BaseFee: []*big.Int{baseFee}, + } + client.On("FeeHistory", mock.Anything, uint64(3), (*big.Int)(nil), []float64{60, 90}).Return(feeHistoryResult, nil).Once() + + cfg := gas.FeeHistoryEstimatorConfig{ + BlockHistorySize: 3, + RewardPercentile: 60, + ConnectivityPercentile: 90, + EIP1559: true, + } + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) + require.NoError(t, u.RefreshDynamicFee()) + + maxFee, err := u.GetMaxDynamicFee(assets.NewWeiI(1000)) + require.NoError(t, err) + assert.Equal(t, assets.NewWeiI(30), maxFee.GasTipCap) + }) } func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { @@ -381,7 +439,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { EIP1559: true, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), nil, cfg, chainID, nil) fee, err := u.GetMaxDynamicFee(maxPrice) require.Error(t, err) assert.ErrorContains(t, err, "priorityFeeThreshold not set") @@ -409,7 +467,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { BlockHistorySize: 2, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) err := u.RefreshDynamicFee() require.NoError(t, err) @@ -433,7 +491,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { client.On("FeeHistory", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(feeHistoryResult, nil).Once() cfg := gas.FeeHistoryEstimatorConfig{BumpPercent: 20, RewardPercentile: 60, EIP1559: true, BlockHistorySize: 2} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) require.NoError(t, u.RefreshDynamicFee()) fee, err := u.GetMaxDynamicFee(maxPrice) @@ -469,7 +527,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { BlockHistorySize: 2, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) require.NoError(t, u.RefreshDynamicFee()) // The priority fees are still unset, but the base fee has been cached. _, err := u.GetMaxDynamicFee(maxPrice) @@ -511,7 +569,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { BlockHistorySize: 2, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) require.NoError(t, u.RefreshDynamicFee()) require.NoError(t, u.RefreshDynamicFee()) @@ -547,7 +605,7 @@ func TestFeeHistoryEstimatorGetMaxDynamicFee(t *testing.T) { BlockHistorySize: 2, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) require.NoError(t, u.RefreshDynamicFee()) maxFee, err := u.GetMaxDynamicFee(maxPrice) @@ -592,7 +650,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { expectedFeeCap := originalFee.GasFeeCap.AddPercentage(cfg.BumpPercent) expectedTipCap := originalFee.GasTipCap.AddPercentage(cfg.BumpPercent) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) err := u.RefreshDynamicFee() assert.NoError(t, err) dynamicFee, err := u.BumpDynamicFee(t.Context(), originalFee, globalMaxPrice, nil) @@ -606,7 +664,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { maxPrice := assets.NewWeiI(20) cfg := gas.FeeHistoryEstimatorConfig{BlockHistorySize: 1} - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) // nil original fee var originalFee gas.DynamicFee _, err := u.BumpDynamicFee(t.Context(), originalFee, maxPrice, nil) @@ -654,7 +712,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { BumpPercent: 50, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) err := u.RefreshDynamicFee() assert.NoError(t, err) bumpedFee, err := u.BumpDynamicFee(t.Context(), originalFee, globalMaxPrice, nil) @@ -688,7 +746,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { BumpPercent: 50, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) err := u.RefreshDynamicFee() assert.NoError(t, err) _, err = u.BumpDynamicFee(t.Context(), originalFee, globalMaxPrice, nil) @@ -721,7 +779,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { BumpPercent: 50, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) err := u.RefreshDynamicFee() assert.NoError(t, err) bumpedFee, err := u.BumpDynamicFee(t.Context(), originalFee, maxPrice, nil) @@ -754,7 +812,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { BumpPercent: 50, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) err := u.RefreshDynamicFee() assert.NoError(t, err) _, err = u.BumpDynamicFee(t.Context(), originalFee, maxPrice, nil) @@ -788,7 +846,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { // No mempool means the wider staleness buffer applies. maxFeePerGas := assets.NewWei(baseFee).AddPercentage(gas.NoMempoolBaseFeeBufferPercentage) - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) servicetest.RunHealthy(t, u) bumpedFee, err := u.BumpDynamicFee(t.Context(), originalFee, globalMaxPrice, nil) assert.NoError(t, err) @@ -805,7 +863,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { } // The client is never called because the estimator isn't started. - u := gas.NewFeeHistoryEstimator(logger.Test(t), mocks.NewFeeHistoryEstimatorClient(t), cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), mocks.NewFeeHistoryEstimatorClient(t), cfg, chainID, nil) _, err := u.BumpDynamicFee(t.Context(), gas.DynamicFee{GasFeeCap: assets.NewWeiI(40), GasTipCap: assets.NewWeiI(0)}, globalMaxPrice, nil) require.ErrorContains(t, err, "estimator not started") }) @@ -821,7 +879,7 @@ func TestFeeHistoryEstimatorBumpDynamicFee(t *testing.T) { EIP1559: true, } - u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, "", nil) + u := gas.NewFeeHistoryEstimator(logger.Test(t), client, cfg, chainID, nil) servicetest.RunHealthy(t, u) _, err := u.BumpDynamicFee(t.Context(), gas.DynamicFee{GasFeeCap: assets.NewWeiI(40), GasTipCap: assets.NewWeiI(0)}, globalMaxPrice, nil) require.ErrorContains(t, err, "RPC unreachable") diff --git a/pkg/gas/models.go b/pkg/gas/models.go index 4b9b9b8456..2b88e8e819 100644 --- a/pkg/gas/models.go +++ b/pkg/gas/models.go @@ -106,13 +106,15 @@ func NewEstimator(lggr logger.Logger, ethClient FeeEstimatorClient, chainType ch newEstimator = NewSuggestedPriceEstimator(lggr, ethClient, geCfg, chainType, l1Oracle) case "FeeHistory": ccfg := FeeHistoryEstimatorConfig{ - BumpPercent: geCfg.BumpPercent(), - CacheTimeout: geCfg.FeeHistory().CacheTimeout(), - EIP1559: geCfg.EIP1559DynamicFees(), - BlockHistorySize: uint64(geCfg.BlockHistory().BlockHistorySize()), - RewardPercentile: float64(geCfg.BlockHistory().TransactionPercentile()), + BumpPercent: geCfg.BumpPercent(), + CacheTimeout: geCfg.FeeHistory().CacheTimeout(), + EIP1559: geCfg.EIP1559DynamicFees(), + BlockHistorySize: uint64(geCfg.BlockHistory().BlockHistorySize()), + RewardPercentile: float64(geCfg.BlockHistory().TransactionPercentile()), + ConnectivityPercentile: float64(geCfg.BlockHistory().CheckInclusionPercentile()), + ChainType: chainType, } - newEstimator = NewFeeHistoryEstimator(lggr, ethClient, ccfg, chainID, chainType, l1Oracle) + newEstimator = NewFeeHistoryEstimator(lggr, ethClient, ccfg, chainID, l1Oracle) default: lggr.Warnf("GasEstimator: unrecognised mode '%s', falling back to FixedPriceEstimator", s) newEstimator = NewFixedPriceEstimator(geCfg, ethClient, bh.EIP1559FeeCapBufferBlocks(), lggr, l1Oracle) From 4c04076ca1a24d6abad9c6ac53780f4d3cce81be Mon Sep 17 00:00:00 2001 From: Dimitris Date: Mon, 23 Nov 2026 19:14:53 +0200 Subject: [PATCH 3/5] Fix lint --- pkg/gas/arbitrum_estimator_test.go | 24 ++++++++++++------------ pkg/gas/fee_history_estimator.go | 8 +++++--- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/pkg/gas/arbitrum_estimator_test.go b/pkg/gas/arbitrum_estimator_test.go index 3d9b3cf89d..f648405cc5 100644 --- a/pkg/gas/arbitrum_estimator_test.go +++ b/pkg/gas/arbitrum_estimator_test.go @@ -38,13 +38,13 @@ func (a *arbFeeHistoryConfig) CacheTimeout() time.Duration { } type arbConfig struct { - v uint64 - bumpPercent uint16 - bumpMin *assets.Wei - eip1559 bool - feeHistory arbFeeHistoryConfig - blockHistory gas.MockBlockHistoryConfig - limitMultiplier float32 + v uint64 + bumpPercent uint16 + bumpMin *assets.Wei + eip1559 bool + feeHistory arbFeeHistoryConfig + blockHistory gas.MockBlockHistoryConfig + limitMultiplier float32 } func (a *arbConfig) LimitMax() uint64 { @@ -365,7 +365,7 @@ func TestArbitrumEstimator(t *testing.T) { var fee gas.EvmFee var estLimit uint64 require.Eventually(t, func() bool { - fee, estLimit, err = wrapped.GetFee(tests.Context(t), calldata, gasLimit, maxFeePrice, nil, nil) + fee, estLimit, err = wrapped.GetFee(t.Context(), calldata, gasLimit, maxFeePrice, nil, nil) return err == nil }, 5*time.Second, 20*time.Millisecond) @@ -375,7 +375,7 @@ func TestArbitrumEstimator(t *testing.T) { assert.Nil(t, fee.GasPrice) assert.Equal(t, expLimit, estLimit) - maxFee, maxEstLimit, err := wrapped.GetMaxFee(tests.Context(t), calldata, gasLimit, maxFeePrice, nil, nil) + maxFee, maxEstLimit, err := wrapped.GetMaxFee(t.Context(), calldata, gasLimit, maxFeePrice, nil, nil) require.NoError(t, err) expectedMaxFeeCap := assets.NewWei(baseFee).AddPercentage(gas.NoMempoolBaseFeeBufferPercentage).Add(assets.NewWei(priorityThreshold)) assert.Equal(t, expectedMaxFeeCap, maxFee.GasFeeCap) @@ -421,7 +421,7 @@ func TestArbitrumEstimator(t *testing.T) { maxFeePrice := assets.NewWeiI(1000) require.Eventually(t, func() bool { - _, _, err = wrapped.GetFee(tests.Context(t), calldata, gasLimit, maxFeePrice, nil, nil) + _, _, err = wrapped.GetFee(t.Context(), calldata, gasLimit, maxFeePrice, nil, nil) return err != nil && err.Error() != "dynamic fee not set" }, 5*time.Second, 20*time.Millisecond) assert.ErrorContains(t, err, "is greater than the maximum gas limit configured") @@ -475,12 +475,12 @@ func TestArbitrumEstimator(t *testing.T) { maxFeePrice := assets.NewWeiI(1000) var estLimit uint64 require.Eventually(t, func() bool { - _, estLimit, err = wrapped.GetFee(tests.Context(t), calldata, gasLimit, maxFeePrice, nil, nil) + _, estLimit, err = wrapped.GetFee(t.Context(), calldata, gasLimit, maxFeePrice, nil, nil) return err == nil }, 5*time.Second, 20*time.Millisecond) assert.Equal(t, gasLimit+10_000+1_000*uint64(len(calldata)), estLimit) - _, estLimit, err = wrapped.GetFee(tests.Context(t), calldata, gasLimit, maxFeePrice, nil, nil, fees.OptForceRefetch) + _, estLimit, err = wrapped.GetFee(t.Context(), calldata, gasLimit, maxFeePrice, nil, nil, fees.OptForceRefetch) require.NoError(t, err) assert.Equal(t, gasLimit+20_000+2_000*uint64(len(calldata)), estLimit) }) diff --git a/pkg/gas/fee_history_estimator.go b/pkg/gas/fee_history_estimator.go index 7e43858861..b78e0f2c87 100644 --- a/pkg/gas/fee_history_estimator.go +++ b/pkg/gas/fee_history_estimator.go @@ -48,9 +48,11 @@ type FeeHistoryEstimatorConfig struct { BumpPercent uint16 CacheTimeout time.Duration - EIP1559 bool - BlockHistorySize uint64 - RewardPercentile float64 + EIP1559 bool + BlockHistorySize uint64 + RewardPercentile float64 + + // If you're not sure what to set, use the defaults. ConnectivityPercentile float64 ChainType chaintype.ChainType } From 21efac33ca2658aab84bb7026bb104fc35729676 Mon Sep 17 00:00:00 2001 From: Dimitris Date: Mon, 23 Nov 2026 19:32:27 +0200 Subject: [PATCH 4/5] Remove unused chainID --- pkg/gas/fee_history_estimator.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/pkg/gas/fee_history_estimator.go b/pkg/gas/fee_history_estimator.go index b78e0f2c87..dc14789057 100644 --- a/pkg/gas/fee_history_estimator.go +++ b/pkg/gas/fee_history_estimator.go @@ -88,10 +88,9 @@ type feeHistoryEstimatorClient interface { type FeeHistoryEstimator struct { services.StateMachine - client feeHistoryEstimatorClient - logger logger.Logger - config FeeHistoryEstimatorConfig - chainID *big.Int + client feeHistoryEstimatorClient + logger logger.Logger + config FeeHistoryEstimatorConfig gasPriceMu sync.RWMutex gasPrice *assets.Wei @@ -117,7 +116,6 @@ func NewFeeHistoryEstimator(lggr logger.Logger, client feeHistoryEstimatorClient client: client, logger: l, config: cfg, - chainID: chainID, l1Oracle: l1Oracle, metrics: newFeeHistoryEstimatorMetrics(l, chainID), wg: new(sync.WaitGroup), From f8b6fb5507fe18de365f45d47f3531df6a87477f Mon Sep 17 00:00:00 2001 From: Dimitris Date: Tue, 24 Nov 2026 14:18:09 +0200 Subject: [PATCH 5/5] Fix gas multiplier --- pkg/gas/models.go | 9 ++- pkg/gas/models_test.go | 8 +-- pkg/txm/attempt_builder.go | 4 +- pkg/txm/attempt_builder_test.go | 103 ++++++++++++++++++++++++++++++++ pkg/txmgr/attempts_test.go | 61 +++++++++++++++++++ 5 files changed, 175 insertions(+), 10 deletions(-) diff --git a/pkg/gas/models.go b/pkg/gas/models.go index 2b88e8e819..1a148ff8c5 100644 --- a/pkg/gas/models.go +++ b/pkg/gas/models.go @@ -35,6 +35,8 @@ type EvmFeeEstimator interface { // L1Oracle returns the L1 gas price oracle only if the chain has one, e.g. OP stack L2s and Arbitrum. L1Oracle() rollups.L1Oracle GetFee(ctx context.Context, calldata []byte, feeLimit uint64, maxFeePrice *assets.Wei, fromAddress, toAddress *common.Address, opts ...fees.Opt) (fee EvmFee, estimatedFeeLimit uint64, err error) + // BumpFee bumps the fee of a previous attempt. feeLimit must be the previous attempt's limit, which already includes + // chain-specific adjustments and LimitMultiplier, so it is returned as is rather than multiplied again. BumpFee(ctx context.Context, originalFee EvmFee, feeLimit uint64, maxFeePrice *assets.Wei, attempts []EvmPriorAttempt) (bumpedFee EvmFee, chainSpecificFeeLimit uint64, err error) // GetMaxCost returns the total value = max price x fee units + transferred value @@ -363,7 +365,8 @@ func (e *evmFeeEstimator) BumpFee(ctx context.Context, originalFee EvmFee, feeLi if err != nil { return } - chainSpecificFeeLimit, err = fees.ApplyMultiplier(feeLimit, e.geCfg.LimitMultiplier()) + // feeLimit is the previous attempt's limit, which already includes chain-specific adjustments and LimitMultiplier. + chainSpecificFeeLimit = feeLimit bumpedFee.GasFeeCap = bumpedDynamic.GasFeeCap bumpedFee.GasTipCap = bumpedDynamic.GasTipCap return @@ -371,10 +374,6 @@ func (e *evmFeeEstimator) BumpFee(ctx context.Context, originalFee EvmFee, feeLi // bump legacy fee bumpedFee.GasPrice, chainSpecificFeeLimit, err = e.EvmEstimator.BumpLegacyGas(ctx, originalFee.GasPrice, feeLimit, maxFeePrice, attempts) - if err != nil { - return - } - chainSpecificFeeLimit, err = fees.ApplyMultiplier(chainSpecificFeeLimit, e.geCfg.LimitMultiplier()) return } diff --git a/pkg/gas/models_test.go b/pkg/gas/models_test.go index 2edaad41a3..b50939613a 100644 --- a/pkg/gas/models_test.go +++ b/pkg/gas/models_test.go @@ -112,20 +112,20 @@ func TestWrappedEvmEstimator(t *testing.T) { dynamicFees := false estimator := gas.NewEvmFeeEstimator(lggr, est, dynamicFees, geCfg, nil) - // expect legacy fee data + // expect legacy fee data without re-applying limitMultiplier fee, max, err := estimator.BumpFee(ctx, gas.EvmFee{GasPrice: assets.NewWeiI(0)}, 0, nil, nil) require.NoError(t, err) - assert.Equal(t, uint64(float32(gasLimit)*limitMultiplier), max) + assert.Equal(t, gasLimit, max) assert.True(t, legacyFee.Equal(fee.GasPrice)) assert.Nil(t, fee.GasTipCap) assert.Nil(t, fee.GasFeeCap) - // expect dynamic fee data + // expect dynamic fee data without re-applying limitMultiplier fee, max, err = estimator.BumpFee(ctx, gas.EvmFee{ DynamicFee: gas.DynamicFee{GasFeeCap: assets.NewWeiI(0), GasTipCap: assets.NewWeiI(0)}, }, gasLimit, nil, nil) require.NoError(t, err) - assert.Equal(t, uint64(float32(gasLimit)*limitMultiplier), max) + assert.Equal(t, gasLimit, max) assert.True(t, dynamicFee.GasFeeCap.Equal(fee.GasFeeCap)) assert.True(t, dynamicFee.GasTipCap.Equal(fee.GasTipCap)) assert.Nil(t, fee.GasPrice) diff --git a/pkg/txm/attempt_builder.go b/pkg/txm/attempt_builder.go index b388619cee..c43eea6eaf 100644 --- a/pkg/txm/attempt_builder.go +++ b/pkg/txm/attempt_builder.go @@ -107,7 +107,9 @@ func (a *attemptBuilder) NewAttempt(ctx context.Context, lggr logger.Logger, tx } func (a *attemptBuilder) NewBumpAttempt(ctx context.Context, lggr logger.Logger, tx *types.Transaction, previousAttempt types.Attempt) (*types.Attempt, error) { - gasLimit := tx.SpecifiedGasLimit + // Use the previous attempt's gas limit to preserve chain-specific adjustments. + // Note: this assumes the previous gas estimation is still valid because NewAgnosticBumpAttempt calls NewAttempt right before this function. + gasLimit := previousAttempt.GasLimit if tx.IsPurgeable { gasLimit = a.config.EmptyTxLimitDefault } diff --git a/pkg/txm/attempt_builder_test.go b/pkg/txm/attempt_builder_test.go index bd984cec6e..618dfcbc07 100644 --- a/pkg/txm/attempt_builder_test.go +++ b/pkg/txm/attempt_builder_test.go @@ -19,6 +19,7 @@ import ( "github.com/smartcontractkit/chainlink-evm/pkg/keys/keystest" "github.com/smartcontractkit/chainlink-evm/pkg/testutils" "github.com/smartcontractkit/chainlink-evm/pkg/txm/types" + pkgtypes "github.com/smartcontractkit/chainlink-evm/pkg/types" "github.com/smartcontractkit/chainlink-framework/chains/fees" ) @@ -504,3 +505,105 @@ func TestAttemptBuilder_NewAgnosticBumpAttempt(t *testing.T) { mockEstimator.AssertExpectations(t) }) } + +type staticLimitConfig struct { + limitMultiplier float32 +} + +func (c staticLimitConfig) LimitMultiplier() float32 { return c.limitMultiplier } +func (c staticLimitConfig) EstimateLimit() bool { return false } +func (c staticLimitConfig) SenderAddress() *pkgtypes.EIP55Address { return nil } + +func TestAttemptBuilder_NewBumpAttempt_PreservesAdjustedGasLimit(t *testing.T) { + address := testutils.NewAddress() + lggr := logger.Test(t) + var nonce uint64 = 7 + priceMaxKey := func(addr common.Address) *assets.Wei { return assets.GWei(100) } + + t.Run("preserves L1-adjusted dynamic attempt limit without re-applying LimitMultiplier", func(t *testing.T) { + underlying := mocks.NewEvmEstimator(t) + initialFee := gas.DynamicFee{GasFeeCap: assets.GWei(10), GasTipCap: assets.GWei(1)} + bumpedFee := gas.DynamicFee{GasFeeCap: assets.GWei(12), GasTipCap: assets.GWei(2)} + underlying.On("BumpDynamicFee", mock.Anything, initialFee, assets.GWei(100), mock.Anything). + Return(bumpedFee, nil).Once() + + feeEstimator := gas.NewEvmFeeEstimator(lggr, underlying, true, staticLimitConfig{limitMultiplier: 1.5}, nil) + ab := NewAttemptBuilder(priceMaxKey, feeEstimator, keystest.TxSigner(nil), 21000, false) + + const specifiedLimit uint64 = 80_000 + const adjustedPrevLimit uint64 = 180_000 // e.g. (specifiedLimit + L1 calldata cost) * LimitMultiplier + tx := &types.Transaction{ + ID: 1, + FromAddress: address, + Nonce: &nonce, + SpecifiedGasLimit: specifiedLimit, + } + prevAttempt := types.Attempt{ + Fee: gas.EvmFee{DynamicFee: initialFee}, + GasLimit: adjustedPrevLimit, + Type: evmtypes.DynamicFeeTxType, + } + + bumped, err := ab.NewBumpAttempt(t.Context(), lggr, tx, prevAttempt) + require.NoError(t, err) + assert.Equal(t, adjustedPrevLimit, bumped.GasLimit) + assert.Equal(t, adjustedPrevLimit, bumped.SignedTransaction.Gas()) + assert.Equal(t, bumpedFee.GasFeeCap, bumped.Fee.GasFeeCap) + assert.Equal(t, bumpedFee.GasTipCap, bumped.Fee.GasTipCap) + }) + + t.Run("preserves adjusted legacy attempt limit without re-applying LimitMultiplier", func(t *testing.T) { + underlying := mocks.NewEvmEstimator(t) + const adjustedPrevLimit uint64 = 180_000 + underlying.On("BumpLegacyGas", mock.Anything, assets.GWei(10), adjustedPrevLimit, assets.GWei(100), mock.Anything). + Return(assets.GWei(12), adjustedPrevLimit, nil).Once() + + feeEstimator := gas.NewEvmFeeEstimator(lggr, underlying, false, staticLimitConfig{limitMultiplier: 1.5}, nil) + ab := NewAttemptBuilder(priceMaxKey, feeEstimator, keystest.TxSigner(nil), 21000, false) + + tx := &types.Transaction{ + ID: 2, + FromAddress: address, + Nonce: &nonce, + SpecifiedGasLimit: 80_000, + } + prevAttempt := types.Attempt{ + Fee: gas.EvmFee{GasPrice: assets.GWei(10)}, + GasLimit: adjustedPrevLimit, + Type: evmtypes.LegacyTxType, + } + + bumped, err := ab.NewBumpAttempt(t.Context(), lggr, tx, prevAttempt) + require.NoError(t, err) + assert.Equal(t, adjustedPrevLimit, bumped.GasLimit) + assert.Equal(t, adjustedPrevLimit, bumped.SignedTransaction.Gas()) + }) + + t.Run("uses EmptyTxLimitDefault for purgeable tx", func(t *testing.T) { + underlying := mocks.NewEvmEstimator(t) + initialFee := gas.DynamicFee{GasFeeCap: assets.GWei(10), GasTipCap: assets.GWei(1)} + bumpedFee := gas.DynamicFee{GasFeeCap: assets.GWei(12), GasTipCap: assets.GWei(2)} + underlying.On("BumpDynamicFee", mock.Anything, initialFee, assets.GWei(100), mock.Anything). + Return(bumpedFee, nil).Once() + + feeEstimator := gas.NewEvmFeeEstimator(lggr, underlying, true, staticLimitConfig{limitMultiplier: 1.5}, nil) + ab := NewAttemptBuilder(priceMaxKey, feeEstimator, keystest.TxSigner(nil), 21000, false) + + tx := &types.Transaction{ + ID: 3, + FromAddress: address, + Nonce: &nonce, + IsPurgeable: true, + SpecifiedGasLimit: 80_000, + } + prevAttempt := types.Attempt{ + Fee: gas.EvmFee{DynamicFee: initialFee}, + GasLimit: 180_000, + Type: evmtypes.DynamicFeeTxType, + } + + bumped, err := ab.NewBumpAttempt(t.Context(), lggr, tx, prevAttempt) + require.NoError(t, err) + assert.Equal(t, uint64(21000), bumped.GasLimit) + }) +} diff --git a/pkg/txmgr/attempts_test.go b/pkg/txmgr/attempts_test.go index 81afa557d2..b06717a177 100644 --- a/pkg/txmgr/attempts_test.go +++ b/pkg/txmgr/attempts_test.go @@ -354,3 +354,64 @@ func TestTxm_EvmTxAttemptBuilder_RetryableEstimatorError(t *testing.T) { assert.True(t, retryable) }) } + +type testLimitEstimationConfig struct { + limitMultiplier float32 +} + +func (c testLimitEstimationConfig) LimitMultiplier() float32 { return c.limitMultiplier } +func (c testLimitEstimationConfig) EstimateLimit() bool { return false } +func (c testLimitEstimationConfig) SenderAddress() *evmtypes.EIP55Address { return nil } + +func TestTxm_NewBumpTxAttempt_PreservesAdjustedFeeLimit(t *testing.T) { + addr := NewEvmAddress() + kst := keystest.TxSigner(nil) + lggr := logger.Test(t) + n := evmtypes.Nonce(1) + + gc := newFeeConfig() + gc.eip1559DynamicFees = true + gc.priceMin = assets.GWei(1) + gc.priceMax = assets.GWei(100) + gc.tipCapMin = assets.GWei(1) + + const adjustedLimit uint64 = 180_000 + + t.Run("dynamic bump preserves previous ChainSpecificFeeLimit without re-applying LimitMultiplier", func(t *testing.T) { + underlying := gasmocks.NewEvmEstimator(t) + initialFee := gas.DynamicFee{GasFeeCap: assets.GWei(10), GasTipCap: assets.GWei(2)} + bumpedFee := gas.DynamicFee{GasFeeCap: assets.GWei(12), GasTipCap: assets.GWei(3)} + underlying.On("BumpDynamicFee", mock.Anything, initialFee, gc.priceMax, mock.Anything). + Return(bumpedFee, nil).Once() + + est := gas.NewEvmFeeEstimator(lggr, underlying, true, testLimitEstimationConfig{limitMultiplier: 1.5}, nil) + cks := txmgr.NewEvmTxAttemptBuilder(*big.NewInt(1), gc, kst, est) + + etx := txmgr.Tx{Sequence: &n, FromAddress: addr, FeeLimit: 80_000} + prevAttempt, _, err := cks.NewCustomTxAttempt(t.Context(), etx, gas.EvmFee{DynamicFee: initialFee}, adjustedLimit, 0x2, lggr) + require.NoError(t, err) + + bumped, _, bumpedLimit, _, err := cks.NewBumpTxAttempt(t.Context(), etx, prevAttempt, nil, lggr) + require.NoError(t, err) + assert.Equal(t, adjustedLimit, bumpedLimit) + assert.Equal(t, adjustedLimit, bumped.ChainSpecificFeeLimit) + }) + + t.Run("legacy bump preserves previous ChainSpecificFeeLimit without re-applying LimitMultiplier", func(t *testing.T) { + underlying := gasmocks.NewEvmEstimator(t) + underlying.On("BumpLegacyGas", mock.Anything, assets.GWei(10), adjustedLimit, gc.priceMax, mock.Anything). + Return(assets.GWei(12), adjustedLimit, nil).Once() + + est := gas.NewEvmFeeEstimator(lggr, underlying, false, testLimitEstimationConfig{limitMultiplier: 1.5}, nil) + cks := txmgr.NewEvmTxAttemptBuilder(*big.NewInt(1), gc, kst, est) + + etx := txmgr.Tx{Sequence: &n, FromAddress: addr, FeeLimit: 80_000} + prevAttempt, _, err := cks.NewCustomTxAttempt(t.Context(), etx, gas.EvmFee{GasPrice: assets.GWei(10)}, adjustedLimit, 0x0, lggr) + require.NoError(t, err) + + bumped, _, bumpedLimit, _, err := cks.NewBumpTxAttempt(t.Context(), etx, prevAttempt, nil, lggr) + require.NoError(t, err) + assert.Equal(t, adjustedLimit, bumpedLimit) + assert.Equal(t, adjustedLimit, bumped.ChainSpecificFeeLimit) + }) +}