Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 29 additions & 4 deletions crates/primitives/src/basefee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
Expand Down Expand Up @@ -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
)
);
}
}
Expand Down