git.delta.rocks / unique-network / refs/commits / 13a972624863

difftreelog

Merge branch 'feature/switch-from-currecy-trait-to-fungible-v2' into feature/update-polkadot-v0.9.42

Grigoriy Simonov2023-05-23parents: #6203316 #a8f92f7.patch.diff
in: master

7 files changed

modifiedpallets/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);
 	}
 
modifiedpallets/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());
 
modifiedpallets/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);
modifiedpallets/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>();
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
64use 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,
8589
86pub 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};
8993
90#[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>>;
441444
442 /// 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>;
444447
445 /// 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 >;
450453
451 /// Dispatcher of operations on collections.454 /// Dispatcher of operations on collections.
11121115
1113 // Take a (non-refundable) deposit of collection creation1116 // Take a (non-refundable) deposit of collection creation
1114 {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)?;
1127
1128 debug_assert!(credit.peek().is_zero())
1130 }1129 }
11311130
1132 <CreatedCollectionCount<T>>::put(created_count);1131 <CreatedCollectionCount<T>>::put(created_count);
modifiedpallets/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())
modifiedpallets/configuration/src/lib.rsdiffbeforeafterboth
--- a/pallets/configuration/src/lib.rs
+++ b/pallets/configuration/src/lib.rs
@@ -42,7 +42,7 @@
 mod pallet {
 	use super::*;
 	use frame_support::{
-		traits::{Get, ReservableCurrency, Currency},
+		traits::{fungible, Get, ReservableCurrency, Currency},
 		pallet_prelude::{StorageValue, ValueQuery, DispatchResult, IsType},
 		log,
 	};
@@ -50,15 +50,19 @@
 
 	pub use crate::weights::WeightInfo;
 	pub type BalanceOf<T> =
-		<<T as Config>::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance;
+		<<T as Config>::Currency as fungible::Inspect<<T as SystemConfig>::AccountId>>::Balance;
 
 	#[pallet::config]
 	pub trait Config: frame_system::Config {
 		/// Overarching event type.
 		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
 
-		/// The currency mechanism.
-		type Currency: ReservableCurrency<Self::AccountId>;
+		type Currency: fungible::Inspect<Self::AccountId>
+			+ fungible::Mutate<Self::AccountId>
+			+ fungible::MutateFreeze<Self::AccountId>
+			+ fungible::InspectHold<Self::AccountId>
+			+ fungible::MutateHold<Self::AccountId>
+			+ fungible::BalancedHold<Self::AccountId>;
 
 		#[pallet::constant]
 		type DefaultWeightToFeeCoefficient: Get<u64>;