Skip to main content

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::{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
22/// Maximum number of entries in the fee history cache
23pub const MAX_FEE_HISTORY_CACHE_SIZE: u64 = 2048u64;
24
25/// Initial base fee for EIP-1559 blocks.
26pub const INITIAL_BASE_FEE: u64 = 1_000_000_000;
27
28/// Initial default gas price for the first block
29pub const INITIAL_GAS_PRICE: u128 = 1_875_000_000;
30
31/// Bounds the amount the base fee can change between blocks.
32pub const BASE_FEE_CHANGE_DENOMINATOR: u128 = 8;
33
34/// Minimum suggested priority fee
35pub const MIN_SUGGESTED_PRIORITY_FEE: u128 = 1e9 as u128;
36
37/// Stores the fee related information
38#[derive(Clone, Debug)]
39pub struct FeeManager {
40    /// Hardfork identifier
41    spec_id: SpecId,
42    /// The blob params that determine blob fees
43    blob_params: Arc<RwLock<BlobParams>>,
44    /// Tracks the base fee for the next block post London
45    ///
46    /// This value will be updated after a new block was mined
47    base_fee: Arc<RwLock<u64>>,
48    /// Whether the minimum suggested priority fee is enforced
49    is_min_priority_fee_enforced: bool,
50    /// Tracks the excess blob gas, and the base fee, for the next block post Cancun
51    ///
52    /// This value will be updated after a new block was mined
53    blob_excess_gas_and_price: Arc<RwLock<BlobExcessGasAndPrice>>,
54    /// The base price to use Pre London
55    ///
56    /// This will be constant value unless changed manually
57    gas_price: Arc<RwLock<u128>>,
58    elasticity: Arc<RwLock<f64>>,
59    /// Network-specific base fee params for EIP-1559 calculations
60    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    /// Returns the base fee params used for EIP-1559 calculations
87    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    /// Returns true for post London
96    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    /// Calculates the current blob gas price
105    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    /// Raw base gas price
118    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    /// Returns the current gas price
131    pub fn set_gas_price(&self, price: u128) {
132        let mut gas = self.gas_price.write();
133        *gas = price;
134    }
135
136    /// Returns the current base fee
137    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    /// Sets the current blob excess gas and price
144    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    /// Calculates the base fee for the next block
151    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        // It's naturally impossible for base fee to be 0;
158        // It means it was set by the user deliberately and therefore we treat it as a constant.
159        // Therefore, we skip the base fee calculation altogether and we return 0.
160        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    /// Calculates the next block blob base fee.
167    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    /// Calculates the next block blob excess gas, using the provided parent blob excess gas and
172    /// parent blob gas used
173    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    /// Configures the blob params
182    pub fn set_blob_params(&self, blob_params: BlobParams) {
183        *self.blob_params.write() = blob_params;
184    }
185
186    /// Returns the active [`BlobParams`]
187    pub fn blob_params(&self) -> BlobParams {
188        *self.blob_params.read()
189    }
190}
191
192/// An async service that takes care of the `FeeHistory` cache
193pub struct FeeHistoryService<N: Network>
194where
195    N::ReceiptEnvelope: TxReceipt<Log = alloy_primitives::Log>,
196{
197    /// blob parameters for the current spec
198    blob_params: BlobParams,
199    /// incoming notifications about new blocks
200    new_blocks: NewBlockNotifications,
201    /// contains all fee history related entries
202    cache: FeeHistoryCache,
203    /// number of items to consider
204    fee_history_limit: u64,
205    /// a type that can fetch ethereum-storage data
206    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    /// Returns the configured history limit
229    pub const fn fee_history_limit(&self) -> u64 {
230        self.fee_history_limit
231    }
232
233    /// Inserts a new cache entry for the given block
234    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    /// Create a new history entry for the block
240    fn create_cache_entry(
241        &self,
242        hash: B256,
243        header: &impl BlockHeader,
244    ) -> (FeeHistoryCacheItem, Option<u64>) {
245        // percentile list from 0.0 to 100.0 with a 0.5 resolution.
246        // this will create 200 percentile points
247        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            // extract useful tx info (gas_used, effective_reward)
291            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            // sort by effective reward asc
311            transactions.sort_by_key(|(_, reward)| *reward);
312
313            // calculate percentile rewards
314            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            // adhere to cache limit
341            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
352// An endless future that listens for new blocks and updates the cache
353impl<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            // add the imported block.
364            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/// A single item in the whole fee history cache
374#[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    /// All values zero
395    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    /// If neither `gas_price` nor `max_fee_per_gas` is `Some`, this will set both to `0`
405    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    /// Turns this type into a tuple
418    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    /// Creates a new instance from the request's gas related values
425    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                // Legacy request, all default to gas price.
434                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                // eip-1559
443                // Ensure `max_priority_fee_per_gas` is less or equal to `max_fee_per_gas`.
444                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}