git.delta.rocks / unique-network / refs/commits / 37e76bc01ac1

difftreelog

source

pallets/app-promotion/src/lib.rs37.8 KiBsourcehistory
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,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		/// Weight information for extrinsics in this pallet.157		type WeightInfo: WeightInfo;158159		// The relay block number provider160		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;161162		/// Events compatible with [`frame_system::Config::Event`].163		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;164	}165166	#[pallet::pallet]167	pub struct Pallet<T>(_);168169	#[pallet::event]170	#[pallet::generate_deposit(pub(super) fn deposit_event)]171	pub enum Event<T: Config> {172		/// Staking recalculation was performed173		///174		/// # Arguments175		/// * AccountId: account of the staker.176		/// * Balance : recalculation base177		/// * Balance : total income178		StakingRecalculation(179			/// An recalculated staker180			T::AccountId,181			/// Base on which interest is calculated182			BalanceOf<T>,183			/// Amount of accrued interest184			BalanceOf<T>,185		),186187		/// Staking was performed188		///189		/// # Arguments190		/// * AccountId: account of the staker191		/// * Balance : staking amount192		Stake(T::AccountId, BalanceOf<T>),193194		/// Unstaking was performed195		///196		/// # Arguments197		/// * AccountId: account of the staker198		/// * Balance : unstaking amount199		Unstake(T::AccountId, BalanceOf<T>),200201		/// The admin was set202		///203		/// # Arguments204		/// * AccountId: account address of the admin205		SetAdmin(T::AccountId),206	}207208	#[pallet::error]209	pub enum Error<T> {210		/// Error due to action requiring admin to be set.211		AdminNotSet,212		/// No permission to perform an action.213		NoPermission,214		/// Insufficient funds to perform an action.215		NotSufficientFunds,216		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.217		PendingForBlockOverflow,218		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.219		SponsorNotSet,220		/// Errors caused by insufficient staked balance.221		InsufficientStakedBalance,222		/// Errors caused by incorrect state of a staker in context of the pallet.223		InconsistencyState,224	}225226	/// Stores the total staked amount.227	#[pallet::storage]228	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;229230	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.231	#[pallet::storage]232	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;233234	/// Stores the amount of tokens staked by account in the blocknumber.235	///236	/// * **Key1** - Staker account.237	/// * **Key2** - Relay block number when the stake was made.238	/// * **(Balance, BlockNumber)** - Balance of the stake.239	/// The number of the relay block in which we must perform the interest recalculation240	#[pallet::storage]241	pub type Staked<T: Config> = StorageNMap<242		Key = (243			Key<Blake2_128Concat, T::AccountId>,244			Key<Twox64Concat, T::BlockNumber>,245		),246		Value = (BalanceOf<T>, T::BlockNumber),247		QueryKind = ValueQuery,248	>;249250	/// Stores number of stake records for an `Account`.251	///252	/// * **Key** - Staker account.253	/// * **Value** - Amount of stakes.254	#[pallet::storage]255	pub type StakesPerAccount<T: Config> =256		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;257258	/// Pending unstake records for an `Account`.259	///260	/// * **Key** - Staker account.261	/// * **Value** - Amount of stakes.262	#[pallet::storage]263	pub type PendingUnstake<T: Config> = StorageMap<264		_,265		Twox64Concat,266		T::BlockNumber,267		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,268		ValueQuery,269	>;270271	/// Stores a key for record for which the revenue recalculation was performed.272	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.273	#[pallet::storage]274	#[pallet::getter(fn get_next_calculated_record)]275	pub type PreviousCalculatedRecord<T: Config> =276		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;277278	// #[pallet::storage]279	// pub(crate) type UpgradedToFreezes<T: Config> =280	// 	StorageValue<Value = bool, QueryKind = ValueQuery>;281282	#[pallet::hooks]283	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {284		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize285		/// implies the execution of a strictly limited number of relatively lightweight operations.286		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.287		fn on_initialize(current_block_number: T::BlockNumber) -> Weight288		where289			<T as frame_system::Config>::BlockNumber: From<u32>,290		{291			let block_pending = PendingUnstake::<T>::take(current_block_number);292			let counter = block_pending.len() as u32;293294			if !block_pending.is_empty() {295				block_pending.into_iter().for_each(|(staker, amount)| {296					Self::get_frozen_balance(&staker).map(|b| {297						let new_state = b.checked_sub(&amount).unwrap_or_default();298						Self::set_freeze_unchecked(&staker, new_state);299					});300				});301			}302303			<T as Config>::WeightInfo::on_initialize(counter)304		}305306		// fn on_runtime_upgrade() -> Weight {307		// 	use scale_info::prelude::collections::HashSet;308		// 	let mut consumed_weight = Weight::zero();309		// 	let mut add_weight = |reads, writes, weight| {310		// 		consumed_weight += T::DbWeight::get().reads_writes(reads, writes);311		// 		consumed_weight += weight;312		// 	};313314		// 	let mut stakes_unstakes = vec![];315316		// 	if <UpgradedToFreezes<T>>::get() {317		// 		add_weight(1, 0, Weight::zero());318		// 		return consumed_weight;319		// 	} else {320		// 		add_weight(1, 1, Weight::zero());321		// 		<UpgradedToFreezes<T>>::set(true);322		// 	}323		// 	<Staked<T>>::iter_keys().for_each(|(staker_id, _)| {324		// 		add_weight(1, 0, Weight::zero());325		// 		stakes_unstakes.push(staker_id);326		// 	});327328		// 	<PendingUnstake<T>>::iter().for_each(|(_, v)| {329		// 		add_weight(1, 0, Weight::zero());330		// 		v.into_iter().for_each(|(staker, _)| {331		// 			stakes_unstakes.push(staker);332		// 		});333		// 	});334335		// 	// filter duplicated id.336		// 	stakes_unstakes = stakes_unstakes337		// 		.into_iter()338		// 		.map(|key| key)339		// 		.collect::<HashSet<_>>()340		// 		.into_iter()341		// 		.collect();342343		// 	stakes_unstakes344		// 		.map(|a| (a, <Pallet<T>>::get_locked_balance(&a).amount))345		// 		.for_each(|(staker, amount)| {346		// 			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(347		// 				LOCK_IDENTIFIER,348		// 				&staker,349		// 			);350		// 			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(351		// 				&<T as Config>::FreezeIdentifier::get(),352		// 				&staker,353		// 				amount,354		// 			);355		// 			add_weight(1, 2, Weight::zero())356		// 		});357358		// 	consumed_weight359		// }360361		// #[cfg(feature = "try-runtime")]362		// fn pre_upgrade() -> Result<Vec<u8>, &'static str> {363		// 	use sp_std::collections::btree_map::BTreeMap;364		// 	if <UpgradedToFreezes<T>>::get() {365		// 		return Ok(Default::default());366		// 	}367		// 	// Staker -> (total (stakes and unstakes) locked by promotion);368		// 	let mut pre_state: BTreeMap<T::AccountId, BalanceOf<T>> = BTreeMap::new();369370		// 	<Staked<T>>::iter().for_each(|((staker, _), (amount, _))| {371		// 		if let Some(locked_balance) = pre_state.get_mut(&staker) {372		// 			*locked_balance += amount;373		// 		} else {374		// 			pre_state.insert(staker, amount);375		// 		}376		// 	});377378		// 	<PendingUnstake<T>>::iter().for_each(|(_, v)| {379		// 		v.into_iter().for_each(|(staker, amount)| {380		// 			if let Some(locked_balance) = pre_state.get_mut(&staker) {381		// 				*locked_balance += amount;382		// 			} else {383		// 				pre_state.insert(staker, amount);384		// 			}385		// 		})386		// 	});387388		// 	Ok(pre_state.encode())389		// }390391		// #[cfg(feature = "try-runtime")]392		// fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {393		// 	use sp_std::collections::btree_map::BTreeMap;394395		// 	if <UpgradedToFreezes<T>>::get() {396		// 		return Ok(());397		// 	}398399		// 	let mut is_ok = true;400401		// 	let pre_state: BTreeMap<T::AccountId, BalanceOf<T>> =402		// 		Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;403		// 	for (staker, frozen_by_promo) in pre_state.into_iter() {404		// 		let storage_freeze_state = <<T as Config>::Currency as InspectFreeze<405		// 			T::AccountId,406		// 		>>::balance_frozen(407		// 			&<T as Config>::FreezeIdentifier::get(), staker408		// 		);409		// 		if storage_freeze_state != frozen_by_promo {410		// 			is_ok = false;411		// 			log::error!(412		// 						"Incorrect frozen balance for {:?}. New balance: {:?}. Before runtime upgrade: locked by promo - {:?}",413		// 						staker, storage_freeze_state, frozen_by_promo414		// 					);415		// 		}416417		// 		if !<Pallet<T>>::get_locked_balance(&staker).amount.is_zero() {418		// 			is_ok = false;419		// 			log::error!(420		// 				"Incorrect(non-zero) locked by app promo balance for {:?}",421		// 				staker422		// 			);423		// 		}424		// 	}425426		// 	if is_ok {427		// 		Ok(())428		// 	} else {429		// 		Err("Incorrect balance for some of stakers... See logs")430		// 	}431		// }432	}433434	#[pallet::call]435	impl<T: Config> Pallet<T>436	where437		T::BlockNumber: From<u32> + Into<u32>,438		<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,439	{440		/// Sets an address as the the admin.441		///442		/// # Permissions443		///444		/// * Sudo445		///446		/// # Arguments447		///448		/// * `admin`: account of the new admin.449		#[pallet::call_index(0)]450		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]451		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {452			ensure_root(origin)?;453454			<Admin<T>>::set(Some(admin.as_sub().to_owned()));455456			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));457458			Ok(())459		}460461		/// Stakes the amount of native tokens.462		/// Sets `amount` to the locked state.463		/// The maximum number of stakes for a staker is 10.464		///465		/// # Arguments466		///467		/// * `amount`: in native tokens.468		#[pallet::call_index(1)]469		#[pallet::weight(<T as Config>::WeightInfo::stake())]470		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {471			let staker_id = ensure_signed(staker)?;472473			ensure!(474				StakesPerAccount::<T>::get(&staker_id) < 10,475				Error::<T>::NoPermission476			);477478			ensure!(479				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),480				ArithmeticError::Underflow481			);482			let config = <PalletConfiguration<T>>::get();483484			let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);485486			// checks that we can freeze `amount` on the `staker` account.487			ensure!(488				amount489					<= match Self::get_frozen_balance(&staker_id) {490						Some(frozen_by_pallet) => balance491							.checked_sub(&frozen_by_pallet)492							.ok_or(ArithmeticError::Underflow)?,493						None => balance,494					},495				ArithmeticError::Underflow496			);497498			Self::add_freeze_balance(&staker_id, amount)?;499500			let block_number = T::RelayBlockNumberProvider::current_block_number();501502			// Calculation of the number of recalculation periods,503			// after how much the first interest calculation should be performed for the stake504			let recalculate_after_interval: T::BlockNumber =505				if block_number % config.recalculation_interval == 0u32.into() {506					1u32.into()507				} else {508					2u32.into()509				};510511			// Сalculation of the number of the relay block512			// in which it is necessary to accrue remuneration for the stake.513			let recalc_block = (block_number / config.recalculation_interval514				+ recalculate_after_interval)515				* config.recalculation_interval;516517			<Staked<T>>::insert((&staker_id, block_number), {518				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));519				balance_and_recalc_block.0 = balance_and_recalc_block520					.0521					.checked_add(&amount)522					.ok_or(ArithmeticError::Overflow)?;523				balance_and_recalc_block.1 = recalc_block;524				balance_and_recalc_block525			});526527			<TotalStaked<T>>::set(528				<TotalStaked<T>>::get()529					.checked_add(&amount)530					.ok_or(ArithmeticError::Overflow)?,531			);532533			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);534535			Self::deposit_event(Event::Stake(staker_id, amount));536537			Ok(())538		}539540		/// Unstakes all stakes.541		/// After the end of `PendingInterval` this sum becomes completely542		/// free for further use.543		#[pallet::call_index(2)]544		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]545		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {546			let staker_id = ensure_signed(staker)?;547548			Self::unstake_all_internal(staker_id)549		}550551		/// Unstakes the amount of balance for the staker.552		/// After the end of `PendingInterval` this sum becomes completely553		/// free for further use.554		///555		///  # Arguments556		///557		/// * `staker`: staker account.558		/// * `amount`: amount of unstaked funds.559		#[pallet::call_index(8)]560		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]561		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {562			let staker_id = ensure_signed(staker)?;563564			Self::unstake_partial_internal(staker_id, amount)565		}566567		/// Sets the pallet to be the sponsor for the collection.568		///569		/// # Permissions570		///571		/// * Pallet admin572		///573		/// # Arguments574		///575		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`576		#[pallet::call_index(3)]577		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]578		pub fn sponsor_collection(579			admin: OriginFor<T>,580			collection_id: CollectionId,581		) -> DispatchResult {582			let admin_id = ensure_signed(admin)?;583			ensure!(584				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,585				Error::<T>::NoPermission586			);587588			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)589		}590591		/// Removes the pallet as the sponsor for the collection.592		/// Returns [`NoPermission`][`Error::NoPermission`]593		/// if the pallet wasn't the sponsor.594		///595		/// # Permissions596		///597		/// * Pallet admin598		///599		/// # Arguments600		///601		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`602		#[pallet::call_index(4)]603		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]604		pub fn stop_sponsoring_collection(605			admin: OriginFor<T>,606			collection_id: CollectionId,607		) -> DispatchResult {608			let admin_id = ensure_signed(admin)?;609610			ensure!(611				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,612				Error::<T>::NoPermission613			);614615			ensure!(616				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?617					== Self::account_id(),618				<Error<T>>::NoPermission619			);620			T::CollectionHandler::remove_collection_sponsor(collection_id)621		}622623		/// Sets the pallet to be the sponsor for the contract.624		///625		/// # Permissions626		///627		/// * Pallet admin628		///629		/// # Arguments630		///631		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`632		#[pallet::call_index(5)]633		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]634		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {635			let admin_id = ensure_signed(admin)?;636637			ensure!(638				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,639				Error::<T>::NoPermission640			);641642			T::ContractHandler::set_sponsor(643				T::CrossAccountId::from_sub(Self::account_id()),644				contract_id,645			)646		}647648		/// Removes the pallet as the sponsor for the contract.649		/// Returns [`NoPermission`][`Error::NoPermission`]650		/// if the pallet wasn't the sponsor.651		///652		/// # Permissions653		///654		/// * Pallet admin655		///656		/// # Arguments657		///658		/// * `contract_id`: the contract address that is sponsored by `pallet_id`659		#[pallet::call_index(6)]660		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]661		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {662			let admin_id = ensure_signed(admin)?;663664			ensure!(665				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,666				Error::<T>::NoPermission667			);668669			ensure!(670				T::ContractHandler::sponsor(contract_id)?671					.ok_or(<Error<T>>::SponsorNotSet)?672					.as_sub() == &Self::account_id(),673				<Error<T>>::NoPermission674			);675			T::ContractHandler::remove_contract_sponsor(contract_id)676		}677678		/// Recalculates interest for the specified number of stakers.679		/// If all stakers are not recalculated, the next call of the extrinsic680		/// will continue the recalculation, from those stakers for whom this681		/// was not perform in last call.682		///683		/// # Permissions684		///685		/// * Pallet admin686		///687		/// # Arguments688		///689		/// * `stakers_number`: the number of stakers for which recalculation will be performed690		#[pallet::call_index(7)]691		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]692		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {693			let admin_id = ensure_signed(admin)?;694695			ensure!(696				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,697				Error::<T>::NoPermission698			);699			let config = <PalletConfiguration<T>>::get();700701			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);702703			ensure!(704				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,705				Error::<T>::NoPermission706			);707708			// calculate the number of the current recalculation block,709			// this is necessary in order to understand which stakers we should calculate interest710			let current_recalc_block = Self::get_current_recalc_block(711				T::RelayBlockNumberProvider::current_block_number(),712				&config,713			);714715			// calculate the number of the next recalculation block,716			// this value is set for the stakers to whom the recalculation will be performed717			let next_recalc_block = current_recalc_block + config.recalculation_interval;718719			let mut storage_iterator = Self::get_next_calculated_key()720				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));721722			PreviousCalculatedRecord::<T>::set(None);723724			{725				// Address handled in the last payout loop iteration (below)726				let last_id = RefCell::new(None);727				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration728				let mut last_staked_calculated_block = Default::default();729				// Reward balance for the address in the iteration730				let income_acc = RefCell::new(BalanceOf::<T>::default());731				// Staked balance for the address in the iteration (before stake is recalculated)732				let amount_acc = RefCell::new(BalanceOf::<T>::default());733734				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout735				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout736				// loop switches to handling the next staker address:737				//   1. Transfer full reward amount to the payee738				//   2. Lock the reward in staking lock739				//   3. Update TotalStaked amount740				//   4. Issue StakingRecalculation event741				let flush_stake = || -> DispatchResult {742					if let Some(last_id) = &*last_id.borrow() {743						if !income_acc.borrow().is_zero() {744							<<T as Config>::Currency as Mutate<T::AccountId>>::transfer(745								&T::TreasuryAccountId::get(),746								last_id,747								*income_acc.borrow(),748								frame_support::traits::tokens::Preservation::Protect,749							)?;750751							Self::add_freeze_balance(last_id, *income_acc.borrow())?;752							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {753								*staked = staked754									.checked_add(&*income_acc.borrow())755									.ok_or(ArithmeticError::Overflow)?;756								Ok(())757							})?;758759							Self::deposit_event(Event::StakingRecalculation(760								last_id.clone(),761								*amount_acc.borrow(),762								*income_acc.borrow(),763							));764						}765766						*income_acc.borrow_mut() = BalanceOf::<T>::default();767						*amount_acc.borrow_mut() = BalanceOf::<T>::default();768					}769					Ok(())770				};771772				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation773				// iterations in one extrinsic call774				//775				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)776				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out777				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)778				while let Some((779					(current_id, staked_block),780					(amount, next_recalc_block_for_stake),781				)) = storage_iterator.next()782				{783					// last_id is not equal current_id when we switch to handling a new staker address784					// or just start handling the very first address. In the latter case last_id will be None and785					// flush_stake will do nothing786					if last_id.borrow().as_ref() != Some(&current_id) {787						if stakers_number > 0 {788							flush_stake()?;789							*last_id.borrow_mut() = Some(current_id.clone());790							stakers_number -= 1;791						}792						// Break out if we reached the address limit793						else {794							if let Some(staker) = &*last_id.borrow() {795								// Save the last calculated record to pick up in the next extrinsic call796								PreviousCalculatedRecord::<T>::set(Some((797									staker.clone(),798									last_staked_calculated_block,799								)));800							}801							break;802						};803					};804805					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount806					if current_recalc_block >= next_recalc_block_for_stake {807						*amount_acc.borrow_mut() += amount;808						Self::recalculate_and_insert_stake(809							&current_id,810							staked_block,811							next_recalc_block,812							amount,813							((current_recalc_block - next_recalc_block_for_stake)814								/ config.recalculation_interval)815								.into() + 1,816							&mut *income_acc.borrow_mut(),817						);818					}819					last_staked_calculated_block = staked_block;820				}821				flush_stake()?;822			}823824			Ok(())825		}826827		///  Migrates lock state into freeze one828		///829		///  # Arguments830		///831		/// * `origin`: Must be `Signed`.832		/// * `stakers`: Accounts to be upgraded.833		#[pallet::call_index(9)]834		#[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]835		pub fn upgrade_accounts(836			origin: OriginFor<T>,837			stakers: Vec<T::AccountId>,838		) -> DispatchResult {839			ensure_signed(origin)?;840841			stakers842				.into_iter()843				.try_for_each(|s| -> Result<_, DispatchError> {844					if let Some(lock) = Self::get_locked_balance(&s) {845						if let Some(_) = Self::get_frozen_balance(&s) {846							return Err(Error::<T>::InconsistencyState.into());847						}848849						<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(850							LOCK_IDENTIFIER,851							&s,852						);853854						Self::set_freeze_unchecked(&s, lock.amount);855						Ok(())856					} else {857						Ok(())858					}859				})?;860861			Ok(())862		}863	}864}865866impl<T: Config> Pallet<T> {867	/// The account address of the app promotion pot.868	///869	/// This actually does computation. If you need to keep using it, then make sure you cache the870	/// value and only call this once.871	pub fn account_id() -> T::AccountId {872		T::PalletId::get().into_account_truncating()873	}874875	/// Unstakes the balance for the staker.876	///877	/// - `staker`: staker account.878	/// - `amount`: amount of unstaked funds.879	fn unstake_partial_internal(880		staker_id: T::AccountId,881		unstaked_balance: BalanceOf<T>,882	) -> DispatchResult {883		if unstaked_balance == Default::default() {884			return Ok(());885		}886887		let config = <PalletConfiguration<T>>::get();888889		// calculate block number where the sum would be free890		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;891892		let mut pendings = <PendingUnstake<T>>::get(unpending_block);893894		// checks that we can do unstake in the block895		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);896897		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();898899		let total_staked = stakes900			.iter()901			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {902				acc + *balance903			});904905		ensure!(906			unstaked_balance <= total_staked,907			<Error<T>>::InsufficientStakedBalance908		);909910		<TotalStaked<T>>::set(911			<TotalStaked<T>>::get()912				.checked_sub(&unstaked_balance)913				.ok_or(ArithmeticError::Underflow)?,914		);915916		stakes.sort_by_key(|(block, _)| *block);917918		let mut acc_amount = unstaked_balance;919		let mut will_deleted_stakes_count = 0u8;920921		let changed_stakes = stakes922			.into_iter()923			.map_while(|(block, (balance_per_block, _))| {924				if acc_amount == <BalanceOf<T>>::default() {925					return None;926				}927				if acc_amount < balance_per_block {928					let res = (block, balance_per_block - acc_amount);929					acc_amount = <BalanceOf<T>>::default();930					return Some(res);931				} else {932					acc_amount -= balance_per_block;933					will_deleted_stakes_count += 1;934					return Some((block, <BalanceOf<T>>::default()));935				}936			})937			.collect::<Vec<_>>();938939		pendings940			.try_push((staker_id.clone(), unstaked_balance))941			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;942943		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {944			*stakes = stakes945				.checked_sub(will_deleted_stakes_count)946				.ok_or(ArithmeticError::Underflow)?;947			Ok(())948		})?;949950		changed_stakes951			.into_iter()952			.for_each(|(staked_block, current_stake_state)| {953				if current_stake_state == Default::default() {954					<Staked<T>>::remove((&staker_id, staked_block));955				} else {956					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {957						*old_stake_state = current_stake_state958					});959				}960			});961962		<PendingUnstake<T>>::insert(unpending_block, pendings);963964		Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));965966		Ok(())967	}968969	/// Adds the balance to locked by the pallet.970	///971	/// - `staker`: staker account.972	/// - `amount`: amount of added locked funds.973	// fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {974	// 	Self::get_locked_balance(staker)975	// 		.map_or(<BalanceOf<T>>::default(), |l| l.amount)976	// 		.checked_add(&amount)977	// 		.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))978	// 		.ok_or(ArithmeticError::Overflow.into())979	// }980981	/// Adds the balance to frozen by the pallet.982	///983	/// - `staker`: staker account.984	/// - `amount`: amount of added frozen funds.985	fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {986		Self::get_frozen_balance(staker)987			.unwrap_or_default()988			.checked_add(&amount)989			.map(|freeze| Self::set_freeze_unchecked(staker, freeze))990			.ok_or(ArithmeticError::Overflow.into())991	}992993	/// Sets the new state of a balance locked by the pallet.994	///995	/// - `staker`: staker account.996	/// - `amount`: amount of locked funds.997	// fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {998	// 	if amount.is_zero() {999	// 		<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(1000	// 			LOCK_IDENTIFIER,1001	// 			&staker,1002	// 		);1003	// 	} else {1004	// 		<<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(1005	// 			LOCK_IDENTIFIER,1006	// 			staker,1007	// 			amount,1008	// 			WithdrawReasons::all(),1009	// 		)1010	// 	}1011	// }10121013	/// Sets the new state of a balance frozen by the pallet.1014	///1015	/// - `staker`: staker account.1016	/// - `amount`: amount of frozen funds.1017	fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {1018		if amount.is_zero() {1019			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(1020				&T::FreezeIdentifier::get(),1021				&staker,1022			);1023		} else {1024			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(1025				&T::FreezeIdentifier::get(),1026				staker,1027				amount,1028			);1029		}1030	}10311032	/// Returns the balance locked by the pallet for the staker.1033	///1034	/// - `staker`: staker account.1035	pub fn get_locked_balance(1036		staker: impl EncodeLike<T::AccountId>,1037	) -> Option<BalanceLock<BalanceOf<T>>> {1038		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)1039			.into_iter()1040			.find(|l| l.id == LOCK_IDENTIFIER)1041	}10421043	/// Returns the balance frozen by the pallet for the staker.1044	///1045	/// - `staker`: staker account.1046	pub fn get_frozen_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {1047		let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(1048			&T::FreezeIdentifier::get(),1049			staker,1050		);10511052		if res == Zero::zero() {1053			None1054		} else {1055			Some(res)1056		}1057	}10581059	/// Returns the total staked balance for the staker.1060	///1061	/// - `staker`: staker account.1062	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {1063		let staked = Staked::<T>::iter_prefix((staker,))1064			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {1065				acc + amount1066			});1067		if staked != <BalanceOf<T>>::default() {1068			Some(staked)1069		} else {1070			None1071		}1072	}10731074	/// Returns all relay block numbers when stake was made,1075	/// the amount of the stake.1076	///1077	/// - `staker`: staker account.1078	pub fn total_staked_by_id_per_block(1079		staker: impl EncodeLike<T::AccountId>,1080	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {1081		let mut staked = Staked::<T>::iter_prefix((staker,))1082			.map(|(block, (amount, _))| (block, amount))1083			.collect::<Vec<_>>();1084		staked.sort_by_key(|(block, _)| *block);1085		if !staked.is_empty() {1086			Some(staked)1087		} else {1088			None1089		}1090	}10911092	/// Returns the total staked balance for the staker.1093	/// If `staker` is `None`, returns the total amount staked.1094	/// - `staker`: staker account.1095	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1096		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1097			Self::total_staked_by_id(s.as_sub())1098		})1099	}11001101	/// Returns all relay block numbers when stake was made,1102	/// the amount of the stake.1103	///1104	/// - `staker`: staker account.1105	pub fn cross_id_total_staked_per_block(1106		staker: T::CrossAccountId,1107	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1108		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1109	}11101111	fn recalculate_and_insert_stake(1112		staker: &T::AccountId,1113		staked_block: T::BlockNumber,1114		next_recalc_block: T::BlockNumber,1115		base: BalanceOf<T>,1116		iters: u32,1117		income_acc: &mut BalanceOf<T>,1118	) {1119		let income = Self::calculate_income(base, iters);11201121		base.checked_add(&income).map(|res| {1122			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1123			*income_acc += income;1124		});1125	}11261127	fn calculate_income<I>(base: I, iters: u32) -> I1128	where1129		I: EncodeLike<BalanceOf<T>> + Balance,1130	{1131		let config = <PalletConfiguration<T>>::get();1132		let mut income = base;11331134		(0..iters).for_each(|_| income += config.interval_income * income);11351136		income - base1137	}11381139	/// Get relay block number rounded down to multiples of config.recalculation_interval.1140	/// We need it to reward stakers in integer parts of recalculation_interval1141	fn get_current_recalc_block(1142		current_relay_block: T::BlockNumber,1143		config: &PalletConfiguration<T>,1144	) -> T::BlockNumber {1145		(current_relay_block / config.recalculation_interval) * config.recalculation_interval1146	}11471148	fn get_next_calculated_key() -> Option<Vec<u8>> {1149		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))1150	}1151}11521153impl<T: Config> Pallet<T>1154where1155	<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1156{1157	/// Returns the amount reserved by the pending.1158	/// If `staker` is `None`, returns the total pending.1159	///1160	/// -`staker`: staker account.1161	///1162	/// Since user funds are not transferred anywhere by staking, overflow protection is provided1163	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1164	/// the staker must have more funds on his account than the maximum set for `Balance` type.1165	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1166		staker.map_or(1167			PendingUnstake::<T>::iter_values()1168				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1169				.sum(),1170			|s| {1171				PendingUnstake::<T>::iter_values()1172					.flatten()1173					.filter_map(|(id, amount)| {1174						if id == *s.as_sub() {1175							Some(amount)1176						} else {1177							None1178						}1179					})1180					.sum()1181			},1182		)1183	}11841185	/// Returns all parachain block numbers when unreserve is expected,1186	/// the amount of the unreserved funds.1187	///1188	/// - `staker`: staker account.1189	pub fn cross_id_pending_unstake_per_block(1190		staker: T::CrossAccountId,1191	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1192		let mut unsorted_res = vec![];1193		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1194			pendings.into_iter().for_each(|(id, amount)| {1195				if id == *staker.as_sub() {1196					unsorted_res.push((block, amount));1197				};1198			})1199		});12001201		unsorted_res.sort_by_key(|(block, _)| *block);1202		unsorted_res1203	}12041205	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1206		let config = <PalletConfiguration<T>>::get();12071208		// calculate block number where the sum would be free1209		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;12101211		let mut pendings = <PendingUnstake<T>>::get(block);12121213		// checks that we can do unstake in the block1214		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);12151216		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1217			.map(|(_, (amount, _))| amount)1218			.sum();12191220		if total_staked.is_zero() {1221			return Ok(());1222		}12231224		pendings1225			.try_push((staker_id.clone(), total_staked))1226			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;12271228		<PendingUnstake<T>>::insert(block, pendings);12291230		TotalStaked::<T>::set(1231			TotalStaked::<T>::get()1232				.checked_sub(&total_staked)1233				.ok_or(ArithmeticError::Underflow)?,1234		);12351236		StakesPerAccount::<T>::remove(&staker_id);12371238		Self::deposit_event(Event::Unstake(staker_id, total_staked));12391240		Ok(())1241	}1242}