Skip to content

Commit

Permalink
Tweak the EVM gas price (#714)
Browse files Browse the repository at this point in the history
* Proper calculation for the WEIGHT_MILLISECS_PER_BLOCK for EVM

* Zero out the DefaultElasticity

* Allow non_snake_case at runtime

* Move DefaultBaseFeePerGas value to consts

* Adjust BLOCK_GAS_LIMIT and move it consts

* Adjust the eth rpc E2E test to the target fee value

* Adjust the max fee per gas estimates in the irrelevant tests

* Add runtime unit test for EVM fee value

* Drop all the sophisticated fee per gas calculation logic

* Set a sensible FEE_PER_GAS value with a proper rationale

* Cleanup the obsolete base and dynamic fee pallet integrations

* Tweak BLOCK_GAS_LIMIT and EVM fee unit test epsilon

* Rename the simple_evm_transaction to simple_evm_transaction_via_query_call_info

* Share the assert_fee fn

* Add a proper EVM runtime estimate test for the fee cost
  • Loading branch information
MOZGIII authored Aug 17, 2023
1 parent 7fc5002 commit 9d11cd4
Show file tree
Hide file tree
Showing 16 changed files with 220 additions and 123 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions crates/humanode-peer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ futures = "0.3"
hex = "0.4.3"
hex-literal = "0.4"
pallet-balances = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" }
pallet-dynamic-fee = { default-features = false, git = "https://github.com/humanode-network/frontier", branch = "locked/polkadot-v0.9.38" }
pallet-im-online = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" }
pallet-transaction-payment = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" }
qr2term = "0.3"
Expand Down Expand Up @@ -114,7 +113,6 @@ try-runtime = [
"humanode-runtime/try-runtime",
"pallet-balances/try-runtime",
"pallet-bioauth/try-runtime",
"pallet-dynamic-fee/try-runtime",
"pallet-im-online/try-runtime",
"pallet-transaction-payment/try-runtime",
"pallet-token-claims/try-runtime",
Expand Down
8 changes: 2 additions & 6 deletions crates/humanode-peer/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use humanode_runtime::{AccountId, Balance, BalancesCall, SystemCall, SLOT_DURATI
use sc_client_api::BlockBackend;
use sp_api::ProvideRuntimeApi;
use sp_consensus_babe::SlotDuration;
use sp_core::{Encode, Pair, U256};
use sp_core::{Encode, Pair};
use sp_inherents::{InherentData, InherentDataProvider};
use sp_keyring::Sr25519Keyring;
use sp_runtime::{generic, OpaqueExtrinsic, SaturatedConversion};
Expand Down Expand Up @@ -87,7 +87,7 @@ impl ExtrinsicBuilder for TransferKeepAliveBuilder {
}

/// Generates inherent data for the `benchmark overhead` command.
pub fn inherent_benchmark_data(config: &Configuration) -> sc_cli::Result<InherentData> {
pub fn inherent_benchmark_data(_config: &Configuration) -> sc_cli::Result<InherentData> {
let mut inherent_data = InherentData::new();

let d = Duration::from_millis(0);
Expand All @@ -103,10 +103,6 @@ pub fn inherent_benchmark_data(config: &Configuration) -> sc_cli::Result<Inheren
futures::executor::block_on(slot.provide_inherent_data(&mut inherent_data))
.map_err(|e| format!("creating slot inherent data: {:?}", e))?;

let dynamic_fees =
pallet_dynamic_fee::InherentDataProvider(U256::from(config.evm.target_gas_price));
futures::executor::block_on(dynamic_fees.provide_inherent_data(&mut inherent_data))
.map_err(|e| format!("creating dynamic fee inherent data: {:?}", e))?;
Ok(inherent_data)
}

Expand Down
2 changes: 0 additions & 2 deletions crates/humanode-peer/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,8 +368,6 @@ fn testnet_genesis(
},
evm_accounts_mapping: Default::default(),
ethereum: EthereumConfig {},
dynamic_fee: Default::default(),
base_fee: Default::default(),
transaction_payment: Default::default(),
fees_pot: Default::default(),
treasury_pot: Default::default(),
Expand Down
8 changes: 0 additions & 8 deletions crates/humanode-peer/src/cli/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,6 @@ pub trait CliConfigurationExt: SubstrateCliConfigurationProvider {
}
});

let evm = {
let params = self.evm_params();
configuration::Evm {
target_gas_price: params.map(|p| p.target_gas_price).unwrap_or(1),
}
};

let ethereum_rpc = self
.ethereum_rpc_params()
.map(|params| configuration::EthereumRpc {
Expand All @@ -77,7 +70,6 @@ pub trait CliConfigurationExt: SubstrateCliConfigurationProvider {
Ok(Configuration {
substrate,
bioauth_flow,
evm,
ethereum_rpc,
time_warp,
})
Expand Down
9 changes: 0 additions & 9 deletions crates/humanode-peer/src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ pub struct Configuration {
/// always required.
pub bioauth_flow: Option<BioauthFlow>,

/// EVM configuration.
pub evm: Evm,

/// Ethereum RPC configuration.
pub ethereum_rpc: Option<EthereumRpc>,

Expand Down Expand Up @@ -58,12 +55,6 @@ impl BioauthFlow {
}
}

/// EVM configuration parameters.
pub struct Evm {
/// The dynamic-fee pallet target gas price set by block author.
pub target_gas_price: u64,
}

/// Ethereum RPC configuration parameters.
pub struct EthereumRpc {
/// Maximum number of blocks to keep the log information available
Expand Down
15 changes: 2 additions & 13 deletions crates/humanode-peer/src/service/inherents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
use sc_client_api::ProvideUncles;
use sc_service::Arc;
use sp_core::U256;
use sp_runtime::traits::Block;

use crate::time_warp::TimeWarp;
Expand All @@ -12,8 +11,6 @@ use crate::time_warp::TimeWarp;
pub struct Creator<Client> {
/// Consensus slot duration.
pub raw_slot_duration: sp_consensus_babe::SlotDuration,
/// Ethereum gas target price.
pub eth_target_gas_price: u64,
/// Time warp peer mode.
pub time_warp: Option<TimeWarp>,
/// Client.
Expand All @@ -25,7 +22,6 @@ pub struct Creator<Client> {
type InherentDataProviders = (
sp_consensus_babe::inherents::InherentDataProvider,
sp_timestamp::InherentDataProvider,
pallet_dynamic_fee::InherentDataProvider,
);

/// The inherents creator for block production.
Expand Down Expand Up @@ -63,10 +59,7 @@ where
self.0.raw_slot_duration,
);

let dynamic_fee =
pallet_dynamic_fee::InherentDataProvider(U256::from(self.0.eth_target_gas_price));

Ok((slot, timestamp, dynamic_fee))
Ok((slot, timestamp))
}
}

Expand Down Expand Up @@ -98,18 +91,14 @@ where
self.0.raw_slot_duration,
);

let dynamic_fee =
pallet_dynamic_fee::InherentDataProvider(U256::from(self.0.eth_target_gas_price));

Ok((slot, timestamp, dynamic_fee))
Ok((slot, timestamp))
}
}

impl<Client> Clone for Creator<Client> {
fn clone(&self) -> Self {
Self {
raw_slot_duration: self.raw_slot_duration,
eth_target_gas_price: self.eth_target_gas_price,
time_warp: self.time_warp.clone(),
client: Arc::clone(&self.client),
}
Expand Down
4 changes: 0 additions & 4 deletions crates/humanode-peer/src/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ pub fn new_partial(
> {
let Configuration {
substrate: config,
evm: evm_config,
time_warp: time_warp_config,
..
} = config;
Expand Down Expand Up @@ -181,10 +180,8 @@ pub fn new_partial(
);

let raw_slot_duration = babe_link.config().slot_duration();
let eth_target_gas_price = evm_config.target_gas_price;
let inherent_data_providers_creator = inherents::Creator {
raw_slot_duration,
eth_target_gas_price,
client: Arc::clone(&client),
time_warp: time_warp_config.clone(),
};
Expand Down Expand Up @@ -243,7 +240,6 @@ pub async fn new_full(config: Configuration) -> Result<TaskManager, ServiceError
let Configuration {
substrate: mut config,
bioauth_flow: bioauth_flow_config,
evm: _evm_config,
ethereum_rpc: ethereum_rpc_config,
..
} = config;
Expand Down
16 changes: 16 additions & 0 deletions crates/humanode-runtime/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,19 @@ pub mod fees {
/// The multiplier to get the fee from length.
pub const LENGTH_TO_FEE: Balance = 1;
}

/// EVM fees related constants.
pub mod evm_fees {
/// The max amount of gas per block.
/// Set to the value that fits our fee requirements.
/// Ref: <https://ethereum.org/en/developers/docs/gas/#block-size>
pub const BLOCK_GAS_LIMIT: u64 = 60_000_000;

/// The amount of fee per gas unit.
/// Comes from the following rationale:
/// - a simple transfer costs 21000 gas
/// - we want the cost of this transfer to be around ~0.2 HMND
/// - so we must charge about 0.2 * 10^18 / 21000 fee per a unit of gas
/// The value below is a nice round number that fits the requirements outlined above.
pub const FEE_PER_GAS: u128 = 10_000_000_000_000;
}
72 changes: 29 additions & 43 deletions crates/humanode-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
#![allow(missing_docs, clippy::missing_docs_in_private_items)]
// Either generate code at stadard mode, or `no_std`, based on the `std` feature presence.
#![cfg_attr(not(feature = "std"), no_std)]
// Runtime impl macros generate non-snake case names.
#![allow(non_snake_case)]

// If we're in standard compilation mode, embed the build-script generated code that pulls in
// the WASM portion of the runtime, so that it is invocable from the native (aka host) side code.
Expand Down Expand Up @@ -104,6 +106,7 @@ pub use constants::{
equivocation::REPORT_LONGEVITY,
im_online::{MAX_KEYS, MAX_PEER_DATA_ENCODING_SIZE, MAX_PEER_IN_HEARTBEATS},
};
use static_assertions::const_assert;

/// An index to a block.
pub type BlockNumber = u32;
Expand Down Expand Up @@ -232,11 +235,14 @@ pub fn native_version() -> NativeVersion {
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
const MAX_BLOCK_LENGTH: u32 = 5 * 1024 * 1024;

/// We allow for 2 seconds of compute with a 6 second average block time.
const EXPECTED_BLOCK_WEIGHT: Weight =
Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX);

parameter_types! {
pub const Version: RuntimeVersion = VERSION;
/// We allow for 2 seconds of compute with a 6 second average block time.
pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights
::with_sensible_defaults(Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX), NORMAL_DISPATCH_RATIO);
::with_sensible_defaults(EXPECTED_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO);
pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
::max_with_normal_ratio(MAX_BLOCK_LENGTH, NORMAL_DISPATCH_RATIO);
pub SS58Prefix: u16 = ChainProperties::ss58_prefix();
Expand Down Expand Up @@ -624,13 +630,19 @@ impl pallet_offences::Config for Runtime {
type OnOffenceHandler = OffenceSlasher;
}

const BLOCK_GAS_LIMIT: u64 = 75_000_000;
const WEIGHT_MILLISECS_PER_BLOCK: u64 = 2000;
const WEIGHT_MILLISECS_PER_BLOCK: u64 = EXPECTED_BLOCK_WEIGHT.ref_time()
/ frame_support::weights::constants::WEIGHT_REF_TIME_PER_MILLIS;
// An assertion to ensure this value is what we expect it to be here.
const_assert!(WEIGHT_MILLISECS_PER_BLOCK == 2000u64);

parameter_types! {
pub BlockGasLimit: U256 = U256::from(BLOCK_GAS_LIMIT);
pub BlockGasLimit: U256 = U256::from(constants::evm_fees::BLOCK_GAS_LIMIT);
pub PrecompilesValue: FrontierPrecompiles<Runtime> = FrontierPrecompiles::<_>::default();
pub WeightPerGas: Weight = Weight::from_ref_time(fp_evm::weight_per_gas(BLOCK_GAS_LIMIT, NORMAL_DISPATCH_RATIO, WEIGHT_MILLISECS_PER_BLOCK));
pub WeightPerGas: Weight = Weight::from_ref_time(fp_evm::weight_per_gas(
constants::evm_fees::BLOCK_GAS_LIMIT,
NORMAL_DISPATCH_RATIO,
WEIGHT_MILLISECS_PER_BLOCK,
));
}

impl pallet_evm_system::Config for Runtime {
Expand Down Expand Up @@ -658,9 +670,18 @@ impl pallet_currency_swap::Config for Runtime {
type WeightInfo = ();
}

/// A simple fixed fee per gas calculator.
pub struct EvmFeePerGas;

impl fp_evm::FeeCalculator for EvmFeePerGas {
fn min_gas_price() -> (U256, Weight) {
(constants::evm_fees::FEE_PER_GAS.into(), Weight::zero())
}
}

impl pallet_evm::Config for Runtime {
type AccountProvider = EvmSystem;
type FeeCalculator = BaseFee;
type FeeCalculator = EvmFeePerGas;
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type WeightPerGas = WeightPerGas;
type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
Expand Down Expand Up @@ -692,39 +713,6 @@ impl pallet_ethereum::Config for Runtime {
type PostLogContent = PostBlockAndTxnHashes;
}

parameter_types! {
pub BoundDivision: U256 = U256::from(1024);
}

impl pallet_dynamic_fee::Config for Runtime {
type MinGasPriceBoundDivisor = BoundDivision;
}

parameter_types! {
pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000);
pub DefaultElasticity: Permill = Permill::from_parts(125_000);
}

pub struct BaseFeeThreshold;
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
fn lower() -> Permill {
Permill::zero()
}
fn ideal() -> Permill {
Permill::from_parts(500_000)
}
fn upper() -> Permill {
Permill::from_parts(1_000_000)
}
}

impl pallet_base_fee::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Threshold = BaseFeeThreshold;
type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
type DefaultElasticity = DefaultElasticity;
}

impl pallet_chain_properties::Config for Runtime {}

impl pallet_ethereum_chain_id::Config for Runtime {}
Expand Down Expand Up @@ -832,8 +820,6 @@ construct_runtime!(
Grandpa: pallet_grandpa = 20,
Ethereum: pallet_ethereum = 21,
EVM: pallet_evm = 22,
DynamicFee: pallet_dynamic_fee = 23,
BaseFee: pallet_base_fee = 24,
ImOnline: pallet_im_online = 25,
EvmAccountsMapping: pallet_evm_accounts_mapping = 26,
TokenClaims: pallet_token_claims = 27,
Expand Down Expand Up @@ -1394,7 +1380,7 @@ impl_runtime_apis! {
}

fn elasticity() -> Option<Permill> {
Some(BaseFee::elasticity())
None
}

fn gas_limit_multiplier_support() {}
Expand Down
8 changes: 0 additions & 8 deletions crates/humanode-runtime/src/tests/claims_and_vesting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,14 +329,6 @@ fn prepare_genesis_json(token_claims: &str, token_claim_pot_balance: u128) -> St
}}
}}
}},
"dynamicFee": {{
"minGasPrice": "0x0"
}},
"baseFee": {{
"baseFeePerGas": "0x0",
"elasticity": 0,
"marker": null
}},
"imOnline": {{
"keys": []
}},
Expand Down
3 changes: 2 additions & 1 deletion crates/humanode-runtime/src/tests/currency_swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ use crate::dev_utils::*;
use crate::opaque::SessionKeys;

pub(crate) static PRECOMPILE_ADDRESS: Lazy<H160> = Lazy::new(|| H160::from_low_u64_be(0x900));
pub(crate) static GAS_PRICE: Lazy<U256> = Lazy::new(|| 1_000_000_000u128.into());
pub(crate) static GAS_PRICE: Lazy<U256> =
Lazy::new(|| <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price().0);

const INIT_BALANCE: Balance = 10u128.pow(18 + 6);

Expand Down
Loading

0 comments on commit 9d11cd4

Please sign in to comment.