1234567891011121314151617#![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 58 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;5960 type Balance: Parameter61 + Member62 + AtLeast32BitUnsigned63 + From<up_common::types::Balance>64 + Codec65 + Default66 + Copy67 + MaybeSerializeDeserialize68 + Debug69 + MaxEncodedLen70 + TypeInfo71 + FixedPointOperand;7273 #[pallet::constant]74 type DefaultWeightToFeeCoefficient: Get<u64>;75 #[pallet::constant]76 type DefaultMinGasPrice: Get<u64>;7778 #[pallet::constant]79 type MaxXcmAllowedLocations: Get<u32>;80 #[pallet::constant]81 type AppPromotionDailyRate: Get<Perbill>;82 #[pallet::constant]83 type DayRelayBlocks: Get<BlockNumberFor<Self>>;8485 #[pallet::constant]86 type DefaultCollatorSelectionMaxCollators: Get<u32>;87 #[pallet::constant]88 type DefaultCollatorSelectionLicenseBond: Get<Self::Balance>;89 #[pallet::constant]90 type DefaultCollatorSelectionKickThreshold: Get<BlockNumberFor<Self>>;9192 93 type WeightInfo: WeightInfo;94 }9596 #[pallet::event]97 #[pallet::generate_deposit(pub(super) fn deposit_event)]98 pub enum Event<T: Config> {99 NewDesiredCollators {100 desired_collators: Option<u32>,101 },102 NewCollatorLicenseBond {103 bond_cost: Option<T::Balance>,104 },105 NewCollatorKickThreshold {106 length_in_blocks: Option<BlockNumberFor<T>>,107 },108 }109110 fn update_base_fee<T: Config>() {111 let base_fee_per_gas: U256 = <MinGasPriceOverride<T>>::get().into();112 let elasticity: Permill = Permill::zero();113 114 sp_io::storage::set(115 &hex_literal::hex!("c1fef3b7207c11a52df13c12884e77263864ade243c642793ebcfe9e16f454ca"),116 &base_fee_per_gas.encode(),117 );118 119 sp_io::storage::set(120 &hex_literal::hex!("c1fef3b7207c11a52df13c12884e772609bc3a1e532c9cb85d57feed02cbff8e"),121 &elasticity.encode(),122 );123 }124125 126 #[pallet::hooks]127 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {128 fn on_runtime_upgrade() -> Weight {129 update_base_fee::<T>();130 T::DbWeight::get().reads_writes(1, 2)131 }132 }133134 #[pallet::genesis_config]135 pub struct GenesisConfig<T>(PhantomData<T>);136137 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> BuildGenesisConfig 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<BlockNumberFor<T>>, 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 = BlockNumberFor<T>,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 221 222 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<BlockNumberFor<T>>,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 256 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<BlockNumberFor<T>>,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 343 pub recalculation_interval: Option<BlockNumber>,344 345 pub pending_interval: Option<BlockNumber>,346 347 pub interval_income: Option<Perbill>,348 349 pub max_stakers_per_calculation: Option<u8>,350}