git.delta.rocks / unique-network / refs/commits / 803eec048f65

difftreelog

refac(app-promo): ensure expr

PraetorP2023-02-15parent: #b190805.patch.diff
in: master

1 file changed

modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
after · pallets/app-promotion/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # App Promotion pallet18//!19//! The pallet implements the mechanics of staking and sponsoring collections/contracts.20//!21//! - [`Config`]22//! - [`Pallet`]23//! - [`Error`]24//! - [`Event`]25//!26//! ## Overview27//! The App Promotion pallet allows fund holders to stake at a certain daily rate of return.28//! The mechanics implemented in the pallet allow it to act as a sponsor for collections / contracts,29//! the list of which is set by the pallet administrator.30//!31//!32//! ## Interface33//!	The pallet provides interfaces for funds, collection/contract operations (see [types] module).3435//!36//! ### Dispatchable Functions37//!	- [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.38//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.39//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.40//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.41//! - [`stop_sponsoring_collection`][`Pallet::stop_sponsoring_collection`] - removes the pallet as the sponsor for the collection.42//! - [`sponsor_contract`][`Pallet::sponsor_contract`] - sets the pallet to be the sponsor for the contract.43//! - [`stop_sponsoring_contract`][`Pallet::stop_sponsoring_contract`] - removes the pallet as the sponsor for the contract.44//! - [`payout_stakers`][`Pallet::payout_stakers`] - recalculates interest for the specified number of stakers.45//!4647// #![recursion_limit = "1024"]48#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57	vec::{Vec},58	vec,59	iter::Sum,60	borrow::ToOwned,61	cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71	dispatch::{DispatchResult},72	traits::{73		Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,74	},75	ensure, BoundedVec,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83	Perbill,84	traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85	ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97	use super::*;98	use frame_support::{99		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100		traits::ReservableCurrency, weights::Weight,101	};102	use frame_system::pallet_prelude::*;103104	#[pallet::config]105	pub trait Config:106		frame_system::Config + pallet_evm::Config + pallet_configuration::Config107	{108		/// Type to interact with the native token109		type Currency: ExtendedLockableCurrency<Self::AccountId>110			+ ReservableCurrency<Self::AccountId>;111112		/// Type for interacting with collections113		type CollectionHandler: CollectionHandler<114			AccountId = Self::AccountId,115			CollectionId = CollectionId,116		>;117118		/// Type for interacting with conrtacts119		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;120121		/// `AccountId` for treasury122		type TreasuryAccountId: Get<Self::AccountId>;123124		/// The app's pallet id, used for deriving its sovereign account address.125		#[pallet::constant]126		type PalletId: Get<PalletId>;127128		/// In relay blocks.129		#[pallet::constant]130		type RecalculationInterval: Get<Self::BlockNumber>;131132		/// In parachain blocks.133		#[pallet::constant]134		type PendingInterval: Get<Self::BlockNumber>;135136		/// Rate of return for interval in blocks defined in `RecalculationInterval`.137		#[pallet::constant]138		type IntervalIncome: Get<Perbill>;139140		/// Decimals for the `Currency`.141		#[pallet::constant]142		type Nominal: Get<BalanceOf<Self>>;143144		/// Weight information for extrinsics in this pallet.145		type WeightInfo: WeightInfo;146147		// The relay block number provider148		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149150		/// Events compatible with [`frame_system::Config::Event`].151		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;152	}153154	#[pallet::pallet]155	#[pallet::generate_store(pub(super) trait Store)]156	pub struct Pallet<T>(_);157158	#[pallet::event]159	#[pallet::generate_deposit(pub(super) fn deposit_event)]160	pub enum Event<T: Config> {161		/// Staking recalculation was performed162		///163		/// # Arguments164		/// * AccountId: account of the staker.165		/// * Balance : recalculation base166		/// * Balance : total income167		StakingRecalculation(168			/// An recalculated staker169			T::AccountId,170			/// Base on which interest is calculated171			BalanceOf<T>,172			/// Amount of accrued interest173			BalanceOf<T>,174		),175176		/// Staking was performed177		///178		/// # Arguments179		/// * AccountId: account of the staker180		/// * Balance : staking amount181		Stake(T::AccountId, BalanceOf<T>),182183		/// Unstaking was performed184		///185		/// # Arguments186		/// * AccountId: account of the staker187		/// * Balance : unstaking amount188		Unstake(T::AccountId, BalanceOf<T>),189190		/// The admin was set191		///192		/// # Arguments193		/// * AccountId: account address of the admin194		SetAdmin(T::AccountId),195	}196197	#[pallet::error]198	pub enum Error<T> {199		/// Error due to action requiring admin to be set.200		AdminNotSet,201		/// No permission to perform an action.202		NoPermission,203		/// Insufficient funds to perform an action.204		NotSufficientFunds,205		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.206		PendingForBlockOverflow,207		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.208		SponsorNotSet,209		/// Errors caused by incorrect actions with a locked balance.210		IncorrectLockedBalanceOperation,211		/// Errors caused by insufficient staked balance.212		InsufficientStakedBalance,213	}214215	/// Stores the total staked amount.216	#[pallet::storage]217	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;218219	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.220	#[pallet::storage]221	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;222223	/// Stores the amount of tokens staked by account in the blocknumber.224	///225	/// * **Key1** - Staker account.226	/// * **Key2** - Relay block number when the stake was made.227	/// * **(Balance, BlockNumber)** - Balance of the stake.228	/// The number of the relay block in which we must perform the interest recalculation229	#[pallet::storage]230	pub type Staked<T: Config> = StorageNMap<231		Key = (232			Key<Blake2_128Concat, T::AccountId>,233			Key<Twox64Concat, T::BlockNumber>,234		),235		Value = (BalanceOf<T>, T::BlockNumber),236		QueryKind = ValueQuery,237	>;238239	/// Stores number of stake records for an `Account`.240	///241	/// * **Key** - Staker account.242	/// * **Value** - Amount of stakes.243	#[pallet::storage]244	pub type StakesPerAccount<T: Config> =245		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;246247	/// Pending unstake records for an `Account`.248	///249	/// * **Key** - Staker account.250	/// * **Value** - Amount of stakes.251	#[pallet::storage]252	pub type PendingUnstake<T: Config> = StorageMap<253		_,254		Twox64Concat,255		T::BlockNumber,256		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,257		ValueQuery,258	>;259260	/// Stores a key for record for which the revenue recalculation was performed.261	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.262	#[pallet::storage]263	#[pallet::getter(fn get_next_calculated_record)]264	pub type PreviousCalculatedRecord<T: Config> =265		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;266267	#[pallet::storage]268	pub(crate) type UpgradedToReserves<T: Config> =269		StorageValue<Value = bool, QueryKind = ValueQuery>;270271	#[pallet::hooks]272	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {273		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize274		/// implies the execution of a strictly limited number of relatively lightweight operations.275		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.276		fn on_initialize(current_block_number: T::BlockNumber) -> Weight277		where278			<T as frame_system::Config>::BlockNumber: From<u32>,279		{280			let block_pending = PendingUnstake::<T>::take(current_block_number);281			let counter = block_pending.len() as u32;282283			if !block_pending.is_empty() {284				block_pending.into_iter().for_each(|(staker, amount)| {285					Self::get_locked_balance(&staker).map(|b| {286						let new_state = b.amount.checked_sub(&amount).unwrap_or_default();287						Self::set_lock_unchecked(&staker, new_state);288					});289				});290			}291292			<T as Config>::WeightInfo::on_initialize(counter)293		}294295		fn on_runtime_upgrade() -> Weight {296			let mut consumed_weight = Weight::zero();297			let mut add_weight = |reads, writes, weight| {298				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);299				consumed_weight += weight;300			};301302			if <UpgradedToReserves<T>>::get() {303				add_weight(1, 0, Weight::zero());304				return consumed_weight;305			} else {306				add_weight(1, 1, Weight::zero());307				<UpgradedToReserves<T>>::set(true);308			}309			<PendingUnstake<T>>::drain().for_each(|(_, v)| {310				add_weight(1, 1, Weight::zero());311				v.into_iter().for_each(|(staker, amount)| {312					<<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(313						&staker, amount,314					);315					add_weight(1, 1, Weight::zero());316				});317			});318319			consumed_weight320		}321322		#[cfg(feature = "try-runtime")]323		fn pre_upgrade() -> Result<Vec<u8>, &'static str> {324			use sp_std::collections::btree_map::BTreeMap;325			if <UpgradedToReserves<T>>::get() {326				return Ok(Default::default());327			}328			// Staker -> (total amount of reserved balance, reserved by promotion);329			let mut pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =330				BTreeMap::new();331332			<PendingUnstake<T>>::iter().for_each(|(_, v)| {333				v.into_iter().for_each(|(staker, amount)| {334					if let Some((_, reserved_balance)) = pre_state.get_mut(&staker) {335						*reserved_balance += amount;336					} else {337						let total_reserve = <<T as Config>::Currency as ReservableCurrency<338							T::AccountId,339						>>::reserved_balance(&staker);340						pre_state.insert(staker, (total_reserve, amount));341					}342				})343			});344345			Ok(pre_state.encode())346		}347348		#[cfg(feature = "try-runtime")]349		fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {350			use sp_std::collections::btree_map::BTreeMap;351352			if <UpgradedToReserves<T>>::get() {353				return Ok(());354			}355356			ensure!(357				<PendingUnstake<T>>::iter().collect::<Vec<_>>().len() == 0,358				"pendingUnstake storage isn't empty"359			);360361			let mut is_ok = true;362363			let pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =364				Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;365			for (staker, (total_reserved, reserved_by_promo)) in pre_state.into_iter() {366				let new_state_reserve = <<T as Config>::Currency as ReservableCurrency<367					T::AccountId,368				>>::reserved_balance(&staker);369				if new_state_reserve != total_reserved - reserved_by_promo {370					is_ok = false;371					log::error!(372								"Incorrect reserved balance for {:?}. New balance: {:?}. Before runtime upgrade: total reserve - {:?}, reserved by promo - {:?}",373								staker, new_state_reserve, total_reserved, reserved_by_promo374							);375				}376			}377378			if is_ok {379				Ok(())380			} else {381				Err("Incorrect balance for some of stakers... See logs")382			}383		}384	}385386	#[pallet::call]387	impl<T: Config> Pallet<T>388	where389		T::BlockNumber: From<u32> + Into<u32>,390		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,391	{392		/// Sets an address as the the admin.393		///394		/// # Permissions395		///396		/// * Sudo397		///398		/// # Arguments399		///400		/// * `admin`: account of the new admin.401		#[pallet::call_index(0)]402		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]403		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {404			ensure_root(origin)?;405406			<Admin<T>>::set(Some(admin.as_sub().to_owned()));407408			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));409410			Ok(())411		}412413		/// Stakes the amount of native tokens.414		/// Sets `amount` to the locked state.415		/// The maximum number of stakes for a staker is 10.416		///417		/// # Arguments418		///419		/// * `amount`: in native tokens.420		#[pallet::call_index(1)]421		#[pallet::weight(<T as Config>::WeightInfo::stake())]422		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {423			let staker_id = ensure_signed(staker)?;424425			ensure!(426				StakesPerAccount::<T>::get(&staker_id) < 10,427				Error::<T>::NoPermission428			);429430			ensure!(431				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),432				ArithmeticError::Underflow433			);434			let config = <PalletConfiguration<T>>::get();435436			let balance =437				<<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);438439			// checks that we can lock `amount` on the `staker` account.440			ensure!(441				amount442					<= match Self::get_locked_balance(&staker_id) {443						Some(lock) => balance444							.checked_sub(&lock.amount)445							.ok_or(ArithmeticError::Underflow)?,446						None => balance,447					},448				ArithmeticError::Underflow449			);450451			Self::add_lock_balance(&staker_id, amount)?;452453			let block_number = T::RelayBlockNumberProvider::current_block_number();454455			// Calculation of the number of recalculation periods,456			// after how much the first interest calculation should be performed for the stake457			let recalculate_after_interval: T::BlockNumber =458				if block_number % config.recalculation_interval == 0u32.into() {459					1u32.into()460				} else {461					2u32.into()462				};463464			// Сalculation of the number of the relay block465			// in which it is necessary to accrue remuneration for the stake.466			let recalc_block = (block_number / config.recalculation_interval467				+ recalculate_after_interval)468				* config.recalculation_interval;469470			<Staked<T>>::insert((&staker_id, block_number), {471				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));472				balance_and_recalc_block.0 = balance_and_recalc_block473					.0474					.checked_add(&amount)475					.ok_or(ArithmeticError::Overflow)?;476				balance_and_recalc_block.1 = recalc_block;477				balance_and_recalc_block478			});479480			<TotalStaked<T>>::set(481				<TotalStaked<T>>::get()482					.checked_add(&amount)483					.ok_or(ArithmeticError::Overflow)?,484			);485486			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);487488			Self::deposit_event(Event::Stake(staker_id, amount));489490			Ok(())491		}492493		/// Unstakes all stakes.494		/// After the end of `PendingInterval` this sum becomes completely495		/// free for further use.496		#[pallet::call_index(2)]497		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]498		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {499			let staker_id = ensure_signed(staker)?;500501			Self::unstake_all_internal(staker_id)502		}503504		/// Unstakes the amount of balance for the staker.505		/// After the end of `PendingInterval` this sum becomes completely506		/// free for further use.507		///508		///  # Arguments509		///510		/// * `staker`: staker account.511		/// * `amount`: amount of unstaked funds.512		#[pallet::call_index(8)]513		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]514		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {515			let staker_id = ensure_signed(staker)?;516517			Self::unstake_partial_internal(staker_id, amount)518		}519520		/// Sets the pallet to be the sponsor for the collection.521		///522		/// # Permissions523		///524		/// * Pallet admin525		///526		/// # Arguments527		///528		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`529		#[pallet::call_index(3)]530		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]531		pub fn sponsor_collection(532			admin: OriginFor<T>,533			collection_id: CollectionId,534		) -> DispatchResult {535			let admin_id = ensure_signed(admin)?;536			ensure!(537				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,538				Error::<T>::NoPermission539			);540541			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)542		}543544		/// Removes the pallet as the sponsor for the collection.545		/// Returns [`NoPermission`][`Error::NoPermission`]546		/// if the pallet wasn't the sponsor.547		///548		/// # Permissions549		///550		/// * Pallet admin551		///552		/// # Arguments553		///554		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`555		#[pallet::call_index(4)]556		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]557		pub fn stop_sponsoring_collection(558			admin: OriginFor<T>,559			collection_id: CollectionId,560		) -> DispatchResult {561			let admin_id = ensure_signed(admin)?;562563			ensure!(564				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,565				Error::<T>::NoPermission566			);567568			ensure!(569				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?570					== Self::account_id(),571				<Error<T>>::NoPermission572			);573			T::CollectionHandler::remove_collection_sponsor(collection_id)574		}575576		/// Sets the pallet to be the sponsor for the contract.577		///578		/// # Permissions579		///580		/// * Pallet admin581		///582		/// # Arguments583		///584		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`585		#[pallet::call_index(5)]586		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]587		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {588			let admin_id = ensure_signed(admin)?;589590			ensure!(591				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,592				Error::<T>::NoPermission593			);594595			T::ContractHandler::set_sponsor(596				T::CrossAccountId::from_sub(Self::account_id()),597				contract_id,598			)599		}600601		/// Removes the pallet as the sponsor for the contract.602		/// Returns [`NoPermission`][`Error::NoPermission`]603		/// if the pallet wasn't the sponsor.604		///605		/// # Permissions606		///607		/// * Pallet admin608		///609		/// # Arguments610		///611		/// * `contract_id`: the contract address that is sponsored by `pallet_id`612		#[pallet::call_index(6)]613		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]614		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {615			let admin_id = ensure_signed(admin)?;616617			ensure!(618				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,619				Error::<T>::NoPermission620			);621622			ensure!(623				T::ContractHandler::sponsor(contract_id)?624					.ok_or(<Error<T>>::SponsorNotSet)?625					.as_sub() == &Self::account_id(),626				<Error<T>>::NoPermission627			);628			T::ContractHandler::remove_contract_sponsor(contract_id)629		}630631		/// Recalculates interest for the specified number of stakers.632		/// If all stakers are not recalculated, the next call of the extrinsic633		/// will continue the recalculation, from those stakers for whom this634		/// was not perform in last call.635		///636		/// # Permissions637		///638		/// * Pallet admin639		///640		/// # Arguments641		///642		/// * `stakers_number`: the number of stakers for which recalculation will be performed643		#[pallet::call_index(7)]644		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]645		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {646			let admin_id = ensure_signed(admin)?;647648			ensure!(649				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,650				Error::<T>::NoPermission651			);652			let config = <PalletConfiguration<T>>::get();653654			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);655656			ensure!(657				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,658				Error::<T>::NoPermission659			);660661			// calculate the number of the current recalculation block,662			// this is necessary in order to understand which stakers we should calculate interest663			let current_recalc_block = Self::get_current_recalc_block(664				T::RelayBlockNumberProvider::current_block_number(),665				&config,666			);667668			// calculate the number of the next recalculation block,669			// this value is set for the stakers to whom the recalculation will be performed670			let next_recalc_block = current_recalc_block + config.recalculation_interval;671672			let mut storage_iterator = Self::get_next_calculated_key()673				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));674675			PreviousCalculatedRecord::<T>::set(None);676677			{678				// Address handled in the last payout loop iteration (below)679				let last_id = RefCell::new(None);680				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration681				let mut last_staked_calculated_block = Default::default();682				// Reward balance for the address in the iteration683				let income_acc = RefCell::new(BalanceOf::<T>::default());684				// Staked balance for the address in the iteration (before stake is recalculated)685				let amount_acc = RefCell::new(BalanceOf::<T>::default());686687				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout688				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout689				// loop switches to handling the next staker address:690				//   1. Transfer full reward amount to the payee691				//   2. Lock the reward in staking lock692				//   3. Update TotalStaked amount693				//   4. Issue StakingRecalculation event694				let flush_stake = || -> DispatchResult {695					if let Some(last_id) = &*last_id.borrow() {696						if !income_acc.borrow().is_zero() {697							<<T as Config>::Currency as Currency<T::AccountId>>::transfer(698								&T::TreasuryAccountId::get(),699								last_id,700								*income_acc.borrow(),701								ExistenceRequirement::KeepAlive,702							)?;703704							Self::add_lock_balance(last_id, *income_acc.borrow())?;705							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {706								*staked = staked707									.checked_add(&*income_acc.borrow())708									.ok_or(ArithmeticError::Overflow)?;709								Ok(())710							})?;711712							Self::deposit_event(Event::StakingRecalculation(713								last_id.clone(),714								*amount_acc.borrow(),715								*income_acc.borrow(),716							));717						}718719						*income_acc.borrow_mut() = BalanceOf::<T>::default();720						*amount_acc.borrow_mut() = BalanceOf::<T>::default();721					}722					Ok(())723				};724725				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation726				// iterations in one extrinsic call727				//728				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)729				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out730				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)731				while let Some((732					(current_id, staked_block),733					(amount, next_recalc_block_for_stake),734				)) = storage_iterator.next()735				{736					// last_id is not equal current_id when we switch to handling a new staker address737					// or just start handling the very first address. In the latter case last_id will be None and738					// flush_stake will do nothing739					if last_id.borrow().as_ref() != Some(&current_id) {740						if stakers_number > 0 {741							flush_stake()?;742							*last_id.borrow_mut() = Some(current_id.clone());743							stakers_number -= 1;744						}745						// Break out if we reached the address limit746						else {747							if let Some(staker) = &*last_id.borrow() {748								// Save the last calculated record to pick up in the next extrinsic call749								PreviousCalculatedRecord::<T>::set(Some((750									staker.clone(),751									last_staked_calculated_block,752								)));753							}754							break;755						};756					};757758					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount759					if current_recalc_block >= next_recalc_block_for_stake {760						*amount_acc.borrow_mut() += amount;761						Self::recalculate_and_insert_stake(762							&current_id,763							staked_block,764							next_recalc_block,765							amount,766							((current_recalc_block - next_recalc_block_for_stake)767								/ config.recalculation_interval)768								.into() + 1,769							&mut *income_acc.borrow_mut(),770						);771					}772					last_staked_calculated_block = staked_block;773				}774				flush_stake()?;775			}776777			Ok(())778		}779	}780}781782impl<T: Config> Pallet<T> {783	/// The account address of the app promotion pot.784	///785	/// This actually does computation. If you need to keep using it, then make sure you cache the786	/// value and only call this once.787	pub fn account_id() -> T::AccountId {788		T::PalletId::get().into_account_truncating()789	}790791	/// Unstakes the balance for the staker.792	///793	/// - `staker`: staker account.794	/// - `amount`: amount of unstaked funds.795	fn unstake_partial_internal(796		staker_id: T::AccountId,797		unstaked_balance: BalanceOf<T>,798	) -> DispatchResult {799		if unstaked_balance == Default::default() {800			return Ok(());801		}802803		let config = <PalletConfiguration<T>>::get();804805		// calculate block number where the sum would be free806		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;807808		let mut pendings = <PendingUnstake<T>>::get(unpending_block);809810		// checks that we can do unstake in the block811		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);812813		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();814815		let total_staked = stakes816			.iter()817			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {818				acc + *balance819			});820821		ensure!(822			unstaked_balance <= total_staked,823			<Error<T>>::InsufficientStakedBalance824		);825826		<TotalStaked<T>>::set(827			<TotalStaked<T>>::get()828				.checked_sub(&unstaked_balance)829				.ok_or(ArithmeticError::Underflow)?,830		);831832		stakes.sort_by_key(|(block, _)| *block);833834		let mut acc_amount = unstaked_balance;835		let mut will_deleted_stakes_count = 0u8;836837		let changed_stakes = stakes838			.into_iter()839			.map_while(|(block, (balance_per_block, _))| {840				if acc_amount == <BalanceOf<T>>::default() {841					return None;842				}843				if acc_amount < balance_per_block {844					let res = (block, balance_per_block - acc_amount);845					acc_amount = <BalanceOf<T>>::default();846					return Some(res);847				} else {848					acc_amount -= balance_per_block;849					will_deleted_stakes_count += 1;850					return Some((block, <BalanceOf<T>>::default()));851				}852			})853			.collect::<Vec<_>>();854855		pendings856			.try_push((staker_id.clone(), unstaked_balance))857			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;858859		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {860			*stakes = stakes861				.checked_sub(will_deleted_stakes_count)862				.ok_or(ArithmeticError::Underflow)?;863			Ok(())864		})?;865866		changed_stakes867			.into_iter()868			.for_each(|(staked_block, current_stake_state)| {869				if current_stake_state == Default::default() {870					<Staked<T>>::remove((&staker_id, staked_block));871				} else {872					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {873						*old_stake_state = current_stake_state874					});875				}876			});877878		<PendingUnstake<T>>::insert(unpending_block, pendings);879880		Self::deposit_event(Event::Unstake(staker_id, total_staked));881882		Ok(())883	}884885	/// Adds the balance to locked by the pallet.886	///887	/// - `staker`: staker account.888	/// - `amount`: amount of added locked funds.889	fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {890		Self::get_locked_balance(staker)891			.map_or(<BalanceOf<T>>::default(), |l| l.amount)892			.checked_add(&amount)893			.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))894			.ok_or(ArithmeticError::Overflow.into())895	}896897	/// Sets the new state of a balance locked by the pallet.898	///899	/// - `staker`: staker account.900	/// - `amount`: amount of locked funds.901	fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {902		if amount.is_zero() {903			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(904				LOCK_IDENTIFIER,905				&staker,906			);907		} else {908			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(909				LOCK_IDENTIFIER,910				staker,911				amount,912				WithdrawReasons::all(),913			)914		}915	}916917	/// Returns the balance locked by the pallet for the staker.918	///919	/// - `staker`: staker account.920	pub fn get_locked_balance(921		staker: impl EncodeLike<T::AccountId>,922	) -> Option<BalanceLock<BalanceOf<T>>> {923		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)924			.into_iter()925			.find(|l| l.id == LOCK_IDENTIFIER)926	}927928	/// Returns the total staked balance for the staker.929	///930	/// - `staker`: staker account.931	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {932		let staked = Staked::<T>::iter_prefix((staker,))933			.into_iter()934			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {935				acc + amount936			});937		if staked != <BalanceOf<T>>::default() {938			Some(staked)939		} else {940			None941		}942	}943944	/// Returns all relay block numbers when stake was made,945	/// the amount of the stake.946	///947	/// - `staker`: staker account.948	pub fn total_staked_by_id_per_block(949		staker: impl EncodeLike<T::AccountId>,950	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {951		let mut staked = Staked::<T>::iter_prefix((staker,))952			.into_iter()953			.map(|(block, (amount, _))| (block, amount))954			.collect::<Vec<_>>();955		staked.sort_by_key(|(block, _)| *block);956		if !staked.is_empty() {957			Some(staked)958		} else {959			None960		}961	}962963	/// Returns the total staked balance for the staker.964	/// If `staker` is `None`, returns the total amount staked.965	/// - `staker`: staker account.966	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {967		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {968			Self::total_staked_by_id(s.as_sub())969		})970	}971972	// pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {973	// 	Self::get_locked_balance(staker.as_sub())974	// 		.map(|l| l.amount)975	// 		.unwrap_or_default()976	// }977978	/// Returns all relay block numbers when stake was made,979	/// the amount of the stake.980	///981	/// - `staker`: staker account.982	pub fn cross_id_total_staked_per_block(983		staker: T::CrossAccountId,984	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {985		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()986	}987988	fn recalculate_and_insert_stake(989		staker: &T::AccountId,990		staked_block: T::BlockNumber,991		next_recalc_block: T::BlockNumber,992		base: BalanceOf<T>,993		iters: u32,994		income_acc: &mut BalanceOf<T>,995	) {996		let income = Self::calculate_income(base, iters);997998		base.checked_add(&income).map(|res| {999			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1000			*income_acc += income;1001		});1002	}10031004	fn calculate_income<I>(base: I, iters: u32) -> I1005	where1006		I: EncodeLike<BalanceOf<T>> + Balance,1007	{1008		let config = <PalletConfiguration<T>>::get();1009		let mut income = base;10101011		(0..iters).for_each(|_| income += config.interval_income * income);10121013		income - base1014	}10151016	/// Get relay block number rounded down to multiples of config.recalculation_interval.1017	/// We need it to reward stakers in integer parts of recalculation_interval1018	fn get_current_recalc_block(1019		current_relay_block: T::BlockNumber,1020		config: &PalletConfiguration<T>,1021	) -> T::BlockNumber {1022		(current_relay_block / config.recalculation_interval) * config.recalculation_interval1023	}10241025	fn get_next_calculated_key() -> Option<Vec<u8>> {1026		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))1027	}1028}10291030impl<T: Config> Pallet<T>1031where1032	<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,1033{1034	/// Returns the amount reserved by the pending.1035	/// If `staker` is `None`, returns the total pending.1036	///1037	/// -`staker`: staker account.1038	///1039	/// Since user funds are not transferred anywhere by staking, overflow protection is provided1040	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1041	/// the staker must have more funds on his account than the maximum set for `Balance` type.1042	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1043		staker.map_or(1044			PendingUnstake::<T>::iter_values()1045				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1046				.sum(),1047			|s| {1048				PendingUnstake::<T>::iter_values()1049					.flatten()1050					.filter_map(|(id, amount)| {1051						if id == *s.as_sub() {1052							Some(amount)1053						} else {1054							None1055						}1056					})1057					.sum()1058			},1059		)1060	}10611062	/// Returns all parachain block numbers when unreserve is expected,1063	/// the amount of the unreserved funds.1064	///1065	/// - `staker`: staker account.1066	pub fn cross_id_pending_unstake_per_block(1067		staker: T::CrossAccountId,1068	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1069		let mut unsorted_res = vec![];1070		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1071			pendings.into_iter().for_each(|(id, amount)| {1072				if id == *staker.as_sub() {1073					unsorted_res.push((block, amount));1074				};1075			})1076		});10771078		unsorted_res.sort_by_key(|(block, _)| *block);1079		unsorted_res1080	}10811082	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1083		let config = <PalletConfiguration<T>>::get();10841085		// calculate block number where the sum would be free1086		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;10871088		let mut pendings = <PendingUnstake<T>>::get(block);10891090		// checks that we can do unstake in the block1091		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);10921093		let mut total_stakes = 0u64;10941095		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1096			.map(|(_, (amount, _))| {1097				total_stakes += 1;1098				amount1099			})1100			.sum();11011102		if total_staked.is_zero() {1103			return Ok(());1104		}11051106		pendings1107			.try_push((staker_id.clone(), total_staked))1108			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;11091110		<PendingUnstake<T>>::insert(block, pendings);11111112		TotalStaked::<T>::set(1113			TotalStaked::<T>::get()1114				.checked_sub(&total_staked)1115				.ok_or(ArithmeticError::Underflow)?,1116		);11171118		StakesPerAccount::<T>::remove(&staker_id);11191120		Self::deposit_event(Event::Unstake(staker_id, total_staked));11211122		Ok(())1123	}1124}