use alloy_primitives::{U128, U64};
pub const EIP1559_FEE_ESTIMATION_PAST_BLOCKS: u64 = 10;
pub const EIP1559_BASE_FEE_MULTIPLIER: u128 = 2;
pub const EIP1559_FEE_ESTIMATION_REWARD_PERCENTILE: f64 = 20.0;
pub const EIP1559_MIN_PRIORITY_FEE: u128 = 1;
pub type EstimatorFunction = fn(u128, &[Vec<u128>]) -> Eip1559Estimation;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Eip1559Estimation {
pub max_fee_per_gas: u128,
pub max_priority_fee_per_gas: u128,
}
fn estimate_priority_fee(rewards: &[Vec<u128>]) -> u128 {
let mut rewards =
rewards.iter().filter_map(|r| r.first()).filter(|r| **r > 0_u128).collect::<Vec<_>>();
if rewards.is_empty() {
return EIP1559_MIN_PRIORITY_FEE;
}
rewards.sort_unstable();
let n = rewards.len();
let median =
if n % 2 == 0 { (*rewards[n / 2 - 1] + *rewards[n / 2]) / 2 } else { *rewards[n / 2] };
std::cmp::max(median, EIP1559_MIN_PRIORITY_FEE)
}
pub fn eip1559_default_estimator(
base_fee_per_gas: u128,
rewards: &[Vec<u128>],
) -> Eip1559Estimation {
let max_priority_fee_per_gas = estimate_priority_fee(rewards);
let potential_max_fee = base_fee_per_gas * EIP1559_BASE_FEE_MULTIPLIER;
Eip1559Estimation {
max_fee_per_gas: potential_max_fee + max_priority_fee_per_gas,
max_priority_fee_per_gas,
}
}
pub(crate) fn convert_u128(r: U128) -> u128 {
r.to::<u128>()
}
pub(crate) fn convert_u64(r: U64) -> u64 {
r.to::<u64>()
}
#[cfg(test)]
mod tests {
use super::*;
use std::vec;
#[test]
fn test_estimate_priority_fee() {
let rewards =
vec![vec![10_000_000_000_u128], vec![200_000_000_000_u128], vec![3_000_000_000_u128]];
assert_eq!(super::estimate_priority_fee(&rewards), 10_000_000_000_u128);
let rewards = vec![
vec![400_000_000_000_u128],
vec![2_000_000_000_u128],
vec![5_000_000_000_u128],
vec![3_000_000_000_u128],
];
assert_eq!(super::estimate_priority_fee(&rewards), 4_000_000_000_u128);
let rewards = vec![vec![0_u128], vec![0_u128], vec![0_u128]];
assert_eq!(super::estimate_priority_fee(&rewards), EIP1559_MIN_PRIORITY_FEE);
assert_eq!(super::estimate_priority_fee(&[]), EIP1559_MIN_PRIORITY_FEE);
}
#[test]
fn test_eip1559_default_estimator() {
let base_fee_per_gas = 1_000_000_000_u128;
let rewards = vec![
vec![200_000_000_000_u128],
vec![200_000_000_000_u128],
vec![300_000_000_000_u128],
];
assert_eq!(
super::eip1559_default_estimator(base_fee_per_gas, &rewards),
Eip1559Estimation {
max_fee_per_gas: 202_000_000_000_u128,
max_priority_fee_per_gas: 200_000_000_000_u128
}
);
let base_fee_per_gas = 0u128;
let rewards = vec![
vec![200_000_000_000_u128],
vec![200_000_000_000_u128],
vec![300_000_000_000_u128],
];
assert_eq!(
super::eip1559_default_estimator(base_fee_per_gas, &rewards),
Eip1559Estimation {
max_fee_per_gas: 200_000_000_000_u128,
max_priority_fee_per_gas: 200_000_000_000_u128
}
);
}
}