git.delta.rocks / unique-network / refs/commits / 65414d643dd4

difftreelog

source

pallets/configuration/src/lib.rs8.8 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};26use codec::{Decode, Encode, MaxEncodedLen};27use scale_info::TypeInfo;28use sp_arithmetic::{29	per_things::{Perbill, PerThing},30	traits::{BaseArithmetic, Unsigned},31};32use smallvec::smallvec;3334pub use pallet::*;35use sp_core::U256;3637#[cfg(feature = "runtime-benchmarks")]38mod benchmarking;39pub mod weights;4041#[pallet]42mod pallet {43	use super::*;44	use frame_support::{45		traits::{fungible, Get},46		pallet_prelude::{StorageValue, ValueQuery, DispatchResult, IsType},47		log,48	};49	use frame_system::{pallet_prelude::OriginFor, ensure_root, Config as SystemConfig};5051	pub use crate::weights::WeightInfo;52	pub type BalanceOf<T> =53		<<T as Config>::Currency as fungible::Inspect<<T as SystemConfig>::AccountId>>::Balance;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 Currency: fungible::Inspect<Self::AccountId>61			+ fungible::Mutate<Self::AccountId>62			+ fungible::MutateFreeze<Self::AccountId>63			+ fungible::InspectHold<Self::AccountId>64			+ fungible::MutateHold<Self::AccountId>65			+ fungible::BalancedHold<Self::AccountId>;6667		#[pallet::constant]68		type DefaultWeightToFeeCoefficient: Get<u64>;69		#[pallet::constant]70		type DefaultMinGasPrice: Get<u64>;7172		#[pallet::constant]73		type MaxXcmAllowedLocations: Get<u32>;74		#[pallet::constant]75		type AppPromotionDailyRate: Get<Perbill>;76		#[pallet::constant]77		type DayRelayBlocks: Get<Self::BlockNumber>;7879		#[pallet::constant]80		type DefaultCollatorSelectionMaxCollators: Get<u32>;81		#[pallet::constant]82		type DefaultCollatorSelectionLicenseBond: Get<BalanceOf<Self>>;83		#[pallet::constant]84		type DefaultCollatorSelectionKickThreshold: Get<Self::BlockNumber>;8586		/// The weight information of this pallet.87		type WeightInfo: WeightInfo;88	}8990	#[pallet::event]91	#[pallet::generate_deposit(pub(super) fn deposit_event)]92	pub enum Event<T: Config> {93		NewDesiredCollators {94			desired_collators: Option<u32>,95		},96		NewCollatorLicenseBond {97			bond_cost: Option<BalanceOf<T>>,98		},99		NewCollatorKickThreshold {100			length_in_blocks: Option<T::BlockNumber>,101		},102	}103104	#[pallet::error]105	pub enum Error<T> {106		InconsistentConfiguration,107	}108109	#[pallet::storage]110	pub type WeightToFeeCoefficientOverride<T: Config> = StorageValue<111		Value = u64,112		QueryKind = ValueQuery,113		OnEmpty = T::DefaultWeightToFeeCoefficient,114	>;115116	#[pallet::storage]117	pub type MinGasPriceOverride<T: Config> =118		StorageValue<Value = u64, QueryKind = ValueQuery, OnEmpty = T::DefaultMinGasPrice>;119120	#[pallet::storage]121	pub type AppPromomotionConfigurationOverride<T: Config> =122		StorageValue<Value = AppPromotionConfiguration<T::BlockNumber>, QueryKind = ValueQuery>;123124	#[pallet::storage]125	pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<126		Value = u32,127		QueryKind = ValueQuery,128		OnEmpty = T::DefaultCollatorSelectionMaxCollators,129	>;130131	#[pallet::storage]132	pub type CollatorSelectionLicenseBondOverride<T: Config> = StorageValue<133		Value = BalanceOf<T>,134		QueryKind = ValueQuery,135		OnEmpty = T::DefaultCollatorSelectionLicenseBond,136	>;137138	#[pallet::storage]139	pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<140		Value = T::BlockNumber,141		QueryKind = ValueQuery,142		OnEmpty = T::DefaultCollatorSelectionKickThreshold,143	>;144145	#[pallet::call]146	impl<T: Config> Pallet<T> {147		#[pallet::call_index(0)]148		#[pallet::weight(T::WeightInfo::set_weight_to_fee_coefficient_override())]149		pub fn set_weight_to_fee_coefficient_override(150			origin: OriginFor<T>,151			coeff: Option<u64>,152		) -> DispatchResult {153			ensure_root(origin)?;154			if let Some(coeff) = coeff {155				<WeightToFeeCoefficientOverride<T>>::set(coeff);156			} else {157				<WeightToFeeCoefficientOverride<T>>::kill();158			}159			Ok(())160		}161162		#[pallet::call_index(1)]163		#[pallet::weight(T::WeightInfo::set_min_gas_price_override())]164		pub fn set_min_gas_price_override(165			origin: OriginFor<T>,166			coeff: Option<u64>,167		) -> DispatchResult {168			ensure_root(origin)?;169			if let Some(coeff) = coeff {170				<MinGasPriceOverride<T>>::set(coeff);171			} else {172				<MinGasPriceOverride<T>>::kill();173			}174			Ok(())175		}176177		#[pallet::call_index(3)]178		#[pallet::weight(T::WeightInfo::set_app_promotion_configuration_override())]179		pub fn set_app_promotion_configuration_override(180			origin: OriginFor<T>,181			mut configuration: AppPromotionConfiguration<T::BlockNumber>,182		) -> DispatchResult {183			ensure_root(origin)?;184			if configuration.interval_income.is_some() {185				return Err(<Error<T>>::InconsistentConfiguration.into());186			}187188			configuration.interval_income = configuration.recalculation_interval.map(|b| {189				Perbill::from_rational(b, T::DayRelayBlocks::get())190					* T::AppPromotionDailyRate::get()191			});192193			<AppPromomotionConfigurationOverride<T>>::set(configuration);194195			Ok(())196		}197198		#[pallet::call_index(4)]199		#[pallet::weight(T::WeightInfo::set_collator_selection_desired_collators())]200		pub fn set_collator_selection_desired_collators(201			origin: OriginFor<T>,202			max: Option<u32>,203		) -> DispatchResult {204			ensure_root(origin)?;205			if let Some(max) = max {206				// we trust origin calls, this is just a for more accurate benchmarking207				if max > T::DefaultCollatorSelectionMaxCollators::get() {208					log::warn!("max > T::DefaultCollatorSelectionMaxCollators; you might need to run benchmarks again");209				}210				<CollatorSelectionDesiredCollatorsOverride<T>>::set(max);211			} else {212				<CollatorSelectionDesiredCollatorsOverride<T>>::kill();213			}214			Self::deposit_event(Event::NewDesiredCollators {215				desired_collators: max,216			});217			Ok(())218		}219220		#[pallet::call_index(5)]221		#[pallet::weight(T::WeightInfo::set_collator_selection_license_bond())]222		pub fn set_collator_selection_license_bond(223			origin: OriginFor<T>,224			amount: Option<BalanceOf<T>>,225		) -> DispatchResult {226			ensure_root(origin)?;227			if let Some(amount) = amount {228				<CollatorSelectionLicenseBondOverride<T>>::set(amount);229			} else {230				<CollatorSelectionLicenseBondOverride<T>>::kill();231			}232			Self::deposit_event(Event::NewCollatorLicenseBond { bond_cost: amount });233			Ok(())234		}235236		#[pallet::call_index(6)]237		#[pallet::weight(T::WeightInfo::set_collator_selection_kick_threshold())]238		pub fn set_collator_selection_kick_threshold(239			origin: OriginFor<T>,240			threshold: Option<T::BlockNumber>,241		) -> DispatchResult {242			ensure_root(origin)?;243			if let Some(threshold) = threshold {244				<CollatorSelectionKickThresholdOverride<T>>::set(threshold);245			} else {246				<CollatorSelectionKickThresholdOverride<T>>::kill();247			}248			Self::deposit_event(Event::NewCollatorKickThreshold {249				length_in_blocks: threshold,250			});251			Ok(())252		}253	}254255	#[pallet::pallet]256	pub struct Pallet<T>(_);257}258259pub struct WeightToFee<T, B>(PhantomData<(T, B)>);260261impl<T, B> WeightToFeePolynomial for WeightToFee<T, B>262where263	T: Config,264	B: BaseArithmetic + From<u32> + From<u64> + Copy + Unsigned,265{266	type Balance = B;267268	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {269		smallvec!(WeightToFeeCoefficient {270			coeff_integer: (<WeightToFeeCoefficientOverride<T>>::get() / Perbill::ACCURACY as u64)271				.into(),272			coeff_frac: Perbill::from_parts(273				(<WeightToFeeCoefficientOverride<T>>::get() % Perbill::ACCURACY as u64) as u32274			),275			negative: false,276			degree: 1,277		})278	}279}280281pub struct FeeCalculator<T>(PhantomData<T>);282impl<T: Config> fp_evm::FeeCalculator for FeeCalculator<T> {283	fn min_gas_price() -> (U256, Weight) {284		(285			<MinGasPriceOverride<T>>::get().into(),286			T::DbWeight::get().reads(1),287		)288	}289}290291#[derive(Encode, Decode, Clone, Debug, Default, TypeInfo, MaxEncodedLen, PartialEq, PartialOrd)]292pub struct AppPromotionConfiguration<BlockNumber> {293	/// In relay blocks.294	pub recalculation_interval: Option<BlockNumber>,295	/// In parachain blocks.296	pub pending_interval: Option<BlockNumber>,297	/// Value for `RecalculationInterval` based on 0.05% per 24h.298	pub interval_income: Option<Perbill>,299	/// Maximum allowable number of stakers calculated per call of the `app-promotion::PayoutStakers` extrinsic.300	pub max_stakers_per_calculation: Option<u8>,301}