reth_rpc_eth_api/helpers/
fee.rs1use 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
21pub trait EthFees:
24 LoadFee<
25 Provider: ChainSpecProvider<ChainSpec: EthChainSpec<Header = ProviderHeader<Self::Provider>>>,
26>
27{
28 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 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 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 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 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 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 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 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 newest_block = BlockNumberOrTag::Latest;
114 }
115
116 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 let end_block_plus = end_block + 1;
135 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 let start_block = end_block_plus - block_count;
145
146 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 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 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 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 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 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 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 let index = (clamped_percentile / (1.0 / resolution as f64)).round() as usize;
291 entry.rewards.get(index).copied().unwrap_or_default()
293 }
294}
295
296pub trait LoadFee: LoadBlock
300where
301 Self::Provider: BlockReaderIdExt,
302{
303 fn gas_oracle(&self) -> &GasPriceOracle<Self::Provider>;
307
308 fn fee_history_cache(&self) -> &FeeHistoryCache<ProviderHeader<Self::Provider>>;
312
313 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 self.gas_price().await
325 }
326 }
327 }
328 }
329
330 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 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 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 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 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 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 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}