git.delta.rocks / unique-network / refs/commits / 76541c4e15e0

difftreelog

fix test

PraetorP2022-09-08parent: #35da4ee.patch.diff
in: master

2 files changed

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 promotion18//!19//! The app promotion pallet is designed to ... .20//!21//! ## Interface22//!23//! ### Dispatchable Functions24//!2526// #![recursion_limit = "1024"]27#![cfg_attr(not(feature = "std"), no_std)]2829#[cfg(feature = "runtime-benchmarks")]30mod benchmarking;31#[cfg(test)]32mod tests;33pub mod types;34pub mod weights;3536use sp_std::{37	vec::{Vec},38	vec,39	iter::Sum,40	borrow::ToOwned,41	cell::RefCell,42};43use sp_core::H160;44use codec::EncodeLike;45use pallet_balances::BalanceLock;46pub use types::*;4748use up_data_structs::CollectionId;4950use frame_support::{51	dispatch::{DispatchResult},52	traits::{53		Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,54	},55	ensure,56};5758use weights::WeightInfo;5960pub use pallet::*;61use pallet_evm::account::CrossAccountId;62use sp_runtime::{63	Perbill,64	traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},65	ArithmeticError,66};6768pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";6970const PENDING_LIMIT_PER_BLOCK: u32 = 3;7172type BalanceOf<T> =73	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;7475#[frame_support::pallet]76pub mod pallet {77	use super::*;78	use frame_support::{79		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,80		traits::ReservableCurrency,81	};82	use frame_system::pallet_prelude::*;8384	#[pallet::config]85	pub trait Config: frame_system::Config + pallet_evm::account::Config {86		/// Type to interact with the native token87		type Currency: ExtendedLockableCurrency<Self::AccountId>88			+ ReservableCurrency<Self::AccountId>;8990		/// Type for interacting with collections91		type CollectionHandler: CollectionHandler<92			AccountId = Self::AccountId,93			CollectionId = CollectionId,94		>;9596		/// Type for interacting with conrtacts97		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;9899		/// ID for treasury100		type TreasuryAccountId: Get<Self::AccountId>;101102		/// The app's pallet id, used for deriving its sovereign account ID.103		#[pallet::constant]104		type PalletId: Get<PalletId>;105106		/// In relay blocks.107		#[pallet::constant]108		type RecalculationInterval: Get<Self::BlockNumber>;109110		/// In parachain blocks.111		#[pallet::constant]112		type PendingInterval: Get<Self::BlockNumber>;113114		/// Rate of return for interval in blocks defined in `RecalculationInterval`.115		#[pallet::constant]116		type IntervalIncome: Get<Perbill>;117118		/// Decimals for the `Currency`.119		#[pallet::constant]120		type Nominal: Get<BalanceOf<Self>>;121122		/// Weight information for extrinsics in this pallet.123		type WeightInfo: WeightInfo;124125		// The relay block number provider126		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;127128		/// Events compatible with [`frame_system::Config::Event`].129		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;130	}131132	#[pallet::pallet]133	#[pallet::generate_store(pub(super) trait Store)]134	pub struct Pallet<T>(_);135136	#[pallet::event]137	#[pallet::generate_deposit(fn deposit_event)]138	pub enum Event<T: Config> {139		/// Staking recalculation was performed140		///141		/// # Arguments142		/// * AccountId: ID of the staker.143		/// * Balance : recalculation base144		/// * Balance : total income145		StakingRecalculation(146			/// An recalculated staker147			T::AccountId,148			/// Base on which interest is calculated149			BalanceOf<T>,150			/// Amount of accrued interest151			BalanceOf<T>,152		),153		154		/// Staking was performed155		///156		/// # Arguments157		/// * AccountId: ID of the staker158		/// * Balance : staking amount159		Stake(T::AccountId, BalanceOf<T>),160		161		/// Unstaking was performed162		///163		/// # Arguments164		/// * AccountId: ID of the staker165		/// * Balance : unstaking amount166		Unstake(T::AccountId, BalanceOf<T>),167		168		/// The admin was set169		///170		/// # Arguments171		/// * AccountId: ID of the admin172		SetAdmin(T::AccountId),173	}174175	#[pallet::error]176	pub enum Error<T> {177		/// Error due to action requiring admin to be set.178		AdminNotSet,179		/// No permission to perform an action.180		NoPermission,181		/// Insufficient funds to perform an action.182		NotSufficientFunds,183		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.184		PendingForBlockOverflow,185		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.186		SponsorNotSet,187		/// Errors caused by incorrect actions with a locked balance.188		IncorrectLockedBalanceOperation,189	}190191	#[pallet::storage]192	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;193194	#[pallet::storage]195	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;196197	/// Amount of tokens staked by account in the blocknumber.198	#[pallet::storage]199	pub type Staked<T: Config> = StorageNMap<200		Key = (201			Key<Blake2_128Concat, T::AccountId>,202			Key<Twox64Concat, T::BlockNumber>,203		),204		Value = (BalanceOf<T>, T::BlockNumber),205		QueryKind = ValueQuery,206	>;207	/// Amount of stakes for an Account208	#[pallet::storage]209	pub type StakesPerAccount<T: Config> =210		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;211212	#[pallet::storage]213	pub type PendingUnstake<T: Config> = StorageMap<214		_,215		Twox64Concat,216		T::BlockNumber,217		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,218		ValueQuery,219	>;220221	/// Stores a key for record for which the next revenue recalculation would be performed.222	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.223	#[pallet::storage]224	#[pallet::getter(fn get_next_calculated_record)]225	pub type NextCalculatedRecord<T: Config> =226		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;227228	#[pallet::hooks]229	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {230		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize231		/// implies the execution of a strictly limited number of relatively lightweight operations.232		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.233		fn on_initialize(current_block_number: T::BlockNumber) -> Weight234		where235			<T as frame_system::Config>::BlockNumber: From<u32>,236		{237			let block_pending = PendingUnstake::<T>::take(current_block_number);238			let counter = block_pending.len() as u32;239240			if !block_pending.is_empty() {241				block_pending.into_iter().for_each(|(staker, amount)| {242					<T::Currency as ReservableCurrency<T::AccountId>>::unreserve(&staker, amount);243				});244			}245246			T::WeightInfo::on_initialize(counter)247		}248	}249250	#[pallet::call]251	impl<T: Config> Pallet<T>252	where253		T::BlockNumber: From<u32> + Into<u32>,254		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,255	{256		#[pallet::weight(T::WeightInfo::set_admin_address())]257		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {258			ensure_root(origin)?;259260			<Admin<T>>::set(Some(admin.as_sub().to_owned()));261262			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));263264			Ok(())265		}266267		#[pallet::weight(T::WeightInfo::stake())]268		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {269			let staker_id = ensure_signed(staker)?;270271			ensure!(272				StakesPerAccount::<T>::get(&staker_id) < 10,273				Error::<T>::NoPermission274			);275276			ensure!(277				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),278				ArithmeticError::Underflow279			);280281			let balance =282				<<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);283284			<<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(285				&staker_id,286				amount,287				WithdrawReasons::all(),288				balance289					.checked_sub(&amount)290					.ok_or(ArithmeticError::Underflow)?,291			)?;292293			Self::add_lock_balance(&staker_id, amount)?;294295			let block_number = T::RelayBlockNumberProvider::current_block_number();296297			let recalculate_after_interval: T::BlockNumber =298				if block_number % T::RecalculationInterval::get() == 0u32.into() {299					1u32.into()300				} else {301					2u32.into()302				};303304			let recalc_block = (block_number / T::RecalculationInterval::get()305				+ recalculate_after_interval)306				* T::RecalculationInterval::get();307308			<Staked<T>>::insert((&staker_id, block_number), {309				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));310				balance_and_recalc_block.0 = balance_and_recalc_block311					.0312					.checked_add(&amount)313					.ok_or(ArithmeticError::Overflow)?;314				balance_and_recalc_block.1 = recalc_block;315				balance_and_recalc_block316			});317318			<TotalStaked<T>>::set(319				<TotalStaked<T>>::get()320					.checked_add(&amount)321					.ok_or(ArithmeticError::Overflow)?,322			);323324			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);325326			Self::deposit_event(Event::Stake(staker_id, amount));327328			Ok(())329		}330331		#[pallet::weight(T::WeightInfo::unstake())]332		pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {333			let staker_id = ensure_signed(staker)?;334			let block = <frame_system::Pallet<T>>::block_number() + T::PendingInterval::get();335			let mut pendings = <PendingUnstake<T>>::get(block);336337			ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);338339			let mut total_stakes = 0u64;340341			let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))342				.map(|(_, (amount, _))| {343					total_stakes += 1;344					amount345				})346				.sum();347348			if total_staked.is_zero() {349				return Ok(None.into()); // TO-DO350			}351352			pendings353				.try_push((staker_id.clone(), total_staked))354				.map_err(|_| Error::<T>::PendingForBlockOverflow)?;355356			<PendingUnstake<T>>::insert(block, pendings);357358			Self::unlock_balance(&staker_id, total_staked)?;359360			<T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;361362			TotalStaked::<T>::set(363				TotalStaked::<T>::get()364					.checked_sub(&total_staked)365					.ok_or(ArithmeticError::Underflow)?,366			);367368			StakesPerAccount::<T>::remove(&staker_id);369370			Self::deposit_event(Event::Unstake(staker_id, total_staked));371372			Ok(None.into())373		}374375		#[pallet::weight(T::WeightInfo::sponsor_collection())]376		pub fn sponsor_collection(377			admin: OriginFor<T>,378			collection_id: CollectionId,379		) -> DispatchResult {380			let admin_id = ensure_signed(admin)?;381			ensure!(382				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,383				Error::<T>::NoPermission384			);385386			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)387		}388		#[pallet::weight(T::WeightInfo::stop_sponsoring_collection())]389		pub fn stop_sponsoring_collection(390			admin: OriginFor<T>,391			collection_id: CollectionId,392		) -> DispatchResult {393			let admin_id = ensure_signed(admin)?;394395			ensure!(396				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,397				Error::<T>::NoPermission398			);399400			ensure!(401				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?402					== Self::account_id(),403				<Error<T>>::NoPermission404			);405			T::CollectionHandler::remove_collection_sponsor(collection_id)406		}407408		#[pallet::weight(T::WeightInfo::sponsor_contract())]409		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {410			let admin_id = ensure_signed(admin)?;411412			ensure!(413				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,414				Error::<T>::NoPermission415			);416417			T::ContractHandler::set_sponsor(418				T::CrossAccountId::from_sub(Self::account_id()),419				contract_id,420			)421		}422423		#[pallet::weight(T::WeightInfo::stop_sponsoring_contract())]424		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {425			let admin_id = ensure_signed(admin)?;426427			ensure!(428				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,429				Error::<T>::NoPermission430			);431432			ensure!(433				T::ContractHandler::sponsor(contract_id)?434					.ok_or(<Error<T>>::SponsorNotSet)?435					.as_sub() == &Self::account_id(),436				<Error<T>>::NoPermission437			);438			T::ContractHandler::remove_contract_sponsor(contract_id)439		}440441		#[pallet::weight(T::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]442		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {443			let admin_id = ensure_signed(admin)?;444445			ensure!(446				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,447				Error::<T>::NoPermission448			);449450			let current_recalc_block =451				Self::get_current_recalc_block(T::RelayBlockNumberProvider::current_block_number());452			let next_recalc_block = current_recalc_block + T::RecalculationInterval::get();453454			let mut storage_iterator = Self::get_next_calculated_key()455				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));456457			NextCalculatedRecord::<T>::set(None);458459			// {460			// 	let mut stakers_number = stakers_number.unwrap_or(20);461			// 	let mut last_id = admin_id;462			// 	let mut income_acc = BalanceOf::<T>::default();463			// 	let mut amount_acc = BalanceOf::<T>::default();464465			// 	while let Some((466			// 		(current_id, staked_block),467			// 		(amount, next_recalc_block_for_stake),468			// 	)) = storage_iterator.next()469			// 	{470			// 		if last_id != current_id {471			// 			if income_acc != BalanceOf::<T>::default() {472			// 				<T::Currency as Currency<T::AccountId>>::transfer(473			// 					&T::TreasuryAccountId::get(),474			// 					&last_id,475			// 					income_acc,476			// 					ExistenceRequirement::KeepAlive,477			// 				)478			// 				.and_then(|_| Self::add_lock_balance(&last_id, income_acc))?;479480			// 				Self::deposit_event(Event::StakingRecalculation(481			// 					last_id, amount, income_acc,482			// 				));483			// 			}484485			// 			if stakers_number == 0 {486			// 				NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));487			// 				break;488			// 			}489			// 			stakers_number -= 1;490			// 			income_acc = BalanceOf::<T>::default();491			// 			last_id = current_id;492			// 		};493			// 		if current_recalc_block >= next_recalc_block_for_stake {494			// 			Self::recalculate_and_insert_stake(495			// 				&last_id,496			// 				staked_block,497			// 				next_recalc_block,498			// 				amount,499			// 				((current_recalc_block - next_recalc_block_for_stake)500			// 					/ T::RecalculationInterval::get())501			// 				.into() + 1,502			// 				&mut income_acc,503			// 			);504			// 		}505			// 	}506			// }507508			{509				let mut stakers_number = stakers_number.unwrap_or(20);510				let last_id = RefCell::new(None);511				let income_acc = RefCell::new(BalanceOf::<T>::default());512				let amount_acc = RefCell::new(BalanceOf::<T>::default());513514				let flush_stake = || -> DispatchResult {515					if let Some(last_id) = &*last_id.borrow() {516						if !income_acc.borrow().is_zero() {517							<T::Currency as Currency<T::AccountId>>::transfer(518								&T::TreasuryAccountId::get(),519								last_id,520								*income_acc.borrow(),521								ExistenceRequirement::KeepAlive,522							)523							.and_then(|_| {524								Self::add_lock_balance(last_id, *income_acc.borrow())?;525								<TotalStaked<T>>::try_mutate(|staked| {526									staked527										.checked_add(&*income_acc.borrow())528										.ok_or(ArithmeticError::Overflow.into())529								})530							})?;531532							Self::deposit_event(Event::StakingRecalculation(533								last_id.clone(),534								*amount_acc.borrow(),535								*income_acc.borrow(),536							));537						}538539						*income_acc.borrow_mut() = BalanceOf::<T>::default();540						*amount_acc.borrow_mut() = BalanceOf::<T>::default();541					}542					Ok(())543				};544545				while let Some((546					(current_id, staked_block),547					(amount, next_recalc_block_for_stake),548				)) = storage_iterator.next()549				{550					if stakers_number == 0 {551						NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));552						break;553					}554					if last_id.borrow().as_ref() != Some(&current_id) {555						flush_stake()?;556						*last_id.borrow_mut() = Some(current_id.clone());557						stakers_number -= 1;558					};559					if current_recalc_block >= next_recalc_block_for_stake {560						*amount_acc.borrow_mut() += amount;561						Self::recalculate_and_insert_stake(562							&current_id,563							staked_block,564							next_recalc_block,565							amount,566							((current_recalc_block - next_recalc_block_for_stake)567								/ T::RecalculationInterval::get())568							.into() + 1,569							&mut *income_acc.borrow_mut(),570						);571					}572				}573				flush_stake()?;574			}575576			Ok(())577		}578	}579}580581impl<T: Config> Pallet<T> {582	pub fn account_id() -> T::AccountId {583		T::PalletId::get().into_account_truncating()584	}585586	fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {587		let locked_balance = Self::get_locked_balance(staker)588			.map(|l| l.amount)589			.ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;590591		// It is understood that we cannot unlock more funds than were locked by staking.592		// Therefore, if implemented correctly, this error should not occur.593		Self::set_lock_unchecked(594			staker,595			locked_balance596				.checked_sub(&amount)597				.ok_or(ArithmeticError::Underflow)?,598		);599		Ok(())600	}601602	fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {603		Self::get_locked_balance(staker)604			.map_or(<BalanceOf<T>>::default(), |l| l.amount)605			.checked_add(&amount)606			.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))607			.ok_or(ArithmeticError::Overflow.into())608	}609610	fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {611		if amount.is_zero() {612			<T::Currency as LockableCurrency<T::AccountId>>::remove_lock(LOCK_IDENTIFIER, &staker);613		} else {614			<T::Currency as LockableCurrency<T::AccountId>>::set_lock(615				LOCK_IDENTIFIER,616				staker,617				amount,618				WithdrawReasons::all(),619			)620		}621	}622623	pub fn get_locked_balance(624		staker: impl EncodeLike<T::AccountId>,625	) -> Option<BalanceLock<BalanceOf<T>>> {626		<T::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)627			.into_iter()628			.find(|l| l.id == LOCK_IDENTIFIER)629	}630631	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {632		let staked = Staked::<T>::iter_prefix((staker,))633			.into_iter()634			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {635				acc + amount636			});637		if staked != <BalanceOf<T>>::default() {638			Some(staked)639		} else {640			None641		}642	}643644	pub fn total_staked_by_id_per_block(645		staker: impl EncodeLike<T::AccountId>,646	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {647		let mut staked = Staked::<T>::iter_prefix((staker,))648			.into_iter()649			.map(|(block, (amount, _))| (block, amount))650			.collect::<Vec<_>>();651		staked.sort_by_key(|(block, _)| *block);652		if !staked.is_empty() {653			Some(staked)654		} else {655			None656		}657	}658659	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {660		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {661			Self::total_staked_by_id(s.as_sub())662		})663	}664665	// pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {666	// 	Self::get_locked_balance(staker.as_sub())667	// 		.map(|l| l.amount)668	// 		.unwrap_or_default()669	// }670671	pub fn cross_id_total_staked_per_block(672		staker: T::CrossAccountId,673	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {674		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()675	}676677	fn recalculate_and_insert_stake(678		staker: &T::AccountId,679		staked_block: T::BlockNumber,680		next_recalc_block: T::BlockNumber,681		base: BalanceOf<T>,682		iters: u32,683		income_acc: &mut BalanceOf<T>,684	) {685		let income = Self::calculate_income(base, iters);686687		base.checked_add(&income).map(|res| {688			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));689			*income_acc += income;690		});691	}692693	fn calculate_income<I>(base: I, iters: u32) -> I694	where695		I: EncodeLike<BalanceOf<T>> + Balance,696	{697		let mut income = base;698699		(0..iters).for_each(|_| income += T::IntervalIncome::get() * income);700701		income - base702	}703704	fn get_current_recalc_block(current_relay_block: T::BlockNumber) -> T::BlockNumber {705		(current_relay_block / T::RecalculationInterval::get()) * T::RecalculationInterval::get()706	}707708	// fn get_next_recalc_block(current_relay_block: T::BlockNumber) -> T::BlockNumber {709	// 	Self::get_current_recalc_block(current_relay_block) + T::RecalculationInterval::get()710	// }711712	fn get_next_calculated_key() -> Option<Vec<u8>> {713		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))714	}715}716717impl<T: Config> Pallet<T>718where719	<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,720{721	/// Since user funds are not transferred anywhere by staking, overflow protection is provided722	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,723	/// the staker must have more funds on his account than the maximum set for `Balance` type.724	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {725		staker.map_or(726			PendingUnstake::<T>::iter_values()727				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))728				.sum(),729			|s| {730				PendingUnstake::<T>::iter_values()731					.flatten()732					.filter_map(|(id, amount)| {733						if id == *s.as_sub() {734							Some(amount)735						} else {736							None737						}738					})739					.sum()740			},741		)742	}743744	pub fn cross_id_pending_unstake_per_block(745		staker: T::CrossAccountId,746	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {747		let mut unsorted_res = vec![];748		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {749			pendings.into_iter().for_each(|(id, amount)| {750				if id == *staker.as_sub() {751					unsorted_res.push((block, amount));752				};753			})754		});755756		unsorted_res.sort_by_key(|(block, _)| *block);757		unsorted_res758	}759}
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 promotion18//!19//! The app promotion pallet is designed to ... .20//!21//! ## Interface22//!23//! ### Dispatchable Functions24//!2526// #![recursion_limit = "1024"]27#![cfg_attr(not(feature = "std"), no_std)]2829#[cfg(feature = "runtime-benchmarks")]30mod benchmarking;3132pub mod types;33pub mod weights;3435use sp_std::{36	vec::{Vec},37	vec,38	iter::Sum,39	borrow::ToOwned,40	cell::RefCell,41};42use sp_core::H160;43use codec::EncodeLike;44use pallet_balances::BalanceLock;45pub use types::*;4647use up_data_structs::CollectionId;4849use frame_support::{50	dispatch::{DispatchResult},51	traits::{52		Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,53	},54	ensure,55};5657use weights::WeightInfo;5859pub use pallet::*;60use pallet_evm::account::CrossAccountId;61use sp_runtime::{62	Perbill,63	traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},64	ArithmeticError,65};6667pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";6869const PENDING_LIMIT_PER_BLOCK: u32 = 3;7071type BalanceOf<T> =72	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;7374#[frame_support::pallet]75pub mod pallet {76	use super::*;77	use frame_support::{78		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,79		traits::ReservableCurrency,80	};81	use frame_system::pallet_prelude::*;8283	#[pallet::config]84	pub trait Config: frame_system::Config + pallet_evm::account::Config {85		/// Type to interact with the native token86		type Currency: ExtendedLockableCurrency<Self::AccountId>87			+ ReservableCurrency<Self::AccountId>;8889		/// Type for interacting with collections90		type CollectionHandler: CollectionHandler<91			AccountId = Self::AccountId,92			CollectionId = CollectionId,93		>;9495		/// Type for interacting with conrtacts96		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;9798		/// ID for treasury99		type TreasuryAccountId: Get<Self::AccountId>;100101		/// The app's pallet id, used for deriving its sovereign account ID.102		#[pallet::constant]103		type PalletId: Get<PalletId>;104105		/// In relay blocks.106		#[pallet::constant]107		type RecalculationInterval: Get<Self::BlockNumber>;108109		/// In parachain blocks.110		#[pallet::constant]111		type PendingInterval: Get<Self::BlockNumber>;112113		/// Rate of return for interval in blocks defined in `RecalculationInterval`.114		#[pallet::constant]115		type IntervalIncome: Get<Perbill>;116117		/// Decimals for the `Currency`.118		#[pallet::constant]119		type Nominal: Get<BalanceOf<Self>>;120121		/// Weight information for extrinsics in this pallet.122		type WeightInfo: WeightInfo;123124		// The relay block number provider125		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;126127		/// Events compatible with [`frame_system::Config::Event`].128		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;129	}130131	#[pallet::pallet]132	#[pallet::generate_store(pub(super) trait Store)]133	pub struct Pallet<T>(_);134135	#[pallet::event]136	#[pallet::generate_deposit(fn deposit_event)]137	pub enum Event<T: Config> {138		/// Staking recalculation was performed139		///140		/// # Arguments141		/// * AccountId: ID of the staker.142		/// * Balance : recalculation base143		/// * Balance : total income144		StakingRecalculation(145			/// An recalculated staker146			T::AccountId,147			/// Base on which interest is calculated148			BalanceOf<T>,149			/// Amount of accrued interest150			BalanceOf<T>,151		),152		153		/// Staking was performed154		///155		/// # Arguments156		/// * AccountId: ID of the staker157		/// * Balance : staking amount158		Stake(T::AccountId, BalanceOf<T>),159		160		/// Unstaking was performed161		///162		/// # Arguments163		/// * AccountId: ID of the staker164		/// * Balance : unstaking amount165		Unstake(T::AccountId, BalanceOf<T>),166		167		/// The admin was set168		///169		/// # Arguments170		/// * AccountId: ID of the admin171		SetAdmin(T::AccountId),172	}173174	#[pallet::error]175	pub enum Error<T> {176		/// Error due to action requiring admin to be set.177		AdminNotSet,178		/// No permission to perform an action.179		NoPermission,180		/// Insufficient funds to perform an action.181		NotSufficientFunds,182		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.183		PendingForBlockOverflow,184		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.185		SponsorNotSet,186		/// Errors caused by incorrect actions with a locked balance.187		IncorrectLockedBalanceOperation,188	}189190	#[pallet::storage]191	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;192193	#[pallet::storage]194	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;195196	/// Amount of tokens staked by account in the blocknumber.197	#[pallet::storage]198	pub type Staked<T: Config> = StorageNMap<199		Key = (200			Key<Blake2_128Concat, T::AccountId>,201			Key<Twox64Concat, T::BlockNumber>,202		),203		Value = (BalanceOf<T>, T::BlockNumber),204		QueryKind = ValueQuery,205	>;206	/// Amount of stakes for an Account207	#[pallet::storage]208	pub type StakesPerAccount<T: Config> =209		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;210211	#[pallet::storage]212	pub type PendingUnstake<T: Config> = StorageMap<213		_,214		Twox64Concat,215		T::BlockNumber,216		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,217		ValueQuery,218	>;219220	/// Stores a key for record for which the next revenue recalculation would be performed.221	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.222	#[pallet::storage]223	#[pallet::getter(fn get_next_calculated_record)]224	pub type NextCalculatedRecord<T: Config> =225		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;226227	#[pallet::hooks]228	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {229		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize230		/// implies the execution of a strictly limited number of relatively lightweight operations.231		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.232		fn on_initialize(current_block_number: T::BlockNumber) -> Weight233		where234			<T as frame_system::Config>::BlockNumber: From<u32>,235		{236			let block_pending = PendingUnstake::<T>::take(current_block_number);237			let counter = block_pending.len() as u32;238239			if !block_pending.is_empty() {240				block_pending.into_iter().for_each(|(staker, amount)| {241					<T::Currency as ReservableCurrency<T::AccountId>>::unreserve(&staker, amount);242				});243			}244245			T::WeightInfo::on_initialize(counter)246		}247	}248249	#[pallet::call]250	impl<T: Config> Pallet<T>251	where252		T::BlockNumber: From<u32> + Into<u32>,253		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,254	{255		#[pallet::weight(T::WeightInfo::set_admin_address())]256		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {257			ensure_root(origin)?;258259			<Admin<T>>::set(Some(admin.as_sub().to_owned()));260261			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));262263			Ok(())264		}265266		#[pallet::weight(T::WeightInfo::stake())]267		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {268			let staker_id = ensure_signed(staker)?;269270			ensure!(271				StakesPerAccount::<T>::get(&staker_id) < 10,272				Error::<T>::NoPermission273			);274275			ensure!(276				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),277				ArithmeticError::Underflow278			);279280			let balance =281				<<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);282283			<<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(284				&staker_id,285				amount,286				WithdrawReasons::all(),287				balance288					.checked_sub(&amount)289					.ok_or(ArithmeticError::Underflow)?,290			)?;291292			Self::add_lock_balance(&staker_id, amount)?;293294			let block_number = T::RelayBlockNumberProvider::current_block_number();295296			let recalculate_after_interval: T::BlockNumber =297				if block_number % T::RecalculationInterval::get() == 0u32.into() {298					1u32.into()299				} else {300					2u32.into()301				};302303			let recalc_block = (block_number / T::RecalculationInterval::get()304				+ recalculate_after_interval)305				* T::RecalculationInterval::get();306307			<Staked<T>>::insert((&staker_id, block_number), {308				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));309				balance_and_recalc_block.0 = balance_and_recalc_block310					.0311					.checked_add(&amount)312					.ok_or(ArithmeticError::Overflow)?;313				balance_and_recalc_block.1 = recalc_block;314				balance_and_recalc_block315			});316317			<TotalStaked<T>>::set(318				<TotalStaked<T>>::get()319					.checked_add(&amount)320					.ok_or(ArithmeticError::Overflow)?,321			);322323			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);324325			Self::deposit_event(Event::Stake(staker_id, amount));326327			Ok(())328		}329330		#[pallet::weight(T::WeightInfo::unstake())]331		pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {332			let staker_id = ensure_signed(staker)?;333			let block = <frame_system::Pallet<T>>::block_number() + T::PendingInterval::get();334			let mut pendings = <PendingUnstake<T>>::get(block);335336			ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);337338			let mut total_stakes = 0u64;339340			let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))341				.map(|(_, (amount, _))| {342					total_stakes += 1;343					amount344				})345				.sum();346347			if total_staked.is_zero() {348				return Ok(None.into()); // TO-DO349			}350351			pendings352				.try_push((staker_id.clone(), total_staked))353				.map_err(|_| Error::<T>::PendingForBlockOverflow)?;354355			<PendingUnstake<T>>::insert(block, pendings);356357			Self::unlock_balance(&staker_id, total_staked)?;358359			<T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;360361			TotalStaked::<T>::set(362				TotalStaked::<T>::get()363					.checked_sub(&total_staked)364					.ok_or(ArithmeticError::Underflow)?,365			);366367			StakesPerAccount::<T>::remove(&staker_id);368369			Self::deposit_event(Event::Unstake(staker_id, total_staked));370371			Ok(None.into())372		}373374		#[pallet::weight(T::WeightInfo::sponsor_collection())]375		pub fn sponsor_collection(376			admin: OriginFor<T>,377			collection_id: CollectionId,378		) -> DispatchResult {379			let admin_id = ensure_signed(admin)?;380			ensure!(381				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,382				Error::<T>::NoPermission383			);384385			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)386		}387		#[pallet::weight(T::WeightInfo::stop_sponsoring_collection())]388		pub fn stop_sponsoring_collection(389			admin: OriginFor<T>,390			collection_id: CollectionId,391		) -> DispatchResult {392			let admin_id = ensure_signed(admin)?;393394			ensure!(395				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,396				Error::<T>::NoPermission397			);398399			ensure!(400				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?401					== Self::account_id(),402				<Error<T>>::NoPermission403			);404			T::CollectionHandler::remove_collection_sponsor(collection_id)405		}406407		#[pallet::weight(T::WeightInfo::sponsor_contract())]408		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {409			let admin_id = ensure_signed(admin)?;410411			ensure!(412				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,413				Error::<T>::NoPermission414			);415416			T::ContractHandler::set_sponsor(417				T::CrossAccountId::from_sub(Self::account_id()),418				contract_id,419			)420		}421422		#[pallet::weight(T::WeightInfo::stop_sponsoring_contract())]423		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {424			let admin_id = ensure_signed(admin)?;425426			ensure!(427				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,428				Error::<T>::NoPermission429			);430431			ensure!(432				T::ContractHandler::sponsor(contract_id)?433					.ok_or(<Error<T>>::SponsorNotSet)?434					.as_sub() == &Self::account_id(),435				<Error<T>>::NoPermission436			);437			T::ContractHandler::remove_contract_sponsor(contract_id)438		}439440		#[pallet::weight(T::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]441		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {442			let admin_id = ensure_signed(admin)?;443444			ensure!(445				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,446				Error::<T>::NoPermission447			);448449			let current_recalc_block =450				Self::get_current_recalc_block(T::RelayBlockNumberProvider::current_block_number());451			let next_recalc_block = current_recalc_block + T::RecalculationInterval::get();452453			let mut storage_iterator = Self::get_next_calculated_key()454				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));455456			NextCalculatedRecord::<T>::set(None);457458			// {459			// 	let mut stakers_number = stakers_number.unwrap_or(20);460			// 	let mut last_id = admin_id;461			// 	let mut income_acc = BalanceOf::<T>::default();462			// 	let mut amount_acc = BalanceOf::<T>::default();463464			// 	while let Some((465			// 		(current_id, staked_block),466			// 		(amount, next_recalc_block_for_stake),467			// 	)) = storage_iterator.next()468			// 	{469			// 		if last_id != current_id {470			// 			if income_acc != BalanceOf::<T>::default() {471			// 				<T::Currency as Currency<T::AccountId>>::transfer(472			// 					&T::TreasuryAccountId::get(),473			// 					&last_id,474			// 					income_acc,475			// 					ExistenceRequirement::KeepAlive,476			// 				)477			// 				.and_then(|_| Self::add_lock_balance(&last_id, income_acc))?;478479			// 				Self::deposit_event(Event::StakingRecalculation(480			// 					last_id, amount, income_acc,481			// 				));482			// 			}483484			// 			if stakers_number == 0 {485			// 				NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));486			// 				break;487			// 			}488			// 			stakers_number -= 1;489			// 			income_acc = BalanceOf::<T>::default();490			// 			last_id = current_id;491			// 		};492			// 		if current_recalc_block >= next_recalc_block_for_stake {493			// 			Self::recalculate_and_insert_stake(494			// 				&last_id,495			// 				staked_block,496			// 				next_recalc_block,497			// 				amount,498			// 				((current_recalc_block - next_recalc_block_for_stake)499			// 					/ T::RecalculationInterval::get())500			// 				.into() + 1,501			// 				&mut income_acc,502			// 			);503			// 		}504			// 	}505			// }506507			{508				let mut stakers_number = stakers_number.unwrap_or(20);509				let last_id = RefCell::new(None);510				let income_acc = RefCell::new(BalanceOf::<T>::default());511				let amount_acc = RefCell::new(BalanceOf::<T>::default());512513				let flush_stake = || -> DispatchResult {514					if let Some(last_id) = &*last_id.borrow() {515						if !income_acc.borrow().is_zero() {516							<T::Currency as Currency<T::AccountId>>::transfer(517								&T::TreasuryAccountId::get(),518								last_id,519								*income_acc.borrow(),520								ExistenceRequirement::KeepAlive,521							)522							.and_then(|_| {523								Self::add_lock_balance(last_id, *income_acc.borrow())?;524								<TotalStaked<T>>::try_mutate(|staked| {525									staked526										.checked_add(&*income_acc.borrow())527										.ok_or(ArithmeticError::Overflow.into())528								})529							})?;530531							Self::deposit_event(Event::StakingRecalculation(532								last_id.clone(),533								*amount_acc.borrow(),534								*income_acc.borrow(),535							));536						}537538						*income_acc.borrow_mut() = BalanceOf::<T>::default();539						*amount_acc.borrow_mut() = BalanceOf::<T>::default();540					}541					Ok(())542				};543544				while let Some((545					(current_id, staked_block),546					(amount, next_recalc_block_for_stake),547				)) = storage_iterator.next()548				{549					if stakers_number == 0 {550						NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));551						break;552					}553					if last_id.borrow().as_ref() != Some(&current_id) {554						flush_stake()?;555						*last_id.borrow_mut() = Some(current_id.clone());556						stakers_number -= 1;557					};558					if current_recalc_block >= next_recalc_block_for_stake {559						*amount_acc.borrow_mut() += amount;560						Self::recalculate_and_insert_stake(561							&current_id,562							staked_block,563							next_recalc_block,564							amount,565							((current_recalc_block - next_recalc_block_for_stake)566								/ T::RecalculationInterval::get())567							.into() + 1,568							&mut *income_acc.borrow_mut(),569						);570					}571				}572				flush_stake()?;573			}574575			Ok(())576		}577	}578}579580impl<T: Config> Pallet<T> {581	pub fn account_id() -> T::AccountId {582		T::PalletId::get().into_account_truncating()583	}584585	fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {586		let locked_balance = Self::get_locked_balance(staker)587			.map(|l| l.amount)588			.ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;589590		// It is understood that we cannot unlock more funds than were locked by staking.591		// Therefore, if implemented correctly, this error should not occur.592		Self::set_lock_unchecked(593			staker,594			locked_balance595				.checked_sub(&amount)596				.ok_or(ArithmeticError::Underflow)?,597		);598		Ok(())599	}600601	fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {602		Self::get_locked_balance(staker)603			.map_or(<BalanceOf<T>>::default(), |l| l.amount)604			.checked_add(&amount)605			.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))606			.ok_or(ArithmeticError::Overflow.into())607	}608609	fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {610		if amount.is_zero() {611			<T::Currency as LockableCurrency<T::AccountId>>::remove_lock(LOCK_IDENTIFIER, &staker);612		} else {613			<T::Currency as LockableCurrency<T::AccountId>>::set_lock(614				LOCK_IDENTIFIER,615				staker,616				amount,617				WithdrawReasons::all(),618			)619		}620	}621622	pub fn get_locked_balance(623		staker: impl EncodeLike<T::AccountId>,624	) -> Option<BalanceLock<BalanceOf<T>>> {625		<T::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)626			.into_iter()627			.find(|l| l.id == LOCK_IDENTIFIER)628	}629630	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {631		let staked = Staked::<T>::iter_prefix((staker,))632			.into_iter()633			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {634				acc + amount635			});636		if staked != <BalanceOf<T>>::default() {637			Some(staked)638		} else {639			None640		}641	}642643	pub fn total_staked_by_id_per_block(644		staker: impl EncodeLike<T::AccountId>,645	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {646		let mut staked = Staked::<T>::iter_prefix((staker,))647			.into_iter()648			.map(|(block, (amount, _))| (block, amount))649			.collect::<Vec<_>>();650		staked.sort_by_key(|(block, _)| *block);651		if !staked.is_empty() {652			Some(staked)653		} else {654			None655		}656	}657658	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {659		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {660			Self::total_staked_by_id(s.as_sub())661		})662	}663664	// pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {665	// 	Self::get_locked_balance(staker.as_sub())666	// 		.map(|l| l.amount)667	// 		.unwrap_or_default()668	// }669670	pub fn cross_id_total_staked_per_block(671		staker: T::CrossAccountId,672	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {673		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()674	}675676	fn recalculate_and_insert_stake(677		staker: &T::AccountId,678		staked_block: T::BlockNumber,679		next_recalc_block: T::BlockNumber,680		base: BalanceOf<T>,681		iters: u32,682		income_acc: &mut BalanceOf<T>,683	) {684		let income = Self::calculate_income(base, iters);685686		base.checked_add(&income).map(|res| {687			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));688			*income_acc += income;689		});690	}691692	fn calculate_income<I>(base: I, iters: u32) -> I693	where694		I: EncodeLike<BalanceOf<T>> + Balance,695	{696		let mut income = base;697698		(0..iters).for_each(|_| income += T::IntervalIncome::get() * income);699700		income - base701	}702703	fn get_current_recalc_block(current_relay_block: T::BlockNumber) -> T::BlockNumber {704		(current_relay_block / T::RecalculationInterval::get()) * T::RecalculationInterval::get()705	}706707	// fn get_next_recalc_block(current_relay_block: T::BlockNumber) -> T::BlockNumber {708	// 	Self::get_current_recalc_block(current_relay_block) + T::RecalculationInterval::get()709	// }710711	fn get_next_calculated_key() -> Option<Vec<u8>> {712		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))713	}714}715716impl<T: Config> Pallet<T>717where718	<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,719{720	/// Since user funds are not transferred anywhere by staking, overflow protection is provided721	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,722	/// the staker must have more funds on his account than the maximum set for `Balance` type.723	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {724		staker.map_or(725			PendingUnstake::<T>::iter_values()726				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))727				.sum(),728			|s| {729				PendingUnstake::<T>::iter_values()730					.flatten()731					.filter_map(|(id, amount)| {732						if id == *s.as_sub() {733							Some(amount)734						} else {735							None736						}737					})738					.sum()739			},740		)741	}742743	pub fn cross_id_pending_unstake_per_block(744		staker: T::CrossAccountId,745	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {746		let mut unsorted_res = vec![];747		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {748			pendings.into_iter().for_each(|(id, amount)| {749				if id == *staker.as_sub() {750					unsorted_res.push((block, amount));751				};752			})753		});754755		unsorted_res.sort_by_key(|(block, _)| *block);756		unsorted_res757	}758}
deletedpallets/app-promotion/src/tests.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/tests.rs
+++ /dev/null
@@ -1,150 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-#![cfg(test)]
-#![allow(clippy::from_over_into)]
-// use crate as pallet_promotion;
-
-// use frame_benchmarking::{add_benchmark, BenchmarkBatch};
-// use frame_support::{
-// 	assert_ok, parameter_types,
-// 	traits::{Currency, OnInitialize, Everything, ConstU32},
-// };
-// use frame_system::RawOrigin;
-// use sp_core::H256;
-// use sp_runtime::{
-// 	traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},
-// 	testing::Header,
-// 	Perbill, Perquintill,
-// };
-
-// type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
-// type Block = frame_system::mocking::MockBlock<Test>;
-
-// parameter_types! {
-// 	pub const BlockHashCount: u64 = 250;
-// 	pub BlockWeights: frame_system::limits::BlockWeights =
-// 		frame_system::limits::BlockWeights::simple_max(1024);
-// 	pub const SS58Prefix: u8 = 42;
-// 	pub TreasuryAccountId: u64 = 1234;
-// 	pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied
-// 	pub static MockBlockNumberProvider: u64 = 0;
-// 	pub const ExistentialDeposit: u64 = 1;
-// 	pub const MaxLocks: u32 = 50;
-// }
-
-// impl BlockNumberProvider for MockBlockNumberProvider {
-// 	type BlockNumber = u64;
-
-// 	fn current_block_number() -> Self::BlockNumber {
-// 		Self::get()
-// 	}
-// }
-
-// frame_support::construct_runtime!(
-// 	pub enum Test where
-// 		Block = Block,
-// 		NodeBlock = Block,
-// 		UncheckedExtrinsic = UncheckedExtrinsic,
-// 	{
-// 		Balances: pallet_balances::{Pallet, Call, Storage},
-// 		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
-// 		Promotion: pallet_promotion::{Pallet, Call, Storage}
-// 	}
-// );
-
-// impl frame_system::Config for Test {
-// 	type BaseCallFilter = Everything;
-// 	type BlockWeights = ();
-// 	type BlockLength = ();
-// 	type DbWeight = ();
-// 	type Origin = Origin;
-// 	type Call = Call;
-// 	type Index = u64;
-// 	type BlockNumber = u64;
-// 	type Hash = H256;
-// 	type Hashing = BlakeTwo256;
-// 	type AccountId = u64;
-// 	type Lookup = IdentityLookup<Self::AccountId>;
-// 	type Header = Header;
-// 	type Event = ();
-// 	type BlockHashCount = BlockHashCount;
-// 	type Version = ();
-// 	type PalletInfo = PalletInfo;
-// 	type AccountData = pallet_balances::AccountData<u64>;
-// 	type OnNewAccount = ();
-// 	type OnKilledAccount = ();
-// 	type SystemWeightInfo = ();
-// 	type SS58Prefix = SS58Prefix;
-// 	type OnSetCode = ();
-// 	type MaxConsumers = ConstU32<16>;
-// }
-
-// impl pallet_balances::Config for Test {
-// 	type AccountStore = System;
-// 	type Balance = u64;
-// 	type DustRemoval = ();
-// 	type Event = ();
-// 	type ExistentialDeposit = ExistentialDeposit;
-// 	type WeightInfo = ();
-// 	type MaxLocks = MaxLocks;
-// 	type MaxReserves = ();
-// 	type ReserveIdentifier = [u8; 8];
-// }
-
-// impl pallet_promotion::Config for Test {
-// 	type Currency = Balances;
-
-// 	type TreasuryAccountId = TreasuryAccountId;
-
-// 	type BlockNumberProvider = MockBlockNumberProvider;
-// }
-
-// pub fn new_test_ext() -> sp_io::TestExternalities {
-// 	frame_system::GenesisConfig::default()
-// 		.build_storage::<Test>()
-// 		.unwrap()
-// 		.into()
-// }
-
-// #[test]
-// fn test_benchmark() {
-// 	new_test_ext().execute_with(|| {
-// 		test_benchmark_stake::<Test>();
-// 	} )
-// }
-
-// #[test]
-// fn test_perbill() {
-// 	const ONE_UNIQE: u128 = 1_000_000_000_000_000_000;
-// 	const SECONDS_TO_BLOCK: u32 = 12;
-// 	const DAY: u32 = 60 * 60 * 24 / SECONDS_TO_BLOCK;
-// 	const RECALCULATION_INTERVAL: u32 = 10;
-// 	let day_rate = Perbill::from_rational(5u64, 10_000);
-// 	let interval_rate =
-// 		Perbill::from_rational::<u64>(RECALCULATION_INTERVAL.into(), DAY.into()) * day_rate;
-// 	println!("{:?}", interval_rate * ONE_UNIQE + ONE_UNIQE);
-// 	println!("{:?}", day_rate * ONE_UNIQE);
-// 	println!("{:?}", Perbill::one() * ONE_UNIQE);
-// 	println!("{:?}", ONE_UNIQE);
-// 	let mut next_iters = ONE_UNIQE + interval_rate * ONE_UNIQE;
-// 	next_iters += interval_rate * next_iters;
-// 	println!("{:?}", next_iters);
-// 	let day_income = day_rate * ONE_UNIQE;
-// 	let interval_income = interval_rate * ONE_UNIQE;
-// 	let ratio = day_income / interval_income;
-// 	println!("{:?} || {:?}", ratio, DAY / RECALCULATION_INTERVAL);
-// }