1use std::{
2 collections::BTreeMap,
3 fmt,
4 pin::Pin,
5 sync::Arc,
6 task::{Context, Poll},
7};
8
9use alloy_consensus::{BlockHeader, Transaction, TxReceipt};
10use alloy_eips::{calc_next_block_base_fee, eip1559::BaseFeeParams, eip7840::BlobParams};
11use alloy_network::Network;
12use alloy_primitives::B256;
13use futures::StreamExt;
14use parking_lot::{Mutex, RwLock};
15use revm::{context_interface::block::BlobExcessGasAndPrice, primitives::hardfork::SpecId};
16
17use crate::eth::{
18 backend::{info::StorageInfo, notifications::NewBlockNotifications},
19 error::BlockchainError,
20};
21
22pub const MAX_FEE_HISTORY_CACHE_SIZE: u64 = 2048u64;
24
25pub const INITIAL_BASE_FEE: u64 = 1_000_000_000;
27
28pub const INITIAL_GAS_PRICE: u128 = 1_875_000_000;
30
31pub const BASE_FEE_CHANGE_DENOMINATOR: u128 = 8;
33
34pub const MIN_SUGGESTED_PRIORITY_FEE: u128 = 1e9 as u128;
36
37#[derive(Clone, Debug)]
39pub struct FeeManager {
40 spec_id: SpecId,
42 blob_params: Arc<RwLock<BlobParams>>,
44 base_fee: Arc<RwLock<u64>>,
48 is_min_priority_fee_enforced: bool,
50 blob_excess_gas_and_price: Arc<RwLock<BlobExcessGasAndPrice>>,
54 gas_price: Arc<RwLock<u128>>,
58 elasticity: Arc<RwLock<f64>>,
59 base_fee_params: BaseFeeParams,
61}
62
63impl FeeManager {
64 pub fn new(
65 spec_id: SpecId,
66 base_fee: u64,
67 is_min_priority_fee_enforced: bool,
68 gas_price: u128,
69 blob_excess_gas_and_price: BlobExcessGasAndPrice,
70 blob_params: BlobParams,
71 base_fee_params: BaseFeeParams,
72 ) -> Self {
73 let elasticity = 1f64 / base_fee_params.elasticity_multiplier as f64;
74 Self {
75 spec_id,
76 blob_params: Arc::new(RwLock::new(blob_params)),
77 base_fee: Arc::new(RwLock::new(base_fee)),
78 is_min_priority_fee_enforced,
79 gas_price: Arc::new(RwLock::new(gas_price)),
80 blob_excess_gas_and_price: Arc::new(RwLock::new(blob_excess_gas_and_price)),
81 elasticity: Arc::new(RwLock::new(elasticity)),
82 base_fee_params,
83 }
84 }
85
86 pub const fn base_fee_params(&self) -> BaseFeeParams {
88 self.base_fee_params
89 }
90
91 pub fn elasticity(&self) -> f64 {
92 *self.elasticity.read()
93 }
94
95 pub const fn is_eip1559(&self) -> bool {
97 (self.spec_id as u8) >= (SpecId::LONDON as u8)
98 }
99
100 pub const fn is_eip4844(&self) -> bool {
101 (self.spec_id as u8) >= (SpecId::CANCUN as u8)
102 }
103
104 pub fn blob_gas_price(&self) -> u128 {
106 if self.is_eip4844() { self.base_fee_per_blob_gas() } else { 0 }
107 }
108
109 pub fn base_fee(&self) -> u64 {
110 if self.is_eip1559() { *self.base_fee.read() } else { 0 }
111 }
112
113 pub const fn is_min_priority_fee_enforced(&self) -> bool {
114 self.is_min_priority_fee_enforced
115 }
116
117 pub fn raw_gas_price(&self) -> u128 {
119 *self.gas_price.read()
120 }
121
122 pub fn excess_blob_gas_and_price(&self) -> Option<BlobExcessGasAndPrice> {
123 self.is_eip4844().then(|| *self.blob_excess_gas_and_price.read())
124 }
125
126 pub fn base_fee_per_blob_gas(&self) -> u128 {
127 if self.is_eip4844() { self.blob_excess_gas_and_price.read().blob_gasprice } else { 0 }
128 }
129
130 pub fn set_gas_price(&self, price: u128) {
132 let mut gas = self.gas_price.write();
133 *gas = price;
134 }
135
136 pub fn set_base_fee(&self, fee: u64) {
138 trace!(target: "backend::fees", "updated base fee {:?}", fee);
139 let mut base = self.base_fee.write();
140 *base = fee;
141 }
142
143 pub fn set_blob_excess_gas_and_price(&self, blob_excess_gas_and_price: BlobExcessGasAndPrice) {
145 trace!(target: "backend::fees", "updated blob base fee {:?}", blob_excess_gas_and_price);
146 let mut base = self.blob_excess_gas_and_price.write();
147 *base = blob_excess_gas_and_price;
148 }
149
150 pub fn get_next_block_base_fee_per_gas(
152 &self,
153 gas_used: u64,
154 gas_limit: u64,
155 last_fee_per_gas: u64,
156 ) -> u64 {
157 if self.base_fee() == 0 {
161 return 0;
162 }
163 calc_next_block_base_fee(gas_used, gas_limit, last_fee_per_gas, self.base_fee_params)
164 }
165
166 pub fn get_next_block_blob_base_fee_per_gas(&self) -> u128 {
168 self.blob_params().calc_blob_fee(self.blob_excess_gas_and_price.read().excess_blob_gas)
169 }
170
171 pub fn get_next_block_blob_excess_gas(&self, blob_excess_gas: u64, blob_gas_used: u64) -> u64 {
174 self.blob_params().next_block_excess_blob_gas_osaka(
175 blob_excess_gas,
176 blob_gas_used,
177 self.base_fee(),
178 )
179 }
180
181 pub fn set_blob_params(&self, blob_params: BlobParams) {
183 *self.blob_params.write() = blob_params;
184 }
185
186 pub fn blob_params(&self) -> BlobParams {
188 *self.blob_params.read()
189 }
190}
191
192pub struct FeeHistoryService<N: Network>
194where
195 N::ReceiptEnvelope: TxReceipt<Log = alloy_primitives::Log>,
196{
197 blob_params: BlobParams,
199 new_blocks: NewBlockNotifications,
201 cache: FeeHistoryCache,
203 fee_history_limit: u64,
205 storage_info: StorageInfo<N>,
207}
208
209impl<N: Network> FeeHistoryService<N>
210where
211 N::ReceiptEnvelope: TxReceipt<Log = alloy_primitives::Log>,
212{
213 pub const fn new(
214 blob_params: BlobParams,
215 new_blocks: NewBlockNotifications,
216 cache: FeeHistoryCache,
217 storage_info: StorageInfo<N>,
218 ) -> Self {
219 Self {
220 blob_params,
221 new_blocks,
222 cache,
223 fee_history_limit: MAX_FEE_HISTORY_CACHE_SIZE,
224 storage_info,
225 }
226 }
227
228 pub const fn fee_history_limit(&self) -> u64 {
230 self.fee_history_limit
231 }
232
233 pub(crate) fn insert_cache_entry_for_block(&self, hash: B256, header: &impl BlockHeader) {
235 let (result, block_number) = self.create_cache_entry(hash, header);
236 self.insert_cache_entry(result, block_number);
237 }
238
239 fn create_cache_entry(
241 &self,
242 hash: B256,
243 header: &impl BlockHeader,
244 ) -> (FeeHistoryCacheItem, Option<u64>) {
245 let reward_percentiles: Vec<f64> = {
248 let mut percentile: f64 = 0.0;
249 (0..=200)
250 .map(|_| {
251 let val = percentile;
252 percentile += 0.5;
253 val
254 })
255 .collect()
256 };
257
258 let mut block_number: Option<u64> = None;
259 let base_fee = header.base_fee_per_gas().unwrap_or_default();
260 let excess_blob_gas = header.excess_blob_gas().map(|g| g as u128);
261 let blob_gas_used = header.blob_gas_used().map(|g| g as u128);
262 let base_fee_per_blob_gas = header.blob_fee(self.blob_params);
263
264 let mut item = FeeHistoryCacheItem {
265 base_fee: base_fee as u128,
266 gas_used_ratio: 0f64,
267 blob_gas_used_ratio: 0f64,
268 rewards: Vec::new(),
269 excess_blob_gas,
270 base_fee_per_blob_gas,
271 blob_gas_used,
272 };
273
274 let current_block = self.storage_info.block(hash);
275 let current_receipts = self.storage_info.receipts(hash);
276
277 if let (Some(block), Some(receipts)) = (current_block, current_receipts) {
278 block_number = Some(block.header.number());
279
280 let gas_used = block.header.gas_used() as f64;
281 let blob_gas_used = block.header.blob_gas_used().map(|g| g as f64);
282 item.gas_used_ratio = gas_used / block.header.gas_limit() as f64;
283 item.blob_gas_used_ratio = blob_gas_used
284 .map(|g| {
285 let max = self.blob_params.max_blob_gas_per_block() as f64;
286 if max == 0.0 { 0.0 } else { g / max }
287 })
288 .unwrap_or(0.0);
289
290 let mut transactions: Vec<(_, _)> = receipts
292 .iter()
293 .enumerate()
294 .map(|(i, receipt)| {
295 let cumulative = receipt.cumulative_gas_used();
296 let prev_cumulative =
297 if i > 0 { receipts[i - 1].cumulative_gas_used() } else { 0 };
298 let gas_used = cumulative - prev_cumulative;
299 let effective_reward = block
300 .body
301 .transactions
302 .get(i)
303 .map(|tx| tx.as_ref().effective_tip_per_gas(base_fee).unwrap_or(0))
304 .unwrap_or(0);
305
306 (gas_used, effective_reward)
307 })
308 .collect();
309
310 transactions.sort_by_key(|(_, reward)| *reward);
312
313 item.rewards = reward_percentiles
315 .into_iter()
316 .filter_map(|p| {
317 let target_gas = (p * gas_used / 100f64) as u64;
318 let mut sum_gas = 0;
319 for (gas_used, effective_reward) in transactions.iter().copied() {
320 sum_gas += gas_used;
321 if target_gas <= sum_gas {
322 return Some(effective_reward);
323 }
324 }
325 None
326 })
327 .collect();
328 } else {
329 item.rewards = vec![0; reward_percentiles.len()];
330 }
331 (item, block_number)
332 }
333
334 fn insert_cache_entry(&self, item: FeeHistoryCacheItem, block_number: Option<u64>) {
335 if let Some(block_number) = block_number {
336 trace!(target: "fees", "insert new history item={:?} for {}", item, block_number);
337 let mut cache = self.cache.lock();
338 cache.insert(block_number, item);
339
340 let pop_next = block_number.saturating_sub(self.fee_history_limit);
342
343 let num_remove = (cache.len() as u64).saturating_sub(self.fee_history_limit);
344 for num in 0..num_remove {
345 let key = pop_next - num;
346 cache.remove(&key);
347 }
348 }
349 }
350}
351
352impl<N: Network> Future for FeeHistoryService<N>
354where
355 N::ReceiptEnvelope: TxReceipt<Log = alloy_primitives::Log>,
356{
357 type Output = ();
358
359 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
360 let pin = self.get_mut();
361
362 while let Poll::Ready(Some(notification)) = pin.new_blocks.poll_next_unpin(cx) {
363 pin.insert_cache_entry_for_block(notification.hash, notification.header.as_ref());
365 }
366
367 Poll::Pending
368 }
369}
370
371pub type FeeHistoryCache = Arc<Mutex<BTreeMap<u64, FeeHistoryCacheItem>>>;
372
373#[derive(Clone, Debug)]
375pub struct FeeHistoryCacheItem {
376 pub base_fee: u128,
377 pub gas_used_ratio: f64,
378 pub base_fee_per_blob_gas: Option<u128>,
379 pub blob_gas_used_ratio: f64,
380 pub excess_blob_gas: Option<u128>,
381 pub blob_gas_used: Option<u128>,
382 pub rewards: Vec<u128>,
383}
384
385#[derive(Clone, Default)]
386pub struct FeeDetails {
387 pub gas_price: Option<u128>,
388 pub max_fee_per_gas: Option<u128>,
389 pub max_priority_fee_per_gas: Option<u128>,
390 pub max_fee_per_blob_gas: Option<u128>,
391}
392
393impl FeeDetails {
394 pub const fn zero() -> Self {
396 Self {
397 gas_price: Some(0),
398 max_fee_per_gas: Some(0),
399 max_priority_fee_per_gas: Some(0),
400 max_fee_per_blob_gas: None,
401 }
402 }
403
404 pub const fn or_zero_fees(self) -> Self {
406 let Self { gas_price, max_fee_per_gas, max_priority_fee_per_gas, max_fee_per_blob_gas } =
407 self;
408
409 let no_fees = gas_price.is_none() && max_fee_per_gas.is_none();
410 let gas_price = if no_fees { Some(0) } else { gas_price };
411 let max_fee_per_gas = if no_fees { Some(0) } else { max_fee_per_gas };
412 let max_fee_per_blob_gas = if no_fees { None } else { max_fee_per_blob_gas };
413
414 Self { gas_price, max_fee_per_gas, max_priority_fee_per_gas, max_fee_per_blob_gas }
415 }
416
417 pub const fn split(self) -> (Option<u128>, Option<u128>, Option<u128>, Option<u128>) {
419 let Self { gas_price, max_fee_per_gas, max_priority_fee_per_gas, max_fee_per_blob_gas } =
420 self;
421 (gas_price, max_fee_per_gas, max_priority_fee_per_gas, max_fee_per_blob_gas)
422 }
423
424 pub fn new(
426 request_gas_price: Option<u128>,
427 request_max_fee: Option<u128>,
428 request_priority: Option<u128>,
429 max_fee_per_blob_gas: Option<u128>,
430 ) -> Result<Self, BlockchainError> {
431 match (request_gas_price, request_max_fee, request_priority, max_fee_per_blob_gas) {
432 (gas_price, None, None, None) => {
433 Ok(Self {
435 gas_price,
436 max_fee_per_gas: gas_price,
437 max_priority_fee_per_gas: gas_price,
438 max_fee_per_blob_gas: None,
439 })
440 }
441 (_, max_fee, max_priority, max_fee_per_blob_gas) => {
442 if let Some(max_priority) = max_priority {
445 let max_fee = max_fee.unwrap_or_default();
446 if max_priority > max_fee {
447 return Err(BlockchainError::InvalidFeeInput);
448 }
449 }
450 Ok(Self {
451 gas_price: max_fee,
452 max_fee_per_gas: max_fee,
453 max_priority_fee_per_gas: max_priority,
454 max_fee_per_blob_gas,
455 })
456 }
457 }
458 }
459}
460
461impl fmt::Debug for FeeDetails {
462 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
463 write!(fmt, "Fees {{ ")?;
464 write!(fmt, "gas_price: {:?}, ", self.gas_price)?;
465 write!(fmt, "max_fee_per_gas: {:?}, ", self.max_fee_per_gas)?;
466 write!(fmt, "max_priority_fee_per_gas: {:?}, ", self.max_priority_fee_per_gas)?;
467 write!(fmt, "}}")?;
468 Ok(())
469 }
470}