difftreelog
Breaking: migration to `Fungible` traits in app-promotion pallet
in: master
Migration from `Currency` traits to `Fungible` ones in constraints for `Config::Currency` associated type.
6 files changed
Cargo.lockdiffbeforeafterboth612561256126[[package]]6126[[package]]6127name = "pallet-app-promotion"6127name = "pallet-app-promotion"6128version = "0.1.6"6128version = "0.2.0"6129dependencies = [6129dependencies = [6130 "frame-benchmarking",6130 "frame-benchmarking",6131 "frame-support",6131 "frame-support",pallets/app-promotion/CHANGELOG.mddiffbeforeafterboth3All notable changes to this project will be documented in this file.3All notable changes to this project will be documented in this file.445<!-- bureaucrate goes here -->5<!-- bureaucrate goes here -->6## [0.2.0] - 2023-05-1978### Changed910- **Breaking:** migration from `Currency` traits to `Fungible` ones in constraints11 for `Config::Currency` associated type.126## [0.1.6] - 2023-04-1913## [0.1.6] - 2023-04-197148- ### Fixed15- ### Fixedpallets/app-promotion/Cargo.tomldiffbeforeafterboth9license = 'GPLv3'9license = 'GPLv3'10name = 'pallet-app-promotion'10name = 'pallet-app-promotion'11repository = 'https://github.com/UniqueNetwork/unique-chain'11repository = 'https://github.com/UniqueNetwork/unique-chain'12version = '0.1.6'12version = '0.2.0'131314[package.metadata.docs.rs]14[package.metadata.docs.rs]15targets = ['x86_64-unknown-linux-gnu']15targets = ['x86_64-unknown-linux-gnu']pallets/app-promotion/src/lib.rsdiffbeforeafterboth70use 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;919392type 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;949695#[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;103105104 #[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::Config107 {109 {108 /// Type to interact with the native token110 /// Type to interact with the native token109 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>;111114112 /// Type for interacting with collections115 /// Type for interacting with collections113 type CollectionHandler: CollectionHandler<116 type CollectionHandler: CollectionHandler<125 #[pallet::constant]128 #[pallet::constant]126 type PalletId: Get<PalletId>;129 type PalletId: Get<PalletId>;130131 /// Freeze identifier used by the pallet132 #[pallet::constant]133 type FreezeIdentifier: Get<<<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id>;127134128 /// 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 InconsistencyState212 }221 }213222214 /// 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>;274275 // #[pallet::storage]276 // pub(crate) type UpgradedToFreezes<T: Config> =277 // StorageValue<Value = bool, QueryKind = ValueQuery>;265278266 #[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> {277290278 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 }286299287 <T as Config>::WeightInfo::on_initialize(counter)300 <T as Config>::WeightInfo::on_initialize(counter)288 }301 }302303 // 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 // };310311 // let mut stakes_unstakes = vec![];312313 // 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 // });324325 // <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 // });331332 // // filter duplicated id.333 // stakes_unstakes = stakes_unstakes334 // .into_iter()335 // .map(|key| key)336 // .collect::<HashSet<_>>()337 // .into_iter()338 // .collect();339340 // stakes_unstakes341 // .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 // });354355 // consumed_weight356 // }357358 // #[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();366367 // <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 // });374375 // <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 // });384385 // Ok(pre_state.encode())386 // }387388 // #[cfg(feature = "try-runtime")]389 // fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {390 // use sp_std::collections::btree_map::BTreeMap;391392 // if <UpgradedToFreezes<T>>::get() {393 // return Ok(());394 // }395396 // let mut is_ok = true;397398 // 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(), staker405 // );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_promo411 // );412 // }413414 // 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 // staker419 // );420 // }421 // }422423 // if is_ok {424 // Ok(())425 // } else {426 // Err("Incorrect balance for some of stakers... See logs")427 // }428 // }289 }429 }290430291 #[pallet::call]431 #[pallet::call]292 impl<T: Config> Pallet<T>432 impl<T: Config> Pallet<T>293 where433 where294 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();340480341 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);343482344 // 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 amount347 <= match Self::get_locked_balance(&staker_id) {486 <= match Self::get_freezed_balance(&staker_id) {348 Some(lock) => balance487 Some(freezed_by_pallet) => balance349 .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::Underflow354 );493 );355494356 Self::add_lock_balance(&staker_id, amount)?;495 Self::add_freeze_balance(&staker_id, amount)?;357496358 let block_number = T::RelayBlockNumberProvider::current_block_number();497 let block_number = T::RelayBlockNumberProvider::current_block_number();359498599 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 )?;608747609 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 = staked612 .checked_add(&*income_acc.borrow())751 .checked_add(&*income_acc.borrow())682 Ok(())821 Ok(())683 }822 }823824 /// Migrates lock state into freeze one825 ///826 /// # Arguments827 ///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)?;837838 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 );849850 Self::set_freeze_unchecked(&s, lock.amount);851 Ok(())852 } else {853 Ok(())854 }855 })?;856 857 Ok(())858 }684 }859 }685}860}686861791 ///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 // }976977 /// 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 }801988802 /// 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 // }10081009 /// 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 }8211027830 .find(|l| l.id == LOCK_IDENTIFIER)1036 .find(|l| l.id == LOCK_IDENTIFIER)831 }1037 }10381039 /// 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 );10471048 if res == Zero::zero() {1049 None1050 } else {1051 Some(res)1052 }1053 }8321054833 /// Returns the total staked balance for the staker.1055 /// Returns the total staked balance for the staker.834 ///1056 ///9261148927impl<T: Config> Pallet<T>1149impl<T: Config> Pallet<T>928where1150where929 <<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 block988 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);1210 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);989990 let mut total_stakes = 0u64;9911211992 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 amount996 })997 .sum();1214 .sum();9981215999 if total_staked.is_zero() {1216 if total_staked.is_zero() {pallets/common/src/lib.rsdiffbeforeafterboth420420421#[frame_support::pallet]421#[frame_support::pallet]422pub mod pallet {422pub mod pallet {423 use core::marker::PhantomData;424423425 use super::*;424 use super::*;426 use dispatch::CollectionDispatch;425 use dispatch::CollectionDispatch;pallets/nonfungible/src/lib.rsdiffbeforeafterboth151 use frame_support::{151 use frame_support::{152 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,152 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,153 };153 };154 use frame_system::pallet_prelude::*;155 use up_data_structs::{CollectionId, TokenId};154 use up_data_structs::{CollectionId, TokenId};156 use super::weights::WeightInfo;155 use super::weights::WeightInfo;157156