difftreelog
feat removed reservation & added `on_runtime_upgrade`
in: master
Removed balance reservation when calling the unstake method.
3 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5803,11 +5803,12 @@
[[package]]
name = "pallet-app-promotion"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"frame-benchmarking",
"frame-support",
"frame-system",
+ "log",
"pallet-balances",
"pallet-common",
"pallet-configuration",
pallets/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.3'
+version = '0.1.4'
[package.metadata.docs.rs]
targets = ['x86_64-unknown-linux-gnu']
@@ -67,3 +67,6 @@
# [dev-dependencies]
################################################################################
+# Other
+
+log = { version = "0.4.16", default-features = false }
\ No newline at end of file
pallets/app-promotion/src/lib.rsdiffbeforeafterboth97 use super::*;97 use super::*;98 use frame_support::{98 use frame_support::{99 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,99 Blake2_128Concat, Twox64Concat,100 pallet_prelude::{*, ValueQuery, StorageValue},101 storage::Key,102 PalletId,100 traits::ReservableCurrency,103 traits::ReservableCurrency,104 weights::Weight,101 };105 };102 use frame_system::pallet_prelude::*;106 use frame_system::pallet_prelude::*;103107262 pub type PreviousCalculatedRecord<T: Config> =266 pub type PreviousCalculatedRecord<T: Config> =263 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;267 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;268269 #[pallet::storage]270 pub(crate) type IsMigrated<T: Config> = StorageValue<Value = bool, QueryKind = ValueQuery>;264271265 #[pallet::hooks]272 #[pallet::hooks]266 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {273 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {276283277 if !block_pending.is_empty() {284 if !block_pending.is_empty() {278 block_pending.into_iter().for_each(|(staker, amount)| {285 block_pending.into_iter().for_each(|(staker, amount)| {279 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(286 Self::get_locked_balance(&staker).map(|b| {287 let new_state = b.amount.checked_sub(&amount).unwrap_or_default();280 &staker, amount,288 Self::set_lock_unchecked(&staker, new_state);281 );289 });282 });290 });283 }291 }284292285 <T as Config>::WeightInfo::on_initialize(counter)293 <T as Config>::WeightInfo::on_initialize(counter)286 }294 }295296 fn on_runtime_upgrade() -> Weight {297 let mut consumed_weight = Weight::zero();298 let mut add_weight = |reads, writes, weight| {299 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);300 consumed_weight += weight;301 };302303 if <IsMigrated<T>>::get() {304 add_weight(1, 0, Weight::zero());305 return consumed_weight;306 } else {307 add_weight(1, 1, Weight::zero());308 <IsMigrated<T>>::set(true);309 }310 <PendingUnstake<T>>::drain().for_each(|(_, v)| {311 add_weight(1, 1, Weight::zero());312 v.into_iter().for_each(|(staker, amount)| {313 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(314 &staker, amount,315 );316 add_weight(1, 1, Weight::zero());317 });318 });319320 consumed_weight321 }322323 #[cfg(feature = "try-runtime")]324 fn pre_upgrade() -> Result<Vec<u8>, &'static str> {325 use sp_std::collections::btree_map::BTreeMap;326 if <IsMigrated<T>>::get() {327 return Ok(Default::default());328 }329 // Staker -> (total amount of reserved balance, reserved by promotion);330 let mut pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =331 BTreeMap::new();332333 <PendingUnstake<T>>::iter().for_each(|(_, v)| {334 v.into_iter().for_each(|(staker, amount)| {335 if let Some((_, reserved_balance)) = pre_state.get_mut(&staker) {336 *reserved_balance += amount;337 } else {338 let total_reserve = <<T as Config>::Currency as ReservableCurrency<339 T::AccountId,340 >>::reserved_balance(&staker);341 pre_state.insert(staker, (total_reserve, amount));342 }343 })344 });345346 Ok(pre_state.encode())347 }348349 #[cfg(feature = "try-runtime")]350 fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {351 use sp_std::collections::btree_map::BTreeMap;352353 if <IsMigrated<T>>::get() {354 return Ok(());355 }356 357 ensure!(358 <PendingUnstake<T>>::iter().collect::<Vec<_>>().len() == 0,359 "pendingUnstake storage isn't empty"360 );361 362 let mut is_ok = true;363364 let pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =365 Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;366 for (staker, (total_reserved, reserved_by_promo)) in pre_state.into_iter() {367 let new_state_reserve = <<T as Config>::Currency as ReservableCurrency<368 T::AccountId,369 >>::reserved_balance(&staker);370 if new_state_reserve != total_reserved - reserved_by_promo {371 is_ok = false;372 log::error!(373 "Incorrect reserved balance for {:?}. New balance: {:?}. Before runtime upgrade: total reserve - {:?}, reserved by promo - {:?}",374 staker, new_state_reserve, total_reserved, reserved_by_promo375 );376 }377 }378379 if is_ok {380 Ok(())381 } else {382 Err("Incorrect balance for some of stakers... See logs")383 }384 }287 }385 }288386289 #[pallet::call]387 #[pallet::call]340 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);438 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);341439342 // checks that we can lock `amount` on the `staker` account.440 // checks that we can lock `amount` on the `staker` account.343 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(441 ensure!(344 &staker_id,345 amount,442 amount346 WithdrawReasons::all(),443 <= match Self::get_locked_balance(&staker_id) {347 balance444 Some(lock) => balance348 .checked_sub(&amount)445 .checked_sub(&lock.amount)349 .ok_or(ArithmeticError::Underflow)?,446 .ok_or(ArithmeticError::Underflow)?,447 None => balance,448 },449 ArithmeticError::Underflow350 )?;450 );351451352 Self::add_lock_balance(&staker_id, amount)?;452 Self::add_lock_balance(&staker_id, amount)?;353453428528429 <PendingUnstake<T>>::insert(block, pendings);529 <PendingUnstake<T>>::insert(block, pendings);430530431 Self::unlock_balance(&staker_id, total_staked)?;432433 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::reserve(434 &staker_id,435 total_staked,436 )?;437531438 TotalStaked::<T>::set(532 TotalStaked::<T>::set(439 TotalStaked::<T>::get()533 TotalStaked::<T>::get()719 T::PalletId::get().into_account_truncating()813 T::PalletId::get().into_account_truncating()720 }814 }721815722 /// Unlocks the balance that was locked by the pallet.816 // /// Unlocks the balance that was locked by the pallet.723 ///817 // ///724 /// - `staker`: staker account.818 // /// - `staker`: staker account.725 /// - `amount`: amount of unlocked funds.819 // /// - `amount`: amount of unlocked funds.726 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {820 // fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {727 let locked_balance = Self::get_locked_balance(staker)821 // let locked_balance = Self::get_locked_balance(staker)728 .map(|l| l.amount)822 // .map(|l| l.amount)729 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;823 // .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;730824731 // It is understood that we cannot unlock more funds than were locked by staking.825 // // It is understood that we cannot unlock more funds than were locked by staking.732 // Therefore, if implemented correctly, this error should not occur.826 // // Therefore, if implemented correctly, this error should not occur.733 Self::set_lock_unchecked(827 // Self::set_lock_unchecked(734 staker,828 // staker,735 locked_balance829 // locked_balance736 .checked_sub(&amount)830 // .checked_sub(&amount)737 .ok_or(ArithmeticError::Underflow)?,831 // .ok_or(ArithmeticError::Underflow)?,738 );832 // );739 Ok(())833 // Ok(())740 }834 // }741835742 /// Adds the balance to locked by the pallet.836 /// Adds the balance to locked by the pallet.743 ///837 ///