git.delta.rocks / unique-network / refs/commits / da133e176114

difftreelog

refac(app-promo): impl for `unstake_all` & `unstake_partial` extrinsics

PraetorP2023-02-14parent: #59f9c8e.patch.diff
in: master
Added benchmark for `unstake_partial` extrinsic

7 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()).map_err(|e| e.error)?;
 			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
before · 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	}212213	/// Stores the total staked amount.214	#[pallet::storage]215	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;216217	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.218	#[pallet::storage]219	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;220221	/// Stores the amount of tokens staked by account in the blocknumber.222	///223	/// * **Key1** - Staker account.224	/// * **Key2** - Relay block number when the stake was made.225	/// * **(Balance, BlockNumber)** - Balance of the stake.226	/// The number of the relay block in which we must perform the interest recalculation227	#[pallet::storage]228	pub type Staked<T: Config> = StorageNMap<229		Key = (230			Key<Blake2_128Concat, T::AccountId>,231			Key<Twox64Concat, T::BlockNumber>,232		),233		Value = (BalanceOf<T>, T::BlockNumber),234		QueryKind = ValueQuery,235	>;236237	/// Stores number of stake records for an `Account`.238	///239	/// * **Key** - Staker account.240	/// * **Value** - Amount of stakes.241	#[pallet::storage]242	pub type StakesPerAccount<T: Config> =243		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;244245	/// Pending unstake records for an `Account`.246	///247	/// * **Key** - Staker account.248	/// * **Value** - Amount of stakes.249	#[pallet::storage]250	pub type PendingUnstake<T: Config> = StorageMap<251		_,252		Twox64Concat,253		T::BlockNumber,254		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,255		ValueQuery,256	>;257258	/// Stores a key for record for which the revenue recalculation was performed.259	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.260	#[pallet::storage]261	#[pallet::getter(fn get_next_calculated_record)]262	pub type PreviousCalculatedRecord<T: Config> =263		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;264265	#[pallet::storage]266	pub(crate) type UpgradedToReserves<T: Config> =267		StorageValue<Value = bool, QueryKind = ValueQuery>;268269	#[pallet::hooks]270	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {271		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize272		/// implies the execution of a strictly limited number of relatively lightweight operations.273		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.274		fn on_initialize(current_block_number: T::BlockNumber) -> Weight275		where276			<T as frame_system::Config>::BlockNumber: From<u32>,277		{278			let block_pending = PendingUnstake::<T>::take(current_block_number);279			let counter = block_pending.len() as u32;280281			if !block_pending.is_empty() {282				block_pending.into_iter().for_each(|(staker, amount)| {283					Self::get_locked_balance(&staker).map(|b| {284						let new_state = b.amount.checked_sub(&amount).unwrap_or_default();285						Self::set_lock_unchecked(&staker, new_state);286					});287				});288			}289290			<T as Config>::WeightInfo::on_initialize(counter)291		}292293		fn on_runtime_upgrade() -> Weight {294			let mut consumed_weight = Weight::zero();295			let mut add_weight = |reads, writes, weight| {296				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);297				consumed_weight += weight;298			};299300			if <UpgradedToReserves<T>>::get() {301				add_weight(1, 0, Weight::zero());302				return consumed_weight;303			} else {304				add_weight(1, 1, Weight::zero());305				<UpgradedToReserves<T>>::set(true);306			}307			<PendingUnstake<T>>::drain().for_each(|(_, v)| {308				add_weight(1, 1, Weight::zero());309				v.into_iter().for_each(|(staker, amount)| {310					<<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(311						&staker, amount,312					);313					add_weight(1, 1, Weight::zero());314				});315			});316317			consumed_weight318		}319320		#[cfg(feature = "try-runtime")]321		fn pre_upgrade() -> Result<Vec<u8>, &'static str> {322			use sp_std::collections::btree_map::BTreeMap;323			if <UpgradedToReserves<T>>::get() {324				return Ok(Default::default());325			}326			// Staker -> (total amount of reserved balance, reserved by promotion);327			let mut pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =328				BTreeMap::new();329330			<PendingUnstake<T>>::iter().for_each(|(_, v)| {331				v.into_iter().for_each(|(staker, amount)| {332					if let Some((_, reserved_balance)) = pre_state.get_mut(&staker) {333						*reserved_balance += amount;334					} else {335						let total_reserve = <<T as Config>::Currency as ReservableCurrency<336							T::AccountId,337						>>::reserved_balance(&staker);338						pre_state.insert(staker, (total_reserve, amount));339					}340				})341			});342343			Ok(pre_state.encode())344		}345346		#[cfg(feature = "try-runtime")]347		fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {348			use sp_std::collections::btree_map::BTreeMap;349350			if <UpgradedToReserves<T>>::get() {351				return Ok(());352			}353354			ensure!(355				<PendingUnstake<T>>::iter().collect::<Vec<_>>().len() == 0,356				"pendingUnstake storage isn't empty"357			);358359			let mut is_ok = true;360361			let pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =362				Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;363			for (staker, (total_reserved, reserved_by_promo)) in pre_state.into_iter() {364				let new_state_reserve = <<T as Config>::Currency as ReservableCurrency<365					T::AccountId,366				>>::reserved_balance(&staker);367				if new_state_reserve != total_reserved - reserved_by_promo {368					is_ok = false;369					log::error!(370								"Incorrect reserved balance for {:?}. New balance: {:?}. Before runtime upgrade: total reserve - {:?}, reserved by promo - {:?}",371								staker, new_state_reserve, total_reserved, reserved_by_promo372							);373				}374			}375376			if is_ok {377				Ok(())378			} else {379				Err("Incorrect balance for some of stakers... See logs")380			}381		}382	}383384	#[pallet::call]385	impl<T: Config> Pallet<T>386	where387		T::BlockNumber: From<u32> + Into<u32>,388		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,389	{390		/// Sets an address as the the admin.391		///392		/// # Permissions393		///394		/// * Sudo395		///396		/// # Arguments397		///398		/// * `admin`: account of the new admin.399		#[pallet::call_index(0)]400		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]401		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {402			ensure_root(origin)?;403404			<Admin<T>>::set(Some(admin.as_sub().to_owned()));405406			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));407408			Ok(())409		}410411		/// Stakes the amount of native tokens.412		/// Sets `amount` to the locked state.413		/// The maximum number of stakes for a staker is 10.414		///415		/// # Arguments416		///417		/// * `amount`: in native tokens.418		#[pallet::call_index(1)]419		#[pallet::weight(<T as Config>::WeightInfo::stake())]420		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {421			let staker_id = ensure_signed(staker)?;422423			ensure!(424				StakesPerAccount::<T>::get(&staker_id) < 10,425				Error::<T>::NoPermission426			);427428			ensure!(429				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),430				ArithmeticError::Underflow431			);432			let config = <PalletConfiguration<T>>::get();433434			let balance =435				<<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);436437			// checks that we can lock `amount` on the `staker` account.438			ensure!(439				amount440					<= match Self::get_locked_balance(&staker_id) {441						Some(lock) => balance442							.checked_sub(&lock.amount)443							.ok_or(ArithmeticError::Underflow)?,444						None => balance,445					},446				ArithmeticError::Underflow447			);448449			Self::add_lock_balance(&staker_id, amount)?;450451			let block_number = T::RelayBlockNumberProvider::current_block_number();452453			// Calculation of the number of recalculation periods,454			// after how much the first interest calculation should be performed for the stake455			let recalculate_after_interval: T::BlockNumber =456				if block_number % config.recalculation_interval == 0u32.into() {457					1u32.into()458				} else {459					2u32.into()460				};461462			// Сalculation of the number of the relay block463			// in which it is necessary to accrue remuneration for the stake.464			let recalc_block = (block_number / config.recalculation_interval465				+ recalculate_after_interval)466				* config.recalculation_interval;467468			<Staked<T>>::insert((&staker_id, block_number), {469				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));470				balance_and_recalc_block.0 = balance_and_recalc_block471					.0472					.checked_add(&amount)473					.ok_or(ArithmeticError::Overflow)?;474				balance_and_recalc_block.1 = recalc_block;475				balance_and_recalc_block476			});477478			<TotalStaked<T>>::set(479				<TotalStaked<T>>::get()480					.checked_add(&amount)481					.ok_or(ArithmeticError::Overflow)?,482			);483484			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);485486			Self::deposit_event(Event::Stake(staker_id, amount));487488			Ok(())489		}490491		/// Unstakes all stakes.492		/// Moves the sum of all stakes to the `reserved` state.493		/// After the end of `PendingInterval` this sum becomes completely494		/// free for further use.495		#[pallet::call_index(2)]496		#[pallet::weight(<T as Config>::WeightInfo::unstake())]497		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResultWithPostInfo {498			let staker_id = ensure_signed(staker)?;499			let config = <PalletConfiguration<T>>::get();500501			// calculate block number where the sum would be free502			let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;503504			let mut pendings = <PendingUnstake<T>>::get(block);505506			// checks that we can do unreserve stakes in the block507			ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);508509			let mut total_stakes = 0u64;510511			let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))512				.map(|(_, (amount, _))| {513					total_stakes += 1;514					amount515				})516				.sum();517518			if total_staked.is_zero() {519				return Ok(None::<Weight>.into()); // TO-DO520			}521522			pendings523				.try_push((staker_id.clone(), total_staked))524				.map_err(|_| Error::<T>::PendingForBlockOverflow)?;525526			<PendingUnstake<T>>::insert(block, pendings);527528			TotalStaked::<T>::set(529				TotalStaked::<T>::get()530					.checked_sub(&total_staked)531					.ok_or(ArithmeticError::Underflow)?,532			);533534			StakesPerAccount::<T>::remove(&staker_id);535536			Self::deposit_event(Event::Unstake(staker_id, total_staked));537538			Ok(None::<Weight>.into())539		}540541		/// Unstakes all stakes.542		/// Moves the sum of all stakes to the `reserved` state.543		/// After the end of `PendingInterval` this sum becomes completely544		/// free for further use.545		#[pallet::call_index(8)]546		#[pallet::weight(<T as Config>::WeightInfo::unstake())]547		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {548			let staker_id = ensure_signed(staker)?;549550			Self::partial_unstake(&staker_id, amount)551		}552553		/// Sets the pallet to be the sponsor for the collection.554		///555		/// # Permissions556		///557		/// * Pallet admin558		///559		/// # Arguments560		///561		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`562		#[pallet::call_index(3)]563		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]564		pub fn sponsor_collection(565			admin: OriginFor<T>,566			collection_id: CollectionId,567		) -> DispatchResult {568			let admin_id = ensure_signed(admin)?;569			ensure!(570				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,571				Error::<T>::NoPermission572			);573574			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)575		}576577		/// Removes the pallet as the sponsor for the collection.578		/// Returns [`NoPermission`][`Error::NoPermission`]579		/// if the pallet wasn't the sponsor.580		///581		/// # Permissions582		///583		/// * Pallet admin584		///585		/// # Arguments586		///587		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`588		#[pallet::call_index(4)]589		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]590		pub fn stop_sponsoring_collection(591			admin: OriginFor<T>,592			collection_id: CollectionId,593		) -> DispatchResult {594			let admin_id = ensure_signed(admin)?;595596			ensure!(597				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,598				Error::<T>::NoPermission599			);600601			ensure!(602				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?603					== Self::account_id(),604				<Error<T>>::NoPermission605			);606			T::CollectionHandler::remove_collection_sponsor(collection_id)607		}608609		/// Sets the pallet to be the sponsor for the contract.610		///611		/// # Permissions612		///613		/// * Pallet admin614		///615		/// # Arguments616		///617		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`618		#[pallet::call_index(5)]619		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]620		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {621			let admin_id = ensure_signed(admin)?;622623			ensure!(624				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,625				Error::<T>::NoPermission626			);627628			T::ContractHandler::set_sponsor(629				T::CrossAccountId::from_sub(Self::account_id()),630				contract_id,631			)632		}633634		/// Removes the pallet as the sponsor for the contract.635		/// Returns [`NoPermission`][`Error::NoPermission`]636		/// if the pallet wasn't the sponsor.637		///638		/// # Permissions639		///640		/// * Pallet admin641		///642		/// # Arguments643		///644		/// * `contract_id`: the contract address that is sponsored by `pallet_id`645		#[pallet::call_index(6)]646		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]647		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {648			let admin_id = ensure_signed(admin)?;649650			ensure!(651				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,652				Error::<T>::NoPermission653			);654655			ensure!(656				T::ContractHandler::sponsor(contract_id)?657					.ok_or(<Error<T>>::SponsorNotSet)?658					.as_sub() == &Self::account_id(),659				<Error<T>>::NoPermission660			);661			T::ContractHandler::remove_contract_sponsor(contract_id)662		}663664		/// Recalculates interest for the specified number of stakers.665		/// If all stakers are not recalculated, the next call of the extrinsic666		/// will continue the recalculation, from those stakers for whom this667		/// was not perform in last call.668		///669		/// # Permissions670		///671		/// * Pallet admin672		///673		/// # Arguments674		///675		/// * `stakers_number`: the number of stakers for which recalculation will be performed676		#[pallet::call_index(7)]677		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]678		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {679			let admin_id = ensure_signed(admin)?;680681			ensure!(682				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,683				Error::<T>::NoPermission684			);685			let config = <PalletConfiguration<T>>::get();686687			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);688689			ensure!(690				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,691				Error::<T>::NoPermission692			);693694			// calculate the number of the current recalculation block,695			// this is necessary in order to understand which stakers we should calculate interest696			let current_recalc_block = Self::get_current_recalc_block(697				T::RelayBlockNumberProvider::current_block_number(),698				&config,699			);700701			// calculate the number of the next recalculation block,702			// this value is set for the stakers to whom the recalculation will be performed703			let next_recalc_block = current_recalc_block + config.recalculation_interval;704705			let mut storage_iterator = Self::get_next_calculated_key()706				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));707708			PreviousCalculatedRecord::<T>::set(None);709710			{711				// Address handled in the last payout loop iteration (below)712				let last_id = RefCell::new(None);713				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration714				let mut last_staked_calculated_block = Default::default();715				// Reward balance for the address in the iteration716				let income_acc = RefCell::new(BalanceOf::<T>::default());717				// Staked balance for the address in the iteration (before stake is recalculated)718				let amount_acc = RefCell::new(BalanceOf::<T>::default());719720				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout721				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout722				// loop switches to handling the next staker address:723				//   1. Transfer full reward amount to the payee724				//   2. Lock the reward in staking lock725				//   3. Update TotalStaked amount726				//   4. Issue StakingRecalculation event727				let flush_stake = || -> DispatchResult {728					if let Some(last_id) = &*last_id.borrow() {729						if !income_acc.borrow().is_zero() {730							<<T as Config>::Currency as Currency<T::AccountId>>::transfer(731								&T::TreasuryAccountId::get(),732								last_id,733								*income_acc.borrow(),734								ExistenceRequirement::KeepAlive,735							)?;736737							Self::add_lock_balance(last_id, *income_acc.borrow())?;738							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {739								*staked = staked740									.checked_add(&*income_acc.borrow())741									.ok_or(ArithmeticError::Overflow)?;742								Ok(())743							})?;744745							Self::deposit_event(Event::StakingRecalculation(746								last_id.clone(),747								*amount_acc.borrow(),748								*income_acc.borrow(),749							));750						}751752						*income_acc.borrow_mut() = BalanceOf::<T>::default();753						*amount_acc.borrow_mut() = BalanceOf::<T>::default();754					}755					Ok(())756				};757758				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation759				// iterations in one extrinsic call760				//761				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)762				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out763				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)764				while let Some((765					(current_id, staked_block),766					(amount, next_recalc_block_for_stake),767				)) = storage_iterator.next()768				{769					// last_id is not equal current_id when we switch to handling a new staker address770					// or just start handling the very first address. In the latter case last_id will be None and771					// flush_stake will do nothing772					if last_id.borrow().as_ref() != Some(&current_id) {773						if stakers_number > 0 {774							flush_stake()?;775							*last_id.borrow_mut() = Some(current_id.clone());776							stakers_number -= 1;777						}778						// Break out if we reached the address limit779						else {780							if let Some(staker) = &*last_id.borrow() {781								// Save the last calculated record to pick up in the next extrinsic call782								PreviousCalculatedRecord::<T>::set(Some((783									staker.clone(),784									last_staked_calculated_block,785								)));786							}787							break;788						};789					};790791					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount792					if current_recalc_block >= next_recalc_block_for_stake {793						*amount_acc.borrow_mut() += amount;794						Self::recalculate_and_insert_stake(795							&current_id,796							staked_block,797							next_recalc_block,798							amount,799							((current_recalc_block - next_recalc_block_for_stake)800								/ config.recalculation_interval)801								.into() + 1,802							&mut *income_acc.borrow_mut(),803						);804					}805					last_staked_calculated_block = staked_block;806				}807				flush_stake()?;808			}809810			Ok(())811		}812	}813}814815impl<T: Config> Pallet<T> {816	/// The account address of the app promotion pot.817	///818	/// This actually does computation. If you need to keep using it, then make sure you cache the819	/// value and only call this once.820	pub fn account_id() -> T::AccountId {821		T::PalletId::get().into_account_truncating()822	}823824	fn partial_unstake(staker_id: &T::AccountId, unstaked_balance: BalanceOf<T>) -> DispatchResult {825		826		if unstaked_balance == Default::default() {827			return Ok(());828		}829		830		let config = <PalletConfiguration<T>>::get();831832		// calculate block number where the sum would be free833		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;834835		let mut pendings = <PendingUnstake<T>>::get(unpending_block);836837		// checks that we can do unreserve stakes in the block838		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);839840		let mut stakes = Staked::<T>::iter_prefix((staker_id,)).collect::<Vec<_>>();841842		let total_staked = stakes843			.iter()844			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {845				acc + *balance846			});847848		ensure!(total_staked >= unstaked_balance, ArithmeticError::Underflow);849850		<TotalStaked<T>>::set(851			<TotalStaked<T>>::get()852				.checked_sub(&unstaked_balance)853				.ok_or(ArithmeticError::Underflow)?,854		);855856		stakes.sort_by_key(|(block, _)| *block);857858		let mut acc_amount = unstaked_balance;859		let mut will_deleted_stakes_count = 0u8;860861		let changed_stakes = stakes862			.into_iter()863			.map_while(|(block, (balance_per_block, recalc_block))| {864				if acc_amount == <BalanceOf<T>>::default() {865					return None;866				}867				if acc_amount < balance_per_block {868					let res = (block, (balance_per_block - acc_amount, recalc_block));869					acc_amount = <BalanceOf<T>>::default();870					return Some(res);871				} else {872					acc_amount -= balance_per_block;873					will_deleted_stakes_count += 1;874					return Some((block, (<BalanceOf<T>>::default(), recalc_block)));875				}876			})877			.collect::<Vec<_>>();878879		pendings880			.try_push((staker_id.clone(), unstaked_balance))881			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;882883		StakesPerAccount::<T>::try_mutate(staker_id, |stakes| -> DispatchResult {884			*stakes = stakes885				.checked_sub(will_deleted_stakes_count)886				.ok_or(ArithmeticError::Underflow)?;887			Ok(())888		})?;889890		changed_stakes891			.iter()892			.for_each(|(staked_block, (current_stake_state, _))| {893				if current_stake_state == &Default::default() {894					<Staked<T>>::remove((staker_id, staked_block));895				} else {896					<Staked<T>>::mutate((staker_id, staked_block), |(old_stake_state, _)| {897						*old_stake_state = *current_stake_state898					});899				}900			});901902		<PendingUnstake<T>>::insert(unpending_block, pendings);903904		Self::deposit_event(Event::Unstake(staker_id.clone(), total_staked));905906		Ok(())907	}908909	/// Adds the balance to locked by the pallet.910	///911	/// - `staker`: staker account.912	/// - `amount`: amount of added locked funds.913	fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {914		Self::get_locked_balance(staker)915			.map_or(<BalanceOf<T>>::default(), |l| l.amount)916			.checked_add(&amount)917			.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))918			.ok_or(ArithmeticError::Overflow.into())919	}920921	/// Sets the new state of a balance locked by the pallet.922	///923	/// - `staker`: staker account.924	/// - `amount`: amount of locked funds.925	fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {926		if amount.is_zero() {927			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(928				LOCK_IDENTIFIER,929				&staker,930			);931		} else {932			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(933				LOCK_IDENTIFIER,934				staker,935				amount,936				WithdrawReasons::all(),937			)938		}939	}940941	/// Returns the balance locked by the pallet for the staker.942	///943	/// - `staker`: staker account.944	pub fn get_locked_balance(945		staker: impl EncodeLike<T::AccountId>,946	) -> Option<BalanceLock<BalanceOf<T>>> {947		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)948			.into_iter()949			.find(|l| l.id == LOCK_IDENTIFIER)950	}951952	/// Returns the total staked balance for the staker.953	///954	/// - `staker`: staker account.955	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {956		let staked = Staked::<T>::iter_prefix((staker,))957			.into_iter()958			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {959				acc + amount960			});961		if staked != <BalanceOf<T>>::default() {962			Some(staked)963		} else {964			None965		}966	}967968	/// Returns all relay block numbers when stake was made,969	/// the amount of the stake.970	///971	/// - `staker`: staker account.972	pub fn total_staked_by_id_per_block(973		staker: impl EncodeLike<T::AccountId>,974	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {975		let mut staked = Staked::<T>::iter_prefix((staker,))976			.into_iter()977			.map(|(block, (amount, _))| (block, amount))978			.collect::<Vec<_>>();979		staked.sort_by_key(|(block, _)| *block);980		if !staked.is_empty() {981			Some(staked)982		} else {983			None984		}985	}986987	/// Returns the total staked balance for the staker.988	/// If `staker` is `None`, returns the total amount staked.989	/// - `staker`: staker account.990	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {991		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {992			Self::total_staked_by_id(s.as_sub())993		})994	}995996	// pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {997	// 	Self::get_locked_balance(staker.as_sub())998	// 		.map(|l| l.amount)999	// 		.unwrap_or_default()1000	// }10011002	/// Returns all relay block numbers when stake was made,1003	/// the amount of the stake.1004	///1005	/// - `staker`: staker account.1006	pub fn cross_id_total_staked_per_block(1007		staker: T::CrossAccountId,1008	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1009		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1010	}10111012	fn recalculate_and_insert_stake(1013		staker: &T::AccountId,1014		staked_block: T::BlockNumber,1015		next_recalc_block: T::BlockNumber,1016		base: BalanceOf<T>,1017		iters: u32,1018		income_acc: &mut BalanceOf<T>,1019	) {1020		let income = Self::calculate_income(base, iters);10211022		base.checked_add(&income).map(|res| {1023			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1024			*income_acc += income;1025		});1026	}10271028	fn calculate_income<I>(base: I, iters: u32) -> I1029	where1030		I: EncodeLike<BalanceOf<T>> + Balance,1031	{1032		let config = <PalletConfiguration<T>>::get();1033		let mut income = base;10341035		(0..iters).for_each(|_| income += config.interval_income * income);10361037		income - base1038	}10391040	/// Get relay block number rounded down to multiples of config.recalculation_interval.1041	/// We need it to reward stakers in integer parts of recalculation_interval1042	fn get_current_recalc_block(1043		current_relay_block: T::BlockNumber,1044		config: &PalletConfiguration<T>,1045	) -> T::BlockNumber {1046		(current_relay_block / config.recalculation_interval) * config.recalculation_interval1047	}10481049	fn get_next_calculated_key() -> Option<Vec<u8>> {1050		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))1051	}1052}10531054impl<T: Config> Pallet<T>1055where1056	<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,1057{1058	/// Returns the amount reserved by the pending.1059	/// If `staker` is `None`, returns the total pending.1060	///1061	/// -`staker`: staker account.1062	///1063	/// Since user funds are not transferred anywhere by staking, overflow protection is provided1064	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1065	/// the staker must have more funds on his account than the maximum set for `Balance` type.1066	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1067		staker.map_or(1068			PendingUnstake::<T>::iter_values()1069				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1070				.sum(),1071			|s| {1072				PendingUnstake::<T>::iter_values()1073					.flatten()1074					.filter_map(|(id, amount)| {1075						if id == *s.as_sub() {1076							Some(amount)1077						} else {1078							None1079						}1080					})1081					.sum()1082			},1083		)1084	}10851086	/// Returns all parachain block numbers when unreserve is expected,1087	/// the amount of the unreserved funds.1088	///1089	/// - `staker`: staker account.1090	pub fn cross_id_pending_unstake_per_block(1091		staker: T::CrossAccountId,1092	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1093		let mut unsorted_res = vec![];1094		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1095			pendings.into_iter().for_each(|(id, amount)| {1096				if id == *staker.as_sub() {1097					unsorted_res.push((block, amount));1098				};1099			})1100		});11011102		unsorted_res.sort_by_key(|(block, _)| *block);1103		unsorted_res1104	}1105}
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-14, 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_562_275 as u64)
+			// Standard Error: 21_950
+			.saturating_add(Weight::from_ref_time(7_177_129 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_146_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_035_000 as u64)
+			// Standard Error: 19_434
+			.saturating_add(Weight::from_ref_time(47_251_111 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_078_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_038_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(48_863_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(14_808_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_587_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_791_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_576_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_562_275 as u64)
+			// Standard Error: 21_950
+			.saturating_add(Weight::from_ref_time(7_177_129 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_146_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_035_000 as u64)
+			// Standard Error: 19_434
+			.saturating_add(Weight::from_ref_time(47_251_111 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_078_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_038_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(48_863_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(14_808_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_587_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_791_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_576_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
modifiedtests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth
--- a/tests/src/sub/appPromotion/appPromotion.test.ts
+++ b/tests/src/sub/appPromotion/appPromotion.test.ts
@@ -247,7 +247,7 @@
         // 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('Arithmetic: Underflow');
+          : 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
@@ -262,7 +262,7 @@
           await helper.staking.unstakeAll(staker);
         } else {
           await helper.staking.unstakePartial(staker, 100n * nominal);
-          await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('Arithmetic: Underflow');
+          await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');
         }
 
         expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);