anvil/eth/
fees.rs

1use std::{
2    collections::BTreeMap,
3    fmt,
4    pin::Pin,
5    sync::Arc,
6    task::{Context, Poll},
7};
8
9use alloy_consensus::{Header, Transaction};
10use alloy_eips::{
11    calc_next_block_base_fee, eip1559::BaseFeeParams, eip7691::MAX_BLOBS_PER_BLOCK_ELECTRA,
12    eip7840::BlobParams,
13};
14use alloy_primitives::B256;
15use futures::StreamExt;
16use parking_lot::{Mutex, RwLock};
17use revm::{context_interface::block::BlobExcessGasAndPrice, primitives::hardfork::SpecId};
18
19use crate::eth::{
20    backend::{info::StorageInfo, notifications::NewBlockNotifications},
21    error::BlockchainError,
22};
23
24/// Maximum number of entries in the fee history cache
25pub const MAX_FEE_HISTORY_CACHE_SIZE: u64 = 2048u64;
26
27/// Initial base fee for EIP-1559 blocks.
28pub const INITIAL_BASE_FEE: u64 = 1_000_000_000;
29
30/// Initial default gas price for the first block
31pub const INITIAL_GAS_PRICE: u128 = 1_875_000_000;
32
33/// Bounds the amount the base fee can change between blocks.
34pub const BASE_FEE_CHANGE_DENOMINATOR: u128 = 8;
35
36/// Minimum suggested priority fee
37pub const MIN_SUGGESTED_PRIORITY_FEE: u128 = 1e9 as u128;
38
39/// Stores the fee related information
40#[derive(Clone, Debug)]
41pub struct FeeManager {
42    /// Hardfork identifier
43    spec_id: SpecId,
44    /// The blob params that determine blob fees
45    blob_params: Arc<RwLock<BlobParams>>,
46    /// Tracks the base fee for the next block post London
47    ///
48    /// This value will be updated after a new block was mined
49    base_fee: Arc<RwLock<u64>>,
50    /// Whether the minimum suggested priority fee is enforced
51    is_min_priority_fee_enforced: bool,
52    /// Tracks the excess blob gas, and the base fee, for the next block post Cancun
53    ///
54    /// This value will be updated after a new block was mined
55    blob_excess_gas_and_price: Arc<RwLock<BlobExcessGasAndPrice>>,
56    /// The base price to use Pre London
57    ///
58    /// This will be constant value unless changed manually
59    gas_price: Arc<RwLock<u128>>,
60    elasticity: Arc<RwLock<f64>>,
61    /// Network-specific base fee params for EIP-1559 calculations
62    base_fee_params: BaseFeeParams,
63}
64
65impl FeeManager {
66    pub fn new(
67        spec_id: SpecId,
68        base_fee: u64,
69        is_min_priority_fee_enforced: bool,
70        gas_price: u128,
71        blob_excess_gas_and_price: BlobExcessGasAndPrice,
72        blob_params: BlobParams,
73        base_fee_params: BaseFeeParams,
74    ) -> Self {
75        let elasticity = 1f64 / base_fee_params.elasticity_multiplier as f64;
76        Self {
77            spec_id,
78            blob_params: Arc::new(RwLock::new(blob_params)),
79            base_fee: Arc::new(RwLock::new(base_fee)),
80            is_min_priority_fee_enforced,
81            gas_price: Arc::new(RwLock::new(gas_price)),
82            blob_excess_gas_and_price: Arc::new(RwLock::new(blob_excess_gas_and_price)),
83            elasticity: Arc::new(RwLock::new(elasticity)),
84            base_fee_params,
85        }
86    }
87
88    /// Returns the base fee params used for EIP-1559 calculations
89    pub fn base_fee_params(&self) -> BaseFeeParams {
90        self.base_fee_params
91    }
92
93    pub fn elasticity(&self) -> f64 {
94        *self.elasticity.read()
95    }
96
97    /// Returns true for post London
98    pub fn is_eip1559(&self) -> bool {
99        (self.spec_id as u8) >= (SpecId::LONDON as u8)
100    }
101
102    pub fn is_eip4844(&self) -> bool {
103        (self.spec_id as u8) >= (SpecId::CANCUN as u8)
104    }
105
106    /// Calculates the current blob gas price
107    pub fn blob_gas_price(&self) -> u128 {
108        if self.is_eip4844() { self.base_fee_per_blob_gas() } else { 0 }
109    }
110
111    pub fn base_fee(&self) -> u64 {
112        if self.is_eip1559() { *self.base_fee.read() } else { 0 }
113    }
114
115    pub fn is_min_priority_fee_enforced(&self) -> bool {
116        self.is_min_priority_fee_enforced
117    }
118
119    /// Raw base gas price
120    pub fn raw_gas_price(&self) -> u128 {
121        *self.gas_price.read()
122    }
123
124    pub fn excess_blob_gas_and_price(&self) -> Option<BlobExcessGasAndPrice> {
125        if self.is_eip4844() { Some(*self.blob_excess_gas_and_price.read()) } else { None }
126    }
127
128    pub fn base_fee_per_blob_gas(&self) -> u128 {
129        if self.is_eip4844() { self.blob_excess_gas_and_price.read().blob_gasprice } else { 0 }
130    }
131
132    /// Returns the current gas price
133    pub fn set_gas_price(&self, price: u128) {
134        let mut gas = self.gas_price.write();
135        *gas = price;
136    }
137
138    /// Returns the current base fee
139    pub fn set_base_fee(&self, fee: u64) {
140        trace!(target: "backend::fees", "updated base fee {:?}", fee);
141        let mut base = self.base_fee.write();
142        *base = fee;
143    }
144
145    /// Sets the current blob excess gas and price
146    pub fn set_blob_excess_gas_and_price(&self, blob_excess_gas_and_price: BlobExcessGasAndPrice) {
147        trace!(target: "backend::fees", "updated blob base fee {:?}", blob_excess_gas_and_price);
148        let mut base = self.blob_excess_gas_and_price.write();
149        *base = blob_excess_gas_and_price;
150    }
151
152    /// Calculates the base fee for the next block
153    pub fn get_next_block_base_fee_per_gas(
154        &self,
155        gas_used: u64,
156        gas_limit: u64,
157        last_fee_per_gas: u64,
158    ) -> u64 {
159        // It's naturally impossible for base fee to be 0;
160        // It means it was set by the user deliberately and therefore we treat it as a constant.
161        // Therefore, we skip the base fee calculation altogether and we return 0.
162        if self.base_fee() == 0 {
163            return 0;
164        }
165        calc_next_block_base_fee(gas_used, gas_limit, last_fee_per_gas, self.base_fee_params)
166    }
167
168    /// Calculates the next block blob base fee.
169    pub fn get_next_block_blob_base_fee_per_gas(&self) -> u128 {
170        self.blob_params().calc_blob_fee(self.blob_excess_gas_and_price.read().excess_blob_gas)
171    }
172
173    /// Calculates the next block blob excess gas, using the provided parent blob gas used and
174    /// parent blob excess gas
175    pub fn get_next_block_blob_excess_gas(&self, blob_gas_used: u64, blob_excess_gas: u64) -> u64 {
176        self.blob_params().next_block_excess_blob_gas_osaka(
177            blob_excess_gas,
178            blob_gas_used,
179            self.base_fee(),
180        )
181    }
182
183    /// Configures the blob params
184    pub fn set_blob_params(&self, blob_params: BlobParams) {
185        *self.blob_params.write() = blob_params;
186    }
187
188    /// Returns the active [`BlobParams`]
189    pub fn blob_params(&self) -> BlobParams {
190        *self.blob_params.read()
191    }
192}
193
194/// An async service that takes care of the `FeeHistory` cache
195pub struct FeeHistoryService {
196    /// blob parameters for the current spec
197    blob_params: BlobParams,
198    /// incoming notifications about new blocks
199    new_blocks: NewBlockNotifications,
200    /// contains all fee history related entries
201    cache: FeeHistoryCache,
202    /// number of items to consider
203    fee_history_limit: u64,
204    /// a type that can fetch ethereum-storage data
205    storage_info: StorageInfo,
206}
207
208impl FeeHistoryService {
209    pub fn new(
210        blob_params: BlobParams,
211        new_blocks: NewBlockNotifications,
212        cache: FeeHistoryCache,
213        storage_info: StorageInfo,
214    ) -> Self {
215        Self {
216            blob_params,
217            new_blocks,
218            cache,
219            fee_history_limit: MAX_FEE_HISTORY_CACHE_SIZE,
220            storage_info,
221        }
222    }
223
224    /// Returns the configured history limit
225    pub fn fee_history_limit(&self) -> u64 {
226        self.fee_history_limit
227    }
228
229    /// Inserts a new cache entry for the given block
230    pub(crate) fn insert_cache_entry_for_block(&self, hash: B256, header: &Header) {
231        let (result, block_number) = self.create_cache_entry(hash, header);
232        self.insert_cache_entry(result, block_number);
233    }
234
235    /// Create a new history entry for the block
236    fn create_cache_entry(
237        &self,
238        hash: B256,
239        header: &Header,
240    ) -> (FeeHistoryCacheItem, Option<u64>) {
241        // percentile list from 0.0 to 100.0 with a 0.5 resolution.
242        // this will create 200 percentile points
243        let reward_percentiles: Vec<f64> = {
244            let mut percentile: f64 = 0.0;
245            (0..=200)
246                .map(|_| {
247                    let val = percentile;
248                    percentile += 0.5;
249                    val
250                })
251                .collect()
252        };
253
254        let mut block_number: Option<u64> = None;
255        let base_fee = header.base_fee_per_gas.unwrap_or_default();
256        let excess_blob_gas = header.excess_blob_gas.map(|g| g as u128);
257        let blob_gas_used = header.blob_gas_used.map(|g| g as u128);
258        let base_fee_per_blob_gas = header.blob_fee(self.blob_params);
259
260        let mut item = FeeHistoryCacheItem {
261            base_fee: base_fee as u128,
262            gas_used_ratio: 0f64,
263            blob_gas_used_ratio: 0f64,
264            rewards: Vec::new(),
265            excess_blob_gas,
266            base_fee_per_blob_gas,
267            blob_gas_used,
268        };
269
270        let current_block = self.storage_info.block(hash);
271        let current_receipts = self.storage_info.receipts(hash);
272
273        if let (Some(block), Some(receipts)) = (current_block, current_receipts) {
274            block_number = Some(block.header.number);
275
276            let gas_used = block.header.gas_used as f64;
277            let blob_gas_used = block.header.blob_gas_used.map(|g| g as f64);
278            item.gas_used_ratio = gas_used / block.header.gas_limit as f64;
279            item.blob_gas_used_ratio =
280                blob_gas_used.map(|g| g / MAX_BLOBS_PER_BLOCK_ELECTRA as f64).unwrap_or(0 as f64);
281
282            // extract useful tx info (gas_used, effective_reward)
283            let mut transactions: Vec<(_, _)> = receipts
284                .iter()
285                .enumerate()
286                .map(|(i, receipt)| {
287                    let gas_used = receipt.cumulative_gas_used();
288                    let effective_reward = block
289                        .body
290                        .transactions
291                        .get(i)
292                        .map(|tx| tx.as_ref().effective_tip_per_gas(base_fee).unwrap_or(0))
293                        .unwrap_or(0);
294
295                    (gas_used, effective_reward)
296                })
297                .collect();
298
299            // sort by effective reward asc
300            transactions.sort_by(|(_, a), (_, b)| a.cmp(b));
301
302            // calculate percentile rewards
303            item.rewards = reward_percentiles
304                .into_iter()
305                .filter_map(|p| {
306                    let target_gas = (p * gas_used / 100f64) as u64;
307                    let mut sum_gas = 0;
308                    for (gas_used, effective_reward) in transactions.iter().copied() {
309                        sum_gas += gas_used;
310                        if target_gas <= sum_gas {
311                            return Some(effective_reward);
312                        }
313                    }
314                    None
315                })
316                .collect();
317        } else {
318            item.rewards = vec![0; reward_percentiles.len()];
319        }
320        (item, block_number)
321    }
322
323    fn insert_cache_entry(&self, item: FeeHistoryCacheItem, block_number: Option<u64>) {
324        if let Some(block_number) = block_number {
325            trace!(target: "fees", "insert new history item={:?} for {}", item, block_number);
326            let mut cache = self.cache.lock();
327            cache.insert(block_number, item);
328
329            // adhere to cache limit
330            let pop_next = block_number.saturating_sub(self.fee_history_limit);
331
332            let num_remove = (cache.len() as u64).saturating_sub(self.fee_history_limit);
333            for num in 0..num_remove {
334                let key = pop_next - num;
335                cache.remove(&key);
336            }
337        }
338    }
339}
340
341// An endless future that listens for new blocks and updates the cache
342impl Future for FeeHistoryService {
343    type Output = ();
344
345    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
346        let pin = self.get_mut();
347
348        while let Poll::Ready(Some(notification)) = pin.new_blocks.poll_next_unpin(cx) {
349            // add the imported block.
350            pin.insert_cache_entry_for_block(notification.hash, notification.header.as_ref());
351        }
352
353        Poll::Pending
354    }
355}
356
357pub type FeeHistoryCache = Arc<Mutex<BTreeMap<u64, FeeHistoryCacheItem>>>;
358
359/// A single item in the whole fee history cache
360#[derive(Clone, Debug)]
361pub struct FeeHistoryCacheItem {
362    pub base_fee: u128,
363    pub gas_used_ratio: f64,
364    pub base_fee_per_blob_gas: Option<u128>,
365    pub blob_gas_used_ratio: f64,
366    pub excess_blob_gas: Option<u128>,
367    pub blob_gas_used: Option<u128>,
368    pub rewards: Vec<u128>,
369}
370
371#[derive(Clone, Default)]
372pub struct FeeDetails {
373    pub gas_price: Option<u128>,
374    pub max_fee_per_gas: Option<u128>,
375    pub max_priority_fee_per_gas: Option<u128>,
376    pub max_fee_per_blob_gas: Option<u128>,
377}
378
379impl FeeDetails {
380    /// All values zero
381    pub fn zero() -> Self {
382        Self {
383            gas_price: Some(0),
384            max_fee_per_gas: Some(0),
385            max_priority_fee_per_gas: Some(0),
386            max_fee_per_blob_gas: None,
387        }
388    }
389
390    /// If neither `gas_price` nor `max_fee_per_gas` is `Some`, this will set both to `0`
391    pub fn or_zero_fees(self) -> Self {
392        let Self { gas_price, max_fee_per_gas, max_priority_fee_per_gas, max_fee_per_blob_gas } =
393            self;
394
395        let no_fees = gas_price.is_none() && max_fee_per_gas.is_none();
396        let gas_price = if no_fees { Some(0) } else { gas_price };
397        let max_fee_per_gas = if no_fees { Some(0) } else { max_fee_per_gas };
398        let max_fee_per_blob_gas = if no_fees { None } else { max_fee_per_blob_gas };
399
400        Self { gas_price, max_fee_per_gas, max_priority_fee_per_gas, max_fee_per_blob_gas }
401    }
402
403    /// Turns this type into a tuple
404    pub fn split(self) -> (Option<u128>, Option<u128>, Option<u128>, Option<u128>) {
405        let Self { gas_price, max_fee_per_gas, max_priority_fee_per_gas, max_fee_per_blob_gas } =
406            self;
407        (gas_price, max_fee_per_gas, max_priority_fee_per_gas, max_fee_per_blob_gas)
408    }
409
410    /// Creates a new instance from the request's gas related values
411    pub fn new(
412        request_gas_price: Option<u128>,
413        request_max_fee: Option<u128>,
414        request_priority: Option<u128>,
415        max_fee_per_blob_gas: Option<u128>,
416    ) -> Result<Self, BlockchainError> {
417        match (request_gas_price, request_max_fee, request_priority, max_fee_per_blob_gas) {
418            (gas_price, None, None, None) => {
419                // Legacy request, all default to gas price.
420                Ok(Self {
421                    gas_price,
422                    max_fee_per_gas: gas_price,
423                    max_priority_fee_per_gas: gas_price,
424                    max_fee_per_blob_gas: None,
425                })
426            }
427            (_, max_fee, max_priority, None) => {
428                // eip-1559
429                // Ensure `max_priority_fee_per_gas` is less or equal to `max_fee_per_gas`.
430                if let Some(max_priority) = max_priority {
431                    let max_fee = max_fee.unwrap_or_default();
432                    if max_priority > max_fee {
433                        return Err(BlockchainError::InvalidFeeInput);
434                    }
435                }
436                Ok(Self {
437                    gas_price: max_fee,
438                    max_fee_per_gas: max_fee,
439                    max_priority_fee_per_gas: max_priority,
440                    max_fee_per_blob_gas: None,
441                })
442            }
443            (_, max_fee, max_priority, max_fee_per_blob_gas) => {
444                // eip-1559
445                // Ensure `max_priority_fee_per_gas` is less or equal to `max_fee_per_gas`.
446                if let Some(max_priority) = max_priority {
447                    let max_fee = max_fee.unwrap_or_default();
448                    if max_priority > max_fee {
449                        return Err(BlockchainError::InvalidFeeInput);
450                    }
451                }
452                Ok(Self {
453                    gas_price: max_fee,
454                    max_fee_per_gas: max_fee,
455                    max_priority_fee_per_gas: max_priority,
456                    max_fee_per_blob_gas,
457                })
458            }
459        }
460    }
461}
462
463impl fmt::Debug for FeeDetails {
464    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
465        write!(fmt, "Fees {{ ")?;
466        write!(fmt, "gas_price: {:?}, ", self.gas_price)?;
467        write!(fmt, "max_fee_per_gas: {:?}, ", self.max_fee_per_gas)?;
468        write!(fmt, "max_priority_fee_per_gas: {:?}, ", self.max_priority_fee_per_gas)?;
469        write!(fmt, "}}")?;
470        Ok(())
471    }
472}