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
before · pallets/app-promotion/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # App Promotion pallet18//!19//! The pallet implements the mechanics of staking and sponsoring collections/contracts.20//!21//! - [`Config`]22//! - [`Pallet`]23//! - [`Error`]24//! - [`Event`]25//!26//! ## Overview27//! The App Promotion pallet allows fund holders to stake at a certain daily rate of return.28//! The mechanics implemented in the pallet allow it to act as a sponsor for collections / contracts,29//! the list of which is set by the pallet administrator.30//!31//!32//! ## Interface33//!	The pallet provides interfaces for funds, collection/contract operations (see [types] module).3435//!36//! ### Dispatchable Functions37//!	- [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.38//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.39//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.40//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.41//! - [`stop_sponsoring_collection`][`Pallet::stop_sponsoring_collection`] - removes the pallet as the sponsor for the collection.42//! - [`sponsor_contract`][`Pallet::sponsor_contract`] - sets the pallet to be the sponsor for the contract.43//! - [`stop_sponsoring_contract`][`Pallet::stop_sponsoring_contract`] - removes the pallet as the sponsor for the contract.44//! - [`payout_stakers`][`Pallet::payout_stakers`] - recalculates interest for the specified number of stakers.45//!4647// #![recursion_limit = "1024"]48#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57	vec::{Vec},58	vec,59	iter::Sum,60	borrow::ToOwned,61	cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71	dispatch::{DispatchResult},72	traits::{73		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::storage]282	// pub(crate) type UpgradedToFreezes<T: Config> =283	// 	StorageValue<Value = bool, QueryKind = ValueQuery>;284285	#[pallet::hooks]286	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {287		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize288		/// implies the execution of a strictly limited number of relatively lightweight operations.289		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.290		fn on_initialize(current_block_number: T::BlockNumber) -> Weight291		where292			<T as frame_system::Config>::BlockNumber: From<u32>,293		{294			if T::IsMaintenanceModeEnabled::get() {295				return T::DbWeight::get().reads_writes(1, 0);296			}297298			let block_pending = PendingUnstake::<T>::take(current_block_number);299			let counter = block_pending.len() as u32;300301			if !block_pending.is_empty() {302				block_pending.into_iter().for_each(|(staker, amount)| {303					Self::get_frozen_balance(&staker).map(|b| {304						let new_state = b.checked_sub(&amount).unwrap_or_default();305						Self::set_freeze_unchecked(&staker, new_state);306					});307				});308			}309310			<T as Config>::WeightInfo::on_initialize(counter)311		}312313		// fn on_runtime_upgrade() -> Weight {314		// 	use scale_info::prelude::collections::HashSet;315		// 	let mut consumed_weight = Weight::zero();316		// 	let mut add_weight = |reads, writes, weight| {317		// 		consumed_weight += T::DbWeight::get().reads_writes(reads, writes);318		// 		consumed_weight += weight;319		// 	};320321		// 	let mut stakes_unstakes = vec![];322323		// 	if <UpgradedToFreezes<T>>::get() {324		// 		add_weight(1, 0, Weight::zero());325		// 		return consumed_weight;326		// 	} else {327		// 		add_weight(1, 1, Weight::zero());328		// 		<UpgradedToFreezes<T>>::set(true);329		// 	}330		// 	<Staked<T>>::iter_keys().for_each(|(staker_id, _)| {331		// 		add_weight(1, 0, Weight::zero());332		// 		stakes_unstakes.push(staker_id);333		// 	});334335		// 	<PendingUnstake<T>>::iter().for_each(|(_, v)| {336		// 		add_weight(1, 0, Weight::zero());337		// 		v.into_iter().for_each(|(staker, _)| {338		// 			stakes_unstakes.push(staker);339		// 		});340		// 	});341342		// 	// filter duplicated id.343		// 	stakes_unstakes = stakes_unstakes344		// 		.into_iter()345		// 		.map(|key| key)346		// 		.collect::<HashSet<_>>()347		// 		.into_iter()348		// 		.collect();349350		// 	stakes_unstakes351		// 		.map(|a| (a, <Pallet<T>>::get_locked_balance(&a).amount))352		// 		.for_each(|(staker, amount)| {353		// 			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(354		// 				LOCK_IDENTIFIER,355		// 				&staker,356		// 			);357		// 			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(358		// 				&<T as Config>::FreezeIdentifier::get(),359		// 				&staker,360		// 				amount,361		// 			);362		// 			add_weight(1, 2, Weight::zero())363		// 		});364365		// 	consumed_weight366		// }367368		// #[cfg(feature = "try-runtime")]369		// fn pre_upgrade() -> Result<Vec<u8>, &'static str> {370		// 	use sp_std::collections::btree_map::BTreeMap;371		// 	if <UpgradedToFreezes<T>>::get() {372		// 		return Ok(Default::default());373		// 	}374		// 	// Staker -> (total (stakes and unstakes) locked by promotion);375		// 	let mut pre_state: BTreeMap<T::AccountId, BalanceOf<T>> = BTreeMap::new();376377		// 	<Staked<T>>::iter().for_each(|((staker, _), (amount, _))| {378		// 		if let Some(locked_balance) = pre_state.get_mut(&staker) {379		// 			*locked_balance += amount;380		// 		} else {381		// 			pre_state.insert(staker, amount);382		// 		}383		// 	});384385		// 	<PendingUnstake<T>>::iter().for_each(|(_, v)| {386		// 		v.into_iter().for_each(|(staker, amount)| {387		// 			if let Some(locked_balance) = pre_state.get_mut(&staker) {388		// 				*locked_balance += amount;389		// 			} else {390		// 				pre_state.insert(staker, amount);391		// 			}392		// 		})393		// 	});394395		// 	Ok(pre_state.encode())396		// }397398		// #[cfg(feature = "try-runtime")]399		// fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {400		// 	use sp_std::collections::btree_map::BTreeMap;401402		// 	if <UpgradedToFreezes<T>>::get() {403		// 		return Ok(());404		// 	}405406		// 	let mut is_ok = true;407408		// 	let pre_state: BTreeMap<T::AccountId, BalanceOf<T>> =409		// 		Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;410		// 	for (staker, frozen_by_promo) in pre_state.into_iter() {411		// 		let storage_freeze_state = <<T as Config>::Currency as InspectFreeze<412		// 			T::AccountId,413		// 		>>::balance_frozen(414		// 			&<T as Config>::FreezeIdentifier::get(), staker415		// 		);416		// 		if storage_freeze_state != frozen_by_promo {417		// 			is_ok = false;418		// 			log::error!(419		// 						"Incorrect frozen balance for {:?}. New balance: {:?}. Before runtime upgrade: locked by promo - {:?}",420		// 						staker, storage_freeze_state, frozen_by_promo421		// 					);422		// 		}423424		// 		if !<Pallet<T>>::get_locked_balance(&staker).amount.is_zero() {425		// 			is_ok = false;426		// 			log::error!(427		// 				"Incorrect(non-zero) locked by app promo balance for {:?}",428		// 				staker429		// 			);430		// 		}431		// 	}432433		// 	if is_ok {434		// 		Ok(())435		// 	} else {436		// 		Err("Incorrect balance for some of stakers... See logs")437		// 	}438		// }439	}440441	#[pallet::call]442	impl<T: Config> Pallet<T>443	where444		T::BlockNumber: From<u32> + Into<u32>,445		<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,446	{447		/// Sets an address as the the admin.448		///449		/// # Permissions450		///451		/// * Sudo452		///453		/// # Arguments454		///455		/// * `admin`: account of the new admin.456		#[pallet::call_index(0)]457		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]458		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {459			ensure_root(origin)?;460461			<Admin<T>>::set(Some(admin.as_sub().to_owned()));462463			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));464465			Ok(())466		}467468		/// Stakes the amount of native tokens.469		/// Sets `amount` to the locked state.470		/// The maximum number of stakes for a staker is 10.471		///472		/// # Arguments473		///474		/// * `amount`: in native tokens.475		#[pallet::call_index(1)]476		#[pallet::weight(<T as Config>::WeightInfo::stake())]477		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {478			let staker_id = ensure_signed(staker)?;479480			ensure!(481				StakesPerAccount::<T>::get(&staker_id) < 10,482				Error::<T>::NoPermission483			);484485			ensure!(486				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),487				ArithmeticError::Underflow488			);489			let config = <PalletConfiguration<T>>::get();490491			let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);492493			// checks that we can freeze `amount` on the `staker` account.494			ensure!(495				amount496					<= match Self::get_frozen_balance(&staker_id) {497						Some(frozen_by_pallet) => balance498							.checked_sub(&frozen_by_pallet)499							.ok_or(ArithmeticError::Underflow)?,500						None => balance,501					},502				ArithmeticError::Underflow503			);504505			Self::add_freeze_balance(&staker_id, amount)?;506507			let block_number = T::RelayBlockNumberProvider::current_block_number();508509			// Calculation of the number of recalculation periods,510			// after how much the first interest calculation should be performed for the stake511			let recalculate_after_interval: T::BlockNumber =512				if block_number % config.recalculation_interval == 0u32.into() {513					1u32.into()514				} else {515					2u32.into()516				};517518			// Сalculation of the number of the relay block519			// in which it is necessary to accrue remuneration for the stake.520			let recalc_block = (block_number / config.recalculation_interval521				+ recalculate_after_interval)522				* config.recalculation_interval;523524			<Staked<T>>::insert((&staker_id, block_number), {525				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));526				balance_and_recalc_block.0 = balance_and_recalc_block527					.0528					.checked_add(&amount)529					.ok_or(ArithmeticError::Overflow)?;530				balance_and_recalc_block.1 = recalc_block;531				balance_and_recalc_block532			});533534			<TotalStaked<T>>::set(535				<TotalStaked<T>>::get()536					.checked_add(&amount)537					.ok_or(ArithmeticError::Overflow)?,538			);539540			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);541542			Self::deposit_event(Event::Stake(staker_id, amount));543544			Ok(())545		}546547		/// Unstakes all stakes.548		/// After the end of `PendingInterval` this sum becomes completely549		/// free for further use.550		#[pallet::call_index(2)]551		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]552		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {553			let staker_id = ensure_signed(staker)?;554555			Self::unstake_all_internal(staker_id)556		}557558		/// Unstakes the amount of balance for the staker.559		/// After the end of `PendingInterval` this sum becomes completely560		/// free for further use.561		///562		///  # Arguments563		///564		/// * `staker`: staker account.565		/// * `amount`: amount of unstaked funds.566		#[pallet::call_index(8)]567		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]568		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {569			let staker_id = ensure_signed(staker)?;570571			Self::unstake_partial_internal(staker_id, amount)572		}573574		/// Sets the pallet to be the sponsor for the collection.575		///576		/// # Permissions577		///578		/// * Pallet admin579		///580		/// # Arguments581		///582		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`583		#[pallet::call_index(3)]584		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]585		pub fn sponsor_collection(586			admin: OriginFor<T>,587			collection_id: CollectionId,588		) -> DispatchResult {589			let admin_id = ensure_signed(admin)?;590			ensure!(591				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,592				Error::<T>::NoPermission593			);594595			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)596		}597598		/// Removes the pallet as the sponsor for the collection.599		/// Returns [`NoPermission`][`Error::NoPermission`]600		/// if the pallet wasn't the sponsor.601		///602		/// # Permissions603		///604		/// * Pallet admin605		///606		/// # Arguments607		///608		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`609		#[pallet::call_index(4)]610		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]611		pub fn stop_sponsoring_collection(612			admin: OriginFor<T>,613			collection_id: CollectionId,614		) -> 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::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?624					== Self::account_id(),625				<Error<T>>::NoPermission626			);627			T::CollectionHandler::remove_collection_sponsor(collection_id)628		}629630		/// Sets the pallet to be the sponsor for the contract.631		///632		/// # Permissions633		///634		/// * Pallet admin635		///636		/// # Arguments637		///638		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`639		#[pallet::call_index(5)]640		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]641		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {642			let admin_id = ensure_signed(admin)?;643644			ensure!(645				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,646				Error::<T>::NoPermission647			);648649			T::ContractHandler::set_sponsor(650				T::CrossAccountId::from_sub(Self::account_id()),651				contract_id,652			)653		}654655		/// Removes the pallet as the sponsor for the contract.656		/// Returns [`NoPermission`][`Error::NoPermission`]657		/// if the pallet wasn't the sponsor.658		///659		/// # Permissions660		///661		/// * Pallet admin662		///663		/// # Arguments664		///665		/// * `contract_id`: the contract address that is sponsored by `pallet_id`666		#[pallet::call_index(6)]667		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]668		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {669			let admin_id = ensure_signed(admin)?;670671			ensure!(672				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,673				Error::<T>::NoPermission674			);675676			ensure!(677				T::ContractHandler::sponsor(contract_id)?678					.ok_or(<Error<T>>::SponsorNotSet)?679					.as_sub() == &Self::account_id(),680				<Error<T>>::NoPermission681			);682			T::ContractHandler::remove_contract_sponsor(contract_id)683		}684685		/// Recalculates interest for the specified number of stakers.686		/// If all stakers are not recalculated, the next call of the extrinsic687		/// will continue the recalculation, from those stakers for whom this688		/// was not perform in last call.689		///690		/// # Permissions691		///692		/// * Pallet admin693		///694		/// # Arguments695		///696		/// * `stakers_number`: the number of stakers for which recalculation will be performed697		#[pallet::call_index(7)]698		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]699		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {700			let admin_id = ensure_signed(admin)?;701702			ensure!(703				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,704				Error::<T>::NoPermission705			);706			let config = <PalletConfiguration<T>>::get();707708			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);709710			ensure!(711				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,712				Error::<T>::NoPermission713			);714715			// calculate the number of the current recalculation block,716			// this is necessary in order to understand which stakers we should calculate interest717			let current_recalc_block = Self::get_current_recalc_block(718				T::RelayBlockNumberProvider::current_block_number(),719				&config,720			);721722			// calculate the number of the next recalculation block,723			// this value is set for the stakers to whom the recalculation will be performed724			let next_recalc_block = current_recalc_block + config.recalculation_interval;725726			let mut storage_iterator = Self::get_next_calculated_key()727				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));728729			PreviousCalculatedRecord::<T>::set(None);730731			{732				// Address handled in the last payout loop iteration (below)733				let last_id = RefCell::new(None);734				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration735				let mut last_staked_calculated_block = Default::default();736				// Reward balance for the address in the iteration737				let income_acc = RefCell::new(BalanceOf::<T>::default());738				// Staked balance for the address in the iteration (before stake is recalculated)739				let amount_acc = RefCell::new(BalanceOf::<T>::default());740741				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout742				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout743				// loop switches to handling the next staker address:744				//   1. Transfer full reward amount to the payee745				//   2. Lock the reward in staking lock746				//   3. Update TotalStaked amount747				//   4. Issue StakingRecalculation event748				let flush_stake = || -> DispatchResult {749					if let Some(last_id) = &*last_id.borrow() {750						if !income_acc.borrow().is_zero() {751							<<T as Config>::Currency as Mutate<T::AccountId>>::transfer(752								&T::TreasuryAccountId::get(),753								last_id,754								*income_acc.borrow(),755								frame_support::traits::tokens::Preservation::Protect,756							)?;757758							Self::add_freeze_balance(last_id, *income_acc.borrow())?;759							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {760								*staked = staked761									.checked_add(&*income_acc.borrow())762									.ok_or(ArithmeticError::Overflow)?;763								Ok(())764							})?;765766							Self::deposit_event(Event::StakingRecalculation(767								last_id.clone(),768								*amount_acc.borrow(),769								*income_acc.borrow(),770							));771						}772773						*income_acc.borrow_mut() = BalanceOf::<T>::default();774						*amount_acc.borrow_mut() = BalanceOf::<T>::default();775					}776					Ok(())777				};778779				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation780				// iterations in one extrinsic call781				//782				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)783				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out784				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)785				while let Some((786					(current_id, staked_block),787					(amount, next_recalc_block_for_stake),788				)) = storage_iterator.next()789				{790					// last_id is not equal current_id when we switch to handling a new staker address791					// or just start handling the very first address. In the latter case last_id will be None and792					// flush_stake will do nothing793					if last_id.borrow().as_ref() != Some(&current_id) {794						if stakers_number > 0 {795							flush_stake()?;796							*last_id.borrow_mut() = Some(current_id.clone());797							stakers_number -= 1;798						}799						// Break out if we reached the address limit800						else {801							if let Some(staker) = &*last_id.borrow() {802								// Save the last calculated record to pick up in the next extrinsic call803								PreviousCalculatedRecord::<T>::set(Some((804									staker.clone(),805									last_staked_calculated_block,806								)));807							}808							break;809						};810					};811812					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount813					if current_recalc_block >= next_recalc_block_for_stake {814						*amount_acc.borrow_mut() += amount;815						Self::recalculate_and_insert_stake(816							&current_id,817							staked_block,818							next_recalc_block,819							amount,820							((current_recalc_block - next_recalc_block_for_stake)821								/ config.recalculation_interval)822								.into() + 1,823							&mut *income_acc.borrow_mut(),824						);825					}826					last_staked_calculated_block = staked_block;827				}828				flush_stake()?;829			}830831			Ok(())832		}833834		///  Migrates lock state into freeze one835		///836		/// # Permissions837		///838		/// * Sudo839		///840		///   # Arguments841		///842		/// * `origin`: Must be `Signed`.843		/// * `stakers`: Accounts to be upgraded.844		#[pallet::call_index(9)]845		#[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]846		pub fn upgrade_accounts(847			origin: OriginFor<T>,848			stakers: Vec<T::AccountId>,849		) -> DispatchResult {850			ensure_root(origin)?;851852			stakers853				.into_iter()854				.try_for_each(|s| -> Result<_, DispatchError> {855					if let Some(BalanceLock { amount, .. }) = Self::get_locked_balance(&s) {856						if Self::get_frozen_balance(&s).is_some() {857							return Err(Error::<T>::InconsistencyState.into());858						}859860						<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(861							LOCK_IDENTIFIER,862							&s,863						);864865						Self::set_freeze_with_result(&s, amount)?;866						Ok(())867					} else {868						Ok(())869					}870				})?;871872			Ok(())873		}874875		/// Called for blocks that, for some reason, have not been unstacked876		///877		/// # Permissions878		///879		/// * Sudo880		///881		///   # Arguments882		///883		/// * `origin`: Must be `Signed`.884		/// * `pending_blocks`: Block numbers that will be processed.885		#[pallet::call_index(10)]886		#[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]887		pub fn force_unstake(888			origin: OriginFor<T>,889			pending_blocks: Vec<T::BlockNumber>,890		) -> DispatchResult {891			ensure_root(origin)?;892893			ensure!(894				pending_blocks895					.iter()896					.all(|b| *b < <frame_system::Pallet<T>>::block_number()),897				<Error<T>>::NoPermission898			);899900			let mut pendings =901				Vec::with_capacity(PENDING_LIMIT_PER_BLOCK as usize * pending_blocks.len());902			pending_blocks903				.into_iter()904				.for_each(|b| pendings.append(&mut PendingUnstake::<T>::take(b).into_inner()));905906			pendings.into_iter().for_each(|(staker, amount)| {907				Self::get_frozen_balance(&staker).map(|b| {908					let new_state = b.checked_sub(&amount).unwrap_or_default();909					Self::set_freeze_unchecked(&staker, new_state);910				});911			});912913			Ok(())914		}915	}916}917918impl<T: Config> Pallet<T> {919	/// The account address of the app promotion pot.920	///921	/// This actually does computation. If you need to keep using it, then make sure you cache the922	/// value and only call this once.923	pub fn account_id() -> T::AccountId {924		T::PalletId::get().into_account_truncating()925	}926927	/// Unstakes the balance for the staker.928	///929	/// - `staker`: staker account.930	/// - `amount`: amount of unstaked funds.931	fn unstake_partial_internal(932		staker_id: T::AccountId,933		unstaked_balance: BalanceOf<T>,934	) -> DispatchResult {935		if unstaked_balance == Default::default() {936			return Ok(());937		}938939		let config = <PalletConfiguration<T>>::get();940941		// calculate block number where the sum would be free942		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;943944		let mut pendings = <PendingUnstake<T>>::get(unpending_block);945946		// checks that we can do unstake in the block947		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);948949		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();950951		let total_staked = stakes952			.iter()953			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {954				acc + *balance955			});956957		ensure!(958			unstaked_balance <= total_staked,959			<Error<T>>::InsufficientStakedBalance960		);961962		<TotalStaked<T>>::set(963			<TotalStaked<T>>::get()964				.checked_sub(&unstaked_balance)965				.ok_or(ArithmeticError::Underflow)?,966		);967968		stakes.sort_by_key(|(block, _)| *block);969970		let mut acc_amount = unstaked_balance;971		let mut will_deleted_stakes_count = 0u8;972973		let changed_stakes = stakes974			.into_iter()975			.map_while(|(block, (balance_per_block, _))| {976				if acc_amount == <BalanceOf<T>>::default() {977					return None;978				}979				if acc_amount < balance_per_block {980					let res = (block, balance_per_block - acc_amount);981					acc_amount = <BalanceOf<T>>::default();982					return Some(res);983				} else {984					acc_amount -= balance_per_block;985					will_deleted_stakes_count += 1;986					return Some((block, <BalanceOf<T>>::default()));987				}988			})989			.collect::<Vec<_>>();990991		pendings992			.try_push((staker_id.clone(), unstaked_balance))993			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;994995		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {996			*stakes = stakes997				.checked_sub(will_deleted_stakes_count)998				.ok_or(ArithmeticError::Underflow)?;999			Ok(())1000		})?;10011002		changed_stakes1003			.into_iter()1004			.for_each(|(staked_block, current_stake_state)| {1005				if current_stake_state == Default::default() {1006					<Staked<T>>::remove((&staker_id, staked_block));1007				} else {1008					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {1009						*old_stake_state = current_stake_state1010					});1011				}1012			});10131014		<PendingUnstake<T>>::insert(unpending_block, pendings);10151016		Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));10171018		Ok(())1019	}10201021	/// Adds the balance to locked by the pallet.1022	///1023	/// - `staker`: staker account.1024	/// - `amount`: amount of added locked funds.1025	// fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {1026	// 	Self::get_locked_balance(staker)1027	// 		.map_or(<BalanceOf<T>>::default(), |l| l.amount)1028	// 		.checked_add(&amount)1029	// 		.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))1030	// 		.ok_or(ArithmeticError::Overflow.into())1031	// }10321033	/// Adds the balance to frozen by the pallet.1034	///1035	/// - `staker`: staker account.1036	/// - `amount`: amount of added frozen funds.1037	fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {1038		Self::get_frozen_balance(staker)1039			.unwrap_or_default()1040			.checked_add(&amount)1041			.map(|freeze| Self::set_freeze_with_result(staker, freeze))1042			.ok_or::<DispatchError>(ArithmeticError::Overflow.into())?1043	}10441045	/// Sets the new state of a balance locked by the pallet.1046	///1047	/// - `staker`: staker account.1048	/// - `amount`: amount of locked funds.1049	// fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {1050	// 	if amount.is_zero() {1051	// 		<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(1052	// 			LOCK_IDENTIFIER,1053	// 			&staker,1054	// 		);1055	// 	} else {1056	// 		<<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(1057	// 			LOCK_IDENTIFIER,1058	// 			staker,1059	// 			amount,1060	// 			WithdrawReasons::all(),1061	// 		)1062	// 	}1063	// }10641065	/// Sets the new state of a balance frozen by the pallet.1066	///1067	/// - `staker`: staker account.1068	/// - `amount`: amount of frozen funds.1069	fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {1070		Self::set_freeze_with_result(staker, amount);1071	}10721073	/// Sets the new state of a balance frozen by the pallet.1074	///1075	/// - `staker`: staker account.1076	/// - `amount`: amount of frozen funds.1077	fn set_freeze_with_result(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {1078		if amount.is_zero() {1079			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(1080				&T::FreezeIdentifier::get(),1081				&staker,1082			)1083		} else {1084			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(1085				&T::FreezeIdentifier::get(),1086				staker,1087				amount,1088			)1089		}1090	}10911092	/// Returns the balance locked by the pallet for the staker.1093	///1094	/// - `staker`: staker account.1095	pub fn get_locked_balance(1096		staker: impl EncodeLike<T::AccountId>,1097	) -> Option<BalanceLock<BalanceOf<T>>> {1098		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)1099			.into_iter()1100			.find(|l| l.id == LOCK_IDENTIFIER)1101	}11021103	/// Returns the balance frozen by the pallet for the staker.1104	///1105	/// - `staker`: staker account.1106	pub fn get_frozen_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {1107		let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(1108			&T::FreezeIdentifier::get(),1109			staker,1110		);11111112		if res == Zero::zero() {1113			None1114		} else {1115			Some(res)1116		}1117	}11181119	/// Returns the total staked balance for the staker.1120	///1121	/// - `staker`: staker account.1122	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {1123		let staked = Staked::<T>::iter_prefix((staker,))1124			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {1125				acc + amount1126			});1127		if staked != <BalanceOf<T>>::default() {1128			Some(staked)1129		} else {1130			None1131		}1132	}11331134	/// Returns all relay block numbers when stake was made,1135	/// the amount of the stake.1136	///1137	/// - `staker`: staker account.1138	pub fn total_staked_by_id_per_block(1139		staker: impl EncodeLike<T::AccountId>,1140	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {1141		let mut staked = Staked::<T>::iter_prefix((staker,))1142			.map(|(block, (amount, _))| (block, amount))1143			.collect::<Vec<_>>();1144		staked.sort_by_key(|(block, _)| *block);1145		if !staked.is_empty() {1146			Some(staked)1147		} else {1148			None1149		}1150	}11511152	/// Returns the total staked balance for the staker.1153	/// If `staker` is `None`, returns the total amount staked.1154	/// - `staker`: staker account.1155	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1156		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1157			Self::total_staked_by_id(s.as_sub())1158		})1159	}11601161	/// Returns all relay block numbers when stake was made,1162	/// the amount of the stake.1163	///1164	/// - `staker`: staker account.1165	pub fn cross_id_total_staked_per_block(1166		staker: T::CrossAccountId,1167	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1168		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1169	}11701171	fn recalculate_and_insert_stake(1172		staker: &T::AccountId,1173		staked_block: T::BlockNumber,1174		next_recalc_block: T::BlockNumber,1175		base: BalanceOf<T>,1176		iters: u32,1177		income_acc: &mut BalanceOf<T>,1178	) {1179		let income = Self::calculate_income(base, iters);11801181		base.checked_add(&income).map(|res| {1182			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1183			*income_acc += income;1184		});1185	}11861187	fn calculate_income<I>(base: I, iters: u32) -> I1188	where1189		I: EncodeLike<BalanceOf<T>> + Balance,1190	{1191		let config = <PalletConfiguration<T>>::get();1192		let mut income = base;11931194		(0..iters).for_each(|_| income += config.interval_income * income);11951196		income - base1197	}11981199	/// Get relay block number rounded down to multiples of config.recalculation_interval.1200	/// We need it to reward stakers in integer parts of recalculation_interval1201	fn get_current_recalc_block(1202		current_relay_block: T::BlockNumber,1203		config: &PalletConfiguration<T>,1204	) -> T::BlockNumber {1205		(current_relay_block / config.recalculation_interval) * config.recalculation_interval1206	}12071208	fn get_next_calculated_key() -> Option<Vec<u8>> {1209		Self::get_next_calculated_record().map(Staked::<T>::hashed_key_for)1210	}1211}12121213impl<T: Config> Pallet<T>1214where1215	<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1216{1217	/// Returns the amount reserved by the pending.1218	/// If `staker` is `None`, returns the total pending.1219	///1220	/// -`staker`: staker account.1221	///1222	/// Since user funds are not transferred anywhere by staking, overflow protection is provided1223	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1224	/// the staker must have more funds on his account than the maximum set for `Balance` type.1225	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1226		staker.map_or(1227			PendingUnstake::<T>::iter_values()1228				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1229				.sum(),1230			|s| {1231				PendingUnstake::<T>::iter_values()1232					.flatten()1233					.filter_map(|(id, amount)| {1234						if id == *s.as_sub() {1235							Some(amount)1236						} else {1237							None1238						}1239					})1240					.sum()1241			},1242		)1243	}12441245	/// Returns all parachain block numbers when unreserve is expected,1246	/// the amount of the unreserved funds.1247	///1248	/// - `staker`: staker account.1249	pub fn cross_id_pending_unstake_per_block(1250		staker: T::CrossAccountId,1251	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1252		let mut unsorted_res = vec![];1253		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1254			pendings.into_iter().for_each(|(id, amount)| {1255				if id == *staker.as_sub() {1256					unsorted_res.push((block, amount));1257				};1258			})1259		});12601261		unsorted_res.sort_by_key(|(block, _)| *block);1262		unsorted_res1263	}12641265	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1266		let config = <PalletConfiguration<T>>::get();12671268		// calculate block number where the sum would be free1269		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;12701271		let mut pendings = <PendingUnstake<T>>::get(block);12721273		// checks that we can do unstake in the block1274		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);12751276		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1277			.map(|(_, (amount, _))| amount)1278			.sum();12791280		if total_staked.is_zero() {1281			return Ok(());1282		}12831284		pendings1285			.try_push((staker_id.clone(), total_staked))1286			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;12871288		<PendingUnstake<T>>::insert(block, pendings);12891290		TotalStaked::<T>::set(1291			TotalStaked::<T>::get()1292				.checked_sub(&total_staked)1293				.ok_or(ArithmeticError::Underflow)?,1294		);12951296		StakesPerAccount::<T>::remove(&staker_id);12971298		Self::deposit_event(Event::Unstake(staker_id, total_staked));12991300		Ok(())1301	}1302}
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}