git.delta.rocks / unique-network / refs/commits / 91c34acacac8

difftreelog

Merge pull request #882 from UniqueNetwork/feature/app-promo-unstake-behaviour

Yaroslav Bolyukin2023-02-15parents: #9f4fc06 #803eec0.patch.diff
in: master
Feature/app promo unstake behaviour

14 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5782,7 +5782,7 @@
 
 [[package]]
 name = "pallet-app-promotion"
-version = "0.1.4"
+version = "0.1.5"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
modifiedpallets/app-promotion/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/app-promotion/CHANGELOG.md
+++ b/pallets/app-promotion/CHANGELOG.md
@@ -4,6 +4,12 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.5] - 2023-02-14
+
+### Added
+
+- `unstake_partial` extrinsic.
+
 ## [0.1.4] - 2023-01-31
 
 ### Changed
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.4'
+version = '0.1.5'
 
 [package.metadata.docs.rs]
 targets = ['x86_64-unknown-linux-gnu']
modifiedpallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/benchmarking.rs
+++ b/pallets/app-promotion/src/benchmarking.rs
@@ -65,7 +65,7 @@
 			let staker = account::<T::AccountId>("staker", index, SEED);
 			<T as Config>::Currency::make_free_balance_be(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 			PromototionPallet::<T>::stake(RawOrigin::Signed(staker.clone()).into(), Into::<BalanceOf<T>>::into(100u128) * T::Nominal::get())?;
-			PromototionPallet::<T>::unstake(RawOrigin::Signed(staker.clone()).into()).map_err(|e| e.error)?;
+			PromototionPallet::<T>::unstake_all(RawOrigin::Signed(staker.clone()).into())?;
 			Result::<(), sp_runtime::DispatchError>::Ok(())
 		})?;
 		let block_number = <frame_system::Pallet<T>>::current_block_number() + T::PendingInterval::get();
@@ -115,7 +115,7 @@
 		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 	} : _(RawOrigin::Signed(caller.clone()), share * <T as Config>::Currency::total_balance(&caller))
 
-	unstake {
+	unstake_all {
 		let caller = account::<T::AccountId>("caller", 0, SEED);
 		let share = Perbill::from_rational(1u32, 20);
 		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
@@ -130,6 +130,21 @@
 
 	} : _(RawOrigin::Signed(caller.clone()))
 
+	unstake_partial {
+		let caller = account::<T::AccountId>("caller", 0, SEED);
+		let share = Perbill::from_rational(1u32, 20);
+		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		(1..11).map(|i| {
+			// used to change block number
+			<frame_system::Pallet<T>>::set_block_number(i.into());
+			T::RelayBlockNumberProvider::set_block_number((2*i).into());
+			assert_eq!(<frame_system::Pallet<T>>::block_number(), i.into());
+			assert_eq!(T::RelayBlockNumberProvider::current_block_number(), (2*i).into());
+			PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), Into::<BalanceOf<T>>::into(100u128) * T::Nominal::get())
+		}).collect::<Result<Vec<_>, _>>()?;
+
+	} : _(RawOrigin::Signed(caller.clone()), Into::<BalanceOf<T>>::into(1000u128) * T::Nominal::get())
+
 	sponsor_collection {
 		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
 		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
after · pallets/app-promotion/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # App Promotion pallet18//!19//! The pallet implements the mechanics of staking and sponsoring collections/contracts.20//!21//! - [`Config`]22//! - [`Pallet`]23//! - [`Error`]24//! - [`Event`]25//!26//! ## Overview27//! The App Promotion pallet allows fund holders to stake at a certain daily rate of return.28//! The mechanics implemented in the pallet allow it to act as a sponsor for collections / contracts,29//! the list of which is set by the pallet administrator.30//!31//!32//! ## Interface33//!	The pallet provides interfaces for funds, collection/contract operations (see [types] module).3435//!36//! ### Dispatchable Functions37//!	- [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.38//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.39//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.40//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.41//! - [`stop_sponsoring_collection`][`Pallet::stop_sponsoring_collection`] - removes the pallet as the sponsor for the collection.42//! - [`sponsor_contract`][`Pallet::sponsor_contract`] - sets the pallet to be the sponsor for the contract.43//! - [`stop_sponsoring_contract`][`Pallet::stop_sponsoring_contract`] - removes the pallet as the sponsor for the contract.44//! - [`payout_stakers`][`Pallet::payout_stakers`] - recalculates interest for the specified number of stakers.45//!4647// #![recursion_limit = "1024"]48#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57	vec::{Vec},58	vec,59	iter::Sum,60	borrow::ToOwned,61	cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71	dispatch::{DispatchResult},72	traits::{73		Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,74	},75	ensure, BoundedVec,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83	Perbill,84	traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85	ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97	use super::*;98	use frame_support::{99		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100		traits::ReservableCurrency, weights::Weight,101	};102	use frame_system::pallet_prelude::*;103104	#[pallet::config]105	pub trait Config:106		frame_system::Config + pallet_evm::Config + pallet_configuration::Config107	{108		/// Type to interact with the native token109		type Currency: ExtendedLockableCurrency<Self::AccountId>110			+ ReservableCurrency<Self::AccountId>;111112		/// Type for interacting with collections113		type CollectionHandler: CollectionHandler<114			AccountId = Self::AccountId,115			CollectionId = CollectionId,116		>;117118		/// Type for interacting with conrtacts119		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;120121		/// `AccountId` for treasury122		type TreasuryAccountId: Get<Self::AccountId>;123124		/// The app's pallet id, used for deriving its sovereign account address.125		#[pallet::constant]126		type PalletId: Get<PalletId>;127128		/// In relay blocks.129		#[pallet::constant]130		type RecalculationInterval: Get<Self::BlockNumber>;131132		/// In parachain blocks.133		#[pallet::constant]134		type PendingInterval: Get<Self::BlockNumber>;135136		/// Rate of return for interval in blocks defined in `RecalculationInterval`.137		#[pallet::constant]138		type IntervalIncome: Get<Perbill>;139140		/// Decimals for the `Currency`.141		#[pallet::constant]142		type Nominal: Get<BalanceOf<Self>>;143144		/// Weight information for extrinsics in this pallet.145		type WeightInfo: WeightInfo;146147		// The relay block number provider148		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149150		/// Events compatible with [`frame_system::Config::Event`].151		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;152	}153154	#[pallet::pallet]155	#[pallet::generate_store(pub(super) trait Store)]156	pub struct Pallet<T>(_);157158	#[pallet::event]159	#[pallet::generate_deposit(pub(super) fn deposit_event)]160	pub enum Event<T: Config> {161		/// Staking recalculation was performed162		///163		/// # Arguments164		/// * AccountId: account of the staker.165		/// * Balance : recalculation base166		/// * Balance : total income167		StakingRecalculation(168			/// An recalculated staker169			T::AccountId,170			/// Base on which interest is calculated171			BalanceOf<T>,172			/// Amount of accrued interest173			BalanceOf<T>,174		),175176		/// Staking was performed177		///178		/// # Arguments179		/// * AccountId: account of the staker180		/// * Balance : staking amount181		Stake(T::AccountId, BalanceOf<T>),182183		/// Unstaking was performed184		///185		/// # Arguments186		/// * AccountId: account of the staker187		/// * Balance : unstaking amount188		Unstake(T::AccountId, BalanceOf<T>),189190		/// The admin was set191		///192		/// # Arguments193		/// * AccountId: account address of the admin194		SetAdmin(T::AccountId),195	}196197	#[pallet::error]198	pub enum Error<T> {199		/// Error due to action requiring admin to be set.200		AdminNotSet,201		/// No permission to perform an action.202		NoPermission,203		/// Insufficient funds to perform an action.204		NotSufficientFunds,205		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.206		PendingForBlockOverflow,207		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.208		SponsorNotSet,209		/// Errors caused by incorrect actions with a locked balance.210		IncorrectLockedBalanceOperation,211		/// Errors caused by insufficient staked balance.212		InsufficientStakedBalance,213	}214215	/// Stores the total staked amount.216	#[pallet::storage]217	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;218219	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.220	#[pallet::storage]221	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;222223	/// Stores the amount of tokens staked by account in the blocknumber.224	///225	/// * **Key1** - Staker account.226	/// * **Key2** - Relay block number when the stake was made.227	/// * **(Balance, BlockNumber)** - Balance of the stake.228	/// The number of the relay block in which we must perform the interest recalculation229	#[pallet::storage]230	pub type Staked<T: Config> = StorageNMap<231		Key = (232			Key<Blake2_128Concat, T::AccountId>,233			Key<Twox64Concat, T::BlockNumber>,234		),235		Value = (BalanceOf<T>, T::BlockNumber),236		QueryKind = ValueQuery,237	>;238239	/// Stores number of stake records for an `Account`.240	///241	/// * **Key** - Staker account.242	/// * **Value** - Amount of stakes.243	#[pallet::storage]244	pub type StakesPerAccount<T: Config> =245		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;246247	/// Pending unstake records for an `Account`.248	///249	/// * **Key** - Staker account.250	/// * **Value** - Amount of stakes.251	#[pallet::storage]252	pub type PendingUnstake<T: Config> = StorageMap<253		_,254		Twox64Concat,255		T::BlockNumber,256		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,257		ValueQuery,258	>;259260	/// Stores a key for record for which the revenue recalculation was performed.261	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.262	#[pallet::storage]263	#[pallet::getter(fn get_next_calculated_record)]264	pub type PreviousCalculatedRecord<T: Config> =265		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;266267	#[pallet::storage]268	pub(crate) type UpgradedToReserves<T: Config> =269		StorageValue<Value = bool, QueryKind = ValueQuery>;270271	#[pallet::hooks]272	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {273		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize274		/// implies the execution of a strictly limited number of relatively lightweight operations.275		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.276		fn on_initialize(current_block_number: T::BlockNumber) -> Weight277		where278			<T as frame_system::Config>::BlockNumber: From<u32>,279		{280			let block_pending = PendingUnstake::<T>::take(current_block_number);281			let counter = block_pending.len() as u32;282283			if !block_pending.is_empty() {284				block_pending.into_iter().for_each(|(staker, amount)| {285					Self::get_locked_balance(&staker).map(|b| {286						let new_state = b.amount.checked_sub(&amount).unwrap_or_default();287						Self::set_lock_unchecked(&staker, new_state);288					});289				});290			}291292			<T as Config>::WeightInfo::on_initialize(counter)293		}294295		fn on_runtime_upgrade() -> Weight {296			let mut consumed_weight = Weight::zero();297			let mut add_weight = |reads, writes, weight| {298				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);299				consumed_weight += weight;300			};301302			if <UpgradedToReserves<T>>::get() {303				add_weight(1, 0, Weight::zero());304				return consumed_weight;305			} else {306				add_weight(1, 1, Weight::zero());307				<UpgradedToReserves<T>>::set(true);308			}309			<PendingUnstake<T>>::drain().for_each(|(_, v)| {310				add_weight(1, 1, Weight::zero());311				v.into_iter().for_each(|(staker, amount)| {312					<<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(313						&staker, amount,314					);315					add_weight(1, 1, Weight::zero());316				});317			});318319			consumed_weight320		}321322		#[cfg(feature = "try-runtime")]323		fn pre_upgrade() -> Result<Vec<u8>, &'static str> {324			use sp_std::collections::btree_map::BTreeMap;325			if <UpgradedToReserves<T>>::get() {326				return Ok(Default::default());327			}328			// Staker -> (total amount of reserved balance, reserved by promotion);329			let mut pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =330				BTreeMap::new();331332			<PendingUnstake<T>>::iter().for_each(|(_, v)| {333				v.into_iter().for_each(|(staker, amount)| {334					if let Some((_, reserved_balance)) = pre_state.get_mut(&staker) {335						*reserved_balance += amount;336					} else {337						let total_reserve = <<T as Config>::Currency as ReservableCurrency<338							T::AccountId,339						>>::reserved_balance(&staker);340						pre_state.insert(staker, (total_reserve, amount));341					}342				})343			});344345			Ok(pre_state.encode())346		}347348		#[cfg(feature = "try-runtime")]349		fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {350			use sp_std::collections::btree_map::BTreeMap;351352			if <UpgradedToReserves<T>>::get() {353				return Ok(());354			}355356			ensure!(357				<PendingUnstake<T>>::iter().collect::<Vec<_>>().len() == 0,358				"pendingUnstake storage isn't empty"359			);360361			let mut is_ok = true;362363			let pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =364				Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;365			for (staker, (total_reserved, reserved_by_promo)) in pre_state.into_iter() {366				let new_state_reserve = <<T as Config>::Currency as ReservableCurrency<367					T::AccountId,368				>>::reserved_balance(&staker);369				if new_state_reserve != total_reserved - reserved_by_promo {370					is_ok = false;371					log::error!(372								"Incorrect reserved balance for {:?}. New balance: {:?}. Before runtime upgrade: total reserve - {:?}, reserved by promo - {:?}",373								staker, new_state_reserve, total_reserved, reserved_by_promo374							);375				}376			}377378			if is_ok {379				Ok(())380			} else {381				Err("Incorrect balance for some of stakers... See logs")382			}383		}384	}385386	#[pallet::call]387	impl<T: Config> Pallet<T>388	where389		T::BlockNumber: From<u32> + Into<u32>,390		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,391	{392		/// Sets an address as the the admin.393		///394		/// # Permissions395		///396		/// * Sudo397		///398		/// # Arguments399		///400		/// * `admin`: account of the new admin.401		#[pallet::call_index(0)]402		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]403		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {404			ensure_root(origin)?;405406			<Admin<T>>::set(Some(admin.as_sub().to_owned()));407408			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));409410			Ok(())411		}412413		/// Stakes the amount of native tokens.414		/// Sets `amount` to the locked state.415		/// The maximum number of stakes for a staker is 10.416		///417		/// # Arguments418		///419		/// * `amount`: in native tokens.420		#[pallet::call_index(1)]421		#[pallet::weight(<T as Config>::WeightInfo::stake())]422		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {423			let staker_id = ensure_signed(staker)?;424425			ensure!(426				StakesPerAccount::<T>::get(&staker_id) < 10,427				Error::<T>::NoPermission428			);429430			ensure!(431				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),432				ArithmeticError::Underflow433			);434			let config = <PalletConfiguration<T>>::get();435436			let balance =437				<<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);438439			// checks that we can lock `amount` on the `staker` account.440			ensure!(441				amount442					<= match Self::get_locked_balance(&staker_id) {443						Some(lock) => balance444							.checked_sub(&lock.amount)445							.ok_or(ArithmeticError::Underflow)?,446						None => balance,447					},448				ArithmeticError::Underflow449			);450451			Self::add_lock_balance(&staker_id, amount)?;452453			let block_number = T::RelayBlockNumberProvider::current_block_number();454455			// Calculation of the number of recalculation periods,456			// after how much the first interest calculation should be performed for the stake457			let recalculate_after_interval: T::BlockNumber =458				if block_number % config.recalculation_interval == 0u32.into() {459					1u32.into()460				} else {461					2u32.into()462				};463464			// Сalculation of the number of the relay block465			// in which it is necessary to accrue remuneration for the stake.466			let recalc_block = (block_number / config.recalculation_interval467				+ recalculate_after_interval)468				* config.recalculation_interval;469470			<Staked<T>>::insert((&staker_id, block_number), {471				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));472				balance_and_recalc_block.0 = balance_and_recalc_block473					.0474					.checked_add(&amount)475					.ok_or(ArithmeticError::Overflow)?;476				balance_and_recalc_block.1 = recalc_block;477				balance_and_recalc_block478			});479480			<TotalStaked<T>>::set(481				<TotalStaked<T>>::get()482					.checked_add(&amount)483					.ok_or(ArithmeticError::Overflow)?,484			);485486			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);487488			Self::deposit_event(Event::Stake(staker_id, amount));489490			Ok(())491		}492493		/// Unstakes all stakes.494		/// After the end of `PendingInterval` this sum becomes completely495		/// free for further use.496		#[pallet::call_index(2)]497		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]498		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {499			let staker_id = ensure_signed(staker)?;500501			Self::unstake_all_internal(staker_id)502		}503504		/// Unstakes the amount of balance for the staker.505		/// After the end of `PendingInterval` this sum becomes completely506		/// free for further use.507		///508		///  # Arguments509		///510		/// * `staker`: staker account.511		/// * `amount`: amount of unstaked funds.512		#[pallet::call_index(8)]513		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]514		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {515			let staker_id = ensure_signed(staker)?;516517			Self::unstake_partial_internal(staker_id, amount)518		}519520		/// Sets the pallet to be the sponsor for the collection.521		///522		/// # Permissions523		///524		/// * Pallet admin525		///526		/// # Arguments527		///528		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`529		#[pallet::call_index(3)]530		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]531		pub fn sponsor_collection(532			admin: OriginFor<T>,533			collection_id: CollectionId,534		) -> DispatchResult {535			let admin_id = ensure_signed(admin)?;536			ensure!(537				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,538				Error::<T>::NoPermission539			);540541			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)542		}543544		/// Removes the pallet as the sponsor for the collection.545		/// Returns [`NoPermission`][`Error::NoPermission`]546		/// if the pallet wasn't the sponsor.547		///548		/// # Permissions549		///550		/// * Pallet admin551		///552		/// # Arguments553		///554		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`555		#[pallet::call_index(4)]556		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]557		pub fn stop_sponsoring_collection(558			admin: OriginFor<T>,559			collection_id: CollectionId,560		) -> DispatchResult {561			let admin_id = ensure_signed(admin)?;562563			ensure!(564				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,565				Error::<T>::NoPermission566			);567568			ensure!(569				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?570					== Self::account_id(),571				<Error<T>>::NoPermission572			);573			T::CollectionHandler::remove_collection_sponsor(collection_id)574		}575576		/// Sets the pallet to be the sponsor for the contract.577		///578		/// # Permissions579		///580		/// * Pallet admin581		///582		/// # Arguments583		///584		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`585		#[pallet::call_index(5)]586		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]587		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {588			let admin_id = ensure_signed(admin)?;589590			ensure!(591				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,592				Error::<T>::NoPermission593			);594595			T::ContractHandler::set_sponsor(596				T::CrossAccountId::from_sub(Self::account_id()),597				contract_id,598			)599		}600601		/// Removes the pallet as the sponsor for the contract.602		/// Returns [`NoPermission`][`Error::NoPermission`]603		/// if the pallet wasn't the sponsor.604		///605		/// # Permissions606		///607		/// * Pallet admin608		///609		/// # Arguments610		///611		/// * `contract_id`: the contract address that is sponsored by `pallet_id`612		#[pallet::call_index(6)]613		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]614		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {615			let admin_id = ensure_signed(admin)?;616617			ensure!(618				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,619				Error::<T>::NoPermission620			);621622			ensure!(623				T::ContractHandler::sponsor(contract_id)?624					.ok_or(<Error<T>>::SponsorNotSet)?625					.as_sub() == &Self::account_id(),626				<Error<T>>::NoPermission627			);628			T::ContractHandler::remove_contract_sponsor(contract_id)629		}630631		/// Recalculates interest for the specified number of stakers.632		/// If all stakers are not recalculated, the next call of the extrinsic633		/// will continue the recalculation, from those stakers for whom this634		/// was not perform in last call.635		///636		/// # Permissions637		///638		/// * Pallet admin639		///640		/// # Arguments641		///642		/// * `stakers_number`: the number of stakers for which recalculation will be performed643		#[pallet::call_index(7)]644		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]645		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {646			let admin_id = ensure_signed(admin)?;647648			ensure!(649				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,650				Error::<T>::NoPermission651			);652			let config = <PalletConfiguration<T>>::get();653654			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);655656			ensure!(657				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,658				Error::<T>::NoPermission659			);660661			// calculate the number of the current recalculation block,662			// this is necessary in order to understand which stakers we should calculate interest663			let current_recalc_block = Self::get_current_recalc_block(664				T::RelayBlockNumberProvider::current_block_number(),665				&config,666			);667668			// calculate the number of the next recalculation block,669			// this value is set for the stakers to whom the recalculation will be performed670			let next_recalc_block = current_recalc_block + config.recalculation_interval;671672			let mut storage_iterator = Self::get_next_calculated_key()673				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));674675			PreviousCalculatedRecord::<T>::set(None);676677			{678				// Address handled in the last payout loop iteration (below)679				let last_id = RefCell::new(None);680				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration681				let mut last_staked_calculated_block = Default::default();682				// Reward balance for the address in the iteration683				let income_acc = RefCell::new(BalanceOf::<T>::default());684				// Staked balance for the address in the iteration (before stake is recalculated)685				let amount_acc = RefCell::new(BalanceOf::<T>::default());686687				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout688				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout689				// loop switches to handling the next staker address:690				//   1. Transfer full reward amount to the payee691				//   2. Lock the reward in staking lock692				//   3. Update TotalStaked amount693				//   4. Issue StakingRecalculation event694				let flush_stake = || -> DispatchResult {695					if let Some(last_id) = &*last_id.borrow() {696						if !income_acc.borrow().is_zero() {697							<<T as Config>::Currency as Currency<T::AccountId>>::transfer(698								&T::TreasuryAccountId::get(),699								last_id,700								*income_acc.borrow(),701								ExistenceRequirement::KeepAlive,702							)?;703704							Self::add_lock_balance(last_id, *income_acc.borrow())?;705							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {706								*staked = staked707									.checked_add(&*income_acc.borrow())708									.ok_or(ArithmeticError::Overflow)?;709								Ok(())710							})?;711712							Self::deposit_event(Event::StakingRecalculation(713								last_id.clone(),714								*amount_acc.borrow(),715								*income_acc.borrow(),716							));717						}718719						*income_acc.borrow_mut() = BalanceOf::<T>::default();720						*amount_acc.borrow_mut() = BalanceOf::<T>::default();721					}722					Ok(())723				};724725				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation726				// iterations in one extrinsic call727				//728				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)729				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out730				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)731				while let Some((732					(current_id, staked_block),733					(amount, next_recalc_block_for_stake),734				)) = storage_iterator.next()735				{736					// last_id is not equal current_id when we switch to handling a new staker address737					// or just start handling the very first address. In the latter case last_id will be None and738					// flush_stake will do nothing739					if last_id.borrow().as_ref() != Some(&current_id) {740						if stakers_number > 0 {741							flush_stake()?;742							*last_id.borrow_mut() = Some(current_id.clone());743							stakers_number -= 1;744						}745						// Break out if we reached the address limit746						else {747							if let Some(staker) = &*last_id.borrow() {748								// Save the last calculated record to pick up in the next extrinsic call749								PreviousCalculatedRecord::<T>::set(Some((750									staker.clone(),751									last_staked_calculated_block,752								)));753							}754							break;755						};756					};757758					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount759					if current_recalc_block >= next_recalc_block_for_stake {760						*amount_acc.borrow_mut() += amount;761						Self::recalculate_and_insert_stake(762							&current_id,763							staked_block,764							next_recalc_block,765							amount,766							((current_recalc_block - next_recalc_block_for_stake)767								/ config.recalculation_interval)768								.into() + 1,769							&mut *income_acc.borrow_mut(),770						);771					}772					last_staked_calculated_block = staked_block;773				}774				flush_stake()?;775			}776777			Ok(())778		}779	}780}781782impl<T: Config> Pallet<T> {783	/// The account address of the app promotion pot.784	///785	/// This actually does computation. If you need to keep using it, then make sure you cache the786	/// value and only call this once.787	pub fn account_id() -> T::AccountId {788		T::PalletId::get().into_account_truncating()789	}790791	/// Unstakes the balance for the staker.792	///793	/// - `staker`: staker account.794	/// - `amount`: amount of unstaked funds.795	fn unstake_partial_internal(796		staker_id: T::AccountId,797		unstaked_balance: BalanceOf<T>,798	) -> DispatchResult {799		if unstaked_balance == Default::default() {800			return Ok(());801		}802803		let config = <PalletConfiguration<T>>::get();804805		// calculate block number where the sum would be free806		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;807808		let mut pendings = <PendingUnstake<T>>::get(unpending_block);809810		// checks that we can do unstake in the block811		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);812813		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();814815		let total_staked = stakes816			.iter()817			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {818				acc + *balance819			});820821		ensure!(822			unstaked_balance <= total_staked,823			<Error<T>>::InsufficientStakedBalance824		);825826		<TotalStaked<T>>::set(827			<TotalStaked<T>>::get()828				.checked_sub(&unstaked_balance)829				.ok_or(ArithmeticError::Underflow)?,830		);831832		stakes.sort_by_key(|(block, _)| *block);833834		let mut acc_amount = unstaked_balance;835		let mut will_deleted_stakes_count = 0u8;836837		let changed_stakes = stakes838			.into_iter()839			.map_while(|(block, (balance_per_block, _))| {840				if acc_amount == <BalanceOf<T>>::default() {841					return None;842				}843				if acc_amount < balance_per_block {844					let res = (block, balance_per_block - acc_amount);845					acc_amount = <BalanceOf<T>>::default();846					return Some(res);847				} else {848					acc_amount -= balance_per_block;849					will_deleted_stakes_count += 1;850					return Some((block, <BalanceOf<T>>::default()));851				}852			})853			.collect::<Vec<_>>();854855		pendings856			.try_push((staker_id.clone(), unstaked_balance))857			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;858859		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {860			*stakes = stakes861				.checked_sub(will_deleted_stakes_count)862				.ok_or(ArithmeticError::Underflow)?;863			Ok(())864		})?;865866		changed_stakes867			.into_iter()868			.for_each(|(staked_block, current_stake_state)| {869				if current_stake_state == Default::default() {870					<Staked<T>>::remove((&staker_id, staked_block));871				} else {872					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {873						*old_stake_state = current_stake_state874					});875				}876			});877878		<PendingUnstake<T>>::insert(unpending_block, pendings);879880		Self::deposit_event(Event::Unstake(staker_id, total_staked));881882		Ok(())883	}884885	/// Adds the balance to locked by the pallet.886	///887	/// - `staker`: staker account.888	/// - `amount`: amount of added locked funds.889	fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {890		Self::get_locked_balance(staker)891			.map_or(<BalanceOf<T>>::default(), |l| l.amount)892			.checked_add(&amount)893			.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))894			.ok_or(ArithmeticError::Overflow.into())895	}896897	/// Sets the new state of a balance locked by the pallet.898	///899	/// - `staker`: staker account.900	/// - `amount`: amount of locked funds.901	fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {902		if amount.is_zero() {903			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(904				LOCK_IDENTIFIER,905				&staker,906			);907		} else {908			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(909				LOCK_IDENTIFIER,910				staker,911				amount,912				WithdrawReasons::all(),913			)914		}915	}916917	/// Returns the balance locked by the pallet for the staker.918	///919	/// - `staker`: staker account.920	pub fn get_locked_balance(921		staker: impl EncodeLike<T::AccountId>,922	) -> Option<BalanceLock<BalanceOf<T>>> {923		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)924			.into_iter()925			.find(|l| l.id == LOCK_IDENTIFIER)926	}927928	/// Returns the total staked balance for the staker.929	///930	/// - `staker`: staker account.931	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {932		let staked = Staked::<T>::iter_prefix((staker,))933			.into_iter()934			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {935				acc + amount936			});937		if staked != <BalanceOf<T>>::default() {938			Some(staked)939		} else {940			None941		}942	}943944	/// Returns all relay block numbers when stake was made,945	/// the amount of the stake.946	///947	/// - `staker`: staker account.948	pub fn total_staked_by_id_per_block(949		staker: impl EncodeLike<T::AccountId>,950	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {951		let mut staked = Staked::<T>::iter_prefix((staker,))952			.into_iter()953			.map(|(block, (amount, _))| (block, amount))954			.collect::<Vec<_>>();955		staked.sort_by_key(|(block, _)| *block);956		if !staked.is_empty() {957			Some(staked)958		} else {959			None960		}961	}962963	/// Returns the total staked balance for the staker.964	/// If `staker` is `None`, returns the total amount staked.965	/// - `staker`: staker account.966	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {967		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {968			Self::total_staked_by_id(s.as_sub())969		})970	}971972	// pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {973	// 	Self::get_locked_balance(staker.as_sub())974	// 		.map(|l| l.amount)975	// 		.unwrap_or_default()976	// }977978	/// Returns all relay block numbers when stake was made,979	/// the amount of the stake.980	///981	/// - `staker`: staker account.982	pub fn cross_id_total_staked_per_block(983		staker: T::CrossAccountId,984	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {985		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()986	}987988	fn recalculate_and_insert_stake(989		staker: &T::AccountId,990		staked_block: T::BlockNumber,991		next_recalc_block: T::BlockNumber,992		base: BalanceOf<T>,993		iters: u32,994		income_acc: &mut BalanceOf<T>,995	) {996		let income = Self::calculate_income(base, iters);997998		base.checked_add(&income).map(|res| {999			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1000			*income_acc += income;1001		});1002	}10031004	fn calculate_income<I>(base: I, iters: u32) -> I1005	where1006		I: EncodeLike<BalanceOf<T>> + Balance,1007	{1008		let config = <PalletConfiguration<T>>::get();1009		let mut income = base;10101011		(0..iters).for_each(|_| income += config.interval_income * income);10121013		income - base1014	}10151016	/// Get relay block number rounded down to multiples of config.recalculation_interval.1017	/// We need it to reward stakers in integer parts of recalculation_interval1018	fn get_current_recalc_block(1019		current_relay_block: T::BlockNumber,1020		config: &PalletConfiguration<T>,1021	) -> T::BlockNumber {1022		(current_relay_block / config.recalculation_interval) * config.recalculation_interval1023	}10241025	fn get_next_calculated_key() -> Option<Vec<u8>> {1026		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))1027	}1028}10291030impl<T: Config> Pallet<T>1031where1032	<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,1033{1034	/// Returns the amount reserved by the pending.1035	/// If `staker` is `None`, returns the total pending.1036	///1037	/// -`staker`: staker account.1038	///1039	/// Since user funds are not transferred anywhere by staking, overflow protection is provided1040	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1041	/// the staker must have more funds on his account than the maximum set for `Balance` type.1042	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1043		staker.map_or(1044			PendingUnstake::<T>::iter_values()1045				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1046				.sum(),1047			|s| {1048				PendingUnstake::<T>::iter_values()1049					.flatten()1050					.filter_map(|(id, amount)| {1051						if id == *s.as_sub() {1052							Some(amount)1053						} else {1054							None1055						}1056					})1057					.sum()1058			},1059		)1060	}10611062	/// Returns all parachain block numbers when unreserve is expected,1063	/// the amount of the unreserved funds.1064	///1065	/// - `staker`: staker account.1066	pub fn cross_id_pending_unstake_per_block(1067		staker: T::CrossAccountId,1068	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1069		let mut unsorted_res = vec![];1070		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1071			pendings.into_iter().for_each(|(id, amount)| {1072				if id == *staker.as_sub() {1073					unsorted_res.push((block, amount));1074				};1075			})1076		});10771078		unsorted_res.sort_by_key(|(block, _)| *block);1079		unsorted_res1080	}10811082	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1083		let config = <PalletConfiguration<T>>::get();10841085		// calculate block number where the sum would be free1086		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;10871088		let mut pendings = <PendingUnstake<T>>::get(block);10891090		// checks that we can do unstake in the block1091		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);10921093		let mut total_stakes = 0u64;10941095		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1096			.map(|(_, (amount, _))| {1097				total_stakes += 1;1098				amount1099			})1100			.sum();11011102		if total_staked.is_zero() {1103			return Ok(());1104		}11051106		pendings1107			.try_push((staker_id.clone(), total_staked))1108			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;11091110		<PendingUnstake<T>>::insert(block, pendings);11111112		TotalStaked::<T>::set(1113			TotalStaked::<T>::get()1114				.checked_sub(&total_staked)1115				.ok_or(ArithmeticError::Underflow)?,1116		);11171118		StakesPerAccount::<T>::remove(&staker_id);11191120		Self::deposit_event(Event::Unstake(staker_id, total_staked));11211122		Ok(())1123	}1124}
modifiedpallets/app-promotion/src/weights.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/weights.rs
+++ b/pallets/app-promotion/src/weights.rs
@@ -3,7 +3,7 @@
 //! Autogenerated weights for pallet_app_promotion
 //!
 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-12-25, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2023-02-15, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
 //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
 
 // Executed Command:
@@ -38,7 +38,8 @@
 	fn set_admin_address() -> Weight;
 	fn payout_stakers(b: u32, ) -> Weight;
 	fn stake() -> Weight;
-	fn unstake() -> Weight;
+	fn unstake_all() -> Weight;
+	fn unstake_partial() -> Weight;
 	fn sponsor_collection() -> Weight;
 	fn stop_sponsoring_collection() -> Weight;
 	fn sponsor_contract() -> Weight;
@@ -49,18 +50,19 @@
 pub struct SubstrateWeight<T>(PhantomData<T>);
 impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
 	// Storage: AppPromotion PendingUnstake (r:1 w:0)
+	// Storage: Balances Locks (r:1 w:1)
 	// Storage: System Account (r:1 w:1)
 	fn on_initialize(b: u32, ) -> Weight {
-		Weight::from_ref_time(3_079_948 as u64)
-			// Standard Error: 30_376
-			.saturating_add(Weight::from_ref_time(6_343_630 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(2_592_346 as u64)
+			// Standard Error: 23_629
+			.saturating_add(Weight::from_ref_time(7_523_802 as u64).saturating_mul(b as u64))
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
-			.saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(b as u64)))
-			.saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(b as u64)))
+			.saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(b as u64)))
+			.saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(b as u64)))
 	}
 	// Storage: AppPromotion Admin (r:0 w:1)
 	fn set_admin_address() -> Weight {
-		Weight::from_ref_time(6_653_000 as u64)
+		Weight::from_ref_time(6_209_000 as u64)
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
@@ -72,9 +74,9 @@
 	// Storage: Balances Locks (r:1 w:1)
 	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	fn payout_stakers(b: u32, ) -> Weight {
-		Weight::from_ref_time(74_048_000 as u64)
-			// Standard Error: 33_223
-			.saturating_add(Weight::from_ref_time(57_702_092 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(64_917_000 as u64)
+			// Standard Error: 34_206
+			.saturating_add(Weight::from_ref_time(51_518_500 as u64).saturating_mul(b as u64))
 			.saturating_add(T::DbWeight::get().reads(7 as u64))
 			.saturating_add(T::DbWeight::get().reads((12 as u64).saturating_mul(b as u64)))
 			.saturating_add(T::DbWeight::get().writes(3 as u64))
@@ -88,47 +90,55 @@
 	// Storage: AppPromotion Staked (r:1 w:1)
 	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	fn stake() -> Weight {
-		Weight::from_ref_time(20_314_000 as u64)
+		Weight::from_ref_time(18_208_000 as u64)
 			.saturating_add(T::DbWeight::get().reads(7 as u64))
 			.saturating_add(T::DbWeight::get().writes(5 as u64))
 	}
 	// Storage: Configuration AppPromomotionConfigurationOverride (r:1 w:0)
 	// Storage: AppPromotion PendingUnstake (r:1 w:1)
 	// Storage: AppPromotion Staked (r:11 w:10)
-	// Storage: Balances Locks (r:1 w:1)
-	// Storage: System Account (r:1 w:1)
 	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	// Storage: AppPromotion StakesPerAccount (r:0 w:1)
-	fn unstake() -> Weight {
-		Weight::from_ref_time(64_582_000 as u64)
-			.saturating_add(T::DbWeight::get().reads(16 as u64))
-			.saturating_add(T::DbWeight::get().writes(15 as u64))
+	fn unstake_all() -> Weight {
+		Weight::from_ref_time(45_018_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(14 as u64))
+			.saturating_add(T::DbWeight::get().writes(13 as u64))
+	}
+	// Storage: Configuration AppPromomotionConfigurationOverride (r:1 w:0)
+	// Storage: AppPromotion PendingUnstake (r:1 w:1)
+	// Storage: AppPromotion Staked (r:11 w:10)
+	// Storage: AppPromotion TotalStaked (r:1 w:1)
+	// Storage: AppPromotion StakesPerAccount (r:1 w:1)
+	fn unstake_partial() -> Weight {
+		Weight::from_ref_time(49_066_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(15 as u64))
+			.saturating_add(T::DbWeight::get().writes(13 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn sponsor_collection() -> Weight {
-		Weight::from_ref_time(16_364_000 as u64)
+		Weight::from_ref_time(15_039_000 as u64)
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn stop_sponsoring_collection() -> Weight {
-		Weight::from_ref_time(15_710_000 as u64)
+		Weight::from_ref_time(14_692_000 as u64)
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:0 w:1)
 	fn sponsor_contract() -> Weight {
-		Weight::from_ref_time(12_669_000 as u64)
+		Weight::from_ref_time(11_810_000 as u64)
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:1 w:1)
 	fn stop_sponsoring_contract() -> Weight {
-		Weight::from_ref_time(14_406_000 as u64)
+		Weight::from_ref_time(13_570_000 as u64)
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
@@ -137,18 +147,19 @@
 // For backwards compatibility and tests
 impl WeightInfo for () {
 	// Storage: AppPromotion PendingUnstake (r:1 w:0)
+	// Storage: Balances Locks (r:1 w:1)
 	// Storage: System Account (r:1 w:1)
 	fn on_initialize(b: u32, ) -> Weight {
-		Weight::from_ref_time(3_079_948 as u64)
-			// Standard Error: 30_376
-			.saturating_add(Weight::from_ref_time(6_343_630 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(2_592_346 as u64)
+			// Standard Error: 23_629
+			.saturating_add(Weight::from_ref_time(7_523_802 as u64).saturating_mul(b as u64))
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
-			.saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(b as u64)))
-			.saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(b as u64)))
+			.saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(b as u64)))
+			.saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(b as u64)))
 	}
 	// Storage: AppPromotion Admin (r:0 w:1)
 	fn set_admin_address() -> Weight {
-		Weight::from_ref_time(6_653_000 as u64)
+		Weight::from_ref_time(6_209_000 as u64)
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
@@ -160,9 +171,9 @@
 	// Storage: Balances Locks (r:1 w:1)
 	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	fn payout_stakers(b: u32, ) -> Weight {
-		Weight::from_ref_time(74_048_000 as u64)
-			// Standard Error: 33_223
-			.saturating_add(Weight::from_ref_time(57_702_092 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(64_917_000 as u64)
+			// Standard Error: 34_206
+			.saturating_add(Weight::from_ref_time(51_518_500 as u64).saturating_mul(b as u64))
 			.saturating_add(RocksDbWeight::get().reads(7 as u64))
 			.saturating_add(RocksDbWeight::get().reads((12 as u64).saturating_mul(b as u64)))
 			.saturating_add(RocksDbWeight::get().writes(3 as u64))
@@ -176,47 +187,55 @@
 	// Storage: AppPromotion Staked (r:1 w:1)
 	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	fn stake() -> Weight {
-		Weight::from_ref_time(20_314_000 as u64)
+		Weight::from_ref_time(18_208_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(7 as u64))
 			.saturating_add(RocksDbWeight::get().writes(5 as u64))
 	}
 	// Storage: Configuration AppPromomotionConfigurationOverride (r:1 w:0)
 	// Storage: AppPromotion PendingUnstake (r:1 w:1)
 	// Storage: AppPromotion Staked (r:11 w:10)
-	// Storage: Balances Locks (r:1 w:1)
-	// Storage: System Account (r:1 w:1)
 	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	// Storage: AppPromotion StakesPerAccount (r:0 w:1)
-	fn unstake() -> Weight {
-		Weight::from_ref_time(64_582_000 as u64)
-			.saturating_add(RocksDbWeight::get().reads(16 as u64))
-			.saturating_add(RocksDbWeight::get().writes(15 as u64))
+	fn unstake_all() -> Weight {
+		Weight::from_ref_time(45_018_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(14 as u64))
+			.saturating_add(RocksDbWeight::get().writes(13 as u64))
 	}
+	// Storage: Configuration AppPromomotionConfigurationOverride (r:1 w:0)
+	// Storage: AppPromotion PendingUnstake (r:1 w:1)
+	// Storage: AppPromotion Staked (r:11 w:10)
+	// Storage: AppPromotion TotalStaked (r:1 w:1)
+	// Storage: AppPromotion StakesPerAccount (r:1 w:1)
+	fn unstake_partial() -> Weight {
+		Weight::from_ref_time(49_066_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(15 as u64))
+			.saturating_add(RocksDbWeight::get().writes(13 as u64))
+	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn sponsor_collection() -> Weight {
-		Weight::from_ref_time(16_364_000 as u64)
+		Weight::from_ref_time(15_039_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn stop_sponsoring_collection() -> Weight {
-		Weight::from_ref_time(15_710_000 as u64)
+		Weight::from_ref_time(14_692_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:0 w:1)
 	fn sponsor_contract() -> Weight {
-		Weight::from_ref_time(12_669_000 as u64)
+		Weight::from_ref_time(11_810_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:1 w:1)
 	fn stop_sponsoring_contract() -> Weight {
-		Weight::from_ref_time(14_406_000 as u64)
+		Weight::from_ref_time(13_570_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -24,7 +24,10 @@
 	CommonCollectionOperations,
 };
 use sp_std::prelude::*;
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited};
+use up_data_structs::{
+	CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited,
+	PropertyPermission,
+};
 
 const SEED: u32 = 1;
 
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -25,7 +25,10 @@
 	benchmarking::{create_collection_raw, property_key, property_value},
 };
 use sp_std::prelude::*;
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited};
+use up_data_structs::{
+	CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited,
+	PropertyPermission,
+};
 
 const SEED: u32 = 1;
 
modifiedtests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth
--- a/tests/src/sub/appPromotion/appPromotion.test.ts
+++ b/tests/src/sub/appPromotion/appPromotion.test.ts
@@ -26,6 +26,13 @@
 let nominal: bigint;
 let palletAddress: string;
 let accounts: IKeyringPair[];
+let usedAccounts: IKeyringPair[] = [];
+
+function getAccount(accountsNumber: number) {
+  const accs = accounts.splice(0, accountsNumber);
+  usedAccounts.push(...accs);
+  return accs;
+}
 // App promotion periods:
 // LOCKING_PERIOD = 12 blocks of relay
 // UNLOCKING_PERIOD = 6 blocks of parachain
@@ -39,15 +46,29 @@
       palletAdmin = await privateKey('//PromotionAdmin');
       nominal = helper.balance.getOneTokenNominal();
 
-      const accountBalances = new Array(100);
-      accountBalances.fill(1000n);
+      const accountBalances = new Array(200).fill(1000n);
       accounts = await helper.arrange.createAccounts(accountBalances, donor); // create accounts-pool to speed up tests
     });
   });
 
+  afterEach(async () => {
+    await usingPlaygrounds(async (helper) => {
+      let unstakeTxs = [];
+      for (const account of usedAccounts) {
+        if (unstakeTxs.length === 3) {
+          await Promise.all(unstakeTxs);
+          unstakeTxs = [];
+        }
+        unstakeTxs.push(helper.staking.unstakeAll(account));
+      }
+      await Promise.all(unstakeTxs);
+      usedAccounts = [];
+    });
+  });
+
   describe('stake extrinsic', () => {
     itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {
-      const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
+      const [staker, recepient] = getAccount(2);
       const totalStakedBefore = await helper.staking.getTotalStaked();
 
       // Minimum stake amount is 100:
@@ -73,26 +94,48 @@
       expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);
     });
 
-    itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {
-      const [staker] = await helper.arrange.createAccounts([2000n], donor);
-      for (let i = 0; i < 10; i++) {
-        await helper.staking.stake(staker, 100n * nominal);
-      }
+    [
+      {unstake: 'unstakeAll' as const},
+      {unstake: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {
+        const [staker] = await helper.arrange.createAccounts([2000n], donor);
+        const ONE_STAKE = 100n * nominal;
+        for (let i = 0; i < 10; i++) {
+          await helper.staking.stake(staker, ONE_STAKE);
+        }
+
+        // can have 10 stakes
+        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);
+        expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);
 
-      // can have 10 stakes
-      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);
-      expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);
+        await expect(helper.staking.stake(staker, ONE_STAKE)).to.be.rejectedWith('appPromotion.NoPermission');
 
-      await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');
+        // After unstake can stake again
 
-      // After unstake can stake again
-      await helper.staking.unstake(staker);
-      await helper.staking.stake(staker, 100n * nominal);
-      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);
+        // CASE 1: unstakeAll
+        if (testCase.unstake === 'unstakeAll') {
+          await helper.staking.unstakeAll(staker);
+          expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);
+          await helper.staking.stake(staker, 100n * nominal);
+          expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);
+        }
+        // CASE 2: unstakePartial
+        else {
+          await helper.staking.unstakePartial(staker, ONE_STAKE);
+          expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);
+          await helper.staking.stake(staker, 100n * nominal);
+          expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(10);
+          await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');
+          await helper.staking.unstakePartial(staker, 150n * nominal);
+          expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);
+          expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(850n * nominal);
+        }
+      });
     });
 
     itSub('should allow to stake() if balance is locked with different id', async ({helper}) => {
-      const staker = accounts.pop()!;
+      const [staker] = getAccount(1);
 
       // staker has tokens locked with vesting id:
       await helper.balance.vestedTransfer(donor, staker.address, {start: 0n, period: 1n, periodCount: 1n, perPeriod: 200n * nominal});
@@ -109,7 +152,7 @@
       expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(1199n * nominal);
 
       // staker can unstake
-      await helper.staking.unstake(staker);
+      await helper.staking.unstakeAll(staker);
       expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1199n * nominal);
       const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
       await helper.wait.forParachainBlockNumber(pendingUnstake.block);
@@ -125,7 +168,7 @@
     });
 
     itSub('should not allow to stake(), if stake amount is more than total free balance minus locked by staking', async ({helper}) => {
-      const staker = accounts.pop()!;
+      const [staker] = getAccount(1);
 
       // Can't stake full balance because Alice needs to pay some fee
       await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected; // With('Arithmetic')
@@ -137,7 +180,7 @@
     });
 
     itSub('for different accounts in one block is possible', async ({helper}) => {
-      const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];
+      const crowd = getAccount(4);
 
       const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));
       await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;
@@ -147,132 +190,271 @@
     });
   });
 
-  describe('unstake extrinsic', () => {
-    itSub('should move tokens to "pendingUnstake" map and subtract it from totalStaked', async ({helper}) => {
-      const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
-      const totalStakedBefore = await helper.staking.getTotalStaked();
-      await helper.staking.stake(staker, 900n * nominal);
-      await helper.staking.unstake(staker);
+  describe('Unstaking', () => {
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should move tokens to "pendingUnstake" and subtract it from totalStaked`, async ({helper}) => {
+        const [staker, recepient] = getAccount(2);
+        const totalStakedBefore = await helper.staking.getTotalStaked();
+        const STAKE_AMOUNT = 900n * nominal;
 
-      // Right after unstake tokens are still locked
-      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: 900n * nominal, reasons: 'All'}]);
-      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 900n * nominal, feeFrozen: 900n * nominal});
-      // Staker can not transfer
-      await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');
-      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);
-      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
-      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);
+        await helper.staking.stake(staker, STAKE_AMOUNT);
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, STAKE_AMOUNT);
+
+        // Right after unstake tokens are still locked
+        expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);
+        expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: STAKE_AMOUNT, reasons: 'All'}]);
+        expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: STAKE_AMOUNT, feeFrozen: STAKE_AMOUNT});
+        // Staker can not transfer
+        await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');
+        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(STAKE_AMOUNT);
+        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
+        expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);
+      });
     });
 
-    itSub('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async ({helper}) => {
-      const staker = accounts.pop()!;
-      await helper.staking.stake(staker, 100n * nominal);
-      await helper.staking.unstake(staker);
-      const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should unlock balance after unlocking period ends and remove it from "pendingUnstake"`, async ({helper}) => {
+        const [staker] = getAccount(1);
+        await helper.staking.stake(staker, 100n * nominal);
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, 100n * nominal);
+        const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
 
-      // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
-      await helper.wait.forParachainBlockNumber(pendingUnstake.block);
-      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});
-      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
+        // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
+        await helper.wait.forParachainBlockNumber(pendingUnstake.block);
+        expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});
+        expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
 
-      // staker can transfer:
-      await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);
-      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);
+        // staker can transfer:
+        await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);
+        expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);
+      });
     });
 
-    itSub('should successfully unstake multiple stakes', async ({helper}) => {
-      const staker = accounts.pop()!;
-      await helper.staking.stake(staker, 100n * nominal);
-      await helper.staking.stake(staker, 200n * nominal);
-      await helper.staking.stake(staker, 300n * nominal);
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should successfully unstake multiple stakes`, async ({helper}) => {
+        const [staker] = getAccount(1);
+        await helper.staking.stake(staker, 100n * nominal);
+        await helper.staking.stake(staker, 200n * nominal);
+        await helper.staking.stake(staker, 300n * nominal);
+
+        // staked: [100, 200, 300]; unstaked: 0
+        let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
+        let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+        let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+        expect(totalPendingUnstake).to.be.deep.equal(0n);
+        expect(pendingUnstake).to.be.deep.equal([]);
+        expect(stakes[0].amount).to.equal(100n * nominal);
+        expect(stakes[1].amount).to.equal(200n * nominal);
+        expect(stakes[2].amount).to.equal(300n * nominal);
 
-      // staked: [100, 200, 300]; unstaked: 0
-      let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
-      let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
-      let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
-      expect(totalPendingUnstake).to.be.deep.equal(0n);
-      expect(pendingUnstake).to.be.deep.equal([]);
-      expect(stakes[0].amount).to.equal(100n * nominal);
-      expect(stakes[1].amount).to.equal(200n * nominal);
-      expect(stakes[2].amount).to.equal(300n * nominal);
+        // Can unstake multiple stakes
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, 600n * nominal);
 
-      // Can unstake multiple stakes
-      await helper.staking.unstake(staker);
-      pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
-      totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
-      stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
-      expect(totalPendingUnstake).to.be.equal(600n * nominal);
-      expect(stakes).to.be.deep.equal([]);
-      expect(pendingUnstake[0].amount).to.equal(600n * nominal);
+        pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+        totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
+        stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+        expect(totalPendingUnstake).to.be.equal(600n * nominal);
+        expect(stakes).to.be.deep.equal([]);
+        expect(pendingUnstake[0].amount).to.equal(600n * nominal);
 
-      expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});
-      expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
-      await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);
-      expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});
-      expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
+        expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});
+        expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
+        await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);
+        expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});
+        expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
+      });
     });
 
-    itSub('should not have any effects if no active stakes', async ({helper}) => {
-      const staker = accounts.pop()!;
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should not have any effects if no active stakes`, async ({helper}) => {
+        const [staker] = getAccount(1);
+
+        // unstake has no effect if no stakes at all
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');
+
+        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);
+        expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper
 
-      // unstake has no effect if no stakes at all
-      await helper.staking.unstake(staker);
-      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);
-      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper
+        // TODO stake() unstake() waitUnstaked() unstake();
 
-      // TODO stake() unstake() waitUnstaked() unstake();
+        // can't unstake if there are only pendingUnstakes
+        await helper.staking.stake(staker, 100n * nominal);
 
-      // can't unstake if there are only pendingUnstakes
-      await helper.staking.stake(staker, 100n * nominal);
-      await helper.staking.unstake(staker);
-      await helper.staking.unstake(staker);
+        if (testCase.method === 'unstakeAll') {
+          await helper.staking.unstakeAll(staker);
+          await helper.staking.unstakeAll(staker);
+        } else {
+          await helper.staking.unstakePartial(staker, 100n * nominal);
+          await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');
+        }
 
-      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
-      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
+        expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);
+        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
+        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
+      });
     });
 
-    itSub('should keep different unlocking block for each unlocking stake', async ({helper}) => {
-      const staker = accounts.pop()!;
-      await helper.staking.stake(staker, 100n * nominal);
-      await helper.staking.unstake(staker);
-      await helper.staking.stake(staker, 120n * nominal);
-      await helper.staking.unstake(staker);
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should create different pending-unlock for each unlocking stake`, async ({helper}) => {
+        const [staker] = getAccount(1);
+        await helper.staking.stake(staker, 100n * nominal);
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, 100n * nominal);
+        await helper.staking.stake(staker, 120n * nominal);
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, 120n * nominal);
 
-      const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
-      expect(unstakingPerBlock).has.length(2);
-      expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);
-      expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);
+        const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+        expect(unstakingPerBlock).has.length(2);
+        expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);
+        expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);
+        expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.equal(0);
+      });
     });
 
-    itSub('should be possible for 3 accounts in one block', async ({helper}) => {
-      const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should be possible for 3 accounts in one block`, async ({helper}) => {
+        const stakers = getAccount(3);
 
-      await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
-      await Promise.all(stakers.map(staker => helper.staking.unstake(staker)));
+        await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
+        await Promise.all(stakers.map(staker => {
+          return testCase.method === 'unstakeAll'
+            ? helper.staking.unstakeAll(staker)
+            : helper.staking.unstakePartial(staker, 100n * nominal);
+        }));
 
-      await Promise.all(stakers.map(async (staker) => {
-        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
-        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
-      }));
+        await Promise.all(stakers.map(async (staker) => {
+          expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
+          expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
+        }));
+      });
     });
 
     itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {
       if (!await helper.arrange.isDevNode()) {
-        const stakers = await helper.arrange.createAccounts([200n,200n,200n,200n,200n,200n,200n,200n,200n,200n], donor);
+        const stakers = getAccount(10);
 
         await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
-        const unstakingResults = await Promise.allSettled(stakers.map(staker => helper.staking.unstake(staker)));
+        const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => {
+          return i % 2 === 0
+            ? helper.staking.unstakeAll(staker)
+            : helper.staking.unstakePartial(staker, 100n * nominal);
+        }));
 
         const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');
         expect(successfulUnstakes).to.have.length(3);
       }
     });
+
+    itSub('Cannot partially unstake more than staked', async ({helper}) => {
+      const [staker] = getAccount(1);
+      // Staker stakes 300:
+      await helper.staking.stake(staker, 100n * nominal);
+      await helper.staking.stake(staker, 200n * nominal);
+
+      // cannot usntake 300.00000...1
+      await expect(helper.staking.unstakePartial(staker, 300n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');
+      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(2);
+
+      await helper.staking.unstakePartial(staker, 150n * nominal);
+      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);
+      await expect(helper.staking.unstakePartial(staker, 150n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');
+      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);
+
+      // nothing broken, can unstake full amount:
+      await helper.staking.unstakePartial(staker, 150n * nominal);
+      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(0);
+    });
+
+    itSub('Can partially unstake arbitrary amount', async ({helper}) => {
+      const [staker] = getAccount(1);
+      await helper.staking.stake(staker, 100n * nominal);
+      await helper.staking.stake(staker, 200n * nominal);
+
+      // 0. Staker cannot unstake negative amount
+      await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;
+
+      // 1. Staker can unstake 0 wei
+      await helper.staking.unstakePartial(staker, 0n);
+      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);
+      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal);
+      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);
+
+      // 2. Staker can unstake 1 wei
+      await helper.staking.unstakePartial(staker, 1n);
+      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);
+      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal - 1n);
+      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1n);
+      // 2.1 The oldest stake decreased:
+      let [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+      expect(stake1.amount).to.eq(100n * nominal - 1n);
+      expect(stake2.amount).to.eq(200n * nominal);
+
+      // 3. Staker can unstake all but 1 wei
+      await helper.staking.unstakePartial(staker, 100n * nominal - 2n);
+      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);
+      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(200n * nominal + 1n);
+      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(100n * nominal - 1n);
+      [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+      expect(stake1.amount).to.eq(1n);
+      expect(stake2.amount).to.eq(200n * nominal);
+    });
+
+    itSub('can mix different type of unstakes', async ({helper}) => {
+      const [staker] = getAccount(1);
+      await helper.staking.stake(staker, 100n * nominal);
+      await helper.staking.stake(staker, 200n * nominal);
+
+      await helper.staking.unstakePartial(staker, 50n * nominal);
+      await helper.staking.unstakeAll(staker);
+      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);
+      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);
+      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(300n * nominal);
+
+      const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+      await helper.wait.forParachainBlockNumber(unstake2.block);
+
+      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([]);
+      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});
+      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);
+      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);
+      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);
+      expect(await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).to.deep.eq([]);
+    });
   });
 
   describe('collection sponsoring', () => {
     itSub('should actually sponsor transactions', async ({helper}) => {
       const api = helper.getApi();
-      const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
+      const [collectionOwner, tokenSender, receiver] = getAccount(3);
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});
       const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});
       await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));
@@ -289,7 +471,7 @@
 
     itSub('can not be set by non admin', async ({helper}) => {
       const api = helper.getApi();
-      const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
+      const [collectionOwner, nonAdmin] = getAccount(2);
 
       const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
 
@@ -299,7 +481,7 @@
 
     itSub('should set pallet address as confirmed admin', async ({helper}) => {
       const api = helper.getApi();
-      const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];
+      const [collectionOwner, oldSponsor] = getAccount(2);
 
       // Can set sponsoring for collection without sponsor
       const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});
@@ -321,7 +503,7 @@
 
     itSub('can be overwritten by collection owner', async ({helper}) => {
       const api = helper.getApi();
-      const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];
+      const [collectionOwner, newSponsor] = getAccount(2);
       const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
       const collectionId = collection.collectionId;
 
@@ -340,7 +522,7 @@
     itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {
       const api = helper.getApi();
       const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};
-      const collectionWithLimits = await helper.nft.mintCollection(accounts.pop()!, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});
+      const collectionWithLimits = await helper.nft.mintCollection(getAccount(1)[0], {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});
 
       await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;
       expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);
@@ -348,7 +530,7 @@
 
     itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {
       const api = helper.getApi();
-      const collectionOwner = accounts.pop()!;
+      const [collectionOwner] = getAccount(1);
 
       // collection has never existed
       await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;
@@ -363,7 +545,7 @@
   describe('stopSponsoringCollection', () => {
     itSub('can not be called by non-admin', async ({helper}) => {
       const api = helper.getApi();
-      const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
+      const [collectionOwner, nonAdmin] = getAccount(2);
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
 
       await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
@@ -374,7 +556,7 @@
 
     itSub('should set sponsoring as disabled', async ({helper}) => {
       const api = helper.getApi();
-      const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];
+      const [collectionOwner, recepient] = getAccount(2);
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});
       const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});
 
@@ -392,7 +574,7 @@
 
     itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {
       const api = helper.getApi();
-      const collectionOwner = accounts.pop()!;
+      const [collectionOwner] = getAccount(1);
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});
       await collection.confirmSponsorship(collectionOwner);
 
@@ -402,7 +584,7 @@
     });
 
     itSub('should reject transaction if collection does not exist', async ({helper}) => {
-      const collectionOwner = accounts.pop()!;
+      const [collectionOwner] = getAccount(1);
       const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
 
       await collection.burn(collectionOwner);
@@ -476,7 +658,7 @@
     });
 
     itEth('can not be set by non admin', async ({helper}) => {
-      const nonAdmin = accounts.pop()!;
+      const [nonAdmin] = getAccount(1);
       const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();
       const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
       const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);
@@ -558,7 +740,7 @@
     });
 
     itEth('can not be called by non-admin', async ({helper}) => {
-      const nonAdmin = accounts.pop()!;
+      const [nonAdmin] = getAccount(1);
       const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();
       const flipper = await helper.eth.deployFlipper(contractOwner);
 
@@ -568,7 +750,7 @@
     });
 
     itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {
-      const nonAdmin = accounts.pop()!;
+      const [nonAdmin] = getAccount(1);
       const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();
       const flipper = await helper.eth.deployFlipper(contractOwner);
       const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);
@@ -580,12 +762,12 @@
 
   describe('payoutStakers', () => {
     itSub('can not be called by non admin', async ({helper}) => {
-      const nonAdmin = accounts.pop()!;
+      const [nonAdmin] = getAccount(1);
       await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');
     });
 
     itSub('should increase total staked', async ({helper}) => {
-      const staker = accounts.pop()!;
+      const [staker] = getAccount(1);
       const totalStakedBefore = await helper.staking.getTotalStaked();
       await helper.staking.stake(staker, 100n * nominal);
 
@@ -597,12 +779,12 @@
       const totalStakedAfter = await helper.staking.getTotalStaked();
       expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);
       // staker can unstake
-      await helper.staking.unstake(staker);
+      await helper.staking.unstakeAll(staker);
       expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));
     });
 
     itSub('should credit 0.05% for staking period', async ({helper}) => {
-      const staker = accounts.pop()!;
+      const [staker] = getAccount(1);
 
       await waitPromotionPeriodDoesntEnd(helper);
 
@@ -628,7 +810,7 @@
     });
 
     itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {
-      const staker = accounts.pop()!;
+      const [staker] = getAccount(1);
 
       await helper.staking.stake(staker, 100n * nominal);
       // wait for two rewards are available:
@@ -647,11 +829,11 @@
 
     itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {
       // staker unstakes before rewards been payed
-      const staker = accounts.pop()!;
+      const [staker] = getAccount(1);
       await helper.staking.stake(staker, 100n * nominal);
       const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
       await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
-      await helper.staking.unstake(staker);
+      await helper.staking.unstakeAll(staker);
 
       // so he did not receive any rewards
       const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);
@@ -662,7 +844,7 @@
     });
 
     itSub('should bring compound interest', async ({helper}) => {
-      const staker = accounts.pop()!;
+      const [staker] = getAccount(1);
 
       await helper.staking.stake(staker, 100n * nominal);
 
@@ -679,36 +861,48 @@
       expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));
     });
 
-    itSub.skip('can be paid 1000 rewards in a time', async ({helper}) => {
-      // all other stakes should be unstaked
-      const oneHundredStakers = await helper.arrange.createCrowd(100, 1050n, donor);
+    itSub('can calculate reward for tiny stake', async ({helper}) => {
+      const [staker] = getAccount(1);
+      await helper.staking.stake(staker, 100n * nominal);
+      await helper.staking.stake(staker, 100n * nominal);
+      await helper.staking.unstakePartial(staker, 100n * nominal - 1n);
 
-      // stakers stakes 10 times each
-      for (let i = 0; i < 10; i++) {
-        await Promise.all(oneHundredStakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
-      }
-      await helper.wait.newBlocks(40);
-      await helper.admin.payoutStakers(palletAdmin, 100);
+      const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));
+
+      const payouts = await helper.admin.payoutStakers(palletAdmin, 100);
+      const stakerPayout = payouts.find(p => p.staker === staker.address);
+      expect(stakerPayout!.stake).to.eq(100n * nominal + 1n);
     });
 
-    itSub.skip('can handle 40.000 rewards', async ({helper}) => {
-      const crowdStakes = async () => {
-        // each account in the crowd stakes 2 times
-        const crowd = await helper.arrange.createCrowd(500, 300n, donor);
-        await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));
-        await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));
-        //
-      };
+    itSub('can eventually pay all rewards', async ({helper}) => {
+      const stakers = getAccount(30);
+      // Create 30 stakes:
+      await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
 
-      for (let i = 0; i < 40; i++) {
-        await crowdStakes();
+      let unstakingTxs = [];
+      for (const staker of stakers) {
+        if (unstakingTxs.length == 3) {
+          await Promise.all(unstakingTxs);
+          unstakingTxs = [];
+        }
+        unstakingTxs.push(helper.staking.unstakePartial(staker, 100n * nominal - 1n));
       }
 
-      // TODO pay rewards for some period
+      const [staker] = getAccount(1);
+      await helper.staking.stake(staker, 100n * nominal);
+      const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));
+
+      let payouts;
+      do {
+        payouts = await helper.admin.payoutStakers(palletAdmin, 20);
+      } while (payouts.length !== 0);
     });
   });
 });
 
+
 function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {
   const DAY = 7200n;
   const ACCURACY = 1_000_000_000n;
modifiedtests/src/util/globalSetup.tsdiffbeforeafterboth
--- a/tests/src/util/globalSetup.ts
+++ b/tests/src/util/globalSetup.ts
@@ -29,8 +29,8 @@
         const api = helper.getApi();
         await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
         const nominal = helper.balance.getOneTokenNominal();
-        await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 1000n * nominal);
-        await helper.balance.transferToSubstrate(superuser, palletAddress, 1000n * nominal);
+        await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 10000n * nominal);
+        await helper.balance.transferToSubstrate(superuser, palletAddress, 10000n * nominal);
         await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [api.tx.configuration
           .setAppPromotionConfigurationOverride({
             recalculationInterval: LOCKING_PERIOD,
modifiedtests/src/util/index.tsdiffbeforeafterboth
--- a/tests/src/util/index.ts
+++ b/tests/src/util/index.ts
@@ -94,7 +94,7 @@
 };
 
 export const MINIMUM_DONOR_FUND = 100_000n;
-export const DONOR_FUNDING = 1_000_000n;
+export const DONOR_FUNDING = 2_000_000n;
 
 // App-promotion periods:
 export const LOCKING_PERIOD = 12n; // 12 blocks of relay
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -20,7 +20,8 @@
         event: IEvent;
       }[];
   },
-  moduleError?: string;
+  blockHash: string,
+  moduleError?: string | object;
 }
 
 export interface ISubscribeBlockEventsData {
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -214,7 +214,7 @@
       accounts.push(recipient);
       if (balance !== 0n) {
         const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);
-        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));
+        transactions.push(this.helper.signTransaction(donor, tx, {nonce, era: 0}, 'account generation'));
         nonce++;
       }
     }
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -6,7 +6,8 @@
 /* eslint-disable no-prototype-builtins */
 
 import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';
-import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';
+import {SignerOptions} from '@polkadot/api/types/submittable';
+import {ApiInterfaceEvents} from '@polkadot/api/types';
 import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';
 import {IKeyringPair} from '@polkadot/types/types';
 import {hexToU8a} from '@polkadot/util/hex';
@@ -561,7 +562,7 @@
           if (status === this.transactionStatus.SUCCESS) {
             this.logger.log(`${label} successful`);
             unsub();
-            resolve({result, status});
+            resolve({result, status, blockHash: result.status.asInBlock.toHuman()});
           } else if (status === this.transactionStatus.FAIL) {
             let moduleError = null;
 
@@ -672,8 +673,15 @@
       params,
     } as IUniqueHelperLog;
 
+    let errorMessage = '';
+
     if(result.status !== this.transactionStatus.SUCCESS) {
-      if (result.moduleError) log.moduleError = result.moduleError;
+      if (result.moduleError) {
+        errorMessage = typeof result.moduleError === 'string'
+          ? result.moduleError
+          : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;
+        log.moduleError = errorMessage;
+      }
       else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;
     }
     if(events.length > 0) log.events = events;
@@ -681,7 +689,7 @@
     this.chainLog.push(log);
 
     if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {
-      if (result.moduleError) throw Error(`${result.moduleError}`);
+      if (result.moduleError) throw Error(`${errorMessage}`);
       else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));
     }
     return result;
@@ -2657,20 +2665,45 @@
   }
 
   /**
-   * Unstake tokens for App Promotion
+   * Unstake all staked tokens
    * @param signer keyring of signer
    * @param amountToUnstake amount of tokens to unstake
    * @param label extra label for log
-   * @returns block number where balances will be unlocked
+   * @returns block hash where unstake happened
    */
-  async unstake(signer: TSigner, label?: string): Promise<number> {
+  async unstakeAll(signer: TSigner, label?: string): Promise<string> {
     if(typeof label === 'undefined') label = `${signer.address}`;
-    const _unstakeResult = await this.helper.executeExtrinsic(
-      signer, 'api.tx.appPromotion.unstake',
+    const unstakeResult = await this.helper.executeExtrinsic(
+      signer, 'api.tx.appPromotion.unstakeAll',
       [], true,
     );
-    // TODO extract block number fron events
-    return 1;
+    return unstakeResult.blockHash;
+  }
+
+  /**
+   * Unstake the part of a staked tokens
+   * @param signer keyring of signer
+   * @param amount amount of tokens to unstake
+   * @param label extra label for log
+   * @returns block hash where unstake happened
+   */
+  async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {
+    if(typeof label === 'undefined') label = `${signer.address}`;
+    const unstakeResult = await this.helper.executeExtrinsic(
+      signer, 'api.tx.appPromotion.unstakePartial',
+      [amount], true,
+    );
+    return unstakeResult.blockHash;
+  }
+
+  /**
+   * Get total number of active stakes
+   * @param address substrate address
+   * @returns {number}
+   */
+  async getStakesNumber(address: ICrossAccountId): Promise<number> {
+    if (address.Ethereum) throw Error('only substrate address');
+    return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();
   }
 
   /**