git.delta.rocks / unique-network / refs/commits / 24f9c77907a0

difftreelog

Breaking: migration to `Fungible` traits in app-promotion pallet

PraetorP2023-05-19parent: #03bc12d.patch.diff
in: master
Migration from `Currency` traits to `Fungible` ones in constraints for `Config::Currency` associated type.

6 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6125,7 +6125,7 @@
 
 [[package]]
 name = "pallet-app-promotion"
-version = "0.1.6"
+version = "0.2.0"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
modifiedpallets/app-promotion/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/app-promotion/CHANGELOG.md
+++ b/pallets/app-promotion/CHANGELOG.md
@@ -3,6 +3,13 @@
 All notable changes to this project will be documented in this file.
 
 <!-- bureaucrate goes here -->
+## [0.2.0] - 2023-05-19
+
+### Changed
+
+- **Breaking:** migration from `Currency` traits to `Fungible` ones in constraints
+  for `Config::Currency` associated type.
+
 ## [0.1.6] - 2023-04-19
 
 - ### Fixed
modifiedpallets/app-promotion/Cargo.tomldiffbeforeafterboth
--- a/pallets/app-promotion/Cargo.toml
+++ b/pallets/app-promotion/Cargo.toml
@@ -9,7 +9,7 @@
 license = 'GPLv3'
 name = 'pallet-app-promotion'
 repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.1.6'
+version = '0.2.0'
 
 [package.metadata.docs.rs]
 targets = ['x86_64-unknown-linux-gnu']
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
70use frame_support::{70use frame_support::{
71 dispatch::{DispatchResult},71 dispatch::{DispatchResult},
72 traits::{72 traits::{
73 Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,73 Get, LockableCurrency,
74 tokens::Balance,
75 fungible::{Inspect, InspectFreeze, Mutate, MutateFreeze},
74 },76 },
75 ensure, BoundedVec,77 ensure, BoundedVec,
76};78};
90const PENDING_LIMIT_PER_BLOCK: u32 = 3;92const PENDING_LIMIT_PER_BLOCK: u32 = 3;
9193
92type BalanceOf<T> =94type BalanceOf<T> =
93 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;95 <<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
9496
95#[frame_support::pallet]97#[frame_support::pallet]
96pub mod pallet {98pub mod pallet {
97 use super::*;99 use super::*;
98 use frame_support::{100 use frame_support::{
99 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,101 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId, weights::Weight,
100 traits::ReservableCurrency, weights::Weight,
101 };102 };
102 use frame_system::pallet_prelude::*;103 use frame_system::pallet_prelude::*;
104use sp_runtime::DispatchError;
103105
104 #[pallet::config]106 #[pallet::config]
105 pub trait Config:107 pub trait Config:
106 frame_system::Config + pallet_evm::Config + pallet_configuration::Config108 frame_system::Config + pallet_evm::Config + pallet_configuration::Config
107 {109 {
108 /// Type to interact with the native token110 /// Type to interact with the native token
109 type Currency: ExtendedLockableCurrency<Self::AccountId>111 type Currency: MutateFreeze<Self::AccountId>
110 + ReservableCurrency<Self::AccountId>;112 + Mutate<Self::AccountId>
113 + ExtendedLockableCurrency<Self::AccountId, Balance = <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance>;
111114
112 /// Type for interacting with collections115 /// Type for interacting with collections
113 type CollectionHandler: CollectionHandler<116 type CollectionHandler: CollectionHandler<
125 #[pallet::constant]128 #[pallet::constant]
126 type PalletId: Get<PalletId>;129 type PalletId: Get<PalletId>;
130
131 /// Freeze identifier used by the pallet
132 #[pallet::constant]
133 type FreezeIdentifier: Get<<<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id>;
127134
128 /// In relay blocks.135 /// In relay blocks.
129 #[pallet::constant]136 #[pallet::constant]
205 PendingForBlockOverflow,212 PendingForBlockOverflow,
206 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.213 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.
207 SponsorNotSet,214 SponsorNotSet,
208 /// Errors caused by incorrect actions with a locked balance.215 ///
209 IncorrectLockedBalanceOperation,216 IncorrectLockedBalanceOperation,
210 /// Errors caused by insufficient staked balance.217 /// Errors caused by insufficient staked balance.
211 InsufficientStakedBalance,218 InsufficientStakedBalance,
219 /// Errors caused by incorrect state of a staker in context of the pallet.
220 InconsistencyState
212 }221 }
213222
214 /// Stores the total staked amount.223 /// Stores the total staked amount.
263 pub type PreviousCalculatedRecord<T: Config> =272 pub type PreviousCalculatedRecord<T: Config> =
264 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;273 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;
274
275 // #[pallet::storage]
276 // pub(crate) type UpgradedToFreezes<T: Config> =
277 // StorageValue<Value = bool, QueryKind = ValueQuery>;
265278
266 #[pallet::hooks]279 #[pallet::hooks]
267 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {280 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
277290
278 if !block_pending.is_empty() {291 if !block_pending.is_empty() {
279 block_pending.into_iter().for_each(|(staker, amount)| {292 block_pending.into_iter().for_each(|(staker, amount)| {
280 Self::get_locked_balance(&staker).map(|b| {293 Self::get_freezed_balance(&staker).map(|b| {
281 let new_state = b.amount.checked_sub(&amount).unwrap_or_default();294 let new_state = b.checked_sub(&amount).unwrap_or_default();
282 Self::set_lock_unchecked(&staker, new_state);295 Self::set_freeze_unchecked(&staker, new_state);
283 });296 });
284 });297 });
285 }298 }
286299
287 <T as Config>::WeightInfo::on_initialize(counter)300 <T as Config>::WeightInfo::on_initialize(counter)
288 }301 }
302
303 // fn on_runtime_upgrade() -> Weight {
304 // use scale_info::prelude::collections::HashSet;
305 // let mut consumed_weight = Weight::zero();
306 // let mut add_weight = |reads, writes, weight| {
307 // consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
308 // consumed_weight += weight;
309 // };
310
311 // let mut stakes_unstakes = vec![];
312
313 // if <UpgradedToFreezes<T>>::get() {
314 // add_weight(1, 0, Weight::zero());
315 // return consumed_weight;
316 // } else {
317 // add_weight(1, 1, Weight::zero());
318 // <UpgradedToFreezes<T>>::set(true);
319 // }
320 // <Staked<T>>::iter_keys().for_each(|(staker_id, _)| {
321 // add_weight(1, 0, Weight::zero());
322 // stakes_unstakes.push(staker_id);
323 // });
324
325 // <PendingUnstake<T>>::iter().for_each(|(_, v)| {
326 // add_weight(1, 0, Weight::zero());
327 // v.into_iter().for_each(|(staker, _)| {
328 // stakes_unstakes.push(staker);
329 // });
330 // });
331
332 // // filter duplicated id.
333 // stakes_unstakes = stakes_unstakes
334 // .into_iter()
335 // .map(|key| key)
336 // .collect::<HashSet<_>>()
337 // .into_iter()
338 // .collect();
339
340 // stakes_unstakes
341 // .map(|a| (a, <Pallet<T>>::get_locked_balance(&a).amount))
342 // .for_each(|(staker, amount)| {
343 // <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(
344 // LOCK_IDENTIFIER,
345 // &staker,
346 // );
347 // <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(
348 // &<T as Config>::FreezeIdentifier::get(),
349 // &staker,
350 // amount,
351 // );
352 // add_weight(1, 2, Weight::zero())
353 // });
354
355 // consumed_weight
356 // }
357
358 // #[cfg(feature = "try-runtime")]
359 // fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
360 // use sp_std::collections::btree_map::BTreeMap;
361 // if <UpgradedToFreezes<T>>::get() {
362 // return Ok(Default::default());
363 // }
364 // // Staker -> (total (stakes and unstakes) locked by promotion);
365 // let mut pre_state: BTreeMap<T::AccountId, BalanceOf<T>> = BTreeMap::new();
366
367 // <Staked<T>>::iter().for_each(|((staker, _), (amount, _))| {
368 // if let Some(locked_balance) = pre_state.get_mut(&staker) {
369 // *locked_balance += amount;
370 // } else {
371 // pre_state.insert(staker, amount);
372 // }
373 // });
374
375 // <PendingUnstake<T>>::iter().for_each(|(_, v)| {
376 // v.into_iter().for_each(|(staker, amount)| {
377 // if let Some(locked_balance) = pre_state.get_mut(&staker) {
378 // *locked_balance += amount;
379 // } else {
380 // pre_state.insert(staker, amount);
381 // }
382 // })
383 // });
384
385 // Ok(pre_state.encode())
386 // }
387
388 // #[cfg(feature = "try-runtime")]
389 // fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {
390 // use sp_std::collections::btree_map::BTreeMap;
391
392 // if <UpgradedToFreezes<T>>::get() {
393 // return Ok(());
394 // }
395
396 // let mut is_ok = true;
397
398 // let pre_state: BTreeMap<T::AccountId, BalanceOf<T>> =
399 // Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;
400 // for (staker, freezed_by_promo) in pre_state.into_iter() {
401 // let storage_freeze_state = <<T as Config>::Currency as InspectFreeze<
402 // T::AccountId,
403 // >>::balance_frozen(
404 // &<T as Config>::FreezeIdentifier::get(), staker
405 // );
406 // if storage_freeze_state != freezed_by_promo {
407 // is_ok = false;
408 // log::error!(
409 // "Incorrect freezed balance for {:?}. New balance: {:?}. Before runtime upgrade: locked by promo - {:?}",
410 // staker, storage_freeze_state, freezed_by_promo
411 // );
412 // }
413
414 // if !<Pallet<T>>::get_locked_balance(&staker).amount.is_zero() {
415 // is_ok = false;
416 // log::error!(
417 // "Incorrect(non-zero) locked by app promo balance for {:?}",
418 // staker
419 // );
420 // }
421 // }
422
423 // if is_ok {
424 // Ok(())
425 // } else {
426 // Err("Incorrect balance for some of stakers... See logs")
427 // }
428 // }
289 }429 }
290430
291 #[pallet::call]431 #[pallet::call]
292 impl<T: Config> Pallet<T>432 impl<T: Config> Pallet<T>
293 where433 where
294 T::BlockNumber: From<u32> + Into<u32>,434 T::BlockNumber: From<u32> + Into<u32>,
295 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,435 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,
296 {436 {
297 /// Sets an address as the the admin.437 /// Sets an address as the the admin.
298 ///438 ///
338 );478 );
339 let config = <PalletConfiguration<T>>::get();479 let config = <PalletConfiguration<T>>::get();
340480
341 let balance =481 let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);
342 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);
343482
344 // checks that we can lock `amount` on the `staker` account.483 // checks that we can freeze `amount` on the `staker` account.
345 ensure!(484 ensure!(
346 amount485 amount
347 <= match Self::get_locked_balance(&staker_id) {486 <= match Self::get_freezed_balance(&staker_id) {
348 Some(lock) => balance487 Some(freezed_by_pallet) => balance
349 .checked_sub(&lock.amount)488 .checked_sub(&freezed_by_pallet)
350 .ok_or(ArithmeticError::Underflow)?,489 .ok_or(ArithmeticError::Underflow)?,
351 None => balance,490 None => balance,
352 },491 },
353 ArithmeticError::Underflow492 ArithmeticError::Underflow
354 );493 );
355494
356 Self::add_lock_balance(&staker_id, amount)?;495 Self::add_freeze_balance(&staker_id, amount)?;
357496
358 let block_number = T::RelayBlockNumberProvider::current_block_number();497 let block_number = T::RelayBlockNumberProvider::current_block_number();
359498
599 let flush_stake = || -> DispatchResult {738 let flush_stake = || -> DispatchResult {
600 if let Some(last_id) = &*last_id.borrow() {739 if let Some(last_id) = &*last_id.borrow() {
601 if !income_acc.borrow().is_zero() {740 if !income_acc.borrow().is_zero() {
602 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(741 <<T as Config>::Currency as Mutate<T::AccountId>>::transfer(
603 &T::TreasuryAccountId::get(),742 &T::TreasuryAccountId::get(),
604 last_id,743 last_id,
605 *income_acc.borrow(),744 *income_acc.borrow(),
606 ExistenceRequirement::KeepAlive,745 frame_support::traits::tokens::Preservation::Protect,
607 )?;746 )?;
608747
609 Self::add_lock_balance(last_id, *income_acc.borrow())?;748 Self::add_freeze_balance(last_id, *income_acc.borrow())?;
610 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {749 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {
611 *staked = staked750 *staked = staked
612 .checked_add(&*income_acc.borrow())751 .checked_add(&*income_acc.borrow())
682 Ok(())821 Ok(())
683 }822 }
823
824 /// Migrates lock state into freeze one
825 ///
826 /// # Arguments
827 ///
828 /// * `origin`: Must be `Signed`.
829 /// * `stakers`: Accounts to be upgraded.
830 #[pallet::call_index(9)]
831 #[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]
832 pub fn upgrade_accounts(
833 origin: OriginFor<T>,
834 stakers: Vec<T::AccountId>,
835 ) -> DispatchResult {
836 ensure_signed(origin)?;
837
838 stakers.into_iter().try_for_each(|s| -> Result<_, DispatchError> {
839 if let Some(lock) = Self::get_locked_balance(&s) {
840
841 if let Some(_) = Self::get_freezed_balance(&s) {
842 return Err(Error::<T>::InconsistencyState.into())
843 }
844
845 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(
846 LOCK_IDENTIFIER,
847 &s,
848 );
849
850 Self::set_freeze_unchecked(&s, lock.amount);
851 Ok(())
852 } else {
853 Ok(())
854 }
855 })?;
856
857 Ok(())
858 }
684 }859 }
685}860}
686861
791 ///966 ///
792 /// - `staker`: staker account.967 /// - `staker`: staker account.
793 /// - `amount`: amount of added locked funds.968 /// - `amount`: amount of added locked funds.
969 // fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {
970 // Self::get_locked_balance(staker)
971 // .map_or(<BalanceOf<T>>::default(), |l| l.amount)
972 // .checked_add(&amount)
973 // .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))
974 // .ok_or(ArithmeticError::Overflow.into())
975 // }
976
977 /// Adds the balance to freezed by the pallet.
978 ///
979 /// - `staker`: staker account.
980 /// - `amount`: amount of added freezed funds.
794 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {981 fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {
795 Self::get_locked_balance(staker)982 Self::get_freezed_balance(staker)
796 .map_or(<BalanceOf<T>>::default(), |l| l.amount)983 .unwrap_or_default()
797 .checked_add(&amount)984 .checked_add(&amount)
798 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))985 .map(|freeze| Self::set_freeze_unchecked(staker, freeze))
799 .ok_or(ArithmeticError::Overflow.into())986 .ok_or(ArithmeticError::Overflow.into())
800 }987 }
801988
802 /// Sets the new state of a balance locked by the pallet.989 /// Sets the new state of a balance locked by the pallet.
803 ///990 ///
804 /// - `staker`: staker account.991 /// - `staker`: staker account.
805 /// - `amount`: amount of locked funds.992 /// - `amount`: amount of locked funds.
993 // fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {
994 // if amount.is_zero() {
995 // <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(
996 // LOCK_IDENTIFIER,
997 // &staker,
998 // );
999 // } else {
1000 // <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(
1001 // LOCK_IDENTIFIER,
1002 // staker,
1003 // amount,
1004 // WithdrawReasons::all(),
1005 // )
1006 // }
1007 // }
1008
1009 /// Sets the new state of a balance freezed by the pallet.
1010 ///
1011 /// - `staker`: staker account.
1012 /// - `amount`: amount of freezed funds.
806 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {1013 fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {
807 if amount.is_zero() {1014 if amount.is_zero() {
808 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(1015 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(
809 LOCK_IDENTIFIER,1016 &T::FreezeIdentifier::get(),
810 &staker,1017 &staker,
811 );1018 );
812 } else {1019 } else {
813 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(1020 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(
814 LOCK_IDENTIFIER,
815 staker,
816 amount,
817 WithdrawReasons::all(),1021 &T::FreezeIdentifier::get(),
1022 staker,
1023 amount,
818 )1024 );
819 }1025 }
820 }1026 }
8211027
830 .find(|l| l.id == LOCK_IDENTIFIER)1036 .find(|l| l.id == LOCK_IDENTIFIER)
831 }1037 }
1038
1039 /// Returns the balance freezed by the pallet for the staker.
1040 ///
1041 /// - `staker`: staker account.
1042 pub fn get_freezed_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {
1043 let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(
1044 &T::FreezeIdentifier::get(),
1045 staker,
1046 );
1047
1048 if res == Zero::zero() {
1049 None
1050 } else {
1051 Some(res)
1052 }
1053 }
8321054
833 /// Returns the total staked balance for the staker.1055 /// Returns the total staked balance for the staker.
834 ///1056 ///
9261148
927impl<T: Config> Pallet<T>1149impl<T: Config> Pallet<T>
928where1150where
929 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,1151 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,
930{1152{
931 /// Returns the amount reserved by the pending.1153 /// Returns the amount reserved by the pending.
932 /// If `staker` is `None`, returns the total pending.1154 /// If `staker` is `None`, returns the total pending.
987 // checks that we can do unstake in the block1209 // checks that we can do unstake in the block
988 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);1210 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);
989
990 let mut total_stakes = 0u64;
9911211
992 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1212 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))
993 .map(|(_, (amount, _))| {1213 .map(|(_, (amount, _))| amount)
994 total_stakes += 1;
995 amount
996 })
997 .sum();1214 .sum();
9981215
999 if total_staked.is_zero() {1216 if total_staked.is_zero() {
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -420,7 +420,6 @@
 
 #[frame_support::pallet]
 pub mod pallet {
-	use core::marker::PhantomData;
 
 	use super::*;
 	use dispatch::CollectionDispatch;
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -151,7 +151,6 @@
 	use frame_support::{
 		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,
 	};
-	use frame_system::pallet_prelude::*;
 	use up_data_structs::{CollectionId, TokenId};
 	use super::weights::WeightInfo;