difftreelog
Merge branch 'feature/switch-from-currecy-trait-to-fungible-v2' into feature/update-polkadot-v0.9.42
in: master
7 files changed
pallets/collator-selection/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/collator-selection/src/benchmarking.rs
+++ b/pallets/collator-selection/src/benchmarking.rs
@@ -40,7 +40,11 @@
use frame_support::{
assert_ok,
codec::Decode,
- traits::{Currency, EnsureOrigin, Get},
+ traits::{
+ EnsureOrigin,
+ fungible::{Inspect, Mutate},
+ Get,
+ },
};
use frame_system::{EventRecord, RawOrigin};
use pallet_authorship::EventHandler;
@@ -78,7 +82,7 @@
) -> T::AccountId {
let user = account(string, n, SEED);
let balance = balance_unit::<T>() * balance_factor.into();
- let _ = T::Currency::make_free_balance_be(&user, balance);
+ let _ = T::Currency::set_balance(&user, balance);
user
}
@@ -137,7 +141,7 @@
);
for who in candidates {
- T::Currency::make_free_balance_be(&who, <LicenseBond<T>>::get() * 2u32.into());
+ T::Currency::set_balance(&who, <LicenseBond<T>>::get() * 2u32.into());
<CollatorSelection<T>>::get_license(RawOrigin::Signed(who.clone()).into()).unwrap();
<CollatorSelection<T>>::onboard(RawOrigin::Signed(who).into()).unwrap();
}
@@ -153,14 +157,14 @@
);
for who in candidates {
- T::Currency::make_free_balance_be(&who, <LicenseBond<T>>::get() * 2u32.into());
+ T::Currency::set_balance(&who, <LicenseBond<T>>::get() * 2u32.into());
<CollatorSelection<T>>::get_license(RawOrigin::Signed(who.clone()).into()).unwrap();
}
}
/// `Currency::minimum_balance` was used originally, but in unique-chain, we have
/// zero existential deposit, thus triggering zero bond assertion.
-fn balance_unit<T: Config>() -> <T::Currency as Currency<T::AccountId>>::Balance {
+fn balance_unit<T: Config>() -> BalanceOf<T> {
200u32.into()
}
@@ -168,7 +172,9 @@
const INITIAL_INVULNERABLES: u32 = 2;
benchmarks! {
- where_clause { where T: pallet_authorship::Config + session::Config + configuration::Config }
+ where_clause { where
+ T: pallet_authorship::Config + session::Config + configuration::Config
+ }
// todo:collator this and all the following do not work for some reason, going all the way up to 10 in length
// Both invulnerables and candidates count together against MaxCollators.
@@ -182,7 +188,7 @@
let new_invulnerable: T::AccountId = whitelisted_caller();
let bond: BalanceOf<T> = balance_unit::<T>() * 2u32.into();
- T::Currency::make_free_balance_be(&new_invulnerable, bond.clone());
+ T::Currency::set_balance(&new_invulnerable, bond.clone());
<session::Pallet<T>>::set_keys(
RawOrigin::Signed(new_invulnerable.clone()).into(),
@@ -227,7 +233,7 @@
let caller: T::AccountId = whitelisted_caller();
let bond: BalanceOf<T> = balance_unit::<T>() * 2u32.into();
- T::Currency::make_free_balance_be(&caller, bond.clone());
+ T::Currency::set_balance(&caller, bond.clone());
<session::Pallet<T>>::set_keys(
RawOrigin::Signed(caller.clone()).into(),
@@ -253,7 +259,7 @@
let caller: T::AccountId = whitelisted_caller();
let bond: BalanceOf<T> = balance_unit::<T>() * 2u32.into();
- T::Currency::make_free_balance_be(&caller, bond.clone());
+ T::Currency::set_balance(&caller, bond.clone());
let origin = RawOrigin::Signed(caller.clone());
@@ -329,7 +335,7 @@
// worst case is paying a non-existing candidate account.
note_author {
<LicenseBond<T>>::put(balance_unit::<T>());
- T::Currency::make_free_balance_be(
+ T::Currency::set_balance(
&<CollatorSelection<T>>::account_id(),
balance_unit::<T>() * 4u32.into(),
);
@@ -337,11 +343,11 @@
let new_block: T::BlockNumber = 10u32.into();
frame_system::Pallet::<T>::set_block_number(new_block);
- assert!(T::Currency::free_balance(&author) == 0u32.into());
+ assert!(T::Currency::balance(&author) == 0u32.into());
}: {
<CollatorSelection<T> as EventHandler<_, _>>::note_author(author.clone())
} verify {
- assert!(T::Currency::free_balance(&author) > 0u32.into());
+ assert!(T::Currency::balance(&author) > 0u32.into());
assert_eq!(frame_system::Pallet::<T>::block_number(), new_block);
}
pallets/collator-selection/src/lib.rsdiffbeforeafterboth--- a/pallets/collator-selection/src/lib.rs
+++ b/pallets/collator-selection/src/lib.rs
@@ -92,6 +92,7 @@
#[frame_support::pallet]
pub mod pallet {
+ use super::*;
pub use crate::weights::WeightInfo;
use core::ops::Div;
use frame_support::{
@@ -100,8 +101,10 @@
pallet_prelude::*,
sp_runtime::traits::{AccountIdConversion, CheckedSub, Saturating, Zero},
traits::{
- Currency, EnsureOrigin, ExistenceRequirement::KeepAlive, ReservableCurrency,
+ EnsureOrigin,
+ fungible::{Balanced, BalancedHold, Inspect, InspectHold, Mutate, MutateHold},
ValidatorRegistration,
+ tokens::{Precision, Preservation},
},
BoundedVec, PalletId,
};
@@ -158,6 +161,9 @@
/// The weight information of this pallet.
type WeightInfo: WeightInfo;
+
+ #[pallet::constant]
+ type LicenceBondIdentifier: Get<<<Self as pallet_configuration::Config>::Currency as InspectHold<Self::AccountId>>::Reason>;
}
#[pallet::pallet]
@@ -361,7 +367,7 @@
let deposit = <LicenseBond<T>>::get();
- T::Currency::reserve(&who, deposit)?;
+ T::Currency::hold(&T::LicenceBondIdentifier::get(), &who, deposit)?;
LicenseDepositOf::<T>::insert(who.clone(), deposit);
Self::deposit_event(Event::LicenseObtained {
@@ -523,17 +529,24 @@
let slashed = T::SlashRatio::get() * deposit;
let remaining = deposit - slashed;
- let (imbalance, _) = T::Currency::slash_reserved(who, slashed);
+ let (imbalance, _) =
+ T::Currency::slash(&T::LicenceBondIdentifier::get(), who, slashed);
//T::Currency::unreserve(who, remaining);
deposit_returned = remaining;
- T::Currency::resolve_creating(&T::TreasuryAccountId::get(), imbalance);
+ T::Currency::resolve(&T::TreasuryAccountId::get(), imbalance)
+ .map_err(|_| DispatchError::Other("Failed to deposit imbalance"))?;
} else {
//T::Currency::unreserve(who, deposit);
deposit_returned = deposit;
}
- T::Currency::unreserve(who, deposit_returned);
+ T::Currency::release(
+ &T::LicenceBondIdentifier::get(),
+ who,
+ deposit_returned,
+ Precision::Exact,
+ )?;
Ok(())
} else {
Err(Error::<T>::NoLicense.into())
@@ -594,12 +607,12 @@
fn note_author(author: T::AccountId) {
let pot = Self::account_id();
// assumes an ED will be sent to pot.
- let reward = T::Currency::free_balance(&pot)
+ let reward = T::Currency::balance(&pot)
.checked_sub(&T::Currency::minimum_balance())
.unwrap_or_else(Zero::zero)
.div(2u32.into());
// `reward` is half of pot account minus ED, this should never fail.
- let _success = T::Currency::transfer(&pot, &author, reward, KeepAlive);
+ let _success = T::Currency::transfer(&pot, &author, reward, Preservation::Preserve);
debug_assert!(_success.is_ok());
<LastAuthoredBlock<T>>::insert(author, frame_system::Pallet::<T>::block_number());
pallets/collator-selection/src/tests.rsdiffbeforeafterboth--- a/pallets/collator-selection/src/tests.rs
+++ b/pallets/collator-selection/src/tests.rs
@@ -417,7 +417,10 @@
fn authorship_event_handler() {
new_test_ext().execute_with(|| {
// put 100 in the pot + 5 for ED
- Balances::make_free_balance_be(&CollatorSelection::account_id(), 105);
+ <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::set_balance(
+ &CollatorSelection::account_id(),
+ 105,
+ );
// 4 is the default author.
assert_eq!(Balances::free_balance(4), 100);
@@ -441,7 +444,10 @@
// Nothing panics, no reward when no ED in balance
Authorship::on_initialize(1);
// put some money into the pot at ED
- Balances::make_free_balance_be(&CollatorSelection::account_id(), 5);
+ <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::set_balance(
+ &CollatorSelection::account_id(),
+ 5,
+ );
// 4 is the default author.
assert_eq!(Balances::free_balance(4), 100);
get_license_and_onboard(4);
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -27,12 +27,12 @@
MAX_PROPERTIES_PER_ITEM,
};
use frame_support::{
- traits::{Currency, Get},
+ traits::{Get, fungible::Balanced, Imbalance, tokens::Precision},
pallet_prelude::ConstU32,
BoundedVec,
};
use core::convert::TryInto;
-use sp_runtime::DispatchError;
+use sp_runtime::{DispatchError, traits::Zero};
const SEED: u32 = 1;
@@ -85,7 +85,12 @@
) -> Result<CollectionId, DispatchError>,
cast: impl FnOnce(CollectionHandle<T>) -> R,
) -> Result<R, DispatchError> {
- <T as Config>::Currency::deposit_creating(&owner.as_sub(), T::CollectionCreationPrice::get());
+ let imbalance = <T as Config>::Currency::deposit(
+ &owner.as_sub(),
+ T::CollectionCreationPrice::get(),
+ Precision::Exact,
+ )?;
+ debug_assert!(imbalance.peek().is_zero());
let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -64,7 +64,11 @@
use frame_support::{
dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
ensure,
- traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},
+ traits::{
+ Get,
+ fungible::{Balanced, Debt, Inspect},
+ tokens::{Imbalance, Precision, Preservation},
+ },
dispatch::Pays,
transactional, fail,
};
@@ -85,7 +89,7 @@
pub use pallet::*;
use sp_core::H160;
-use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
+use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, traits::Zero};
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
@@ -424,7 +428,6 @@
use super::*;
use dispatch::CollectionDispatch;
use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};
- use frame_support::traits::Currency;
use up_data_structs::{TokenId, mapping::TokenAddressMapping};
use scale_info::TypeInfo;
use weights::WeightInfo;
@@ -440,12 +443,12 @@
type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;
/// Handler of accounts and payment.
- type Currency: Currency<Self::AccountId>;
+ type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;
/// Set price to create a collection.
#[pallet::constant]
type CollectionCreationPrice: Get<
- <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,
+ <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,
>;
/// Dispatcher of operations on collections.
@@ -1112,21 +1115,17 @@
// Take a (non-refundable) deposit of collection creation
{
- let mut imbalance =
- <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();
- imbalance.subsume(
- <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(
- &T::TreasuryAccountId::get(),
- T::CollectionCreationPrice::get(),
- ),
- );
- <T as Config>::Currency::settle(
- payer.as_sub(),
- imbalance,
- WithdrawReasons::TRANSFER,
- ExistenceRequirement::KeepAlive,
- )
- .map_err(|_| Error::<T>::NotSufficientFounds)?;
+ let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();
+ imbalance.subsume(<T as Config>::Currency::deposit(
+ &T::TreasuryAccountId::get(),
+ T::CollectionCreationPrice::get(),
+ Precision::Exact,
+ )?);
+ let credit =
+ <T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)
+ .map_err(|_| Error::<T>::NotSufficientFounds)?;
+
+ debug_assert!(credit.peek().is_zero())
}
<CreatedCollectionCount<T>>::put(created_count);
pallets/configuration/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/configuration/src/benchmarking.rs
+++ b/pallets/configuration/src/benchmarking.rs
@@ -19,7 +19,7 @@
use super::*;
use frame_benchmarking::benchmarks;
use frame_system::{EventRecord, RawOrigin};
-use frame_support::{assert_ok, traits::Currency};
+use frame_support::{assert_ok, traits::fungible::Inspect};
fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
let events = frame_system::Pallet::<T>::events();
@@ -68,7 +68,7 @@
}
set_collator_selection_license_bond {
- let bond_cost: Option<BalanceOf<T>> = Some(T::Currency::minimum_balance() * 10u32.into());
+ let bond_cost: Option<BalanceOf<T>> = Some(T::Balances::minimum_balance() * 10u32.into());
}: {
assert_ok!(
<Pallet<T>>::set_collator_selection_license_bond(RawOrigin::Root.into(), bond_cost.clone())
pallets/configuration/src/lib.rsdiffbeforeafterboth1// 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::{Get, ReservableCurrency, Currency},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 Currency<<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 /// The currency mechanism.61 type Currency: ReservableCurrency<Self::AccountId>;6263 #[pallet::constant]64 type DefaultWeightToFeeCoefficient: Get<u64>;65 #[pallet::constant]66 type DefaultMinGasPrice: Get<u64>;6768 #[pallet::constant]69 type MaxXcmAllowedLocations: Get<u32>;70 #[pallet::constant]71 type AppPromotionDailyRate: Get<Perbill>;72 #[pallet::constant]73 type DayRelayBlocks: Get<Self::BlockNumber>;7475 #[pallet::constant]76 type DefaultCollatorSelectionMaxCollators: Get<u32>;77 #[pallet::constant]78 type DefaultCollatorSelectionLicenseBond: Get<BalanceOf<Self>>;79 #[pallet::constant]80 type DefaultCollatorSelectionKickThreshold: Get<Self::BlockNumber>;8182 /// The weight information of this pallet.83 type WeightInfo: WeightInfo;84 }8586 #[pallet::event]87 #[pallet::generate_deposit(pub(super) fn deposit_event)]88 pub enum Event<T: Config> {89 NewDesiredCollators {90 desired_collators: Option<u32>,91 },92 NewCollatorLicenseBond {93 bond_cost: Option<BalanceOf<T>>,94 },95 NewCollatorKickThreshold {96 length_in_blocks: Option<T::BlockNumber>,97 },98 }99100 #[pallet::error]101 pub enum Error<T> {102 InconsistentConfiguration,103 }104105 #[pallet::storage]106 pub type WeightToFeeCoefficientOverride<T: Config> = StorageValue<107 Value = u64,108 QueryKind = ValueQuery,109 OnEmpty = T::DefaultWeightToFeeCoefficient,110 >;111112 #[pallet::storage]113 pub type MinGasPriceOverride<T: Config> =114 StorageValue<Value = u64, QueryKind = ValueQuery, OnEmpty = T::DefaultMinGasPrice>;115116 #[pallet::storage]117 pub type AppPromomotionConfigurationOverride<T: Config> =118 StorageValue<Value = AppPromotionConfiguration<T::BlockNumber>, QueryKind = ValueQuery>;119120 #[pallet::storage]121 pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<122 Value = u32,123 QueryKind = ValueQuery,124 OnEmpty = T::DefaultCollatorSelectionMaxCollators,125 >;126127 #[pallet::storage]128 pub type CollatorSelectionLicenseBondOverride<T: Config> = StorageValue<129 Value = BalanceOf<T>,130 QueryKind = ValueQuery,131 OnEmpty = T::DefaultCollatorSelectionLicenseBond,132 >;133134 #[pallet::storage]135 pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<136 Value = T::BlockNumber,137 QueryKind = ValueQuery,138 OnEmpty = T::DefaultCollatorSelectionKickThreshold,139 >;140141 #[pallet::call]142 impl<T: Config> Pallet<T> {143 #[pallet::call_index(0)]144 #[pallet::weight(T::WeightInfo::set_weight_to_fee_coefficient_override())]145 pub fn set_weight_to_fee_coefficient_override(146 origin: OriginFor<T>,147 coeff: Option<u64>,148 ) -> DispatchResult {149 ensure_root(origin)?;150 if let Some(coeff) = coeff {151 <WeightToFeeCoefficientOverride<T>>::set(coeff);152 } else {153 <WeightToFeeCoefficientOverride<T>>::kill();154 }155 Ok(())156 }157158 #[pallet::call_index(1)]159 #[pallet::weight(T::WeightInfo::set_min_gas_price_override())]160 pub fn set_min_gas_price_override(161 origin: OriginFor<T>,162 coeff: Option<u64>,163 ) -> DispatchResult {164 ensure_root(origin)?;165 if let Some(coeff) = coeff {166 <MinGasPriceOverride<T>>::set(coeff);167 } else {168 <MinGasPriceOverride<T>>::kill();169 }170 Ok(())171 }172173 #[pallet::call_index(3)]174 #[pallet::weight(T::WeightInfo::set_app_promotion_configuration_override())]175 pub fn set_app_promotion_configuration_override(176 origin: OriginFor<T>,177 mut configuration: AppPromotionConfiguration<T::BlockNumber>,178 ) -> DispatchResult {179 ensure_root(origin)?;180 if configuration.interval_income.is_some() {181 return Err(<Error<T>>::InconsistentConfiguration.into());182 }183184 configuration.interval_income = configuration.recalculation_interval.map(|b| {185 Perbill::from_rational(b, T::DayRelayBlocks::get())186 * T::AppPromotionDailyRate::get()187 });188189 <AppPromomotionConfigurationOverride<T>>::set(configuration);190191 Ok(())192 }193194 #[pallet::call_index(4)]195 #[pallet::weight(T::WeightInfo::set_collator_selection_desired_collators())]196 pub fn set_collator_selection_desired_collators(197 origin: OriginFor<T>,198 max: Option<u32>,199 ) -> DispatchResult {200 ensure_root(origin)?;201 if let Some(max) = max {202 // we trust origin calls, this is just a for more accurate benchmarking203 if max > T::DefaultCollatorSelectionMaxCollators::get() {204 log::warn!("max > T::DefaultCollatorSelectionMaxCollators; you might need to run benchmarks again");205 }206 <CollatorSelectionDesiredCollatorsOverride<T>>::set(max);207 } else {208 <CollatorSelectionDesiredCollatorsOverride<T>>::kill();209 }210 Self::deposit_event(Event::NewDesiredCollators {211 desired_collators: max,212 });213 Ok(())214 }215216 #[pallet::call_index(5)]217 #[pallet::weight(T::WeightInfo::set_collator_selection_license_bond())]218 pub fn set_collator_selection_license_bond(219 origin: OriginFor<T>,220 amount: Option<BalanceOf<T>>,221 ) -> DispatchResult {222 ensure_root(origin)?;223 if let Some(amount) = amount {224 <CollatorSelectionLicenseBondOverride<T>>::set(amount);225 } else {226 <CollatorSelectionLicenseBondOverride<T>>::kill();227 }228 Self::deposit_event(Event::NewCollatorLicenseBond { bond_cost: amount });229 Ok(())230 }231232 #[pallet::call_index(6)]233 #[pallet::weight(T::WeightInfo::set_collator_selection_kick_threshold())]234 pub fn set_collator_selection_kick_threshold(235 origin: OriginFor<T>,236 threshold: Option<T::BlockNumber>,237 ) -> DispatchResult {238 ensure_root(origin)?;239 if let Some(threshold) = threshold {240 <CollatorSelectionKickThresholdOverride<T>>::set(threshold);241 } else {242 <CollatorSelectionKickThresholdOverride<T>>::kill();243 }244 Self::deposit_event(Event::NewCollatorKickThreshold {245 length_in_blocks: threshold,246 });247 Ok(())248 }249 }250251 #[pallet::pallet]252 pub struct Pallet<T>(_);253}254255pub struct WeightToFee<T, B>(PhantomData<(T, B)>);256257impl<T, B> WeightToFeePolynomial for WeightToFee<T, B>258where259 T: Config,260 B: BaseArithmetic + From<u32> + From<u64> + Copy + Unsigned,261{262 type Balance = B;263264 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {265 smallvec!(WeightToFeeCoefficient {266 coeff_integer: (<WeightToFeeCoefficientOverride<T>>::get() / Perbill::ACCURACY as u64)267 .into(),268 coeff_frac: Perbill::from_parts(269 (<WeightToFeeCoefficientOverride<T>>::get() % Perbill::ACCURACY as u64) as u32270 ),271 negative: false,272 degree: 1,273 })274 }275}276277pub struct FeeCalculator<T>(PhantomData<T>);278impl<T: Config> fp_evm::FeeCalculator for FeeCalculator<T> {279 fn min_gas_price() -> (U256, Weight) {280 (281 <MinGasPriceOverride<T>>::get().into(),282 T::DbWeight::get().reads(1),283 )284 }285}286287#[derive(Encode, Decode, Clone, Debug, Default, TypeInfo, MaxEncodedLen, PartialEq, PartialOrd)]288pub struct AppPromotionConfiguration<BlockNumber> {289 /// In relay blocks.290 pub recalculation_interval: Option<BlockNumber>,291 /// In parachain blocks.292 pub pending_interval: Option<BlockNumber>,293 /// Value for `RecalculationInterval` based on 0.05% per 24h.294 pub interval_income: Option<Perbill>,295 /// Maximum allowable number of stakers calculated per call of the `app-promotion::PayoutStakers` extrinsic.296 pub max_stakers_per_calculation: Option<u8>,297}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, ReservableCurrency, Currency},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}