reth_rpc_eth_api/helpers/
fee.rs

1//! Loads fee history from database. Helper trait for `eth_` fee and transaction RPC methods.
2
3use super::LoadBlock;
4use crate::FromEthApiError;
5use alloy_consensus::BlockHeader;
6use alloy_eips::eip7840::BlobParams;
7use alloy_primitives::U256;
8use alloy_rpc_types_eth::{BlockNumberOrTag, FeeHistory};
9use futures::Future;
10use reth_chainspec::{ChainSpecProvider, EthChainSpec};
11use reth_primitives_traits::BlockBody;
12use reth_rpc_eth_types::{
13    fee_history::calculate_reward_percentiles_for_block, utils::checked_blob_gas_used_ratio,
14    EthApiError, FeeHistoryCache, FeeHistoryEntry, GasPriceOracle, RpcInvalidTransactionError,
15};
16use reth_storage_api::{BlockIdReader, BlockReaderIdExt, HeaderProvider, ProviderHeader};
17use tracing::debug;
18
19/// Fee related functions for the [`EthApiServer`](crate::EthApiServer) trait in the
20/// `eth_` namespace.
21pub trait EthFees:
22    LoadFee<
23    Provider: ChainSpecProvider<ChainSpec: EthChainSpec<Header = ProviderHeader<Self::Provider>>>,
24>
25{
26    /// Returns a suggestion for a gas price for legacy transactions.
27    ///
28    /// See also: <https://github.com/ethereum/pm/issues/328#issuecomment-853234014>
29    fn gas_price(&self) -> impl Future<Output = Result<U256, Self::Error>> + Send
30    where
31        Self: LoadBlock,
32    {
33        LoadFee::gas_price(self)
34    }
35
36    /// Returns a suggestion for a base fee for blob transactions.
37    fn blob_base_fee(&self) -> impl Future<Output = Result<U256, Self::Error>> + Send
38    where
39        Self: LoadBlock,
40    {
41        LoadFee::blob_base_fee(self)
42    }
43
44    /// Returns a suggestion for the priority fee (the tip)
45    fn suggested_priority_fee(&self) -> impl Future<Output = Result<U256, Self::Error>> + Send
46    where
47        Self: 'static,
48    {
49        LoadFee::suggested_priority_fee(self)
50    }
51
52    /// Reports the fee history, for the given amount of blocks, up until the given newest block.
53    ///
54    /// If `reward_percentiles` are provided the [`FeeHistory`] will include the _approximated_
55    /// rewards for the requested range.
56    fn fee_history(
57        &self,
58        mut block_count: u64,
59        mut newest_block: BlockNumberOrTag,
60        reward_percentiles: Option<Vec<f64>>,
61    ) -> impl Future<Output = Result<FeeHistory, Self::Error>> + Send {
62        async move {
63            if block_count == 0 {
64                return Ok(FeeHistory::default())
65            }
66
67            // ensure the given reward percentiles aren't excessive
68            if reward_percentiles.as_ref().map(|perc| perc.len() as u64) >
69                Some(self.gas_oracle().config().max_reward_percentile_count)
70            {
71                return Err(EthApiError::InvalidRewardPercentiles.into())
72            }
73
74            // See https://github.com/ethereum/go-ethereum/blob/2754b197c935ee63101cbbca2752338246384fec/eth/gasprice/feehistory.go#L218C8-L225
75            let max_fee_history = if reward_percentiles.is_none() {
76                self.gas_oracle().config().max_header_history
77            } else {
78                self.gas_oracle().config().max_block_history
79            };
80
81            if block_count > max_fee_history {
82                debug!(
83                    requested = block_count,
84                    truncated = max_fee_history,
85                    "Sanitizing fee history block count"
86                );
87                block_count = max_fee_history
88            }
89
90            if newest_block.is_pending() {
91                // cap the target block since we don't have fee history for the pending block
92                newest_block = BlockNumberOrTag::Latest;
93            }
94
95            let end_block = self
96                .provider()
97                .block_number_for_id(newest_block.into())
98                .map_err(Self::Error::from_eth_err)?
99                .ok_or(EthApiError::HeaderNotFound(newest_block.into()))?;
100
101            // need to add 1 to the end block to get the correct (inclusive) range
102            let end_block_plus = end_block + 1;
103            // Ensure that we would not be querying outside of genesis
104            if end_block_plus < block_count {
105                block_count = end_block_plus;
106            }
107
108            // If reward percentiles were specified, we
109            // need to validate that they are monotonically
110            // increasing and 0 <= p <= 100
111            // Note: The types used ensure that the percentiles are never < 0
112            if let Some(percentiles) = &reward_percentiles {
113                if percentiles.windows(2).any(|w| w[0] > w[1] || w[0] > 100.) {
114                    return Err(EthApiError::InvalidRewardPercentiles.into())
115                }
116            }
117
118            // Fetch the headers and ensure we got all of them
119            //
120            // Treat a request for 1 block as a request for `newest_block..=newest_block`,
121            // otherwise `newest_block - 2`
122            // NOTE: We ensured that block count is capped
123            let start_block = end_block_plus - block_count;
124
125            // Collect base fees, gas usage ratios and (optionally) reward percentile data
126            let mut base_fee_per_gas: Vec<u128> = Vec::new();
127            let mut gas_used_ratio: Vec<f64> = Vec::new();
128
129            let mut base_fee_per_blob_gas: Vec<u128> = Vec::new();
130            let mut blob_gas_used_ratio: Vec<f64> = Vec::new();
131
132            let mut rewards: Vec<Vec<u128>> = Vec::new();
133
134            // Check if the requested range is within the cache bounds
135            let fee_entries = self.fee_history_cache().get_history(start_block, end_block).await;
136
137            if let Some(fee_entries) = fee_entries {
138                if fee_entries.len() != block_count as usize {
139                    return Err(EthApiError::InvalidBlockRange.into())
140                }
141
142                for entry in &fee_entries {
143                    base_fee_per_gas
144                        .push(entry.header.base_fee_per_gas().unwrap_or_default() as u128);
145                    gas_used_ratio.push(entry.gas_used_ratio);
146                    base_fee_per_blob_gas.push(entry.base_fee_per_blob_gas.unwrap_or_default());
147                    blob_gas_used_ratio.push(entry.blob_gas_used_ratio);
148
149                    if let Some(percentiles) = &reward_percentiles {
150                        let mut block_rewards = Vec::with_capacity(percentiles.len());
151                        for &percentile in percentiles {
152                            block_rewards.push(self.approximate_percentile(entry, percentile));
153                        }
154                        rewards.push(block_rewards);
155                    }
156                }
157                let last_entry = fee_entries.last().expect("is not empty");
158
159                // Also need to include the `base_fee_per_gas` and `base_fee_per_blob_gas` for the
160                // next block
161                base_fee_per_gas.push(
162                    self.provider()
163                        .chain_spec()
164                        .next_block_base_fee(&last_entry.header, last_entry.header.timestamp())
165                        .unwrap_or_default() as u128,
166                );
167
168                base_fee_per_blob_gas.push(last_entry.next_block_blob_fee().unwrap_or_default());
169            } else {
170                // read the requested header range
171                let headers = self.provider()
172                    .sealed_headers_range(start_block..=end_block)
173                    .map_err(Self::Error::from_eth_err)?;
174                if headers.len() != block_count as usize {
175                    return Err(EthApiError::InvalidBlockRange.into())
176                }
177
178                let chain_spec = self.provider().chain_spec();
179                for header in &headers {
180                    base_fee_per_gas.push(header.base_fee_per_gas().unwrap_or_default() as u128);
181                    gas_used_ratio.push(header.gas_used() as f64 / header.gas_limit() as f64);
182
183                    let blob_params = chain_spec
184                        .blob_params_at_timestamp(header.timestamp())
185                        .unwrap_or_else(BlobParams::cancun);
186
187                    base_fee_per_blob_gas.push(header.blob_fee(blob_params).unwrap_or_default());
188                    blob_gas_used_ratio.push(
189                        checked_blob_gas_used_ratio(
190                            header.blob_gas_used().unwrap_or_default(),
191                            blob_params.max_blob_gas_per_block(),
192                        )
193                    );
194
195                    // Percentiles were specified, so we need to collect reward percentile info
196                    if let Some(percentiles) = &reward_percentiles {
197                        let (block, receipts) = self.cache()
198                            .get_block_and_receipts(header.hash())
199                            .await
200                            .map_err(Self::Error::from_eth_err)?
201                            .ok_or(EthApiError::InvalidBlockRange)?;
202                        rewards.push(
203                            calculate_reward_percentiles_for_block(
204                                percentiles,
205                                header.gas_used(),
206                                header.base_fee_per_gas().unwrap_or_default(),
207                                block.body().transactions(),
208                                &receipts,
209                            )
210                            .unwrap_or_default(),
211                        );
212                    }
213                }
214
215                // The spec states that `base_fee_per_gas` "[..] includes the next block after the
216                // newest of the returned range, because this value can be derived from the
217                // newest block"
218                //
219                // The unwrap is safe since we checked earlier that we got at least 1 header.
220                let last_header = headers.last().expect("is present");
221                base_fee_per_gas.push(
222                    chain_spec
223                        .next_block_base_fee(last_header.header(), last_header.timestamp())
224                        .unwrap_or_default() as u128,
225                );
226                // Same goes for the `base_fee_per_blob_gas`:
227                // > "[..] includes the next block after the newest of the returned range, because this value can be derived from the newest block.
228                base_fee_per_blob_gas.push(
229                    last_header
230                    .maybe_next_block_blob_fee(
231                        chain_spec.blob_params_at_timestamp(last_header.timestamp())
232                    ).unwrap_or_default()
233                );
234            };
235
236            Ok(FeeHistory {
237                base_fee_per_gas,
238                gas_used_ratio,
239                base_fee_per_blob_gas,
240                blob_gas_used_ratio,
241                oldest_block: start_block,
242                reward: reward_percentiles.map(|_| rewards),
243            })
244        }
245    }
246
247    /// Approximates reward at a given percentile for a specific block
248    /// Based on the configured resolution
249    fn approximate_percentile(
250        &self,
251        entry: &FeeHistoryEntry<ProviderHeader<Self::Provider>>,
252        requested_percentile: f64,
253    ) -> u128 {
254        let resolution = self.fee_history_cache().resolution();
255        let rounded_percentile =
256            (requested_percentile * resolution as f64).round() / resolution as f64;
257        let clamped_percentile = rounded_percentile.clamp(0.0, 100.0);
258
259        // Calculate the index in the precomputed rewards array
260        let index = (clamped_percentile / (1.0 / resolution as f64)).round() as usize;
261        // Fetch the reward from the FeeHistoryEntry
262        entry.rewards.get(index).copied().unwrap_or_default()
263    }
264}
265
266/// Loads fee from database.
267///
268/// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` fees RPC methods.
269pub trait LoadFee: LoadBlock
270where
271    Self::Provider: BlockReaderIdExt,
272{
273    /// Returns a handle for reading gas price.
274    ///
275    /// Data access in default (L1) trait method implementations.
276    fn gas_oracle(&self) -> &GasPriceOracle<Self::Provider>;
277
278    /// Returns a handle for reading fee history data from memory.
279    ///
280    /// Data access in default (L1) trait method implementations.
281    fn fee_history_cache(&self) -> &FeeHistoryCache<ProviderHeader<Self::Provider>>;
282
283    /// Returns the gas price if it is set, otherwise fetches a suggested gas price for legacy
284    /// transactions.
285    fn legacy_gas_price(
286        &self,
287        gas_price: Option<U256>,
288    ) -> impl Future<Output = Result<U256, Self::Error>> + Send {
289        async move {
290            match gas_price {
291                Some(gas_price) => Ok(gas_price),
292                None => {
293                    // fetch a suggested gas price
294                    self.gas_price().await
295                }
296            }
297        }
298    }
299
300    /// Returns the EIP-1559 fees if they are set, otherwise fetches a suggested gas price for
301    /// EIP-1559 transactions.
302    ///
303    /// Returns (`base_fee`, `priority_fee`)
304    fn eip1559_fees(
305        &self,
306        base_fee: Option<U256>,
307        max_priority_fee_per_gas: Option<U256>,
308    ) -> impl Future<Output = Result<(U256, U256), Self::Error>> + Send {
309        async move {
310            let base_fee = match base_fee {
311                Some(base_fee) => base_fee,
312                None => {
313                    // fetch pending base fee
314                    let base_fee = self
315                        .recovered_block(BlockNumberOrTag::Pending.into())
316                        .await?
317                        .ok_or(EthApiError::HeaderNotFound(BlockNumberOrTag::Pending.into()))?
318                        .base_fee_per_gas()
319                        .ok_or(EthApiError::InvalidTransaction(
320                            RpcInvalidTransactionError::TxTypeNotSupported,
321                        ))?;
322                    U256::from(base_fee)
323                }
324            };
325
326            let max_priority_fee_per_gas = match max_priority_fee_per_gas {
327                Some(max_priority_fee_per_gas) => max_priority_fee_per_gas,
328                None => self.suggested_priority_fee().await?,
329            };
330            Ok((base_fee, max_priority_fee_per_gas))
331        }
332    }
333
334    /// Returns the EIP-4844 blob fee if it is set, otherwise fetches a blob fee.
335    fn eip4844_blob_fee(
336        &self,
337        blob_fee: Option<U256>,
338    ) -> impl Future<Output = Result<U256, Self::Error>> + Send {
339        async move {
340            match blob_fee {
341                Some(blob_fee) => Ok(blob_fee),
342                None => self.blob_base_fee().await,
343            }
344        }
345    }
346
347    /// Returns a suggestion for a gas price for legacy transactions.
348    ///
349    /// See also: <https://github.com/ethereum/pm/issues/328#issuecomment-853234014>
350    fn gas_price(&self) -> impl Future<Output = Result<U256, Self::Error>> + Send {
351        async move {
352            let header = self.provider().latest_header().map_err(Self::Error::from_eth_err)?;
353            let suggested_tip = self.suggested_priority_fee().await?;
354            let base_fee = header.and_then(|h| h.base_fee_per_gas()).unwrap_or_default();
355            Ok(suggested_tip + U256::from(base_fee))
356        }
357    }
358
359    /// Returns a suggestion for a base fee for blob transactions.
360    fn blob_base_fee(&self) -> impl Future<Output = Result<U256, Self::Error>> + Send {
361        async move {
362            self.provider()
363                .latest_header()
364                .map_err(Self::Error::from_eth_err)?
365                .and_then(|h| {
366                    h.maybe_next_block_blob_fee(
367                        self.provider().chain_spec().blob_params_at_timestamp(h.timestamp()),
368                    )
369                })
370                .ok_or(EthApiError::ExcessBlobGasNotSet.into())
371                .map(U256::from)
372        }
373    }
374
375    /// Returns a suggestion for the priority fee (the tip)
376    fn suggested_priority_fee(&self) -> impl Future<Output = Result<U256, Self::Error>> + Send
377    where
378        Self: 'static,
379    {
380        async move { self.gas_oracle().suggest_tip_cap().await.map_err(Self::Error::from_eth_err) }
381    }
382}