git.delta.rocks / unique-network / refs/commits / f28d992941c5

difftreelog

feat update BaseFee storage from pallet-configuration

Yaroslav Bolyukin2023-06-16parent: #55ce0a6.patch.diff
in: master

2 files changed

modifiedpallets/configuration/Cargo.tomldiffbeforeafterboth
--- a/pallets/configuration/Cargo.toml
+++ b/pallets/configuration/Cargo.toml
@@ -16,8 +16,11 @@
 sp-arithmetic = { workspace = true }
 sp-core = { workspace = true }
 sp-std = { workspace = true }
+sp-io = { workspace = true }
 xcm = { workspace = true }
 
+hex-literal = { workspace = true }
+
 [features]
 default = ["std"]
 runtime-benchmarks = ["frame-benchmarking"]
modifiedpallets/configuration/src/lib.rsdiffbeforeafterboth
before · pallets/configuration/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::marker::PhantomData;2021use frame_support::{22	pallet,23	weights::{WeightToFeePolynomial, WeightToFeeCoefficients, WeightToFeeCoefficient, Weight},24	traits::Get,25	Parameter,26};27use codec::{Decode, Encode, MaxEncodedLen};28use scale_info::TypeInfo;29use sp_arithmetic::{30	per_things::{Perbill, PerThing},31	traits::{BaseArithmetic, Unsigned},32};33use smallvec::smallvec;3435pub use pallet::*;36use sp_core::U256;3738#[cfg(feature = "runtime-benchmarks")]39mod benchmarking;40pub mod weights;4142#[pallet]43mod pallet {44	use super::*;45	use frame_support::{46		traits::{Get},47		pallet_prelude::{48			StorageValue, ValueQuery, DispatchResult, IsType, Member, MaybeSerializeDeserialize,49		},50		log,51		dispatch::{Codec, fmt::Debug},52	};53	use frame_system::{pallet_prelude::OriginFor, ensure_root};54	use sp_arithmetic::{FixedPointOperand, traits::AtLeast32BitUnsigned};55	pub use crate::weights::WeightInfo;5657	#[pallet::config]58	pub trait Config: frame_system::Config {59		/// Overarching event type.60		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;6162		type Balance: Parameter63			+ Member64			+ AtLeast32BitUnsigned65			+ Codec66			+ Default67			+ Copy68			+ MaybeSerializeDeserialize69			+ Debug70			+ MaxEncodedLen71			+ TypeInfo72			+ FixedPointOperand;7374		#[pallet::constant]75		type DefaultWeightToFeeCoefficient: Get<u64>;76		#[pallet::constant]77		type DefaultMinGasPrice: Get<u64>;7879		#[pallet::constant]80		type MaxXcmAllowedLocations: Get<u32>;81		#[pallet::constant]82		type AppPromotionDailyRate: Get<Perbill>;83		#[pallet::constant]84		type DayRelayBlocks: Get<Self::BlockNumber>;8586		#[pallet::constant]87		type DefaultCollatorSelectionMaxCollators: Get<u32>;88		#[pallet::constant]89		type DefaultCollatorSelectionLicenseBond: Get<Self::Balance>;90		#[pallet::constant]91		type DefaultCollatorSelectionKickThreshold: Get<Self::BlockNumber>;9293		/// The weight information of this pallet.94		type WeightInfo: WeightInfo;95	}9697	#[pallet::event]98	#[pallet::generate_deposit(pub(super) fn deposit_event)]99	pub enum Event<T: Config> {100		NewDesiredCollators {101			desired_collators: Option<u32>,102		},103		NewCollatorLicenseBond {104			bond_cost: Option<T::Balance>,105		},106		NewCollatorKickThreshold {107			length_in_blocks: Option<T::BlockNumber>,108		},109	}110111	#[pallet::error]112	pub enum Error<T> {113		InconsistentConfiguration,114	}115116	#[pallet::storage]117	pub type WeightToFeeCoefficientOverride<T: Config> = StorageValue<118		Value = u64,119		QueryKind = ValueQuery,120		OnEmpty = T::DefaultWeightToFeeCoefficient,121	>;122123	#[pallet::storage]124	pub type MinGasPriceOverride<T: Config> =125		StorageValue<Value = u64, QueryKind = ValueQuery, OnEmpty = T::DefaultMinGasPrice>;126127	#[pallet::storage]128	pub type AppPromomotionConfigurationOverride<T: Config> =129		StorageValue<Value = AppPromotionConfiguration<T::BlockNumber>, QueryKind = ValueQuery>;130131	#[pallet::storage]132	pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<133		Value = u32,134		QueryKind = ValueQuery,135		OnEmpty = T::DefaultCollatorSelectionMaxCollators,136	>;137138	#[pallet::storage]139	pub type CollatorSelectionLicenseBondOverride<T: Config> = StorageValue<140		Value = T::Balance,141		QueryKind = ValueQuery,142		OnEmpty = T::DefaultCollatorSelectionLicenseBond,143	>;144145	#[pallet::storage]146	pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<147		Value = T::BlockNumber,148		QueryKind = ValueQuery,149		OnEmpty = T::DefaultCollatorSelectionKickThreshold,150	>;151152	#[pallet::call]153	impl<T: Config> Pallet<T> {154		#[pallet::call_index(0)]155		#[pallet::weight(T::WeightInfo::set_weight_to_fee_coefficient_override())]156		pub fn set_weight_to_fee_coefficient_override(157			origin: OriginFor<T>,158			coeff: Option<u64>,159		) -> DispatchResult {160			ensure_root(origin)?;161			if let Some(coeff) = coeff {162				<WeightToFeeCoefficientOverride<T>>::set(coeff);163			} else {164				<WeightToFeeCoefficientOverride<T>>::kill();165			}166			Ok(())167		}168169		#[pallet::call_index(1)]170		#[pallet::weight(T::WeightInfo::set_min_gas_price_override())]171		pub fn set_min_gas_price_override(172			origin: OriginFor<T>,173			coeff: Option<u64>,174		) -> DispatchResult {175			ensure_root(origin)?;176			if let Some(coeff) = coeff {177				<MinGasPriceOverride<T>>::set(coeff);178			} else {179				<MinGasPriceOverride<T>>::kill();180			}181			Ok(())182		}183184		#[pallet::call_index(3)]185		#[pallet::weight(T::WeightInfo::set_app_promotion_configuration_override())]186		pub fn set_app_promotion_configuration_override(187			origin: OriginFor<T>,188			mut configuration: AppPromotionConfiguration<T::BlockNumber>,189		) -> DispatchResult {190			ensure_root(origin)?;191			if configuration.interval_income.is_some() {192				return Err(<Error<T>>::InconsistentConfiguration.into());193			}194195			configuration.interval_income = configuration.recalculation_interval.map(|b| {196				Perbill::from_rational(b, T::DayRelayBlocks::get())197					* T::AppPromotionDailyRate::get()198			});199200			<AppPromomotionConfigurationOverride<T>>::set(configuration);201202			Ok(())203		}204205		#[pallet::call_index(4)]206		#[pallet::weight(T::WeightInfo::set_collator_selection_desired_collators())]207		pub fn set_collator_selection_desired_collators(208			origin: OriginFor<T>,209			max: Option<u32>,210		) -> DispatchResult {211			ensure_root(origin)?;212			if let Some(max) = max {213				// we trust origin calls, this is just a for more accurate benchmarking214				if max > T::DefaultCollatorSelectionMaxCollators::get() {215					log::warn!("max > T::DefaultCollatorSelectionMaxCollators; you might need to run benchmarks again");216				}217				<CollatorSelectionDesiredCollatorsOverride<T>>::set(max);218			} else {219				<CollatorSelectionDesiredCollatorsOverride<T>>::kill();220			}221			Self::deposit_event(Event::NewDesiredCollators {222				desired_collators: max,223			});224			Ok(())225		}226227		#[pallet::call_index(5)]228		#[pallet::weight(T::WeightInfo::set_collator_selection_license_bond())]229		pub fn set_collator_selection_license_bond(230			origin: OriginFor<T>,231			amount: Option<<T as Config>::Balance>,232		) -> DispatchResult {233			ensure_root(origin)?;234			if let Some(amount) = amount {235				<CollatorSelectionLicenseBondOverride<T>>::set(amount);236			} else {237				<CollatorSelectionLicenseBondOverride<T>>::kill();238			}239			Self::deposit_event(Event::NewCollatorLicenseBond { bond_cost: amount });240			Ok(())241		}242243		#[pallet::call_index(6)]244		#[pallet::weight(T::WeightInfo::set_collator_selection_kick_threshold())]245		pub fn set_collator_selection_kick_threshold(246			origin: OriginFor<T>,247			threshold: Option<T::BlockNumber>,248		) -> DispatchResult {249			ensure_root(origin)?;250			if let Some(threshold) = threshold {251				<CollatorSelectionKickThresholdOverride<T>>::set(threshold);252			} else {253				<CollatorSelectionKickThresholdOverride<T>>::kill();254			}255			Self::deposit_event(Event::NewCollatorKickThreshold {256				length_in_blocks: threshold,257			});258			Ok(())259		}260	}261262	#[pallet::pallet]263	pub struct Pallet<T>(_);264}265266pub struct WeightToFee<T, B>(PhantomData<(T, B)>);267268impl<T, B> WeightToFeePolynomial for WeightToFee<T, B>269where270	T: Config,271	B: BaseArithmetic + From<u32> + From<u64> + Copy + Unsigned,272{273	type Balance = B;274275	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {276		smallvec!(WeightToFeeCoefficient {277			coeff_integer: (<WeightToFeeCoefficientOverride<T>>::get() / Perbill::ACCURACY as u64)278				.into(),279			coeff_frac: Perbill::from_parts(280				(<WeightToFeeCoefficientOverride<T>>::get() % Perbill::ACCURACY as u64) as u32281			),282			negative: false,283			degree: 1,284		})285	}286}287288pub struct FeeCalculator<T>(PhantomData<T>);289impl<T: Config> fp_evm::FeeCalculator for FeeCalculator<T> {290	fn min_gas_price() -> (U256, Weight) {291		(292			<MinGasPriceOverride<T>>::get().into(),293			T::DbWeight::get().reads(1),294		)295	}296}297298#[derive(Encode, Decode, Clone, Debug, Default, TypeInfo, MaxEncodedLen, PartialEq, PartialOrd)]299pub struct AppPromotionConfiguration<BlockNumber> {300	/// In relay blocks.301	pub recalculation_interval: Option<BlockNumber>,302	/// In parachain blocks.303	pub pending_interval: Option<BlockNumber>,304	/// Value for `RecalculationInterval` based on 0.05% per 24h.305	pub interval_income: Option<Perbill>,306	/// Maximum allowable number of stakers calculated per call of the `app-promotion::PayoutStakers` extrinsic.307	pub max_stakers_per_calculation: Option<u8>,308}
after · pallets/configuration/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::marker::PhantomData;2021use frame_support::{22	pallet,23	weights::{WeightToFeePolynomial, WeightToFeeCoefficients, WeightToFeeCoefficient, Weight},24	traits::Get,25	Parameter,26};27use codec::{Decode, Encode, MaxEncodedLen};28use scale_info::TypeInfo;29use sp_arithmetic::{30	per_things::{Perbill, PerThing},31	traits::{BaseArithmetic, Unsigned},32};33use smallvec::smallvec;3435pub use pallet::*;36use sp_core::U256;3738#[cfg(feature = "runtime-benchmarks")]39mod benchmarking;40pub mod weights;4142#[pallet]43mod pallet {44	use super::*;45	use frame_support::{46		traits::Get,47		pallet_prelude::*,48		log,49		dispatch::{Codec, fmt::Debug},50	};51	use frame_system::{pallet_prelude::OriginFor, ensure_root, pallet_prelude::*};52	use sp_arithmetic::{FixedPointOperand, traits::AtLeast32BitUnsigned, Permill};53	pub use crate::weights::WeightInfo;5455	#[pallet::config]56	pub trait Config: frame_system::Config {57		/// Overarching event type.58		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;5960		type Balance: Parameter61			+ Member62			+ AtLeast32BitUnsigned63			+ Codec64			+ Default65			+ Copy66			+ MaybeSerializeDeserialize67			+ Debug68			+ MaxEncodedLen69			+ TypeInfo70			+ FixedPointOperand;7172		#[pallet::constant]73		type DefaultWeightToFeeCoefficient: Get<u64>;74		#[pallet::constant]75		type DefaultMinGasPrice: Get<u64>;7677		#[pallet::constant]78		type MaxXcmAllowedLocations: Get<u32>;79		#[pallet::constant]80		type AppPromotionDailyRate: Get<Perbill>;81		#[pallet::constant]82		type DayRelayBlocks: Get<Self::BlockNumber>;8384		#[pallet::constant]85		type DefaultCollatorSelectionMaxCollators: Get<u32>;86		#[pallet::constant]87		type DefaultCollatorSelectionLicenseBond: Get<Self::Balance>;88		#[pallet::constant]89		type DefaultCollatorSelectionKickThreshold: Get<Self::BlockNumber>;9091		/// The weight information of this pallet.92		type WeightInfo: WeightInfo;93	}9495	#[pallet::event]96	#[pallet::generate_deposit(pub(super) fn deposit_event)]97	pub enum Event<T: Config> {98		NewDesiredCollators {99			desired_collators: Option<u32>,100		},101		NewCollatorLicenseBond {102			bond_cost: Option<T::Balance>,103		},104		NewCollatorKickThreshold {105			length_in_blocks: Option<T::BlockNumber>,106		},107	}108109	fn update_base_fee<T: Config>() {110		let base_fee_per_gas: U256 = <MinGasPriceOverride<T>>::get().into();111		let elasticity: Permill = Permill::zero();112		// twox_128(BaseFee) ++ twox_128(BaseFeePerGas)113		sp_io::storage::set(114			&hex_literal::hex!("c1fef3b7207c11a52df13c12884e77263864ade243c642793ebcfe9e16f454ca"),115			&base_fee_per_gas.encode(),116		);117		// twox_128(BaseFee) ++ twox_128(Elasticity)118		sp_io::storage::set(119			&hex_literal::hex!("c1fef3b7207c11a52df13c12884e772609bc3a1e532c9cb85d57feed02cbff8e"),120			&elasticity.encode(),121		);122	}123124	/// We update our default weights on every release125	#[pallet::hooks]126	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {127		fn on_runtime_upgrade() -> Weight {128			update_base_fee::<T>();129			T::DbWeight::get().reads_writes(1, 2)130		}131	}132133	#[pallet::genesis_config]134	pub struct GenesisConfig<T>(PhantomData<T>);135136	#[cfg(feature = "std")]137	impl<T: Config> Default for GenesisConfig<T> {138		fn default() -> Self {139			Self(Default::default())140		}141	}142143	#[pallet::genesis_build]144	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {145		fn build(&self) {146			update_base_fee::<T>();147		}148	}149150	#[pallet::error]151	pub enum Error<T> {152		InconsistentConfiguration,153	}154155	#[pallet::storage]156	pub type WeightToFeeCoefficientOverride<T: Config> = StorageValue<157		Value = u64,158		QueryKind = ValueQuery,159		OnEmpty = T::DefaultWeightToFeeCoefficient,160	>;161162	#[pallet::storage]163	pub type MinGasPriceOverride<T: Config> =164		StorageValue<Value = u64, QueryKind = ValueQuery, OnEmpty = T::DefaultMinGasPrice>;165166	#[pallet::storage]167	pub type AppPromomotionConfigurationOverride<T: Config> =168		StorageValue<Value = AppPromotionConfiguration<T::BlockNumber>, QueryKind = ValueQuery>;169170	#[pallet::storage]171	pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<172		Value = u32,173		QueryKind = ValueQuery,174		OnEmpty = T::DefaultCollatorSelectionMaxCollators,175	>;176177	#[pallet::storage]178	pub type CollatorSelectionLicenseBondOverride<T: Config> = StorageValue<179		Value = T::Balance,180		QueryKind = ValueQuery,181		OnEmpty = T::DefaultCollatorSelectionLicenseBond,182	>;183184	#[pallet::storage]185	pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<186		Value = T::BlockNumber,187		QueryKind = ValueQuery,188		OnEmpty = T::DefaultCollatorSelectionKickThreshold,189	>;190191	#[pallet::call]192	impl<T: Config> Pallet<T> {193		#[pallet::call_index(0)]194		#[pallet::weight(T::WeightInfo::set_weight_to_fee_coefficient_override())]195		pub fn set_weight_to_fee_coefficient_override(196			origin: OriginFor<T>,197			coeff: Option<u64>,198		) -> DispatchResult {199			ensure_root(origin)?;200			if let Some(coeff) = coeff {201				<WeightToFeeCoefficientOverride<T>>::set(coeff);202			} else {203				<WeightToFeeCoefficientOverride<T>>::kill();204			}205			Ok(())206		}207208		#[pallet::call_index(1)]209		#[pallet::weight(T::WeightInfo::set_min_gas_price_override())]210		pub fn set_min_gas_price_override(211			origin: OriginFor<T>,212			coeff: Option<u64>,213		) -> DispatchResult {214			ensure_root(origin)?;215			if let Some(coeff) = coeff {216				<MinGasPriceOverride<T>>::set(coeff);217			} else {218				<MinGasPriceOverride<T>>::kill();219			}220			// This code should not be called in production, but why keep development in the221			// inconsistent state222			update_base_fee::<T>();223			Ok(())224		}225226		#[pallet::call_index(3)]227		#[pallet::weight(T::WeightInfo::set_app_promotion_configuration_override())]228		pub fn set_app_promotion_configuration_override(229			origin: OriginFor<T>,230			mut configuration: AppPromotionConfiguration<T::BlockNumber>,231		) -> DispatchResult {232			ensure_root(origin)?;233			if configuration.interval_income.is_some() {234				return Err(<Error<T>>::InconsistentConfiguration.into());235			}236237			configuration.interval_income = configuration.recalculation_interval.map(|b| {238				Perbill::from_rational(b, T::DayRelayBlocks::get())239					* T::AppPromotionDailyRate::get()240			});241242			<AppPromomotionConfigurationOverride<T>>::set(configuration);243244			Ok(())245		}246247		#[pallet::call_index(4)]248		#[pallet::weight(T::WeightInfo::set_collator_selection_desired_collators())]249		pub fn set_collator_selection_desired_collators(250			origin: OriginFor<T>,251			max: Option<u32>,252		) -> DispatchResult {253			ensure_root(origin)?;254			if let Some(max) = max {255				// we trust origin calls, this is just a for more accurate benchmarking256				if max > T::DefaultCollatorSelectionMaxCollators::get() {257					log::warn!("max > T::DefaultCollatorSelectionMaxCollators; you might need to run benchmarks again");258				}259				<CollatorSelectionDesiredCollatorsOverride<T>>::set(max);260			} else {261				<CollatorSelectionDesiredCollatorsOverride<T>>::kill();262			}263			Self::deposit_event(Event::NewDesiredCollators {264				desired_collators: max,265			});266			Ok(())267		}268269		#[pallet::call_index(5)]270		#[pallet::weight(T::WeightInfo::set_collator_selection_license_bond())]271		pub fn set_collator_selection_license_bond(272			origin: OriginFor<T>,273			amount: Option<<T as Config>::Balance>,274		) -> DispatchResult {275			ensure_root(origin)?;276			if let Some(amount) = amount {277				<CollatorSelectionLicenseBondOverride<T>>::set(amount);278			} else {279				<CollatorSelectionLicenseBondOverride<T>>::kill();280			}281			Self::deposit_event(Event::NewCollatorLicenseBond { bond_cost: amount });282			Ok(())283		}284285		#[pallet::call_index(6)]286		#[pallet::weight(T::WeightInfo::set_collator_selection_kick_threshold())]287		pub fn set_collator_selection_kick_threshold(288			origin: OriginFor<T>,289			threshold: Option<T::BlockNumber>,290		) -> DispatchResult {291			ensure_root(origin)?;292			if let Some(threshold) = threshold {293				<CollatorSelectionKickThresholdOverride<T>>::set(threshold);294			} else {295				<CollatorSelectionKickThresholdOverride<T>>::kill();296			}297			Self::deposit_event(Event::NewCollatorKickThreshold {298				length_in_blocks: threshold,299			});300			Ok(())301		}302	}303304	#[pallet::pallet]305	pub struct Pallet<T>(_);306}307308pub struct WeightToFee<T, B>(PhantomData<(T, B)>);309310impl<T, B> WeightToFeePolynomial for WeightToFee<T, B>311where312	T: Config,313	B: BaseArithmetic + From<u32> + From<u64> + Copy + Unsigned,314{315	type Balance = B;316317	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {318		smallvec!(WeightToFeeCoefficient {319			coeff_integer: (<WeightToFeeCoefficientOverride<T>>::get() / Perbill::ACCURACY as u64)320				.into(),321			coeff_frac: Perbill::from_parts(322				(<WeightToFeeCoefficientOverride<T>>::get() % Perbill::ACCURACY as u64) as u32323			),324			negative: false,325			degree: 1,326		})327	}328}329330pub struct FeeCalculator<T>(PhantomData<T>);331impl<T: Config> fp_evm::FeeCalculator for FeeCalculator<T> {332	fn min_gas_price() -> (U256, Weight) {333		(334			<MinGasPriceOverride<T>>::get().into(),335			T::DbWeight::get().reads(1),336		)337	}338}339340#[derive(Encode, Decode, Clone, Debug, Default, TypeInfo, MaxEncodedLen, PartialEq, PartialOrd)]341pub struct AppPromotionConfiguration<BlockNumber> {342	/// In relay blocks.343	pub recalculation_interval: Option<BlockNumber>,344	/// In parachain blocks.345	pub pending_interval: Option<BlockNumber>,346	/// Value for `RecalculationInterval` based on 0.05% per 24h.347	pub interval_income: Option<Perbill>,348	/// Maximum allowable number of stakers calculated per call of the `app-promotion::PayoutStakers` extrinsic.349	pub max_stakers_per_calculation: Option<u8>,350}