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

difftreelog

chore(app-promo) changes based on review

PraetorP2023-05-31parent: #313d931.patch.diff
in: master
Added a comment for code. Change `force_unstake` ext behaviour.

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		Get, LockableCurrency,74		tokens::Balance,75		fungible::{Inspect, InspectFreeze, Mutate, MutateFreeze},76	},77	ensure, BoundedVec,78};7980use weights::WeightInfo;8182pub use pallet::*;83use pallet_evm::account::CrossAccountId;84use sp_runtime::{85	Perbill,86	traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},87	ArithmeticError, DispatchError,88};8990pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";9192const PENDING_LIMIT_PER_BLOCK: u32 = 3;9394type BalanceOf<T> =95	<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;9697#[frame_support::pallet]98pub mod pallet {99	use super::*;100	use frame_support::{101		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId, weights::Weight,102	};103	use frame_system::pallet_prelude::*;104	use sp_runtime::DispatchError;105106	#[pallet::config]107	pub trait Config:108		frame_system::Config + pallet_evm::Config + pallet_configuration::Config109	{110		/// Type to interact with the native token111		type Currency: MutateFreeze<Self::AccountId>112			+ Mutate<Self::AccountId>113			+ ExtendedLockableCurrency<114				Self::AccountId,115				Balance = <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,116			>;117118		/// Type for interacting with collections119		type CollectionHandler: CollectionHandler<120			AccountId = Self::AccountId,121			CollectionId = CollectionId,122		>;123124		/// Type for interacting with conrtacts125		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;126127		/// `AccountId` for treasury128		type TreasuryAccountId: Get<Self::AccountId>;129130		/// The app's pallet id, used for deriving its sovereign account address.131		#[pallet::constant]132		type PalletId: Get<PalletId>;133134		/// Freeze identifier used by the pallet135		#[pallet::constant]136		type FreezeIdentifier: Get<137			<<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id,138		>;139140		/// In relay blocks.141		#[pallet::constant]142		type RecalculationInterval: Get<Self::BlockNumber>;143144		/// In parachain blocks.145		#[pallet::constant]146		type PendingInterval: Get<Self::BlockNumber>;147148		/// Rate of return for interval in blocks defined in `RecalculationInterval`.149		#[pallet::constant]150		type IntervalIncome: Get<Perbill>;151152		/// Decimals for the `Currency`.153		#[pallet::constant]154		type Nominal: Get<BalanceOf<Self>>;155156		/// Maintenance mode status.157		type IsMaintenanceModeEnabled: Get<bool>;158159		/// Weight information for extrinsics in this pallet.160		type WeightInfo: WeightInfo;161162		// The relay block number provider163		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;164165		/// Events compatible with [`frame_system::Config::Event`].166		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;167	}168169	#[pallet::pallet]170	pub struct Pallet<T>(_);171172	#[pallet::event]173	#[pallet::generate_deposit(pub(super) fn deposit_event)]174	pub enum Event<T: Config> {175		/// Staking recalculation was performed176		///177		/// # Arguments178		/// * AccountId: account of the staker.179		/// * Balance : recalculation base180		/// * Balance : total income181		StakingRecalculation(182			/// An recalculated staker183			T::AccountId,184			/// Base on which interest is calculated185			BalanceOf<T>,186			/// Amount of accrued interest187			BalanceOf<T>,188		),189190		/// Staking was performed191		///192		/// # Arguments193		/// * AccountId: account of the staker194		/// * Balance : staking amount195		Stake(T::AccountId, BalanceOf<T>),196197		/// Unstaking was performed198		///199		/// # Arguments200		/// * AccountId: account of the staker201		/// * Balance : unstaking amount202		Unstake(T::AccountId, BalanceOf<T>),203204		/// The admin was set205		///206		/// # Arguments207		/// * AccountId: account address of the admin208		SetAdmin(T::AccountId),209	}210211	#[pallet::error]212	pub enum Error<T> {213		/// Error due to action requiring admin to be set.214		AdminNotSet,215		/// No permission to perform an action.216		NoPermission,217		/// Insufficient funds to perform an action.218		NotSufficientFunds,219		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.220		PendingForBlockOverflow,221		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.222		SponsorNotSet,223		/// Errors caused by insufficient staked balance.224		InsufficientStakedBalance,225		/// Errors caused by incorrect state of a staker in context of the pallet.226		InconsistencyState,227	}228229	/// Stores the total staked amount.230	#[pallet::storage]231	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;232233	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.234	#[pallet::storage]235	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;236237	/// Stores the amount of tokens staked by account in the blocknumber.238	///239	/// * **Key1** - Staker account.240	/// * **Key2** - Relay block number when the stake was made.241	/// * **(Balance, BlockNumber)** - Balance of the stake.242	/// The number of the relay block in which we must perform the interest recalculation243	#[pallet::storage]244	pub type Staked<T: Config> = StorageNMap<245		Key = (246			Key<Blake2_128Concat, T::AccountId>,247			Key<Twox64Concat, T::BlockNumber>,248		),249		Value = (BalanceOf<T>, T::BlockNumber),250		QueryKind = ValueQuery,251	>;252253	/// Stores number of stake records for an `Account`.254	///255	/// * **Key** - Staker account.256	/// * **Value** - Amount of stakes.257	#[pallet::storage]258	pub type StakesPerAccount<T: Config> =259		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;260261	/// Pending unstake records for an `Account`.262	///263	/// * **Key** - Staker account.264	/// * **Value** - Amount of stakes.265	#[pallet::storage]266	pub type PendingUnstake<T: Config> = StorageMap<267		_,268		Twox64Concat,269		T::BlockNumber,270		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,271		ValueQuery,272	>;273274	/// Stores a key for record for which the revenue recalculation was performed.275	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.276	#[pallet::storage]277	#[pallet::getter(fn get_next_calculated_record)]278	pub type PreviousCalculatedRecord<T: Config> =279		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;280281	#[pallet::hooks]282	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {283		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize284		/// implies the execution of a strictly limited number of relatively lightweight operations.285		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.286		fn on_initialize(current_block_number: T::BlockNumber) -> Weight287		where288			<T as frame_system::Config>::BlockNumber: From<u32>,289		{290			if T::IsMaintenanceModeEnabled::get() {291				return T::DbWeight::get().reads_writes(1, 0);292			}293294			let block_pending = PendingUnstake::<T>::take(current_block_number);295			let counter = block_pending.len() as u32;296297			if !block_pending.is_empty() {298				block_pending.into_iter().for_each(|(staker, amount)| {299					Self::get_frozen_balance(&staker).map(|b| {300						let new_state = b.checked_sub(&amount).unwrap_or_default();301302						// In this case, setting a new state for the frozen funds cannot fail303						// because the state change goes in the direction of decreasing the frozen funds304						// and the validity of this transition is ensured by the fact305						// that we cannot (in the current implementation) unfreeze more funds306						// than were originally frozen by the pallet. Either way, `on_initialize()` cannot fail.307						Self::set_freeze_unchecked(&staker, new_state);308					});309				});310			}311312			<T as Config>::WeightInfo::on_initialize(counter)313		}314	}315316	#[pallet::call]317	impl<T: Config> Pallet<T>318	where319		T::BlockNumber: From<u32> + Into<u32>,320		<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,321	{322		/// Sets an address as the the admin.323		///324		/// # Permissions325		///326		/// * Sudo327		///328		/// # Arguments329		///330		/// * `admin`: account of the new admin.331		#[pallet::call_index(0)]332		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]333		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {334			ensure_root(origin)?;335336			<Admin<T>>::set(Some(admin.as_sub().to_owned()));337338			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));339340			Ok(())341		}342343		/// Stakes the amount of native tokens.344		/// Sets `amount` to the locked state.345		/// The maximum number of stakes for a staker is 10.346		///347		/// # Arguments348		///349		/// * `amount`: in native tokens.350		#[pallet::call_index(1)]351		#[pallet::weight(<T as Config>::WeightInfo::stake())]352		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {353			let staker_id = ensure_signed(staker)?;354355			ensure!(356				StakesPerAccount::<T>::get(&staker_id) < 10,357				Error::<T>::NoPermission358			);359360			ensure!(361				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),362				ArithmeticError::Underflow363			);364			let config = <PalletConfiguration<T>>::get();365366			let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);367368			// checks that we can freeze `amount` on the `staker` account.369			ensure!(370				amount371					<= match Self::get_frozen_balance(&staker_id) {372						Some(frozen_by_pallet) => balance373							.checked_sub(&frozen_by_pallet)374							.ok_or(ArithmeticError::Underflow)?,375						None => balance,376					},377				ArithmeticError::Underflow378			);379380			Self::add_freeze_balance(&staker_id, amount)?;381382			let block_number = T::RelayBlockNumberProvider::current_block_number();383384			// Calculation of the number of recalculation periods,385			// after how much the first interest calculation should be performed for the stake386			let recalculate_after_interval: T::BlockNumber =387				if block_number % config.recalculation_interval == 0u32.into() {388					1u32.into()389				} else {390					2u32.into()391				};392393			// Сalculation of the number of the relay block394			// in which it is necessary to accrue remuneration for the stake.395			let recalc_block = (block_number / config.recalculation_interval396				+ recalculate_after_interval)397				* config.recalculation_interval;398399			<Staked<T>>::insert((&staker_id, block_number), {400				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));401				balance_and_recalc_block.0 = balance_and_recalc_block402					.0403					.checked_add(&amount)404					.ok_or(ArithmeticError::Overflow)?;405				balance_and_recalc_block.1 = recalc_block;406				balance_and_recalc_block407			});408409			<TotalStaked<T>>::set(410				<TotalStaked<T>>::get()411					.checked_add(&amount)412					.ok_or(ArithmeticError::Overflow)?,413			);414415			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);416417			Self::deposit_event(Event::Stake(staker_id, amount));418419			Ok(())420		}421422		/// Unstakes all stakes.423		/// After the end of `PendingInterval` this sum becomes completely424		/// free for further use.425		#[pallet::call_index(2)]426		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]427		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {428			let staker_id = ensure_signed(staker)?;429430			Self::unstake_all_internal(staker_id)431		}432433		/// Unstakes the amount of balance for the staker.434		/// After the end of `PendingInterval` this sum becomes completely435		/// free for further use.436		///437		///  # Arguments438		///439		/// * `staker`: staker account.440		/// * `amount`: amount of unstaked funds.441		#[pallet::call_index(8)]442		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]443		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {444			let staker_id = ensure_signed(staker)?;445446			Self::unstake_partial_internal(staker_id, amount)447		}448449		/// Sets the pallet to be the sponsor for the collection.450		///451		/// # Permissions452		///453		/// * Pallet admin454		///455		/// # Arguments456		///457		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`458		#[pallet::call_index(3)]459		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]460		pub fn sponsor_collection(461			admin: OriginFor<T>,462			collection_id: CollectionId,463		) -> DispatchResult {464			let admin_id = ensure_signed(admin)?;465			ensure!(466				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,467				Error::<T>::NoPermission468			);469470			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)471		}472473		/// Removes the pallet as the sponsor for the collection.474		/// Returns [`NoPermission`][`Error::NoPermission`]475		/// if the pallet wasn't the sponsor.476		///477		/// # Permissions478		///479		/// * Pallet admin480		///481		/// # Arguments482		///483		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`484		#[pallet::call_index(4)]485		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]486		pub fn stop_sponsoring_collection(487			admin: OriginFor<T>,488			collection_id: CollectionId,489		) -> DispatchResult {490			let admin_id = ensure_signed(admin)?;491492			ensure!(493				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,494				Error::<T>::NoPermission495			);496497			ensure!(498				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?499					== Self::account_id(),500				<Error<T>>::NoPermission501			);502			T::CollectionHandler::remove_collection_sponsor(collection_id)503		}504505		/// Sets the pallet to be the sponsor for the contract.506		///507		/// # Permissions508		///509		/// * Pallet admin510		///511		/// # Arguments512		///513		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`514		#[pallet::call_index(5)]515		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]516		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {517			let admin_id = ensure_signed(admin)?;518519			ensure!(520				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,521				Error::<T>::NoPermission522			);523524			T::ContractHandler::set_sponsor(525				T::CrossAccountId::from_sub(Self::account_id()),526				contract_id,527			)528		}529530		/// Removes the pallet as the sponsor for the contract.531		/// Returns [`NoPermission`][`Error::NoPermission`]532		/// if the pallet wasn't the sponsor.533		///534		/// # Permissions535		///536		/// * Pallet admin537		///538		/// # Arguments539		///540		/// * `contract_id`: the contract address that is sponsored by `pallet_id`541		#[pallet::call_index(6)]542		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]543		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {544			let admin_id = ensure_signed(admin)?;545546			ensure!(547				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,548				Error::<T>::NoPermission549			);550551			ensure!(552				T::ContractHandler::sponsor(contract_id)?553					.ok_or(<Error<T>>::SponsorNotSet)?554					.as_sub() == &Self::account_id(),555				<Error<T>>::NoPermission556			);557			T::ContractHandler::remove_contract_sponsor(contract_id)558		}559560		/// Recalculates interest for the specified number of stakers.561		/// If all stakers are not recalculated, the next call of the extrinsic562		/// will continue the recalculation, from those stakers for whom this563		/// was not perform in last call.564		///565		/// # Permissions566		///567		/// * Pallet admin568		///569		/// # Arguments570		///571		/// * `stakers_number`: the number of stakers for which recalculation will be performed572		#[pallet::call_index(7)]573		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]574		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {575			let admin_id = ensure_signed(admin)?;576577			ensure!(578				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,579				Error::<T>::NoPermission580			);581			let config = <PalletConfiguration<T>>::get();582583			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);584585			ensure!(586				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,587				Error::<T>::NoPermission588			);589590			// calculate the number of the current recalculation block,591			// this is necessary in order to understand which stakers we should calculate interest592			let current_recalc_block = Self::get_current_recalc_block(593				T::RelayBlockNumberProvider::current_block_number(),594				&config,595			);596597			// calculate the number of the next recalculation block,598			// this value is set for the stakers to whom the recalculation will be performed599			let next_recalc_block = current_recalc_block + config.recalculation_interval;600601			let mut storage_iterator = Self::get_next_calculated_key()602				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));603604			PreviousCalculatedRecord::<T>::set(None);605606			{607				// Address handled in the last payout loop iteration (below)608				let last_id = RefCell::new(None);609				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration610				let mut last_staked_calculated_block = Default::default();611				// Reward balance for the address in the iteration612				let income_acc = RefCell::new(BalanceOf::<T>::default());613				// Staked balance for the address in the iteration (before stake is recalculated)614				let amount_acc = RefCell::new(BalanceOf::<T>::default());615616				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout617				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout618				// loop switches to handling the next staker address:619				//   1. Transfer full reward amount to the payee620				//   2. Lock the reward in staking lock621				//   3. Update TotalStaked amount622				//   4. Issue StakingRecalculation event623				let flush_stake = || -> DispatchResult {624					if let Some(last_id) = &*last_id.borrow() {625						if !income_acc.borrow().is_zero() {626							<<T as Config>::Currency as Mutate<T::AccountId>>::transfer(627								&T::TreasuryAccountId::get(),628								last_id,629								*income_acc.borrow(),630								frame_support::traits::tokens::Preservation::Protect,631							)?;632633							Self::add_freeze_balance(last_id, *income_acc.borrow())?;634							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {635								*staked = staked636									.checked_add(&*income_acc.borrow())637									.ok_or(ArithmeticError::Overflow)?;638								Ok(())639							})?;640641							Self::deposit_event(Event::StakingRecalculation(642								last_id.clone(),643								*amount_acc.borrow(),644								*income_acc.borrow(),645							));646						}647648						*income_acc.borrow_mut() = BalanceOf::<T>::default();649						*amount_acc.borrow_mut() = BalanceOf::<T>::default();650					}651					Ok(())652				};653654				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation655				// iterations in one extrinsic call656				//657				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)658				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out659				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)660				while let Some((661					(current_id, staked_block),662					(amount, next_recalc_block_for_stake),663				)) = storage_iterator.next()664				{665					// last_id is not equal current_id when we switch to handling a new staker address666					// or just start handling the very first address. In the latter case last_id will be None and667					// flush_stake will do nothing668					if last_id.borrow().as_ref() != Some(&current_id) {669						if stakers_number > 0 {670							flush_stake()?;671							*last_id.borrow_mut() = Some(current_id.clone());672							stakers_number -= 1;673						}674						// Break out if we reached the address limit675						else {676							if let Some(staker) = &*last_id.borrow() {677								// Save the last calculated record to pick up in the next extrinsic call678								PreviousCalculatedRecord::<T>::set(Some((679									staker.clone(),680									last_staked_calculated_block,681								)));682							}683							break;684						};685					};686687					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount688					if current_recalc_block >= next_recalc_block_for_stake {689						*amount_acc.borrow_mut() += amount;690						Self::recalculate_and_insert_stake(691							&current_id,692							staked_block,693							next_recalc_block,694							amount,695							((current_recalc_block - next_recalc_block_for_stake)696								/ config.recalculation_interval)697								.into() + 1,698							&mut *income_acc.borrow_mut(),699						);700					}701					last_staked_calculated_block = staked_block;702				}703				flush_stake()?;704			}705706			Ok(())707		}708709		///  Migrates lock state into freeze one710		///711		/// # Permissions712		///713		/// * Sudo714		///715		///   # Arguments716		///717		/// * `origin`: Must be `Signed`.718		/// * `stakers`: Accounts to be upgraded.719		#[pallet::call_index(9)]720		#[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]721		pub fn upgrade_accounts(722			origin: OriginFor<T>,723			stakers: Vec<T::AccountId>,724		) -> DispatchResult {725			ensure_root(origin)?;726727			stakers728				.into_iter()729				.try_for_each(|s| -> Result<_, DispatchError> {730					if let Some(BalanceLock { amount, .. }) = Self::get_locked_balance(&s) {731						if Self::get_frozen_balance(&s).is_some() {732							return Err(Error::<T>::InconsistencyState.into());733						}734735						<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(736							LOCK_IDENTIFIER,737							&s,738						);739740						Self::set_freeze_with_result(&s, amount)?;741						Ok(())742					} else {743						Ok(())744					}745				})?;746747			Ok(())748		}749750		/// Called for blocks that, for some reason, have not been unstacked751		///752		/// # Permissions753		///754		/// * Sudo755		///756		///   # Arguments757		///758		/// * `origin`: Must be `Signed`.759		/// * `pending_blocks`: Block numbers that will be processed.760		#[pallet::call_index(10)]761		#[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]762		pub fn force_unstake(763			origin: OriginFor<T>,764			pending_blocks: Vec<T::BlockNumber>,765		) -> DispatchResult {766			ensure_root(origin)?;767768			ensure!(769				pending_blocks770					.iter()771					.all(|b| *b < <frame_system::Pallet<T>>::block_number()),772				<Error<T>>::NoPermission773			);774775			let mut pendings =776				Vec::with_capacity(PENDING_LIMIT_PER_BLOCK as usize * pending_blocks.len());777			pending_blocks778				.into_iter()779				.for_each(|b| pendings.append(&mut PendingUnstake::<T>::take(b).into_inner()));780781			pendings782				.into_iter()783				.try_for_each(|(staker, amount)| -> Result<(), DispatchError> {784					if let Some(b) = Self::get_frozen_balance(&staker) {785						let new_state = b.checked_sub(&amount).unwrap_or_default();786						Self::set_freeze_with_result(&staker, new_state)?;787					}788789					Ok(())790				})?;791792			Ok(())793		}794	}795}796797impl<T: Config> Pallet<T> {798	/// The account address of the app promotion pot.799	///800	/// This actually does computation. If you need to keep using it, then make sure you cache the801	/// value and only call this once.802	pub fn account_id() -> T::AccountId {803		T::PalletId::get().into_account_truncating()804	}805806	/// Unstakes the balance for the staker.807	///808	/// - `staker`: staker account.809	/// - `amount`: amount of unstaked funds.810	fn unstake_partial_internal(811		staker_id: T::AccountId,812		unstaked_balance: BalanceOf<T>,813	) -> DispatchResult {814		if unstaked_balance == Default::default() {815			return Ok(());816		}817818		let config = <PalletConfiguration<T>>::get();819820		// calculate block number where the sum would be free821		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;822823		let mut pendings = <PendingUnstake<T>>::get(unpending_block);824825		// checks that we can do unstake in the block826		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);827828		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();829830		let total_staked = stakes831			.iter()832			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {833				acc + *balance834			});835836		ensure!(837			unstaked_balance <= total_staked,838			<Error<T>>::InsufficientStakedBalance839		);840841		<TotalStaked<T>>::set(842			<TotalStaked<T>>::get()843				.checked_sub(&unstaked_balance)844				.ok_or(ArithmeticError::Underflow)?,845		);846847		stakes.sort_by_key(|(block, _)| *block);848849		let mut acc_amount = unstaked_balance;850		let mut will_deleted_stakes_count = 0u8;851852		let changed_stakes = stakes853			.into_iter()854			.map_while(|(block, (balance_per_block, _))| {855				if acc_amount == <BalanceOf<T>>::default() {856					return None;857				}858				if acc_amount < balance_per_block {859					let res = (block, balance_per_block - acc_amount);860					acc_amount = <BalanceOf<T>>::default();861					return Some(res);862				} else {863					acc_amount -= balance_per_block;864					will_deleted_stakes_count += 1;865					return Some((block, <BalanceOf<T>>::default()));866				}867			})868			.collect::<Vec<_>>();869870		pendings871			.try_push((staker_id.clone(), unstaked_balance))872			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;873874		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {875			*stakes = stakes876				.checked_sub(will_deleted_stakes_count)877				.ok_or(ArithmeticError::Underflow)?;878			Ok(())879		})?;880881		changed_stakes882			.into_iter()883			.for_each(|(staked_block, current_stake_state)| {884				if current_stake_state == Default::default() {885					<Staked<T>>::remove((&staker_id, staked_block));886				} else {887					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {888						*old_stake_state = current_stake_state889					});890				}891			});892893		<PendingUnstake<T>>::insert(unpending_block, pendings);894895		Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));896897		Ok(())898	}899900	/// Adds the balance to frozen by the pallet.901	///902	/// - `staker`: staker account.903	/// - `amount`: amount of added frozen funds.904	fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {905		Self::get_frozen_balance(staker)906			.unwrap_or_default()907			.checked_add(&amount)908			.map(|freeze| Self::set_freeze_with_result(staker, freeze))909			.ok_or::<DispatchError>(ArithmeticError::Overflow.into())?910	}911912	/// Sets the new state of a balance frozen by the pallet.913	///914	/// - `staker`: staker account.915	/// - `amount`: amount of frozen funds.916	fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {917		let _ = Self::set_freeze_with_result(staker, amount);918	}919920	/// Sets the new state of a balance frozen by the pallet.921	///922	/// - `staker`: staker account.923	/// - `amount`: amount of frozen funds.924	fn set_freeze_with_result(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {925		if amount.is_zero() {926			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(927				&T::FreezeIdentifier::get(),928				&staker,929			)930		} else {931			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(932				&T::FreezeIdentifier::get(),933				staker,934				amount,935			)936		}937	}938939	/// Returns the balance locked by the pallet for the staker.940	///941	/// - `staker`: staker account.942	pub fn get_locked_balance(943		staker: impl EncodeLike<T::AccountId>,944	) -> Option<BalanceLock<BalanceOf<T>>> {945		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)946			.into_iter()947			.find(|l| l.id == LOCK_IDENTIFIER)948	}949950	/// Returns the balance frozen by the pallet for the staker.951	///952	/// - `staker`: staker account.953	pub fn get_frozen_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {954		let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(955			&T::FreezeIdentifier::get(),956			staker,957		);958959		if res == Zero::zero() {960			None961		} else {962			Some(res)963		}964	}965966	/// Returns the total staked balance for the staker.967	///968	/// - `staker`: staker account.969	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {970		let staked = Staked::<T>::iter_prefix((staker,))971			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {972				acc + amount973			});974		if staked != <BalanceOf<T>>::default() {975			Some(staked)976		} else {977			None978		}979	}980981	/// Returns all relay block numbers when stake was made,982	/// the amount of the stake.983	///984	/// - `staker`: staker account.985	pub fn total_staked_by_id_per_block(986		staker: impl EncodeLike<T::AccountId>,987	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {988		let mut staked = Staked::<T>::iter_prefix((staker,))989			.map(|(block, (amount, _))| (block, amount))990			.collect::<Vec<_>>();991		staked.sort_by_key(|(block, _)| *block);992		if !staked.is_empty() {993			Some(staked)994		} else {995			None996		}997	}998999	/// Returns the total staked balance for the staker.1000	/// If `staker` is `None`, returns the total amount staked.1001	/// - `staker`: staker account.1002	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1003		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1004			Self::total_staked_by_id(s.as_sub())1005		})1006	}10071008	/// Returns all relay block numbers when stake was made,1009	/// the amount of the stake.1010	///1011	/// - `staker`: staker account.1012	pub fn cross_id_total_staked_per_block(1013		staker: T::CrossAccountId,1014	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1015		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1016	}10171018	fn recalculate_and_insert_stake(1019		staker: &T::AccountId,1020		staked_block: T::BlockNumber,1021		next_recalc_block: T::BlockNumber,1022		base: BalanceOf<T>,1023		iters: u32,1024		income_acc: &mut BalanceOf<T>,1025	) {1026		let income = Self::calculate_income(base, iters);10271028		base.checked_add(&income).map(|res| {1029			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1030			*income_acc += income;1031		});1032	}10331034	fn calculate_income<I>(base: I, iters: u32) -> I1035	where1036		I: EncodeLike<BalanceOf<T>> + Balance,1037	{1038		let config = <PalletConfiguration<T>>::get();1039		let mut income = base;10401041		(0..iters).for_each(|_| income += config.interval_income * income);10421043		income - base1044	}10451046	/// Get relay block number rounded down to multiples of config.recalculation_interval.1047	/// We need it to reward stakers in integer parts of recalculation_interval1048	fn get_current_recalc_block(1049		current_relay_block: T::BlockNumber,1050		config: &PalletConfiguration<T>,1051	) -> T::BlockNumber {1052		(current_relay_block / config.recalculation_interval) * config.recalculation_interval1053	}10541055	fn get_next_calculated_key() -> Option<Vec<u8>> {1056		Self::get_next_calculated_record().map(Staked::<T>::hashed_key_for)1057	}1058}10591060impl<T: Config> Pallet<T>1061where1062	<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1063{1064	/// Returns the amount reserved by the pending.1065	/// If `staker` is `None`, returns the total pending.1066	///1067	/// -`staker`: staker account.1068	///1069	/// Since user funds are not transferred anywhere by staking, overflow protection is provided1070	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1071	/// the staker must have more funds on his account than the maximum set for `Balance` type.1072	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1073		staker.map_or(1074			PendingUnstake::<T>::iter_values()1075				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1076				.sum(),1077			|s| {1078				PendingUnstake::<T>::iter_values()1079					.flatten()1080					.filter_map(|(id, amount)| {1081						if id == *s.as_sub() {1082							Some(amount)1083						} else {1084							None1085						}1086					})1087					.sum()1088			},1089		)1090	}10911092	/// Returns all parachain block numbers when unreserve is expected,1093	/// the amount of the unreserved funds.1094	///1095	/// - `staker`: staker account.1096	pub fn cross_id_pending_unstake_per_block(1097		staker: T::CrossAccountId,1098	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1099		let mut unsorted_res = vec![];1100		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1101			pendings.into_iter().for_each(|(id, amount)| {1102				if id == *staker.as_sub() {1103					unsorted_res.push((block, amount));1104				};1105			})1106		});11071108		unsorted_res.sort_by_key(|(block, _)| *block);1109		unsorted_res1110	}11111112	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1113		let config = <PalletConfiguration<T>>::get();11141115		// calculate block number where the sum would be free1116		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;11171118		let mut pendings = <PendingUnstake<T>>::get(block);11191120		// checks that we can do unstake in the block1121		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);11221123		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1124			.map(|(_, (amount, _))| amount)1125			.sum();11261127		if total_staked.is_zero() {1128			return Ok(());1129		}11301131		pendings1132			.try_push((staker_id.clone(), total_staked))1133			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;11341135		<PendingUnstake<T>>::insert(block, pendings);11361137		TotalStaked::<T>::set(1138			TotalStaked::<T>::get()1139				.checked_sub(&total_staked)1140				.ok_or(ArithmeticError::Underflow)?,1141		);11421143		StakesPerAccount::<T>::remove(&staker_id);11441145		Self::deposit_event(Event::Unstake(staker_id, total_staked));11461147		Ok(())1148	}1149}