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

difftreelog

source

pallets/app-promotion/src/lib.rs31.9 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		Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,74	},75	ensure, BoundedVec,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83	Perbill,84	traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85	ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97	use super::*;98	use frame_support::{99		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100		traits::ReservableCurrency, weights::Weight,101	};102	use frame_system::pallet_prelude::*;103104	#[pallet::config]105	pub trait Config:106		frame_system::Config + pallet_evm::Config + pallet_configuration::Config107	{108		/// Type to interact with the native token109		type Currency: ExtendedLockableCurrency<Self::AccountId>110			+ ReservableCurrency<Self::AccountId>;111112		/// Type for interacting with collections113		type CollectionHandler: CollectionHandler<114			AccountId = Self::AccountId,115			CollectionId = CollectionId,116		>;117118		/// Type for interacting with conrtacts119		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;120121		/// `AccountId` for treasury122		type TreasuryAccountId: Get<Self::AccountId>;123124		/// The app's pallet id, used for deriving its sovereign account address.125		#[pallet::constant]126		type PalletId: Get<PalletId>;127128		/// In relay blocks.129		#[pallet::constant]130		type RecalculationInterval: Get<Self::BlockNumber>;131132		/// In parachain blocks.133		#[pallet::constant]134		type PendingInterval: Get<Self::BlockNumber>;135136		/// Rate of return for interval in blocks defined in `RecalculationInterval`.137		#[pallet::constant]138		type IntervalIncome: Get<Perbill>;139140		/// Decimals for the `Currency`.141		#[pallet::constant]142		type Nominal: Get<BalanceOf<Self>>;143144		/// Weight information for extrinsics in this pallet.145		type WeightInfo: WeightInfo;146147		// The relay block number provider148		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149150		/// Events compatible with [`frame_system::Config::Event`].151		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;152	}153154	#[pallet::pallet]155	#[pallet::generate_store(pub(super) trait Store)]156	pub struct Pallet<T>(_);157158	#[pallet::event]159	#[pallet::generate_deposit(pub(super) fn deposit_event)]160	pub enum Event<T: Config> {161		/// Staking recalculation was performed162		///163		/// # Arguments164		/// * AccountId: account of the staker.165		/// * Balance : recalculation base166		/// * Balance : total income167		StakingRecalculation(168			/// An recalculated staker169			T::AccountId,170			/// Base on which interest is calculated171			BalanceOf<T>,172			/// Amount of accrued interest173			BalanceOf<T>,174		),175176		/// Staking was performed177		///178		/// # Arguments179		/// * AccountId: account of the staker180		/// * Balance : staking amount181		Stake(T::AccountId, BalanceOf<T>),182183		/// Unstaking was performed184		///185		/// # Arguments186		/// * AccountId: account of the staker187		/// * Balance : unstaking amount188		Unstake(T::AccountId, BalanceOf<T>),189190		/// The admin was set191		///192		/// # Arguments193		/// * AccountId: account address of the admin194		SetAdmin(T::AccountId),195	}196197	#[pallet::error]198	pub enum Error<T> {199		/// Error due to action requiring admin to be set.200		AdminNotSet,201		/// No permission to perform an action.202		NoPermission,203		/// Insufficient funds to perform an action.204		NotSufficientFunds,205		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.206		PendingForBlockOverflow,207		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.208		SponsorNotSet,209		/// Errors caused by incorrect actions with a locked balance.210		IncorrectLockedBalanceOperation,211		/// Errors caused by insufficient staked balance.212		InsufficientStakedBalance,213	}214215	/// Stores the total staked amount.216	#[pallet::storage]217	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;218219	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.220	#[pallet::storage]221	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;222223	/// Stores the amount of tokens staked by account in the blocknumber.224	///225	/// * **Key1** - Staker account.226	/// * **Key2** - Relay block number when the stake was made.227	/// * **(Balance, BlockNumber)** - Balance of the stake.228	/// The number of the relay block in which we must perform the interest recalculation229	#[pallet::storage]230	pub type Staked<T: Config> = StorageNMap<231		Key = (232			Key<Blake2_128Concat, T::AccountId>,233			Key<Twox64Concat, T::BlockNumber>,234		),235		Value = (BalanceOf<T>, T::BlockNumber),236		QueryKind = ValueQuery,237	>;238239	/// Stores number of stake records for an `Account`.240	///241	/// * **Key** - Staker account.242	/// * **Value** - Amount of stakes.243	#[pallet::storage]244	pub type StakesPerAccount<T: Config> =245		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;246247	/// Pending unstake records for an `Account`.248	///249	/// * **Key** - Staker account.250	/// * **Value** - Amount of stakes.251	#[pallet::storage]252	pub type PendingUnstake<T: Config> = StorageMap<253		_,254		Twox64Concat,255		T::BlockNumber,256		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,257		ValueQuery,258	>;259260	/// Stores a key for record for which the revenue recalculation was performed.261	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.262	#[pallet::storage]263	#[pallet::getter(fn get_next_calculated_record)]264	pub type PreviousCalculatedRecord<T: Config> =265		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;266267	#[pallet::storage]268	pub(crate) type UpgradedToReserves<T: Config> =269		StorageValue<Value = bool, QueryKind = ValueQuery>;270271	#[pallet::hooks]272	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {273		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize274		/// implies the execution of a strictly limited number of relatively lightweight operations.275		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.276		fn on_initialize(current_block_number: T::BlockNumber) -> Weight277		where278			<T as frame_system::Config>::BlockNumber: From<u32>,279		{280			let block_pending = PendingUnstake::<T>::take(current_block_number);281			let counter = block_pending.len() as u32;282283			if !block_pending.is_empty() {284				block_pending.into_iter().for_each(|(staker, amount)| {285					Self::get_locked_balance(&staker).map(|b| {286						let new_state = b.amount.checked_sub(&amount).unwrap_or_default();287						Self::set_lock_unchecked(&staker, new_state);288					});289				});290			}291292			<T as Config>::WeightInfo::on_initialize(counter)293		}294295		fn on_runtime_upgrade() -> Weight {296			<UpgradedToReserves<T>>::kill();297298			T::DbWeight::get().reads_writes(0, 1)299		}300	}301302	#[pallet::call]303	impl<T: Config> Pallet<T>304	where305		T::BlockNumber: From<u32> + Into<u32>,306		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,307	{308		/// Sets an address as the the admin.309		///310		/// # Permissions311		///312		/// * Sudo313		///314		/// # Arguments315		///316		/// * `admin`: account of the new admin.317		#[pallet::call_index(0)]318		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]319		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {320			ensure_root(origin)?;321322			<Admin<T>>::set(Some(admin.as_sub().to_owned()));323324			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));325326			Ok(())327		}328329		/// Stakes the amount of native tokens.330		/// Sets `amount` to the locked state.331		/// The maximum number of stakes for a staker is 10.332		///333		/// # Arguments334		///335		/// * `amount`: in native tokens.336		#[pallet::call_index(1)]337		#[pallet::weight(<T as Config>::WeightInfo::stake())]338		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {339			let staker_id = ensure_signed(staker)?;340341			ensure!(342				StakesPerAccount::<T>::get(&staker_id) < 10,343				Error::<T>::NoPermission344			);345346			ensure!(347				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),348				ArithmeticError::Underflow349			);350			let config = <PalletConfiguration<T>>::get();351352			let balance =353				<<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);354355			// checks that we can lock `amount` on the `staker` account.356			ensure!(357				amount358					<= match Self::get_locked_balance(&staker_id) {359						Some(lock) => balance360							.checked_sub(&lock.amount)361							.ok_or(ArithmeticError::Underflow)?,362						None => balance,363					},364				ArithmeticError::Underflow365			);366367			Self::add_lock_balance(&staker_id, amount)?;368369			let block_number = T::RelayBlockNumberProvider::current_block_number();370371			// Calculation of the number of recalculation periods,372			// after how much the first interest calculation should be performed for the stake373			let recalculate_after_interval: T::BlockNumber =374				if block_number % config.recalculation_interval == 0u32.into() {375					1u32.into()376				} else {377					2u32.into()378				};379380			// Сalculation of the number of the relay block381			// in which it is necessary to accrue remuneration for the stake.382			let recalc_block = (block_number / config.recalculation_interval383				+ recalculate_after_interval)384				* config.recalculation_interval;385386			<Staked<T>>::insert((&staker_id, block_number), {387				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));388				balance_and_recalc_block.0 = balance_and_recalc_block389					.0390					.checked_add(&amount)391					.ok_or(ArithmeticError::Overflow)?;392				balance_and_recalc_block.1 = recalc_block;393				balance_and_recalc_block394			});395396			<TotalStaked<T>>::set(397				<TotalStaked<T>>::get()398					.checked_add(&amount)399					.ok_or(ArithmeticError::Overflow)?,400			);401402			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);403404			Self::deposit_event(Event::Stake(staker_id, amount));405406			Ok(())407		}408409		/// Unstakes all stakes.410		/// After the end of `PendingInterval` this sum becomes completely411		/// free for further use.412		#[pallet::call_index(2)]413		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]414		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {415			let staker_id = ensure_signed(staker)?;416417			Self::unstake_all_internal(staker_id)418		}419420		/// Unstakes the amount of balance for the staker.421		/// After the end of `PendingInterval` this sum becomes completely422		/// free for further use.423		///424		///  # Arguments425		///426		/// * `staker`: staker account.427		/// * `amount`: amount of unstaked funds.428		#[pallet::call_index(8)]429		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]430		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {431			let staker_id = ensure_signed(staker)?;432433			Self::unstake_partial_internal(staker_id, amount)434		}435436		/// Sets the pallet to be the sponsor for the collection.437		///438		/// # Permissions439		///440		/// * Pallet admin441		///442		/// # Arguments443		///444		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`445		#[pallet::call_index(3)]446		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]447		pub fn sponsor_collection(448			admin: OriginFor<T>,449			collection_id: CollectionId,450		) -> DispatchResult {451			let admin_id = ensure_signed(admin)?;452			ensure!(453				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,454				Error::<T>::NoPermission455			);456457			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)458		}459460		/// Removes the pallet as the sponsor for the collection.461		/// Returns [`NoPermission`][`Error::NoPermission`]462		/// if the pallet wasn't the sponsor.463		///464		/// # Permissions465		///466		/// * Pallet admin467		///468		/// # Arguments469		///470		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`471		#[pallet::call_index(4)]472		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]473		pub fn stop_sponsoring_collection(474			admin: OriginFor<T>,475			collection_id: CollectionId,476		) -> DispatchResult {477			let admin_id = ensure_signed(admin)?;478479			ensure!(480				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,481				Error::<T>::NoPermission482			);483484			ensure!(485				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?486					== Self::account_id(),487				<Error<T>>::NoPermission488			);489			T::CollectionHandler::remove_collection_sponsor(collection_id)490		}491492		/// Sets the pallet to be the sponsor for the contract.493		///494		/// # Permissions495		///496		/// * Pallet admin497		///498		/// # Arguments499		///500		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`501		#[pallet::call_index(5)]502		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]503		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {504			let admin_id = ensure_signed(admin)?;505506			ensure!(507				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,508				Error::<T>::NoPermission509			);510511			T::ContractHandler::set_sponsor(512				T::CrossAccountId::from_sub(Self::account_id()),513				contract_id,514			)515		}516517		/// Removes the pallet as the sponsor for the contract.518		/// Returns [`NoPermission`][`Error::NoPermission`]519		/// if the pallet wasn't the sponsor.520		///521		/// # Permissions522		///523		/// * Pallet admin524		///525		/// # Arguments526		///527		/// * `contract_id`: the contract address that is sponsored by `pallet_id`528		#[pallet::call_index(6)]529		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]530		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {531			let admin_id = ensure_signed(admin)?;532533			ensure!(534				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,535				Error::<T>::NoPermission536			);537538			ensure!(539				T::ContractHandler::sponsor(contract_id)?540					.ok_or(<Error<T>>::SponsorNotSet)?541					.as_sub() == &Self::account_id(),542				<Error<T>>::NoPermission543			);544			T::ContractHandler::remove_contract_sponsor(contract_id)545		}546547		/// Recalculates interest for the specified number of stakers.548		/// If all stakers are not recalculated, the next call of the extrinsic549		/// will continue the recalculation, from those stakers for whom this550		/// was not perform in last call.551		///552		/// # Permissions553		///554		/// * Pallet admin555		///556		/// # Arguments557		///558		/// * `stakers_number`: the number of stakers for which recalculation will be performed559		#[pallet::call_index(7)]560		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]561		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {562			let admin_id = ensure_signed(admin)?;563564			ensure!(565				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,566				Error::<T>::NoPermission567			);568			let config = <PalletConfiguration<T>>::get();569570			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);571572			ensure!(573				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,574				Error::<T>::NoPermission575			);576577			// calculate the number of the current recalculation block,578			// this is necessary in order to understand which stakers we should calculate interest579			let current_recalc_block = Self::get_current_recalc_block(580				T::RelayBlockNumberProvider::current_block_number(),581				&config,582			);583584			// calculate the number of the next recalculation block,585			// this value is set for the stakers to whom the recalculation will be performed586			let next_recalc_block = current_recalc_block + config.recalculation_interval;587588			let mut storage_iterator = Self::get_next_calculated_key()589				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));590591			PreviousCalculatedRecord::<T>::set(None);592593			{594				// Address handled in the last payout loop iteration (below)595				let last_id = RefCell::new(None);596				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration597				let mut last_staked_calculated_block = Default::default();598				// Reward balance for the address in the iteration599				let income_acc = RefCell::new(BalanceOf::<T>::default());600				// Staked balance for the address in the iteration (before stake is recalculated)601				let amount_acc = RefCell::new(BalanceOf::<T>::default());602603				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout604				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout605				// loop switches to handling the next staker address:606				//   1. Transfer full reward amount to the payee607				//   2. Lock the reward in staking lock608				//   3. Update TotalStaked amount609				//   4. Issue StakingRecalculation event610				let flush_stake = || -> DispatchResult {611					if let Some(last_id) = &*last_id.borrow() {612						if !income_acc.borrow().is_zero() {613							<<T as Config>::Currency as Currency<T::AccountId>>::transfer(614								&T::TreasuryAccountId::get(),615								last_id,616								*income_acc.borrow(),617								ExistenceRequirement::KeepAlive,618							)?;619620							Self::add_lock_balance(last_id, *income_acc.borrow())?;621							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {622								*staked = staked623									.checked_add(&*income_acc.borrow())624									.ok_or(ArithmeticError::Overflow)?;625								Ok(())626							})?;627628							Self::deposit_event(Event::StakingRecalculation(629								last_id.clone(),630								*amount_acc.borrow(),631								*income_acc.borrow(),632							));633						}634635						*income_acc.borrow_mut() = BalanceOf::<T>::default();636						*amount_acc.borrow_mut() = BalanceOf::<T>::default();637					}638					Ok(())639				};640641				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation642				// iterations in one extrinsic call643				//644				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)645				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out646				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)647				while let Some((648					(current_id, staked_block),649					(amount, next_recalc_block_for_stake),650				)) = storage_iterator.next()651				{652					// last_id is not equal current_id when we switch to handling a new staker address653					// or just start handling the very first address. In the latter case last_id will be None and654					// flush_stake will do nothing655					if last_id.borrow().as_ref() != Some(&current_id) {656						if stakers_number > 0 {657							flush_stake()?;658							*last_id.borrow_mut() = Some(current_id.clone());659							stakers_number -= 1;660						}661						// Break out if we reached the address limit662						else {663							if let Some(staker) = &*last_id.borrow() {664								// Save the last calculated record to pick up in the next extrinsic call665								PreviousCalculatedRecord::<T>::set(Some((666									staker.clone(),667									last_staked_calculated_block,668								)));669							}670							break;671						};672					};673674					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount675					if current_recalc_block >= next_recalc_block_for_stake {676						*amount_acc.borrow_mut() += amount;677						Self::recalculate_and_insert_stake(678							&current_id,679							staked_block,680							next_recalc_block,681							amount,682							((current_recalc_block - next_recalc_block_for_stake)683								/ config.recalculation_interval)684								.into() + 1,685							&mut *income_acc.borrow_mut(),686						);687					}688					last_staked_calculated_block = staked_block;689				}690				flush_stake()?;691			}692693			Ok(())694		}695	}696}697698impl<T: Config> Pallet<T> {699	/// The account address of the app promotion pot.700	///701	/// This actually does computation. If you need to keep using it, then make sure you cache the702	/// value and only call this once.703	pub fn account_id() -> T::AccountId {704		T::PalletId::get().into_account_truncating()705	}706707	/// Unstakes the balance for the staker.708	///709	/// - `staker`: staker account.710	/// - `amount`: amount of unstaked funds.711	fn unstake_partial_internal(712		staker_id: T::AccountId,713		unstaked_balance: BalanceOf<T>,714	) -> DispatchResult {715		if unstaked_balance == Default::default() {716			return Ok(());717		}718719		let config = <PalletConfiguration<T>>::get();720721		// calculate block number where the sum would be free722		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;723724		let mut pendings = <PendingUnstake<T>>::get(unpending_block);725726		// checks that we can do unstake in the block727		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);728729		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();730731		let total_staked = stakes732			.iter()733			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {734				acc + *balance735			});736737		ensure!(738			unstaked_balance <= total_staked,739			<Error<T>>::InsufficientStakedBalance740		);741742		<TotalStaked<T>>::set(743			<TotalStaked<T>>::get()744				.checked_sub(&unstaked_balance)745				.ok_or(ArithmeticError::Underflow)?,746		);747748		stakes.sort_by_key(|(block, _)| *block);749750		let mut acc_amount = unstaked_balance;751		let mut will_deleted_stakes_count = 0u8;752753		let changed_stakes = stakes754			.into_iter()755			.map_while(|(block, (balance_per_block, _))| {756				if acc_amount == <BalanceOf<T>>::default() {757					return None;758				}759				if acc_amount < balance_per_block {760					let res = (block, balance_per_block - acc_amount);761					acc_amount = <BalanceOf<T>>::default();762					return Some(res);763				} else {764					acc_amount -= balance_per_block;765					will_deleted_stakes_count += 1;766					return Some((block, <BalanceOf<T>>::default()));767				}768			})769			.collect::<Vec<_>>();770771		pendings772			.try_push((staker_id.clone(), unstaked_balance))773			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;774775		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {776			*stakes = stakes777				.checked_sub(will_deleted_stakes_count)778				.ok_or(ArithmeticError::Underflow)?;779			Ok(())780		})?;781782		changed_stakes783			.into_iter()784			.for_each(|(staked_block, current_stake_state)| {785				if current_stake_state == Default::default() {786					<Staked<T>>::remove((&staker_id, staked_block));787				} else {788					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {789						*old_stake_state = current_stake_state790					});791				}792			});793794		<PendingUnstake<T>>::insert(unpending_block, pendings);795796		Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));797798		Ok(())799	}800801	/// Adds the balance to locked by the pallet.802	///803	/// - `staker`: staker account.804	/// - `amount`: amount of added locked funds.805	fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {806		Self::get_locked_balance(staker)807			.map_or(<BalanceOf<T>>::default(), |l| l.amount)808			.checked_add(&amount)809			.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))810			.ok_or(ArithmeticError::Overflow.into())811	}812813	/// Sets the new state of a balance locked by the pallet.814	///815	/// - `staker`: staker account.816	/// - `amount`: amount of locked funds.817	fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {818		if amount.is_zero() {819			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(820				LOCK_IDENTIFIER,821				&staker,822			);823		} else {824			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(825				LOCK_IDENTIFIER,826				staker,827				amount,828				WithdrawReasons::all(),829			)830		}831	}832833	/// Returns the balance locked by the pallet for the staker.834	///835	/// - `staker`: staker account.836	pub fn get_locked_balance(837		staker: impl EncodeLike<T::AccountId>,838	) -> Option<BalanceLock<BalanceOf<T>>> {839		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)840			.into_iter()841			.find(|l| l.id == LOCK_IDENTIFIER)842	}843844	/// Returns the total staked balance for the staker.845	///846	/// - `staker`: staker account.847	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {848		let staked = Staked::<T>::iter_prefix((staker,))849			.into_iter()850			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {851				acc + amount852			});853		if staked != <BalanceOf<T>>::default() {854			Some(staked)855		} else {856			None857		}858	}859860	/// Returns all relay block numbers when stake was made,861	/// the amount of the stake.862	///863	/// - `staker`: staker account.864	pub fn total_staked_by_id_per_block(865		staker: impl EncodeLike<T::AccountId>,866	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {867		let mut staked = Staked::<T>::iter_prefix((staker,))868			.into_iter()869			.map(|(block, (amount, _))| (block, amount))870			.collect::<Vec<_>>();871		staked.sort_by_key(|(block, _)| *block);872		if !staked.is_empty() {873			Some(staked)874		} else {875			None876		}877	}878879	/// Returns the total staked balance for the staker.880	/// If `staker` is `None`, returns the total amount staked.881	/// - `staker`: staker account.882	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {883		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {884			Self::total_staked_by_id(s.as_sub())885		})886	}887888	// pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {889	// 	Self::get_locked_balance(staker.as_sub())890	// 		.map(|l| l.amount)891	// 		.unwrap_or_default()892	// }893894	/// Returns all relay block numbers when stake was made,895	/// the amount of the stake.896	///897	/// - `staker`: staker account.898	pub fn cross_id_total_staked_per_block(899		staker: T::CrossAccountId,900	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {901		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()902	}903904	fn recalculate_and_insert_stake(905		staker: &T::AccountId,906		staked_block: T::BlockNumber,907		next_recalc_block: T::BlockNumber,908		base: BalanceOf<T>,909		iters: u32,910		income_acc: &mut BalanceOf<T>,911	) {912		let income = Self::calculate_income(base, iters);913914		base.checked_add(&income).map(|res| {915			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));916			*income_acc += income;917		});918	}919920	fn calculate_income<I>(base: I, iters: u32) -> I921	where922		I: EncodeLike<BalanceOf<T>> + Balance,923	{924		let config = <PalletConfiguration<T>>::get();925		let mut income = base;926927		(0..iters).for_each(|_| income += config.interval_income * income);928929		income - base930	}931932	/// Get relay block number rounded down to multiples of config.recalculation_interval.933	/// We need it to reward stakers in integer parts of recalculation_interval934	fn get_current_recalc_block(935		current_relay_block: T::BlockNumber,936		config: &PalletConfiguration<T>,937	) -> T::BlockNumber {938		(current_relay_block / config.recalculation_interval) * config.recalculation_interval939	}940941	fn get_next_calculated_key() -> Option<Vec<u8>> {942		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))943	}944}945946impl<T: Config> Pallet<T>947where948	<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,949{950	/// Returns the amount reserved by the pending.951	/// If `staker` is `None`, returns the total pending.952	///953	/// -`staker`: staker account.954	///955	/// Since user funds are not transferred anywhere by staking, overflow protection is provided956	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,957	/// the staker must have more funds on his account than the maximum set for `Balance` type.958	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {959		staker.map_or(960			PendingUnstake::<T>::iter_values()961				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))962				.sum(),963			|s| {964				PendingUnstake::<T>::iter_values()965					.flatten()966					.filter_map(|(id, amount)| {967						if id == *s.as_sub() {968							Some(amount)969						} else {970							None971						}972					})973					.sum()974			},975		)976	}977978	/// Returns all parachain block numbers when unreserve is expected,979	/// the amount of the unreserved funds.980	///981	/// - `staker`: staker account.982	pub fn cross_id_pending_unstake_per_block(983		staker: T::CrossAccountId,984	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {985		let mut unsorted_res = vec![];986		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {987			pendings.into_iter().for_each(|(id, amount)| {988				if id == *staker.as_sub() {989					unsorted_res.push((block, amount));990				};991			})992		});993994		unsorted_res.sort_by_key(|(block, _)| *block);995		unsorted_res996	}997998	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {999		let config = <PalletConfiguration<T>>::get();10001001		// calculate block number where the sum would be free1002		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;10031004		let mut pendings = <PendingUnstake<T>>::get(block);10051006		// checks that we can do unstake in the block1007		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);10081009		let mut total_stakes = 0u64;10101011		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1012			.map(|(_, (amount, _))| {1013				total_stakes += 1;1014				amount1015			})1016			.sum();10171018		if total_staked.is_zero() {1019			return Ok(());1020		}10211022		pendings1023			.try_push((staker_id.clone(), total_staked))1024			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;10251026		<PendingUnstake<T>>::insert(block, pendings);10271028		TotalStaked::<T>::set(1029			TotalStaked::<T>::get()1030				.checked_sub(&total_staked)1031				.ok_or(ArithmeticError::Underflow)?,1032		);10331034		StakesPerAccount::<T>::remove(&staker_id);10351036		Self::deposit_event(Event::Unstake(staker_id, total_staked));10371038		Ok(())1039	}1040}