Skip to main content

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