git.delta.rocks / unique-network / refs/commits / 20ac01d2fe7c

difftreelog

source

pallets/configuration/src/lib.rs10.0 KiBsourcehistory
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}