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.rsdiffbeforeafterboth40use frame_support::{40use frame_support::{41 assert_ok,41 assert_ok,42 codec::Decode,42 codec::Decode,43 traits::{Currency, EnsureOrigin, Get},43 traits::{44 EnsureOrigin,45 fungible::{Inspect, Mutate},46 Get,47 },44};48};45use frame_system::{EventRecord, RawOrigin};49use frame_system::{EventRecord, RawOrigin};78) -> T::AccountId {82) -> T::AccountId {79 let user = account(string, n, SEED);83 let user = account(string, n, SEED);80 let balance = balance_unit::<T>() * balance_factor.into();84 let balance = balance_unit::<T>() * balance_factor.into();81 let _ = T::Currency::make_free_balance_be(&user, balance);85 let _ = T::Currency::set_balance(&user, balance);82 user86 user83}87}8488137 );141 );138142139 for who in candidates {143 for who in candidates {140 T::Currency::make_free_balance_be(&who, <LicenseBond<T>>::get() * 2u32.into());144 T::Currency::set_balance(&who, <LicenseBond<T>>::get() * 2u32.into());141 <CollatorSelection<T>>::get_license(RawOrigin::Signed(who.clone()).into()).unwrap();145 <CollatorSelection<T>>::get_license(RawOrigin::Signed(who.clone()).into()).unwrap();142 <CollatorSelection<T>>::onboard(RawOrigin::Signed(who).into()).unwrap();146 <CollatorSelection<T>>::onboard(RawOrigin::Signed(who).into()).unwrap();143 }147 }153 );157 );154158155 for who in candidates {159 for who in candidates {156 T::Currency::make_free_balance_be(&who, <LicenseBond<T>>::get() * 2u32.into());160 T::Currency::set_balance(&who, <LicenseBond<T>>::get() * 2u32.into());157 <CollatorSelection<T>>::get_license(RawOrigin::Signed(who.clone()).into()).unwrap();161 <CollatorSelection<T>>::get_license(RawOrigin::Signed(who.clone()).into()).unwrap();158 }162 }159}163}160164161/// `Currency::minimum_balance` was used originally, but in unique-chain, we have165/// `Currency::minimum_balance` was used originally, but in unique-chain, we have162/// zero existential deposit, thus triggering zero bond assertion.166/// zero existential deposit, thus triggering zero bond assertion.163fn balance_unit<T: Config>() -> <T::Currency as Currency<T::AccountId>>::Balance {167fn balance_unit<T: Config>() -> BalanceOf<T> {164 200u32.into()168 200u32.into()165}169}166170182188183 let new_invulnerable: T::AccountId = whitelisted_caller();189 let new_invulnerable: T::AccountId = whitelisted_caller();184 let bond: BalanceOf<T> = balance_unit::<T>() * 2u32.into();190 let bond: BalanceOf<T> = balance_unit::<T>() * 2u32.into();185 T::Currency::make_free_balance_be(&new_invulnerable, bond.clone());191 T::Currency::set_balance(&new_invulnerable, bond.clone());186192187 <session::Pallet<T>>::set_keys(193 <session::Pallet<T>>::set_keys(188 RawOrigin::Signed(new_invulnerable.clone()).into(),194 RawOrigin::Signed(new_invulnerable.clone()).into(),227233228 let caller: T::AccountId = whitelisted_caller();234 let caller: T::AccountId = whitelisted_caller();229 let bond: BalanceOf<T> = balance_unit::<T>() * 2u32.into();235 let bond: BalanceOf<T> = balance_unit::<T>() * 2u32.into();230 T::Currency::make_free_balance_be(&caller, bond.clone());236 T::Currency::set_balance(&caller, bond.clone());231237232 <session::Pallet<T>>::set_keys(238 <session::Pallet<T>>::set_keys(233 RawOrigin::Signed(caller.clone()).into(),239 RawOrigin::Signed(caller.clone()).into(),253259254 let caller: T::AccountId = whitelisted_caller();260 let caller: T::AccountId = whitelisted_caller();255 let bond: BalanceOf<T> = balance_unit::<T>() * 2u32.into();261 let bond: BalanceOf<T> = balance_unit::<T>() * 2u32.into();256 T::Currency::make_free_balance_be(&caller, bond.clone());262 T::Currency::set_balance(&caller, bond.clone());257263258 let origin = RawOrigin::Signed(caller.clone());264 let origin = RawOrigin::Signed(caller.clone());259265329 // worst case is paying a non-existing candidate account.335 // worst case is paying a non-existing candidate account.330 note_author {336 note_author {331 <LicenseBond<T>>::put(balance_unit::<T>());337 <LicenseBond<T>>::put(balance_unit::<T>());332 T::Currency::make_free_balance_be(338 T::Currency::set_balance(333 &<CollatorSelection<T>>::account_id(),339 &<CollatorSelection<T>>::account_id(),334 balance_unit::<T>() * 4u32.into(),340 balance_unit::<T>() * 4u32.into(),335 );341 );336 let author = account("author", 0, SEED);342 let author = account("author", 0, SEED);337 let new_block: T::BlockNumber = 10u32.into();343 let new_block: T::BlockNumber = 10u32.into();338344339 frame_system::Pallet::<T>::set_block_number(new_block);345 frame_system::Pallet::<T>::set_block_number(new_block);340 assert!(T::Currency::free_balance(&author) == 0u32.into());346 assert!(T::Currency::balance(&author) == 0u32.into());341 }: {347 }: {342 <CollatorSelection<T> as EventHandler<_, _>>::note_author(author.clone())348 <CollatorSelection<T> as EventHandler<_, _>>::note_author(author.clone())343 } verify {349 } verify {344 assert!(T::Currency::free_balance(&author) > 0u32.into());350 assert!(T::Currency::balance(&author) > 0u32.into());345 assert_eq!(frame_system::Pallet::<T>::block_number(), new_block);351 assert_eq!(frame_system::Pallet::<T>::block_number(), new_block);346 }352 }347353pallets/collator-selection/src/lib.rsdiffbeforeafterboth929293#[frame_support::pallet]93#[frame_support::pallet]94pub mod pallet {94pub mod pallet {95 use super::*;95 pub use crate::weights::WeightInfo;96 pub use crate::weights::WeightInfo;96 use core::ops::Div;97 use core::ops::Div;97 use frame_support::{98 use frame_support::{100 pallet_prelude::*,101 pallet_prelude::*,101 sp_runtime::traits::{AccountIdConversion, CheckedSub, Saturating, Zero},102 sp_runtime::traits::{AccountIdConversion, CheckedSub, Saturating, Zero},102 traits::{103 traits::{103 Currency, EnsureOrigin, ExistenceRequirement::KeepAlive, ReservableCurrency,104 EnsureOrigin,105 fungible::{Balanced, BalancedHold, Inspect, InspectHold, Mutate, MutateHold},104 ValidatorRegistration,106 ValidatorRegistration,107 tokens::{Precision, Preservation},105 },108 },106 BoundedVec, PalletId,109 BoundedVec, PalletId,107 };110 };159 /// The weight information of this pallet.162 /// The weight information of this pallet.160 type WeightInfo: WeightInfo;163 type WeightInfo: WeightInfo;164165 #[pallet::constant]166 type LicenceBondIdentifier: Get<<<Self as pallet_configuration::Config>::Currency as InspectHold<Self::AccountId>>::Reason>;161 }167 }162168163 #[pallet::pallet]169 #[pallet::pallet]361367362 let deposit = <LicenseBond<T>>::get();368 let deposit = <LicenseBond<T>>::get();363369364 T::Currency::reserve(&who, deposit)?;370 T::Currency::hold(&T::LicenceBondIdentifier::get(), &who, deposit)?;365 LicenseDepositOf::<T>::insert(who.clone(), deposit);371 LicenseDepositOf::<T>::insert(who.clone(), deposit);366372367 Self::deposit_event(Event::LicenseObtained {373 Self::deposit_event(Event::LicenseObtained {523 let slashed = T::SlashRatio::get() * deposit;529 let slashed = T::SlashRatio::get() * deposit;524 let remaining = deposit - slashed;530 let remaining = deposit - slashed;525531526 let (imbalance, _) = T::Currency::slash_reserved(who, slashed);532 let (imbalance, _) =533 T::Currency::slash(&T::LicenceBondIdentifier::get(), who, slashed);527 //T::Currency::unreserve(who, remaining);534 //T::Currency::unreserve(who, remaining);528 deposit_returned = remaining;535 deposit_returned = remaining;529536530 T::Currency::resolve_creating(&T::TreasuryAccountId::get(), imbalance);537 T::Currency::resolve(&T::TreasuryAccountId::get(), imbalance)538 .map_err(|_| DispatchError::Other("Failed to deposit imbalance"))?;531 } else {539 } else {532 //T::Currency::unreserve(who, deposit);540 //T::Currency::unreserve(who, deposit);533 deposit_returned = deposit;541 deposit_returned = deposit;534 }542 }535543536 T::Currency::unreserve(who, deposit_returned);544 T::Currency::release(545 &T::LicenceBondIdentifier::get(),546 who,547 deposit_returned,548 Precision::Exact,549 )?;537 Ok(())550 Ok(())538 } else {551 } else {539 Err(Error::<T>::NoLicense.into())552 Err(Error::<T>::NoLicense.into())594 fn note_author(author: T::AccountId) {607 fn note_author(author: T::AccountId) {595 let pot = Self::account_id();608 let pot = Self::account_id();596 // assumes an ED will be sent to pot.609 // assumes an ED will be sent to pot.597 let reward = T::Currency::free_balance(&pot)610 let reward = T::Currency::balance(&pot)598 .checked_sub(&T::Currency::minimum_balance())611 .checked_sub(&T::Currency::minimum_balance())599 .unwrap_or_else(Zero::zero)612 .unwrap_or_else(Zero::zero)600 .div(2u32.into());613 .div(2u32.into());601 // `reward` is half of pot account minus ED, this should never fail.614 // `reward` is half of pot account minus ED, this should never fail.602 let _success = T::Currency::transfer(&pot, &author, reward, KeepAlive);615 let _success = T::Currency::transfer(&pot, &author, reward, Preservation::Preserve);603 debug_assert!(_success.is_ok());616 debug_assert!(_success.is_ok());604 <LastAuthoredBlock<T>>::insert(author, frame_system::Pallet::<T>::block_number());617 <LastAuthoredBlock<T>>::insert(author, frame_system::Pallet::<T>::block_number());605618pallets/collator-selection/src/tests.rsdiffbeforeafterboth417fn authorship_event_handler() {417fn authorship_event_handler() {418 new_test_ext().execute_with(|| {418 new_test_ext().execute_with(|| {419 // put 100 in the pot + 5 for ED419 // put 100 in the pot + 5 for ED420 Balances::make_free_balance_be(&CollatorSelection::account_id(), 105);420 <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::set_balance(421 &CollatorSelection::account_id(),422 105,423 );441 // Nothing panics, no reward when no ED in balance444 // Nothing panics, no reward when no ED in balance442 Authorship::on_initialize(1);445 Authorship::on_initialize(1);443 // put some money into the pot at ED446 // put some money into the pot at ED444 Balances::make_free_balance_be(&CollatorSelection::account_id(), 5);447 <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::set_balance(448 &CollatorSelection::account_id(),449 5,450 );pallets/common/src/benchmarking.rsdiffbeforeafterboth27 MAX_PROPERTIES_PER_ITEM,27 MAX_PROPERTIES_PER_ITEM,28};28};29use frame_support::{29use frame_support::{30 traits::{Currency, Get},30 traits::{Get, fungible::Balanced, Imbalance, tokens::Precision},31 pallet_prelude::ConstU32,31 pallet_prelude::ConstU32,32 BoundedVec,32 BoundedVec,33};33};34use core::convert::TryInto;34use core::convert::TryInto;35use sp_runtime::DispatchError;35use sp_runtime::{DispatchError, traits::Zero};363637const SEED: u32 = 1;37const SEED: u32 = 1;383885 ) -> Result<CollectionId, DispatchError>,85 ) -> Result<CollectionId, DispatchError>,86 cast: impl FnOnce(CollectionHandle<T>) -> R,86 cast: impl FnOnce(CollectionHandle<T>) -> R,87) -> Result<R, DispatchError> {87) -> Result<R, DispatchError> {88 <T as Config>::Currency::deposit_creating(&owner.as_sub(), T::CollectionCreationPrice::get());88 let imbalance = <T as Config>::Currency::deposit(89 &owner.as_sub(),90 T::CollectionCreationPrice::get(),91 Precision::Exact,92 )?;93 debug_assert!(imbalance.peek().is_zero());89 let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();94 let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();90 let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();95 let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();91 let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();96 let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();pallets/common/src/lib.rsdiffbeforeafterboth64use frame_support::{64use frame_support::{65 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},65 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66 ensure,66 ensure,67 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},67 traits::{68 Get,69 fungible::{Balanced, Debt, Inspect},70 tokens::{Imbalance, Precision, Preservation},71 },68 dispatch::Pays,72 dispatch::Pays,69 transactional, fail,73 transactional, fail,858986pub use pallet::*;90pub use pallet::*;87use sp_core::H160;91use sp_core::H160;88use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};92use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, traits::Zero};899390#[cfg(feature = "runtime-benchmarks")]94#[cfg(feature = "runtime-benchmarks")]91pub mod benchmarking;95pub mod benchmarking;424 use super::*;428 use super::*;425 use dispatch::CollectionDispatch;429 use dispatch::CollectionDispatch;426 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};430 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};427 use frame_support::traits::Currency;428 use up_data_structs::{TokenId, mapping::TokenAddressMapping};431 use up_data_structs::{TokenId, mapping::TokenAddressMapping};429 use scale_info::TypeInfo;432 use scale_info::TypeInfo;430 use weights::WeightInfo;433 use weights::WeightInfo;440 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;443 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;441444442 /// Handler of accounts and payment.445 /// Handler of accounts and payment.443 type Currency: Currency<Self::AccountId>;446 type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;444447445 /// Set price to create a collection.448 /// Set price to create a collection.446 #[pallet::constant]449 #[pallet::constant]447 type CollectionCreationPrice: Get<450 type CollectionCreationPrice: Get<448 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,451 <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,449 >;452 >;450453451 /// Dispatcher of operations on collections.454 /// Dispatcher of operations on collections.111211151113 // Take a (non-refundable) deposit of collection creation1116 // Take a (non-refundable) deposit of collection creation1114 {1117 {1115 let mut imbalance =1118 let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1116 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1117 imbalance.subsume(1119 imbalance.subsume(<T as Config>::Currency::deposit(1118 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1119 &T::TreasuryAccountId::get(),1120 &T::TreasuryAccountId::get(),1120 T::CollectionCreationPrice::get(),1121 T::CollectionCreationPrice::get(),1122 Precision::Exact,1121 ),1123 )?);1122 );1124 let credit =1123 <T as Config>::Currency::settle(1125 <T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1124 payer.as_sub(),1125 imbalance,1126 WithdrawReasons::TRANSFER,1127 ExistenceRequirement::KeepAlive,1128 )1129 .map_err(|_| Error::<T>::NotSufficientFounds)?;1126 .map_err(|_| Error::<T>::NotSufficientFounds)?;11271128 debug_assert!(credit.peek().is_zero())1130 }1129 }113111301132 <CreatedCollectionCount<T>>::put(created_count);1131 <CreatedCollectionCount<T>>::put(created_count);pallets/configuration/src/benchmarking.rsdiffbeforeafterboth19use super::*;19use super::*;20use frame_benchmarking::benchmarks;20use frame_benchmarking::benchmarks;21use frame_system::{EventRecord, RawOrigin};21use frame_system::{EventRecord, RawOrigin};22use frame_support::{assert_ok, traits::Currency};22use frame_support::{assert_ok, traits::fungible::Inspect};232324fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {24fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {25 let events = frame_system::Pallet::<T>::events();25 let events = frame_system::Pallet::<T>::events();68 }68 }696970 set_collator_selection_license_bond {70 set_collator_selection_license_bond {71 let bond_cost: Option<BalanceOf<T>> = Some(T::Currency::minimum_balance() * 10u32.into());71 let bond_cost: Option<BalanceOf<T>> = Some(T::Balances::minimum_balance() * 10u32.into());72 }: {72 }: {73 assert_ok!(73 assert_ok!(74 <Pallet<T>>::set_collator_selection_license_bond(RawOrigin::Root.into(), bond_cost.clone())74 <Pallet<T>>::set_collator_selection_license_bond(RawOrigin::Root.into(), bond_cost.clone())pallets/configuration/src/lib.rsdiffbeforeafterboth42mod pallet {42mod pallet {43 use super::*;43 use super::*;44 use frame_support::{44 use frame_support::{45 traits::{Get, ReservableCurrency, Currency},45 traits::{fungible, Get, ReservableCurrency, Currency},46 pallet_prelude::{StorageValue, ValueQuery, DispatchResult, IsType},46 pallet_prelude::{StorageValue, ValueQuery, DispatchResult, IsType},47 log,47 log,48 };48 };49 use frame_system::{pallet_prelude::OriginFor, ensure_root, Config as SystemConfig};49 use frame_system::{pallet_prelude::OriginFor, ensure_root, Config as SystemConfig};505051 pub use crate::weights::WeightInfo;51 pub use crate::weights::WeightInfo;52 pub type BalanceOf<T> =52 pub type BalanceOf<T> =53 <<T as Config>::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance;53 <<T as Config>::Currency as fungible::Inspect<<T as SystemConfig>::AccountId>>::Balance;545455 #[pallet::config]55 #[pallet::config]56 pub trait Config: frame_system::Config {56 pub trait Config: frame_system::Config {57 /// Overarching event type.57 /// Overarching event type.58 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;58 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;595960 /// The currency mechanism.61 type Currency: ReservableCurrency<Self::AccountId>;60 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>;626663 #[pallet::constant]67 #[pallet::constant]64 type DefaultWeightToFeeCoefficient: Get<u64>;68 type DefaultWeightToFeeCoefficient: Get<u64>;