diff --git a/crates/primitives/src/basefee.rs b/crates/primitives/src/basefee.rs index be60c3dcc4a..b27d1fb2487 100644 --- a/crates/primitives/src/basefee.rs +++ b/crates/primitives/src/basefee.rs @@ -4,7 +4,23 @@ use crate::constants; /// Calculate base fee for next block. [EIP-1559](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md) spec pub fn calculate_next_block_base_fee(gas_used: u64, gas_limit: u64, base_fee: u64) -> u64 { - let gas_target = gas_limit / constants::EIP1559_ELASTICITY_MULTIPLIER; + calculate_next_block_base_fee_with_block_params( + gas_used, + gas_limit, + base_fee, + constants::EIP1559_ELASTICITY_MULTIPLIER, + constants::EIP1559_BASE_FEE_MAX_CHANGE_DENOMINATOR, + ) +} + +fn calculate_next_block_base_fee_with_block_params( + gas_used: u64, + gas_limit: u64, + base_fee: u64, + elasticity_multiplier: u64, + base_fee_max_change_denominator: u64, +) -> u64 { + let gas_target = gas_limit / elasticity_multiplier; if gas_used == gas_target { return base_fee @@ -15,14 +31,14 @@ pub fn calculate_next_block_base_fee(gas_used: u64, gas_limit: u64, base_fee: u6 1, base_fee as u128 * gas_used_delta as u128 / gas_target as u128 / - constants::EIP1559_BASE_FEE_MAX_CHANGE_DENOMINATOR as u128, + base_fee_max_change_denominator as u128, ); base_fee + (base_fee_delta as u64) } else { let gas_used_delta = gas_target - gas_used; let base_fee_per_gas_delta = base_fee as u128 * gas_used_delta as u128 / gas_target as u128 / - constants::EIP1559_BASE_FEE_MAX_CHANGE_DENOMINATOR as u128; + base_fee_max_change_denominator as u128; base_fee.saturating_sub(base_fee_per_gas_delta as u64) } @@ -52,9 +68,18 @@ mod tests { ]; for i in 0..base_fee.len() { + // This test hardcodes the elasticity multiplier and base fee max change denominator + // in order to match the Ethereum mainnet constants regardless of the enabled features, + // which may adjust the constants for certain build targets. assert_eq!( next_base_fee[i], - calculate_next_block_base_fee(gas_used[i], gas_limit[i], base_fee[i]) + calculate_next_block_base_fee_with_block_params( + gas_used[i], + gas_limit[i], + base_fee[i], + 2, + 8 + ) ); } }