difftreelog
feat switch `collator-selection` from `Currency` trait to `fungible::*` traits
in: master
4 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/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::{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>::Balances 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 Balances:61 fungible::Inspect<Self::AccountId>62 + fungible::Mutate::<Self::AccountId>63 + fungible::MutateFreeze::<Self::AccountId>64 + fungible::InspectHold::<Self::AccountId>65 + fungible::MutateHold::<Self::AccountId>66 + fungible::BalancedHold::<Self::AccountId>;6768 #[pallet::constant]69 type DefaultWeightToFeeCoefficient: Get<u64>;70 #[pallet::constant]71 type DefaultMinGasPrice: Get<u64>;7273 #[pallet::constant]74 type MaxXcmAllowedLocations: Get<u32>;75 #[pallet::constant]76 type AppPromotionDailyRate: Get<Perbill>;77 #[pallet::constant]78 type DayRelayBlocks: Get<Self::BlockNumber>;7980 #[pallet::constant]81 type DefaultCollatorSelectionMaxCollators: Get<u32>;82 #[pallet::constant]83 type DefaultCollatorSelectionLicenseBond: Get<BalanceOf<Self>>;84 #[pallet::constant]85 type DefaultCollatorSelectionKickThreshold: Get<Self::BlockNumber>;8687 /// The weight information of this pallet.88 type WeightInfo: WeightInfo;89 }9091 #[pallet::event]92 #[pallet::generate_deposit(pub(super) fn deposit_event)]93 pub enum Event<T: Config> {94 NewDesiredCollators {95 desired_collators: Option<u32>,96 },97 NewCollatorLicenseBond {98 bond_cost: Option<BalanceOf<T>>,99 },100 NewCollatorKickThreshold {101 length_in_blocks: Option<T::BlockNumber>,102 },103 }104105 #[pallet::error]106 pub enum Error<T> {107 InconsistentConfiguration,108 }109110 #[pallet::storage]111 pub type WeightToFeeCoefficientOverride<T: Config> = StorageValue<112 Value = u64,113 QueryKind = ValueQuery,114 OnEmpty = T::DefaultWeightToFeeCoefficient,115 >;116117 #[pallet::storage]118 pub type MinGasPriceOverride<T: Config> =119 StorageValue<Value = u64, QueryKind = ValueQuery, OnEmpty = T::DefaultMinGasPrice>;120121 #[pallet::storage]122 pub type AppPromomotionConfigurationOverride<T: Config> =123 StorageValue<Value = AppPromotionConfiguration<T::BlockNumber>, QueryKind = ValueQuery>;124125 #[pallet::storage]126 pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<127 Value = u32,128 QueryKind = ValueQuery,129 OnEmpty = T::DefaultCollatorSelectionMaxCollators,130 >;131132 #[pallet::storage]133 pub type CollatorSelectionLicenseBondOverride<T: Config> = StorageValue<134 Value = BalanceOf<T>,135 QueryKind = ValueQuery,136 OnEmpty = T::DefaultCollatorSelectionLicenseBond,137 >;138139 #[pallet::storage]140 pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<141 Value = T::BlockNumber,142 QueryKind = ValueQuery,143 OnEmpty = T::DefaultCollatorSelectionKickThreshold,144 >;145146 #[pallet::call]147 impl<T: Config> Pallet<T> {148 #[pallet::call_index(0)]149 #[pallet::weight(T::WeightInfo::set_weight_to_fee_coefficient_override())]150 pub fn set_weight_to_fee_coefficient_override(151 origin: OriginFor<T>,152 coeff: Option<u64>,153 ) -> DispatchResult {154 ensure_root(origin)?;155 if let Some(coeff) = coeff {156 <WeightToFeeCoefficientOverride<T>>::set(coeff);157 } else {158 <WeightToFeeCoefficientOverride<T>>::kill();159 }160 Ok(())161 }162163 #[pallet::call_index(1)]164 #[pallet::weight(T::WeightInfo::set_min_gas_price_override())]165 pub fn set_min_gas_price_override(166 origin: OriginFor<T>,167 coeff: Option<u64>,168 ) -> DispatchResult {169 ensure_root(origin)?;170 if let Some(coeff) = coeff {171 <MinGasPriceOverride<T>>::set(coeff);172 } else {173 <MinGasPriceOverride<T>>::kill();174 }175 Ok(())176 }177178 #[pallet::call_index(3)]179 #[pallet::weight(T::WeightInfo::set_app_promotion_configuration_override())]180 pub fn set_app_promotion_configuration_override(181 origin: OriginFor<T>,182 mut configuration: AppPromotionConfiguration<T::BlockNumber>,183 ) -> DispatchResult {184 ensure_root(origin)?;185 if configuration.interval_income.is_some() {186 return Err(<Error<T>>::InconsistentConfiguration.into());187 }188189 configuration.interval_income = configuration.recalculation_interval.map(|b| {190 Perbill::from_rational(b, T::DayRelayBlocks::get())191 * T::AppPromotionDailyRate::get()192 });193194 <AppPromomotionConfigurationOverride<T>>::set(configuration);195196 Ok(())197 }198199 #[pallet::call_index(4)]200 #[pallet::weight(T::WeightInfo::set_collator_selection_desired_collators())]201 pub fn set_collator_selection_desired_collators(202 origin: OriginFor<T>,203 max: Option<u32>,204 ) -> DispatchResult {205 ensure_root(origin)?;206 if let Some(max) = max {207 // we trust origin calls, this is just a for more accurate benchmarking208 if max > T::DefaultCollatorSelectionMaxCollators::get() {209 log::warn!("max > T::DefaultCollatorSelectionMaxCollators; you might need to run benchmarks again");210 }211 <CollatorSelectionDesiredCollatorsOverride<T>>::set(max);212 } else {213 <CollatorSelectionDesiredCollatorsOverride<T>>::kill();214 }215 Self::deposit_event(Event::NewDesiredCollators {216 desired_collators: max,217 });218 Ok(())219 }220221 #[pallet::call_index(5)]222 #[pallet::weight(T::WeightInfo::set_collator_selection_license_bond())]223 pub fn set_collator_selection_license_bond(224 origin: OriginFor<T>,225 amount: Option<BalanceOf<T>>,226 ) -> DispatchResult {227 ensure_root(origin)?;228 if let Some(amount) = amount {229 <CollatorSelectionLicenseBondOverride<T>>::set(amount);230 } else {231 <CollatorSelectionLicenseBondOverride<T>>::kill();232 }233 Self::deposit_event(Event::NewCollatorLicenseBond { bond_cost: amount });234 Ok(())235 }236237 #[pallet::call_index(6)]238 #[pallet::weight(T::WeightInfo::set_collator_selection_kick_threshold())]239 pub fn set_collator_selection_kick_threshold(240 origin: OriginFor<T>,241 threshold: Option<T::BlockNumber>,242 ) -> DispatchResult {243 ensure_root(origin)?;244 if let Some(threshold) = threshold {245 <CollatorSelectionKickThresholdOverride<T>>::set(threshold);246 } else {247 <CollatorSelectionKickThresholdOverride<T>>::kill();248 }249 Self::deposit_event(Event::NewCollatorKickThreshold {250 length_in_blocks: threshold,251 });252 Ok(())253 }254 }255256 #[pallet::pallet]257 pub struct Pallet<T>(_);258}259260pub struct WeightToFee<T, B>(PhantomData<(T, B)>);261262impl<T, B> WeightToFeePolynomial for WeightToFee<T, B>263where264 T: Config,265 B: BaseArithmetic + From<u32> + From<u64> + Copy + Unsigned,266{267 type Balance = B;268269 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {270 smallvec!(WeightToFeeCoefficient {271 coeff_integer: (<WeightToFeeCoefficientOverride<T>>::get() / Perbill::ACCURACY as u64)272 .into(),273 coeff_frac: Perbill::from_parts(274 (<WeightToFeeCoefficientOverride<T>>::get() % Perbill::ACCURACY as u64) as u32275 ),276 negative: false,277 degree: 1,278 })279 }280}281282pub struct FeeCalculator<T>(PhantomData<T>);283impl<T: Config> fp_evm::FeeCalculator for FeeCalculator<T> {284 fn min_gas_price() -> (U256, Weight) {285 (286 <MinGasPriceOverride<T>>::get().into(),287 T::DbWeight::get().reads(1),288 )289 }290}291292#[derive(Encode, Decode, Clone, Debug, Default, TypeInfo, MaxEncodedLen, PartialEq, PartialOrd)]293pub struct AppPromotionConfiguration<BlockNumber> {294 /// In relay blocks.295 pub recalculation_interval: Option<BlockNumber>,296 /// In parachain blocks.297 pub pending_interval: Option<BlockNumber>,298 /// Value for `RecalculationInterval` based on 0.05% per 24h.299 pub interval_income: Option<Perbill>,300 /// Maximum allowable number of stakers calculated per call of the `app-promotion::PayoutStakers` extrinsic.301 pub max_stakers_per_calculation: Option<u8>,302}