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