Skip to content
This repository has been archived by the owner on Nov 5, 2023. It is now read-only.

use the parameters from the optimism config in 1559 base fee computation #32

Merged
merged 1 commit into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions bin/reth/src/args/rpc_server_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ impl RpcServerArgs {
) -> Result<AuthServerHandle, RpcError>
where
Provider: BlockReaderIdExt
+ ChainSpecProvider
+ HeaderProvider
+ StateProviderFactory
+ EvmEnvProvider
Expand Down
17 changes: 13 additions & 4 deletions crates/consensus/auto-seal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,10 +246,18 @@ impl StorageInner {

/// Fills in pre-execution header fields based on the current best block and given
/// transactions.
pub(crate) fn build_header_template(&self, transactions: &Vec<TransactionSigned>) -> Header {
pub(crate) fn build_header_template(
&self,
transactions: &Vec<TransactionSigned>,
chain_spec: Arc<ChainSpec>,
) -> Header {
// check previous block for base fee
let base_fee_per_gas =
self.headers.get(&self.best_block).and_then(|parent| parent.next_block_base_fee());
let base_fee_per_gas = self.headers.get(&self.best_block).and_then(|parent| {
parent.next_block_base_fee(
chain_spec.elasticity_multiplier(),
chain_spec.base_fee_change_denominator(),
)
});

let mut header = Header {
parent_hash: self.best_hash,
Expand Down Expand Up @@ -335,8 +343,9 @@ impl StorageInner {
&mut self,
transactions: Vec<TransactionSigned>,
executor: &mut Executor<DB>,
chain_spec: Arc<ChainSpec>,
) -> Result<(SealedHeader, PostState), BlockExecutionError> {
let header = self.build_header_template(&transactions);
let header = self.build_header_template(&transactions, chain_spec);

let block = Block { header, body: transactions, ommers: vec![], withdrawals: None };

Expand Down
7 changes: 6 additions & 1 deletion crates/consensus/auto-seal/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ where
let to_engine = this.to_engine.clone();
let client = this.client.clone();
let chain_spec = Arc::clone(&this.chain_spec);
let chain_spec2 = Arc::clone(&this.chain_spec);
let pool = this.pool.clone();
let events = this.pipe_line_events.take();
let canon_state_notification = this.canon_state_notification.clone();
Expand All @@ -131,7 +132,11 @@ where
let substate = SubState::new(State::new(client.latest().unwrap()));
let mut executor = Executor::new(chain_spec, substate);

match storage.build_and_execute(transactions.clone(), &mut executor) {
match storage.build_and_execute(
transactions.clone(),
&mut executor,
chain_spec2,
) {
Ok((new_header, post_state)) => {
// clear all transactions from pool
pool.remove_transactions(transactions.iter().map(|tx| tx.hash()));
Expand Down
7 changes: 6 additions & 1 deletion crates/consensus/common/src/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,12 @@ pub fn validate_header_regarding_parent(
constants::EIP1559_INITIAL_BASE_FEE
} else {
// This BaseFeeMissing will not happen as previous blocks are checked to have them.
parent.next_block_base_fee().ok_or(ConsensusError::BaseFeeMissing)?
parent
.next_block_base_fee(
chain_spec.base_fee_change_denominator(),
chain_spec.elasticity_multiplier(),
)
.ok_or(ConsensusError::BaseFeeMissing)?
};
if expected_base_fee != base_fee {
return Err(ConsensusError::BaseFeeDiff { expected: expected_base_fee, got: base_fee })
Expand Down
9 changes: 8 additions & 1 deletion crates/payload/builder/src/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,14 @@ impl PayloadBuilderAttributes {
prevrandao: Some(self.prev_randao),
gas_limit: U256::from(parent.gas_limit),
// calculate basefee based on parent block's gas usage
basefee: U256::from(parent.next_block_base_fee().unwrap_or_default()),
basefee: U256::from(
parent
.next_block_base_fee(
chain_spec.base_fee_change_denominator(),
chain_spec.elasticity_multiplier(),
)
.unwrap_or_default(),
),
};

(cfg, block_env)
Expand Down
24 changes: 17 additions & 7 deletions crates/primitives/src/basefee.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
//! Helpers for working with EIP-1559 base fee

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;
pub fn calculate_next_block_base_fee(
gas_used: u64,
gas_limit: u64,
base_fee: u64,
elasticity: u64,
change_denominator: u64,
) -> u64 {
let gas_target = gas_limit / elasticity;

if gas_used == gas_target {
return base_fee
Expand All @@ -15,14 +19,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,
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;
change_denominator as u128;

base_fee.saturating_sub(base_fee_per_gas_delta as u64)
}
Expand Down Expand Up @@ -54,7 +58,13 @@ mod tests {
for i in 0..base_fee.len() {
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(
gas_used[i],
gas_limit[i],
base_fee[i],
crate::constants::EIP1559_ELASTICITY_MULTIPLIER,
crate::constants::EIP1559_BASE_FEE_MAX_CHANGE_DENOMINATOR,
)
);
}
}
Expand Down
29 changes: 28 additions & 1 deletion crates/primitives/src/chain/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,10 @@ pub static OP_GOERLI: Lazy<Arc<ChainSpec>> = Lazy::new(|| {
),
(Hardfork::Regolith, ForkCondition::Timestamp(1679079600)),
]),
optimism: Some(OptimismConfig { eip_1559_elasticity: 10, eip_1559_denominator: 50 }),
optimism: Some(OptimismConfig {
eip_1559_elasticity: crate::constants::EIP1559_DEFAULT_OPTIMISM_ELASTICITY_MULTIPLIER,
eip_1559_denominator: crate::constants::EIP1559_DEFAULT_OPTIMISM_CHANGE_DENOMINATOR,
}),
}
.into()
});
Expand Down Expand Up @@ -420,6 +423,30 @@ impl ChainSpec {
ForkId { hash: forkhash, next: 0 }
}

/// Return the configured EIP-1559 max base fee change denominator
pub fn base_fee_change_denominator(&self) -> u64 {
#[cfg(not(feature = "optimism"))]
{
crate::constants::EIP1559_BASE_FEE_MAX_CHANGE_DENOMINATOR
}
#[cfg(feature = "optimism")]
{
self.optimism.as_ref().unwrap().eip_1559_denominator
}
}

/// Return the configured EIP-1559 elasticity multiplier
pub fn elasticity_multiplier(&self) -> u64 {
#[cfg(not(feature = "optimism"))]
{
crate::constants::EIP1559_ELASTICITY_MULTIPLIER
}
#[cfg(feature = "optimism")]
{
self.optimism.as_ref().unwrap().eip_1559_elasticity
}
}

/// Build a chainspec using [`ChainSpecBuilder`]
pub fn builder() -> ChainSpecBuilder {
ChainSpecBuilder::default()
Expand Down
24 changes: 13 additions & 11 deletions crates/primitives/src/constants/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,15 @@ pub const BEACON_NONCE: u64 = 0u64;
/// See <https://github.com/paradigmxyz/reth/issues/3233>.
pub const ETHEREUM_BLOCK_GAS_LIMIT: u64 = 30_000_000;

/// The minimal value the basefee can decrease to.
/// The minimum tx fee below which the txpool will reject the transaction.
///
/// The `BASE_FEE_MAX_CHANGE_DENOMINATOR` <https://eips.ethereum.org/EIPS/eip-1559> is `8`, or 12.5%.
/// Once the base fee has dropped to `7` WEI it cannot decrease further because 12.5% of 7 is less
/// than 1.
/// Configured to `7` WEI which is the lowest possible value of base fee under mainnet EIP-1559
/// parameters. `BASE_FEE_MAX_CHANGE_DENOMINATOR` <https://eips.ethereum.org/EIPS/eip-1559>
/// is `8`, or 12.5%. Once the base fee has dropped to `7` WEI it cannot decrease further because
/// 12.5% of 7 is less than 1.
///
/// Note that min base fee under different 1559 parameterizations (e.g. Optimism's) may differ,
/// but there's no signifant harm in leaving this setting as is.
pub const MIN_PROTOCOL_BASE_FEE: u64 = 7;

/// Same as [MIN_PROTOCOL_BASE_FEE] but as a U256.
Expand All @@ -50,21 +54,19 @@ pub const MIN_PROTOCOL_BASE_FEE_U256: U256 = U256::from_limbs([7u64, 0, 0, 0]);
/// Initial base fee as defined in [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559)
pub const EIP1559_INITIAL_BASE_FEE: u64 = 1_000_000_000;

/// Base fee max change denominator as defined in [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559)
#[cfg(not(feature = "optimism"))]
pub const EIP1559_BASE_FEE_MAX_CHANGE_DENOMINATOR: u64 = 8;

/// Elasticity multiplier as defined in [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559)
#[cfg(not(feature = "optimism"))]
pub const EIP1559_ELASTICITY_MULTIPLIER: u64 = 2;

/// Base fee max change denominator as defined in [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559)
pub const EIP1559_BASE_FEE_MAX_CHANGE_DENOMINATOR: u64 = 8;

/// Base fee max change denominator for Optimism.
#[cfg(feature = "optimism")]
pub const EIP1559_BASE_FEE_MAX_CHANGE_DENOMINATOR: u64 = 50;
pub const EIP1559_DEFAULT_OPTIMISM_CHANGE_DENOMINATOR: u64 = 50;

/// Elasticity multiplier for Optimism.
#[cfg(feature = "optimism")]
pub const EIP1559_ELASTICITY_MULTIPLIER: u64 = 10;
pub const EIP1559_DEFAULT_OPTIMISM_ELASTICITY_MULTIPLIER: u64 = 6;

/// Multiplier for converting gwei to wei.
pub const GWEI_TO_WEI: u64 = 1_000_000_000;
Expand Down
10 changes: 8 additions & 2 deletions crates/primitives/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,14 @@ impl Header {
/// Calculate base fee for next block according to the EIP-1559 spec.
///
/// Returns a `None` if no base fee is set, no EIP-1559 support
pub fn next_block_base_fee(&self) -> Option<u64> {
Some(calculate_next_block_base_fee(self.gas_used, self.gas_limit, self.base_fee_per_gas?))
pub fn next_block_base_fee(&self, elasticity: u64, change_denominator: u64) -> Option<u64> {
Some(calculate_next_block_base_fee(
self.gas_used,
self.gas_limit,
self.base_fee_per_gas?,
elasticity,
change_denominator,
))
}

/// Seal the header with a known hash.
Expand Down
9 changes: 6 additions & 3 deletions crates/rpc/rpc-builder/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ use jsonrpsee::{
};
use reth_network_api::{NetworkInfo, Peers};
use reth_provider::{
BlockReaderIdExt, EvmEnvProvider, HeaderProvider, ReceiptProviderIdExt, StateProviderFactory,
BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, HeaderProvider, ReceiptProviderIdExt,
StateProviderFactory,
};
use reth_rpc::{
eth::{cache::EthStateCache, gas_oracle::GasPriceOracle},
Expand Down Expand Up @@ -40,10 +41,11 @@ pub async fn launch<Provider, Pool, Network, Tasks, EngineApi>(
) -> Result<AuthServerHandle, RpcError>
where
Provider: BlockReaderIdExt
+ ReceiptProviderIdExt
+ ChainSpecProvider
+ EvmEnvProvider
+ HeaderProvider
+ ReceiptProviderIdExt
+ StateProviderFactory
+ EvmEnvProvider
+ Clone
+ Unpin
+ 'static,
Expand Down Expand Up @@ -85,6 +87,7 @@ pub async fn launch_with_eth_api<Provider, Pool, Network, EngineApi>(
) -> Result<AuthServerHandle, RpcError>
where
Provider: BlockReaderIdExt
+ ChainSpecProvider
+ HeaderProvider
+ StateProviderFactory
+ EvmEnvProvider
Expand Down
5 changes: 3 additions & 2 deletions crates/rpc/rpc/src/eth/api/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ use crate::{
};
use reth_network_api::NetworkInfo;
use reth_primitives::{BlockId, BlockNumberOrTag, TransactionMeta};
use reth_provider::{BlockReaderIdExt, EvmEnvProvider, StateProviderFactory};
use reth_provider::{BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, StateProviderFactory};
use reth_rpc_types::{Block, Index, RichBlock, TransactionReceipt};
use reth_transaction_pool::TransactionPool;

impl<Provider, Pool, Network> EthApi<Provider, Pool, Network>
where
Provider: BlockReaderIdExt + StateProviderFactory + EvmEnvProvider + 'static,
Provider:
BlockReaderIdExt + ChainSpecProvider + StateProviderFactory + EvmEnvProvider + 'static,
Pool: TransactionPool + Clone + 'static,
Network: NetworkInfo + Send + Sync + 'static,
{
Expand Down
7 changes: 5 additions & 2 deletions crates/rpc/rpc/src/eth/api/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ use crate::{
use ethers_core::utils::get_contract_address;
use reth_network_api::NetworkInfo;
use reth_primitives::{AccessList, BlockId, BlockNumberOrTag, Bytes, U256};
use reth_provider::{BlockReaderIdExt, EvmEnvProvider, StateProvider, StateProviderFactory};
use reth_provider::{
BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, StateProvider, StateProviderFactory,
};
use reth_revm::{
access_list::AccessListInspector,
database::{State, SubState},
Expand All @@ -34,7 +36,8 @@ const MIN_CREATE_GAS: u64 = 53_000u64;
impl<Provider, Pool, Network> EthApi<Provider, Pool, Network>
where
Pool: TransactionPool + Clone + 'static,
Provider: BlockReaderIdExt + StateProviderFactory + EvmEnvProvider + 'static,
Provider:
BlockReaderIdExt + ChainSpecProvider + StateProviderFactory + EvmEnvProvider + 'static,
Network: NetworkInfo + Send + Sync + 'static,
{
/// Estimate gas needed for execution of the `request` at the [BlockId].
Expand Down
7 changes: 5 additions & 2 deletions crates/rpc/rpc/src/eth/api/fees.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@ use reth_network_api::NetworkInfo;
use reth_primitives::{
basefee::calculate_next_block_base_fee, BlockNumberOrTag, SealedHeader, U256,
};
use reth_provider::{BlockReaderIdExt, EvmEnvProvider, StateProviderFactory};
use reth_provider::{BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, StateProviderFactory};
use reth_rpc_types::{FeeHistory, TxGasAndReward};
use reth_transaction_pool::TransactionPool;
use tracing::debug;

impl<Provider, Pool, Network> EthApi<Provider, Pool, Network>
where
Pool: TransactionPool + Clone + 'static,
Provider: BlockReaderIdExt + StateProviderFactory + EvmEnvProvider + 'static,
Provider:
BlockReaderIdExt + ChainSpecProvider + StateProviderFactory + EvmEnvProvider + 'static,
Network: NetworkInfo + Send + Sync + 'static,
{
/// Returns a suggestion for a gas price for legacy transactions.
Expand Down Expand Up @@ -119,6 +120,8 @@ where
last_header.gas_used,
last_header.gas_limit,
last_header.base_fee_per_gas.unwrap_or_default(),
self.provider().chain_spec().elasticity_multiplier(),
self.provider().chain_spec().base_fee_change_denominator(),
)));

Ok(FeeHistory {
Expand Down
Loading