git.delta.rocks / unique-network / refs/commits / 0564b0f31d0d

difftreelog

refactor(app-promo) delete unused error

PraetorP2023-05-19parent: #24f9c77.patch.diff
in: master

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,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::*;104use 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<Self::AccountId, Balance = <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance>;114115		/// Type for interacting with collections116		type CollectionHandler: CollectionHandler<117			AccountId = Self::AccountId,118			CollectionId = CollectionId,119		>;120121		/// Type for interacting with conrtacts122		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;123124		/// `AccountId` for treasury125		type TreasuryAccountId: Get<Self::AccountId>;126127		/// The app's pallet id, used for deriving its sovereign account address.128		#[pallet::constant]129		type PalletId: Get<PalletId>;130131		/// Freeze identifier used by the pallet132		#[pallet::constant]133		type FreezeIdentifier: Get<<<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id>;134135		/// In relay blocks.136		#[pallet::constant]137		type RecalculationInterval: Get<Self::BlockNumber>;138139		/// In parachain blocks.140		#[pallet::constant]141		type PendingInterval: Get<Self::BlockNumber>;142143		/// Rate of return for interval in blocks defined in `RecalculationInterval`.144		#[pallet::constant]145		type IntervalIncome: Get<Perbill>;146147		/// Decimals for the `Currency`.148		#[pallet::constant]149		type Nominal: Get<BalanceOf<Self>>;150151		/// Weight information for extrinsics in this pallet.152		type WeightInfo: WeightInfo;153154		// The relay block number provider155		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;156157		/// Events compatible with [`frame_system::Config::Event`].158		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;159	}160161	#[pallet::pallet]162	pub struct Pallet<T>(_);163164	#[pallet::event]165	#[pallet::generate_deposit(pub(super) fn deposit_event)]166	pub enum Event<T: Config> {167		/// Staking recalculation was performed168		///169		/// # Arguments170		/// * AccountId: account of the staker.171		/// * Balance : recalculation base172		/// * Balance : total income173		StakingRecalculation(174			/// An recalculated staker175			T::AccountId,176			/// Base on which interest is calculated177			BalanceOf<T>,178			/// Amount of accrued interest179			BalanceOf<T>,180		),181182		/// Staking was performed183		///184		/// # Arguments185		/// * AccountId: account of the staker186		/// * Balance : staking amount187		Stake(T::AccountId, BalanceOf<T>),188189		/// Unstaking was performed190		///191		/// # Arguments192		/// * AccountId: account of the staker193		/// * Balance : unstaking amount194		Unstake(T::AccountId, BalanceOf<T>),195196		/// The admin was set197		///198		/// # Arguments199		/// * AccountId: account address of the admin200		SetAdmin(T::AccountId),201	}202203	#[pallet::error]204	pub enum Error<T> {205		/// Error due to action requiring admin to be set.206		AdminNotSet,207		/// No permission to perform an action.208		NoPermission,209		/// Insufficient funds to perform an action.210		NotSufficientFunds,211		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.212		PendingForBlockOverflow,213		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.214		SponsorNotSet,215		/// 216		IncorrectLockedBalanceOperation,217		/// Errors caused by insufficient staked balance.218		InsufficientStakedBalance,219		/// Errors caused by incorrect state of a staker in context of the pallet.220		InconsistencyState221	}222223	/// Stores the total staked amount.224	#[pallet::storage]225	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;226227	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.228	#[pallet::storage]229	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;230231	/// Stores the amount of tokens staked by account in the blocknumber.232	///233	/// * **Key1** - Staker account.234	/// * **Key2** - Relay block number when the stake was made.235	/// * **(Balance, BlockNumber)** - Balance of the stake.236	/// The number of the relay block in which we must perform the interest recalculation237	#[pallet::storage]238	pub type Staked<T: Config> = StorageNMap<239		Key = (240			Key<Blake2_128Concat, T::AccountId>,241			Key<Twox64Concat, T::BlockNumber>,242		),243		Value = (BalanceOf<T>, T::BlockNumber),244		QueryKind = ValueQuery,245	>;246247	/// Stores number of stake records for an `Account`.248	///249	/// * **Key** - Staker account.250	/// * **Value** - Amount of stakes.251	#[pallet::storage]252	pub type StakesPerAccount<T: Config> =253		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;254255	/// Pending unstake records for an `Account`.256	///257	/// * **Key** - Staker account.258	/// * **Value** - Amount of stakes.259	#[pallet::storage]260	pub type PendingUnstake<T: Config> = StorageMap<261		_,262		Twox64Concat,263		T::BlockNumber,264		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,265		ValueQuery,266	>;267268	/// Stores a key for record for which the revenue recalculation was performed.269	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.270	#[pallet::storage]271	#[pallet::getter(fn get_next_calculated_record)]272	pub type PreviousCalculatedRecord<T: Config> =273		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;274275	// #[pallet::storage]276	// pub(crate) type UpgradedToFreezes<T: Config> =277	// 	StorageValue<Value = bool, QueryKind = ValueQuery>;278279	#[pallet::hooks]280	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {281		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize282		/// implies the execution of a strictly limited number of relatively lightweight operations.283		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.284		fn on_initialize(current_block_number: T::BlockNumber) -> Weight285		where286			<T as frame_system::Config>::BlockNumber: From<u32>,287		{288			let block_pending = PendingUnstake::<T>::take(current_block_number);289			let counter = block_pending.len() as u32;290291			if !block_pending.is_empty() {292				block_pending.into_iter().for_each(|(staker, amount)| {293					Self::get_freezed_balance(&staker).map(|b| {294						let new_state = b.checked_sub(&amount).unwrap_or_default();295						Self::set_freeze_unchecked(&staker, new_state);296					});297				});298			}299300			<T as Config>::WeightInfo::on_initialize(counter)301		}302303		// fn on_runtime_upgrade() -> Weight {304		// 	use scale_info::prelude::collections::HashSet;305		// 	let mut consumed_weight = Weight::zero();306		// 	let mut add_weight = |reads, writes, weight| {307		// 		consumed_weight += T::DbWeight::get().reads_writes(reads, writes);308		// 		consumed_weight += weight;309		// 	};310311		// 	let mut stakes_unstakes = vec![];312313		// 	if <UpgradedToFreezes<T>>::get() {314		// 		add_weight(1, 0, Weight::zero());315		// 		return consumed_weight;316		// 	} else {317		// 		add_weight(1, 1, Weight::zero());318		// 		<UpgradedToFreezes<T>>::set(true);319		// 	}320		// 	<Staked<T>>::iter_keys().for_each(|(staker_id, _)| {321		// 		add_weight(1, 0, Weight::zero());322		// 		stakes_unstakes.push(staker_id);323		// 	});324325		// 	<PendingUnstake<T>>::iter().for_each(|(_, v)| {326		// 		add_weight(1, 0, Weight::zero());327		// 		v.into_iter().for_each(|(staker, _)| {328		// 			stakes_unstakes.push(staker);329		// 		});330		// 	});331332		// 	// filter duplicated id.333		// 	stakes_unstakes = stakes_unstakes334		// 		.into_iter()335		// 		.map(|key| key)336		// 		.collect::<HashSet<_>>()337		// 		.into_iter()338		// 		.collect();339340		// 	stakes_unstakes341		// 		.map(|a| (a, <Pallet<T>>::get_locked_balance(&a).amount))342		// 		.for_each(|(staker, amount)| {343		// 			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(344		// 				LOCK_IDENTIFIER,345		// 				&staker,346		// 			);347		// 			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(348		// 				&<T as Config>::FreezeIdentifier::get(),349		// 				&staker,350		// 				amount,351		// 			);352		// 			add_weight(1, 2, Weight::zero())353		// 		});354355		// 	consumed_weight356		// }357358		// #[cfg(feature = "try-runtime")]359		// fn pre_upgrade() -> Result<Vec<u8>, &'static str> {360		// 	use sp_std::collections::btree_map::BTreeMap;361		// 	if <UpgradedToFreezes<T>>::get() {362		// 		return Ok(Default::default());363		// 	}364		// 	// Staker -> (total (stakes and unstakes) locked by promotion);365		// 	let mut pre_state: BTreeMap<T::AccountId, BalanceOf<T>> = BTreeMap::new();366367		// 	<Staked<T>>::iter().for_each(|((staker, _), (amount, _))| {368		// 		if let Some(locked_balance) = pre_state.get_mut(&staker) {369		// 			*locked_balance += amount;370		// 		} else {371		// 			pre_state.insert(staker, amount);372		// 		}373		// 	});374375		// 	<PendingUnstake<T>>::iter().for_each(|(_, v)| {376		// 		v.into_iter().for_each(|(staker, amount)| {377		// 			if let Some(locked_balance) = pre_state.get_mut(&staker) {378		// 				*locked_balance += amount;379		// 			} else {380		// 				pre_state.insert(staker, amount);381		// 			}382		// 		})383		// 	});384385		// 	Ok(pre_state.encode())386		// }387388		// #[cfg(feature = "try-runtime")]389		// fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {390		// 	use sp_std::collections::btree_map::BTreeMap;391392		// 	if <UpgradedToFreezes<T>>::get() {393		// 		return Ok(());394		// 	}395396		// 	let mut is_ok = true;397398		// 	let pre_state: BTreeMap<T::AccountId, BalanceOf<T>> =399		// 		Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;400		// 	for (staker, freezed_by_promo) in pre_state.into_iter() {401		// 		let storage_freeze_state = <<T as Config>::Currency as InspectFreeze<402		// 			T::AccountId,403		// 		>>::balance_frozen(404		// 			&<T as Config>::FreezeIdentifier::get(), staker405		// 		);406		// 		if storage_freeze_state != freezed_by_promo {407		// 			is_ok = false;408		// 			log::error!(409		// 						"Incorrect freezed balance for {:?}. New balance: {:?}. Before runtime upgrade: locked by promo - {:?}",410		// 						staker, storage_freeze_state, freezed_by_promo411		// 					);412		// 		}413414		// 		if !<Pallet<T>>::get_locked_balance(&staker).amount.is_zero() {415		// 			is_ok = false;416		// 			log::error!(417		// 				"Incorrect(non-zero) locked by app promo balance for {:?}",418		// 				staker419		// 			);420		// 		}421		// 	}422423		// 	if is_ok {424		// 		Ok(())425		// 	} else {426		// 		Err("Incorrect balance for some of stakers... See logs")427		// 	}428		// }429	}430431	#[pallet::call]432	impl<T: Config> Pallet<T>433	where434		T::BlockNumber: From<u32> + Into<u32>,435		<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,436	{437		/// Sets an address as the the admin.438		///439		/// # Permissions440		///441		/// * Sudo442		///443		/// # Arguments444		///445		/// * `admin`: account of the new admin.446		#[pallet::call_index(0)]447		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]448		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {449			ensure_root(origin)?;450451			<Admin<T>>::set(Some(admin.as_sub().to_owned()));452453			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));454455			Ok(())456		}457458		/// Stakes the amount of native tokens.459		/// Sets `amount` to the locked state.460		/// The maximum number of stakes for a staker is 10.461		///462		/// # Arguments463		///464		/// * `amount`: in native tokens.465		#[pallet::call_index(1)]466		#[pallet::weight(<T as Config>::WeightInfo::stake())]467		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {468			let staker_id = ensure_signed(staker)?;469470			ensure!(471				StakesPerAccount::<T>::get(&staker_id) < 10,472				Error::<T>::NoPermission473			);474475			ensure!(476				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),477				ArithmeticError::Underflow478			);479			let config = <PalletConfiguration<T>>::get();480481			let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);482483			// checks that we can freeze `amount` on the `staker` account.484			ensure!(485				amount486					<= match Self::get_freezed_balance(&staker_id) {487						Some(freezed_by_pallet) => balance488							.checked_sub(&freezed_by_pallet)489							.ok_or(ArithmeticError::Underflow)?,490						None => balance,491					},492				ArithmeticError::Underflow493			);494495			Self::add_freeze_balance(&staker_id, amount)?;496497			let block_number = T::RelayBlockNumberProvider::current_block_number();498499			// Calculation of the number of recalculation periods,500			// after how much the first interest calculation should be performed for the stake501			let recalculate_after_interval: T::BlockNumber =502				if block_number % config.recalculation_interval == 0u32.into() {503					1u32.into()504				} else {505					2u32.into()506				};507508			// Сalculation of the number of the relay block509			// in which it is necessary to accrue remuneration for the stake.510			let recalc_block = (block_number / config.recalculation_interval511				+ recalculate_after_interval)512				* config.recalculation_interval;513514			<Staked<T>>::insert((&staker_id, block_number), {515				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));516				balance_and_recalc_block.0 = balance_and_recalc_block517					.0518					.checked_add(&amount)519					.ok_or(ArithmeticError::Overflow)?;520				balance_and_recalc_block.1 = recalc_block;521				balance_and_recalc_block522			});523524			<TotalStaked<T>>::set(525				<TotalStaked<T>>::get()526					.checked_add(&amount)527					.ok_or(ArithmeticError::Overflow)?,528			);529530			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);531532			Self::deposit_event(Event::Stake(staker_id, amount));533534			Ok(())535		}536537		/// Unstakes all stakes.538		/// After the end of `PendingInterval` this sum becomes completely539		/// free for further use.540		#[pallet::call_index(2)]541		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]542		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {543			let staker_id = ensure_signed(staker)?;544545			Self::unstake_all_internal(staker_id)546		}547548		/// Unstakes the amount of balance for the staker.549		/// After the end of `PendingInterval` this sum becomes completely550		/// free for further use.551		///552		///  # Arguments553		///554		/// * `staker`: staker account.555		/// * `amount`: amount of unstaked funds.556		#[pallet::call_index(8)]557		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]558		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {559			let staker_id = ensure_signed(staker)?;560561			Self::unstake_partial_internal(staker_id, amount)562		}563564		/// Sets the pallet to be the sponsor for the collection.565		///566		/// # Permissions567		///568		/// * Pallet admin569		///570		/// # Arguments571		///572		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`573		#[pallet::call_index(3)]574		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]575		pub fn sponsor_collection(576			admin: OriginFor<T>,577			collection_id: CollectionId,578		) -> DispatchResult {579			let admin_id = ensure_signed(admin)?;580			ensure!(581				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,582				Error::<T>::NoPermission583			);584585			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)586		}587588		/// Removes the pallet as the sponsor for the collection.589		/// Returns [`NoPermission`][`Error::NoPermission`]590		/// if the pallet wasn't the sponsor.591		///592		/// # Permissions593		///594		/// * Pallet admin595		///596		/// # Arguments597		///598		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`599		#[pallet::call_index(4)]600		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]601		pub fn stop_sponsoring_collection(602			admin: OriginFor<T>,603			collection_id: CollectionId,604		) -> DispatchResult {605			let admin_id = ensure_signed(admin)?;606607			ensure!(608				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,609				Error::<T>::NoPermission610			);611612			ensure!(613				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?614					== Self::account_id(),615				<Error<T>>::NoPermission616			);617			T::CollectionHandler::remove_collection_sponsor(collection_id)618		}619620		/// Sets the pallet to be the sponsor for the contract.621		///622		/// # Permissions623		///624		/// * Pallet admin625		///626		/// # Arguments627		///628		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`629		#[pallet::call_index(5)]630		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]631		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {632			let admin_id = ensure_signed(admin)?;633634			ensure!(635				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,636				Error::<T>::NoPermission637			);638639			T::ContractHandler::set_sponsor(640				T::CrossAccountId::from_sub(Self::account_id()),641				contract_id,642			)643		}644645		/// Removes the pallet as the sponsor for the contract.646		/// Returns [`NoPermission`][`Error::NoPermission`]647		/// if the pallet wasn't the sponsor.648		///649		/// # Permissions650		///651		/// * Pallet admin652		///653		/// # Arguments654		///655		/// * `contract_id`: the contract address that is sponsored by `pallet_id`656		#[pallet::call_index(6)]657		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]658		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {659			let admin_id = ensure_signed(admin)?;660661			ensure!(662				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,663				Error::<T>::NoPermission664			);665666			ensure!(667				T::ContractHandler::sponsor(contract_id)?668					.ok_or(<Error<T>>::SponsorNotSet)?669					.as_sub() == &Self::account_id(),670				<Error<T>>::NoPermission671			);672			T::ContractHandler::remove_contract_sponsor(contract_id)673		}674675		/// Recalculates interest for the specified number of stakers.676		/// If all stakers are not recalculated, the next call of the extrinsic677		/// will continue the recalculation, from those stakers for whom this678		/// was not perform in last call.679		///680		/// # Permissions681		///682		/// * Pallet admin683		///684		/// # Arguments685		///686		/// * `stakers_number`: the number of stakers for which recalculation will be performed687		#[pallet::call_index(7)]688		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]689		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {690			let admin_id = ensure_signed(admin)?;691692			ensure!(693				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,694				Error::<T>::NoPermission695			);696			let config = <PalletConfiguration<T>>::get();697698			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);699700			ensure!(701				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,702				Error::<T>::NoPermission703			);704705			// calculate the number of the current recalculation block,706			// this is necessary in order to understand which stakers we should calculate interest707			let current_recalc_block = Self::get_current_recalc_block(708				T::RelayBlockNumberProvider::current_block_number(),709				&config,710			);711712			// calculate the number of the next recalculation block,713			// this value is set for the stakers to whom the recalculation will be performed714			let next_recalc_block = current_recalc_block + config.recalculation_interval;715716			let mut storage_iterator = Self::get_next_calculated_key()717				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));718719			PreviousCalculatedRecord::<T>::set(None);720721			{722				// Address handled in the last payout loop iteration (below)723				let last_id = RefCell::new(None);724				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration725				let mut last_staked_calculated_block = Default::default();726				// Reward balance for the address in the iteration727				let income_acc = RefCell::new(BalanceOf::<T>::default());728				// Staked balance for the address in the iteration (before stake is recalculated)729				let amount_acc = RefCell::new(BalanceOf::<T>::default());730731				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout732				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout733				// loop switches to handling the next staker address:734				//   1. Transfer full reward amount to the payee735				//   2. Lock the reward in staking lock736				//   3. Update TotalStaked amount737				//   4. Issue StakingRecalculation event738				let flush_stake = || -> DispatchResult {739					if let Some(last_id) = &*last_id.borrow() {740						if !income_acc.borrow().is_zero() {741							<<T as Config>::Currency as Mutate<T::AccountId>>::transfer(742								&T::TreasuryAccountId::get(),743								last_id,744								*income_acc.borrow(),745								frame_support::traits::tokens::Preservation::Protect,746							)?;747748							Self::add_freeze_balance(last_id, *income_acc.borrow())?;749							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {750								*staked = staked751									.checked_add(&*income_acc.borrow())752									.ok_or(ArithmeticError::Overflow)?;753								Ok(())754							})?;755756							Self::deposit_event(Event::StakingRecalculation(757								last_id.clone(),758								*amount_acc.borrow(),759								*income_acc.borrow(),760							));761						}762763						*income_acc.borrow_mut() = BalanceOf::<T>::default();764						*amount_acc.borrow_mut() = BalanceOf::<T>::default();765					}766					Ok(())767				};768769				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation770				// iterations in one extrinsic call771				//772				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)773				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out774				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)775				while let Some((776					(current_id, staked_block),777					(amount, next_recalc_block_for_stake),778				)) = storage_iterator.next()779				{780					// last_id is not equal current_id when we switch to handling a new staker address781					// or just start handling the very first address. In the latter case last_id will be None and782					// flush_stake will do nothing783					if last_id.borrow().as_ref() != Some(&current_id) {784						if stakers_number > 0 {785							flush_stake()?;786							*last_id.borrow_mut() = Some(current_id.clone());787							stakers_number -= 1;788						}789						// Break out if we reached the address limit790						else {791							if let Some(staker) = &*last_id.borrow() {792								// Save the last calculated record to pick up in the next extrinsic call793								PreviousCalculatedRecord::<T>::set(Some((794									staker.clone(),795									last_staked_calculated_block,796								)));797							}798							break;799						};800					};801802					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount803					if current_recalc_block >= next_recalc_block_for_stake {804						*amount_acc.borrow_mut() += amount;805						Self::recalculate_and_insert_stake(806							&current_id,807							staked_block,808							next_recalc_block,809							amount,810							((current_recalc_block - next_recalc_block_for_stake)811								/ config.recalculation_interval)812								.into() + 1,813							&mut *income_acc.borrow_mut(),814						);815					}816					last_staked_calculated_block = staked_block;817				}818				flush_stake()?;819			}820821			Ok(())822		}823824		///  Migrates lock state into freeze one825		///826		///  # Arguments827		///828		/// * `origin`: Must be `Signed`.829		/// * `stakers`: Accounts to be upgraded.830		#[pallet::call_index(9)]831		#[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]832		pub fn upgrade_accounts(833			origin: OriginFor<T>,834			stakers: Vec<T::AccountId>,835		) -> DispatchResult {836			ensure_signed(origin)?;837838			stakers.into_iter().try_for_each(|s| -> Result<_, DispatchError> {839				if let Some(lock) = Self::get_locked_balance(&s) {840					841					if let Some(_) = Self::get_freezed_balance(&s) {842						return Err(Error::<T>::InconsistencyState.into())843					}844					845					<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(846						LOCK_IDENTIFIER,847						&s,848					);849850					Self::set_freeze_unchecked(&s, lock.amount);851					Ok(())852				} else {853					Ok(())854				}855			})?;856			857			Ok(())858		}859	}860}861862impl<T: Config> Pallet<T> {863	/// The account address of the app promotion pot.864	///865	/// This actually does computation. If you need to keep using it, then make sure you cache the866	/// value and only call this once.867	pub fn account_id() -> T::AccountId {868		T::PalletId::get().into_account_truncating()869	}870871	/// Unstakes the balance for the staker.872	///873	/// - `staker`: staker account.874	/// - `amount`: amount of unstaked funds.875	fn unstake_partial_internal(876		staker_id: T::AccountId,877		unstaked_balance: BalanceOf<T>,878	) -> DispatchResult {879		if unstaked_balance == Default::default() {880			return Ok(());881		}882883		let config = <PalletConfiguration<T>>::get();884885		// calculate block number where the sum would be free886		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;887888		let mut pendings = <PendingUnstake<T>>::get(unpending_block);889890		// checks that we can do unstake in the block891		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);892893		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();894895		let total_staked = stakes896			.iter()897			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {898				acc + *balance899			});900901		ensure!(902			unstaked_balance <= total_staked,903			<Error<T>>::InsufficientStakedBalance904		);905906		<TotalStaked<T>>::set(907			<TotalStaked<T>>::get()908				.checked_sub(&unstaked_balance)909				.ok_or(ArithmeticError::Underflow)?,910		);911912		stakes.sort_by_key(|(block, _)| *block);913914		let mut acc_amount = unstaked_balance;915		let mut will_deleted_stakes_count = 0u8;916917		let changed_stakes = stakes918			.into_iter()919			.map_while(|(block, (balance_per_block, _))| {920				if acc_amount == <BalanceOf<T>>::default() {921					return None;922				}923				if acc_amount < balance_per_block {924					let res = (block, balance_per_block - acc_amount);925					acc_amount = <BalanceOf<T>>::default();926					return Some(res);927				} else {928					acc_amount -= balance_per_block;929					will_deleted_stakes_count += 1;930					return Some((block, <BalanceOf<T>>::default()));931				}932			})933			.collect::<Vec<_>>();934935		pendings936			.try_push((staker_id.clone(), unstaked_balance))937			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;938939		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {940			*stakes = stakes941				.checked_sub(will_deleted_stakes_count)942				.ok_or(ArithmeticError::Underflow)?;943			Ok(())944		})?;945946		changed_stakes947			.into_iter()948			.for_each(|(staked_block, current_stake_state)| {949				if current_stake_state == Default::default() {950					<Staked<T>>::remove((&staker_id, staked_block));951				} else {952					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {953						*old_stake_state = current_stake_state954					});955				}956			});957958		<PendingUnstake<T>>::insert(unpending_block, pendings);959960		Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));961962		Ok(())963	}964965	/// Adds the balance to locked by the pallet.966	///967	/// - `staker`: staker account.968	/// - `amount`: amount of added locked funds.969	// fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {970	// 	Self::get_locked_balance(staker)971	// 		.map_or(<BalanceOf<T>>::default(), |l| l.amount)972	// 		.checked_add(&amount)973	// 		.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))974	// 		.ok_or(ArithmeticError::Overflow.into())975	// }976977	/// Adds the balance to freezed by the pallet.978	///979	/// - `staker`: staker account.980	/// - `amount`: amount of added freezed funds.981	fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {982		Self::get_freezed_balance(staker)983			.unwrap_or_default()984			.checked_add(&amount)985			.map(|freeze| Self::set_freeze_unchecked(staker, freeze))986			.ok_or(ArithmeticError::Overflow.into())987	}988989	/// Sets the new state of a balance locked by the pallet.990	///991	/// - `staker`: staker account.992	/// - `amount`: amount of locked funds.993	// fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {994	// 	if amount.is_zero() {995	// 		<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(996	// 			LOCK_IDENTIFIER,997	// 			&staker,998	// 		);999	// 	} else {1000	// 		<<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(1001	// 			LOCK_IDENTIFIER,1002	// 			staker,1003	// 			amount,1004	// 			WithdrawReasons::all(),1005	// 		)1006	// 	}1007	// }10081009	/// Sets the new state of a balance freezed by the pallet.1010	///1011	/// - `staker`: staker account.1012	/// - `amount`: amount of freezed funds.1013	fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {1014		if amount.is_zero() {1015			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(1016				&T::FreezeIdentifier::get(),1017				&staker,1018			);1019		} else {1020			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(1021				&T::FreezeIdentifier::get(),1022				staker,1023				amount,1024			);1025		}1026	}10271028	/// Returns the balance locked by the pallet for the staker.1029	///1030	/// - `staker`: staker account.1031	pub fn get_locked_balance(1032		staker: impl EncodeLike<T::AccountId>,1033	) -> Option<BalanceLock<BalanceOf<T>>> {1034		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)1035			.into_iter()1036			.find(|l| l.id == LOCK_IDENTIFIER)1037	}10381039	/// Returns the balance freezed by the pallet for the staker.1040	///1041	/// - `staker`: staker account.1042	pub fn get_freezed_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {1043		let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(1044			&T::FreezeIdentifier::get(),1045			staker,1046		);10471048		if res == Zero::zero() {1049			None1050		} else {1051			Some(res)1052		}1053	}10541055	/// Returns the total staked balance for the staker.1056	///1057	/// - `staker`: staker account.1058	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {1059		let staked = Staked::<T>::iter_prefix((staker,))1060			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {1061				acc + amount1062			});1063		if staked != <BalanceOf<T>>::default() {1064			Some(staked)1065		} else {1066			None1067		}1068	}10691070	/// Returns all relay block numbers when stake was made,1071	/// the amount of the stake.1072	///1073	/// - `staker`: staker account.1074	pub fn total_staked_by_id_per_block(1075		staker: impl EncodeLike<T::AccountId>,1076	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {1077		let mut staked = Staked::<T>::iter_prefix((staker,))1078			.map(|(block, (amount, _))| (block, amount))1079			.collect::<Vec<_>>();1080		staked.sort_by_key(|(block, _)| *block);1081		if !staked.is_empty() {1082			Some(staked)1083		} else {1084			None1085		}1086	}10871088	/// Returns the total staked balance for the staker.1089	/// If `staker` is `None`, returns the total amount staked.1090	/// - `staker`: staker account.1091	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1092		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1093			Self::total_staked_by_id(s.as_sub())1094		})1095	}10961097	/// Returns all relay block numbers when stake was made,1098	/// the amount of the stake.1099	///1100	/// - `staker`: staker account.1101	pub fn cross_id_total_staked_per_block(1102		staker: T::CrossAccountId,1103	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1104		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1105	}11061107	fn recalculate_and_insert_stake(1108		staker: &T::AccountId,1109		staked_block: T::BlockNumber,1110		next_recalc_block: T::BlockNumber,1111		base: BalanceOf<T>,1112		iters: u32,1113		income_acc: &mut BalanceOf<T>,1114	) {1115		let income = Self::calculate_income(base, iters);11161117		base.checked_add(&income).map(|res| {1118			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1119			*income_acc += income;1120		});1121	}11221123	fn calculate_income<I>(base: I, iters: u32) -> I1124	where1125		I: EncodeLike<BalanceOf<T>> + Balance,1126	{1127		let config = <PalletConfiguration<T>>::get();1128		let mut income = base;11291130		(0..iters).for_each(|_| income += config.interval_income * income);11311132		income - base1133	}11341135	/// Get relay block number rounded down to multiples of config.recalculation_interval.1136	/// We need it to reward stakers in integer parts of recalculation_interval1137	fn get_current_recalc_block(1138		current_relay_block: T::BlockNumber,1139		config: &PalletConfiguration<T>,1140	) -> T::BlockNumber {1141		(current_relay_block / config.recalculation_interval) * config.recalculation_interval1142	}11431144	fn get_next_calculated_key() -> Option<Vec<u8>> {1145		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))1146	}1147}11481149impl<T: Config> Pallet<T>1150where1151	<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1152{1153	/// Returns the amount reserved by the pending.1154	/// If `staker` is `None`, returns the total pending.1155	///1156	/// -`staker`: staker account.1157	///1158	/// Since user funds are not transferred anywhere by staking, overflow protection is provided1159	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1160	/// the staker must have more funds on his account than the maximum set for `Balance` type.1161	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1162		staker.map_or(1163			PendingUnstake::<T>::iter_values()1164				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1165				.sum(),1166			|s| {1167				PendingUnstake::<T>::iter_values()1168					.flatten()1169					.filter_map(|(id, amount)| {1170						if id == *s.as_sub() {1171							Some(amount)1172						} else {1173							None1174						}1175					})1176					.sum()1177			},1178		)1179	}11801181	/// Returns all parachain block numbers when unreserve is expected,1182	/// the amount of the unreserved funds.1183	///1184	/// - `staker`: staker account.1185	pub fn cross_id_pending_unstake_per_block(1186		staker: T::CrossAccountId,1187	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1188		let mut unsorted_res = vec![];1189		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1190			pendings.into_iter().for_each(|(id, amount)| {1191				if id == *staker.as_sub() {1192					unsorted_res.push((block, amount));1193				};1194			})1195		});11961197		unsorted_res.sort_by_key(|(block, _)| *block);1198		unsorted_res1199	}12001201	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1202		let config = <PalletConfiguration<T>>::get();12031204		// calculate block number where the sum would be free1205		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;12061207		let mut pendings = <PendingUnstake<T>>::get(block);12081209		// checks that we can do unstake in the block1210		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);12111212		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1213			.map(|(_, (amount, _))| amount)1214			.sum();12151216		if total_staked.is_zero() {1217			return Ok(());1218		}12191220		pendings1221			.try_push((staker_id.clone(), total_staked))1222			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;12231224		<PendingUnstake<T>>::insert(block, pendings);12251226		TotalStaked::<T>::set(1227			TotalStaked::<T>::get()1228				.checked_sub(&total_staked)1229				.ok_or(ArithmeticError::Underflow)?,1230		);12311232		StakesPerAccount::<T>::remove(&staker_id);12331234		Self::deposit_event(Event::Unstake(staker_id, total_staked));12351236		Ok(())1237	}1238}
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,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::*;104use 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<Self::AccountId, Balance = <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance>;114115		/// Type for interacting with collections116		type CollectionHandler: CollectionHandler<117			AccountId = Self::AccountId,118			CollectionId = CollectionId,119		>;120121		/// Type for interacting with conrtacts122		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;123124		/// `AccountId` for treasury125		type TreasuryAccountId: Get<Self::AccountId>;126127		/// The app's pallet id, used for deriving its sovereign account address.128		#[pallet::constant]129		type PalletId: Get<PalletId>;130131		/// Freeze identifier used by the pallet132		#[pallet::constant]133		type FreezeIdentifier: Get<<<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id>;134135		/// In relay blocks.136		#[pallet::constant]137		type RecalculationInterval: Get<Self::BlockNumber>;138139		/// In parachain blocks.140		#[pallet::constant]141		type PendingInterval: Get<Self::BlockNumber>;142143		/// Rate of return for interval in blocks defined in `RecalculationInterval`.144		#[pallet::constant]145		type IntervalIncome: Get<Perbill>;146147		/// Decimals for the `Currency`.148		#[pallet::constant]149		type Nominal: Get<BalanceOf<Self>>;150151		/// Weight information for extrinsics in this pallet.152		type WeightInfo: WeightInfo;153154		// The relay block number provider155		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;156157		/// Events compatible with [`frame_system::Config::Event`].158		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;159	}160161	#[pallet::pallet]162	pub struct Pallet<T>(_);163164	#[pallet::event]165	#[pallet::generate_deposit(pub(super) fn deposit_event)]166	pub enum Event<T: Config> {167		/// Staking recalculation was performed168		///169		/// # Arguments170		/// * AccountId: account of the staker.171		/// * Balance : recalculation base172		/// * Balance : total income173		StakingRecalculation(174			/// An recalculated staker175			T::AccountId,176			/// Base on which interest is calculated177			BalanceOf<T>,178			/// Amount of accrued interest179			BalanceOf<T>,180		),181182		/// Staking was performed183		///184		/// # Arguments185		/// * AccountId: account of the staker186		/// * Balance : staking amount187		Stake(T::AccountId, BalanceOf<T>),188189		/// Unstaking was performed190		///191		/// # Arguments192		/// * AccountId: account of the staker193		/// * Balance : unstaking amount194		Unstake(T::AccountId, BalanceOf<T>),195196		/// The admin was set197		///198		/// # Arguments199		/// * AccountId: account address of the admin200		SetAdmin(T::AccountId),201	}202203	#[pallet::error]204	pub enum Error<T> {205		/// Error due to action requiring admin to be set.206		AdminNotSet,207		/// No permission to perform an action.208		NoPermission,209		/// Insufficient funds to perform an action.210		NotSufficientFunds,211		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.212		PendingForBlockOverflow,213		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.214		SponsorNotSet,215		/// Errors caused by insufficient staked balance.216		InsufficientStakedBalance,217		/// Errors caused by incorrect state of a staker in context of the pallet.218		InconsistencyState219	}220221	/// Stores the total staked amount.222	#[pallet::storage]223	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;224225	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.226	#[pallet::storage]227	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;228229	/// Stores the amount of tokens staked by account in the blocknumber.230	///231	/// * **Key1** - Staker account.232	/// * **Key2** - Relay block number when the stake was made.233	/// * **(Balance, BlockNumber)** - Balance of the stake.234	/// The number of the relay block in which we must perform the interest recalculation235	#[pallet::storage]236	pub type Staked<T: Config> = StorageNMap<237		Key = (238			Key<Blake2_128Concat, T::AccountId>,239			Key<Twox64Concat, T::BlockNumber>,240		),241		Value = (BalanceOf<T>, T::BlockNumber),242		QueryKind = ValueQuery,243	>;244245	/// Stores number of stake records for an `Account`.246	///247	/// * **Key** - Staker account.248	/// * **Value** - Amount of stakes.249	#[pallet::storage]250	pub type StakesPerAccount<T: Config> =251		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;252253	/// Pending unstake records for an `Account`.254	///255	/// * **Key** - Staker account.256	/// * **Value** - Amount of stakes.257	#[pallet::storage]258	pub type PendingUnstake<T: Config> = StorageMap<259		_,260		Twox64Concat,261		T::BlockNumber,262		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,263		ValueQuery,264	>;265266	/// Stores a key for record for which the revenue recalculation was performed.267	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.268	#[pallet::storage]269	#[pallet::getter(fn get_next_calculated_record)]270	pub type PreviousCalculatedRecord<T: Config> =271		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;272273	// #[pallet::storage]274	// pub(crate) type UpgradedToFreezes<T: Config> =275	// 	StorageValue<Value = bool, QueryKind = ValueQuery>;276277	#[pallet::hooks]278	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {279		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize280		/// implies the execution of a strictly limited number of relatively lightweight operations.281		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.282		fn on_initialize(current_block_number: T::BlockNumber) -> Weight283		where284			<T as frame_system::Config>::BlockNumber: From<u32>,285		{286			let block_pending = PendingUnstake::<T>::take(current_block_number);287			let counter = block_pending.len() as u32;288289			if !block_pending.is_empty() {290				block_pending.into_iter().for_each(|(staker, amount)| {291					Self::get_freezed_balance(&staker).map(|b| {292						let new_state = b.checked_sub(&amount).unwrap_or_default();293						Self::set_freeze_unchecked(&staker, new_state);294					});295				});296			}297298			<T as Config>::WeightInfo::on_initialize(counter)299		}300301		// fn on_runtime_upgrade() -> Weight {302		// 	use scale_info::prelude::collections::HashSet;303		// 	let mut consumed_weight = Weight::zero();304		// 	let mut add_weight = |reads, writes, weight| {305		// 		consumed_weight += T::DbWeight::get().reads_writes(reads, writes);306		// 		consumed_weight += weight;307		// 	};308309		// 	let mut stakes_unstakes = vec![];310311		// 	if <UpgradedToFreezes<T>>::get() {312		// 		add_weight(1, 0, Weight::zero());313		// 		return consumed_weight;314		// 	} else {315		// 		add_weight(1, 1, Weight::zero());316		// 		<UpgradedToFreezes<T>>::set(true);317		// 	}318		// 	<Staked<T>>::iter_keys().for_each(|(staker_id, _)| {319		// 		add_weight(1, 0, Weight::zero());320		// 		stakes_unstakes.push(staker_id);321		// 	});322323		// 	<PendingUnstake<T>>::iter().for_each(|(_, v)| {324		// 		add_weight(1, 0, Weight::zero());325		// 		v.into_iter().for_each(|(staker, _)| {326		// 			stakes_unstakes.push(staker);327		// 		});328		// 	});329330		// 	// filter duplicated id.331		// 	stakes_unstakes = stakes_unstakes332		// 		.into_iter()333		// 		.map(|key| key)334		// 		.collect::<HashSet<_>>()335		// 		.into_iter()336		// 		.collect();337338		// 	stakes_unstakes339		// 		.map(|a| (a, <Pallet<T>>::get_locked_balance(&a).amount))340		// 		.for_each(|(staker, amount)| {341		// 			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(342		// 				LOCK_IDENTIFIER,343		// 				&staker,344		// 			);345		// 			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(346		// 				&<T as Config>::FreezeIdentifier::get(),347		// 				&staker,348		// 				amount,349		// 			);350		// 			add_weight(1, 2, Weight::zero())351		// 		});352353		// 	consumed_weight354		// }355356		// #[cfg(feature = "try-runtime")]357		// fn pre_upgrade() -> Result<Vec<u8>, &'static str> {358		// 	use sp_std::collections::btree_map::BTreeMap;359		// 	if <UpgradedToFreezes<T>>::get() {360		// 		return Ok(Default::default());361		// 	}362		// 	// Staker -> (total (stakes and unstakes) locked by promotion);363		// 	let mut pre_state: BTreeMap<T::AccountId, BalanceOf<T>> = BTreeMap::new();364365		// 	<Staked<T>>::iter().for_each(|((staker, _), (amount, _))| {366		// 		if let Some(locked_balance) = pre_state.get_mut(&staker) {367		// 			*locked_balance += amount;368		// 		} else {369		// 			pre_state.insert(staker, amount);370		// 		}371		// 	});372373		// 	<PendingUnstake<T>>::iter().for_each(|(_, v)| {374		// 		v.into_iter().for_each(|(staker, amount)| {375		// 			if let Some(locked_balance) = pre_state.get_mut(&staker) {376		// 				*locked_balance += amount;377		// 			} else {378		// 				pre_state.insert(staker, amount);379		// 			}380		// 		})381		// 	});382383		// 	Ok(pre_state.encode())384		// }385386		// #[cfg(feature = "try-runtime")]387		// fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {388		// 	use sp_std::collections::btree_map::BTreeMap;389390		// 	if <UpgradedToFreezes<T>>::get() {391		// 		return Ok(());392		// 	}393394		// 	let mut is_ok = true;395396		// 	let pre_state: BTreeMap<T::AccountId, BalanceOf<T>> =397		// 		Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;398		// 	for (staker, freezed_by_promo) in pre_state.into_iter() {399		// 		let storage_freeze_state = <<T as Config>::Currency as InspectFreeze<400		// 			T::AccountId,401		// 		>>::balance_frozen(402		// 			&<T as Config>::FreezeIdentifier::get(), staker403		// 		);404		// 		if storage_freeze_state != freezed_by_promo {405		// 			is_ok = false;406		// 			log::error!(407		// 						"Incorrect freezed balance for {:?}. New balance: {:?}. Before runtime upgrade: locked by promo - {:?}",408		// 						staker, storage_freeze_state, freezed_by_promo409		// 					);410		// 		}411412		// 		if !<Pallet<T>>::get_locked_balance(&staker).amount.is_zero() {413		// 			is_ok = false;414		// 			log::error!(415		// 				"Incorrect(non-zero) locked by app promo balance for {:?}",416		// 				staker417		// 			);418		// 		}419		// 	}420421		// 	if is_ok {422		// 		Ok(())423		// 	} else {424		// 		Err("Incorrect balance for some of stakers... See logs")425		// 	}426		// }427	}428429	#[pallet::call]430	impl<T: Config> Pallet<T>431	where432		T::BlockNumber: From<u32> + Into<u32>,433		<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,434	{435		/// Sets an address as the the admin.436		///437		/// # Permissions438		///439		/// * Sudo440		///441		/// # Arguments442		///443		/// * `admin`: account of the new admin.444		#[pallet::call_index(0)]445		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]446		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {447			ensure_root(origin)?;448449			<Admin<T>>::set(Some(admin.as_sub().to_owned()));450451			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));452453			Ok(())454		}455456		/// Stakes the amount of native tokens.457		/// Sets `amount` to the locked state.458		/// The maximum number of stakes for a staker is 10.459		///460		/// # Arguments461		///462		/// * `amount`: in native tokens.463		#[pallet::call_index(1)]464		#[pallet::weight(<T as Config>::WeightInfo::stake())]465		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {466			let staker_id = ensure_signed(staker)?;467468			ensure!(469				StakesPerAccount::<T>::get(&staker_id) < 10,470				Error::<T>::NoPermission471			);472473			ensure!(474				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),475				ArithmeticError::Underflow476			);477			let config = <PalletConfiguration<T>>::get();478479			let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);480481			// checks that we can freeze `amount` on the `staker` account.482			ensure!(483				amount484					<= match Self::get_freezed_balance(&staker_id) {485						Some(freezed_by_pallet) => balance486							.checked_sub(&freezed_by_pallet)487							.ok_or(ArithmeticError::Underflow)?,488						None => balance,489					},490				ArithmeticError::Underflow491			);492493			Self::add_freeze_balance(&staker_id, amount)?;494495			let block_number = T::RelayBlockNumberProvider::current_block_number();496497			// Calculation of the number of recalculation periods,498			// after how much the first interest calculation should be performed for the stake499			let recalculate_after_interval: T::BlockNumber =500				if block_number % config.recalculation_interval == 0u32.into() {501					1u32.into()502				} else {503					2u32.into()504				};505506			// Сalculation of the number of the relay block507			// in which it is necessary to accrue remuneration for the stake.508			let recalc_block = (block_number / config.recalculation_interval509				+ recalculate_after_interval)510				* config.recalculation_interval;511512			<Staked<T>>::insert((&staker_id, block_number), {513				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));514				balance_and_recalc_block.0 = balance_and_recalc_block515					.0516					.checked_add(&amount)517					.ok_or(ArithmeticError::Overflow)?;518				balance_and_recalc_block.1 = recalc_block;519				balance_and_recalc_block520			});521522			<TotalStaked<T>>::set(523				<TotalStaked<T>>::get()524					.checked_add(&amount)525					.ok_or(ArithmeticError::Overflow)?,526			);527528			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);529530			Self::deposit_event(Event::Stake(staker_id, amount));531532			Ok(())533		}534535		/// Unstakes all stakes.536		/// After the end of `PendingInterval` this sum becomes completely537		/// free for further use.538		#[pallet::call_index(2)]539		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]540		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {541			let staker_id = ensure_signed(staker)?;542543			Self::unstake_all_internal(staker_id)544		}545546		/// Unstakes the amount of balance for the staker.547		/// After the end of `PendingInterval` this sum becomes completely548		/// free for further use.549		///550		///  # Arguments551		///552		/// * `staker`: staker account.553		/// * `amount`: amount of unstaked funds.554		#[pallet::call_index(8)]555		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]556		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {557			let staker_id = ensure_signed(staker)?;558559			Self::unstake_partial_internal(staker_id, amount)560		}561562		/// Sets the pallet to be the sponsor for the collection.563		///564		/// # Permissions565		///566		/// * Pallet admin567		///568		/// # Arguments569		///570		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`571		#[pallet::call_index(3)]572		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]573		pub fn sponsor_collection(574			admin: OriginFor<T>,575			collection_id: CollectionId,576		) -> DispatchResult {577			let admin_id = ensure_signed(admin)?;578			ensure!(579				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,580				Error::<T>::NoPermission581			);582583			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)584		}585586		/// Removes the pallet as the sponsor for the collection.587		/// Returns [`NoPermission`][`Error::NoPermission`]588		/// if the pallet wasn't the sponsor.589		///590		/// # Permissions591		///592		/// * Pallet admin593		///594		/// # Arguments595		///596		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`597		#[pallet::call_index(4)]598		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]599		pub fn stop_sponsoring_collection(600			admin: OriginFor<T>,601			collection_id: CollectionId,602		) -> DispatchResult {603			let admin_id = ensure_signed(admin)?;604605			ensure!(606				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,607				Error::<T>::NoPermission608			);609610			ensure!(611				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?612					== Self::account_id(),613				<Error<T>>::NoPermission614			);615			T::CollectionHandler::remove_collection_sponsor(collection_id)616		}617618		/// Sets the pallet to be the sponsor for the contract.619		///620		/// # Permissions621		///622		/// * Pallet admin623		///624		/// # Arguments625		///626		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`627		#[pallet::call_index(5)]628		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]629		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {630			let admin_id = ensure_signed(admin)?;631632			ensure!(633				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,634				Error::<T>::NoPermission635			);636637			T::ContractHandler::set_sponsor(638				T::CrossAccountId::from_sub(Self::account_id()),639				contract_id,640			)641		}642643		/// Removes the pallet as the sponsor for the contract.644		/// Returns [`NoPermission`][`Error::NoPermission`]645		/// if the pallet wasn't the sponsor.646		///647		/// # Permissions648		///649		/// * Pallet admin650		///651		/// # Arguments652		///653		/// * `contract_id`: the contract address that is sponsored by `pallet_id`654		#[pallet::call_index(6)]655		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]656		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {657			let admin_id = ensure_signed(admin)?;658659			ensure!(660				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,661				Error::<T>::NoPermission662			);663664			ensure!(665				T::ContractHandler::sponsor(contract_id)?666					.ok_or(<Error<T>>::SponsorNotSet)?667					.as_sub() == &Self::account_id(),668				<Error<T>>::NoPermission669			);670			T::ContractHandler::remove_contract_sponsor(contract_id)671		}672673		/// Recalculates interest for the specified number of stakers.674		/// If all stakers are not recalculated, the next call of the extrinsic675		/// will continue the recalculation, from those stakers for whom this676		/// was not perform in last call.677		///678		/// # Permissions679		///680		/// * Pallet admin681		///682		/// # Arguments683		///684		/// * `stakers_number`: the number of stakers for which recalculation will be performed685		#[pallet::call_index(7)]686		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]687		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {688			let admin_id = ensure_signed(admin)?;689690			ensure!(691				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,692				Error::<T>::NoPermission693			);694			let config = <PalletConfiguration<T>>::get();695696			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);697698			ensure!(699				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,700				Error::<T>::NoPermission701			);702703			// calculate the number of the current recalculation block,704			// this is necessary in order to understand which stakers we should calculate interest705			let current_recalc_block = Self::get_current_recalc_block(706				T::RelayBlockNumberProvider::current_block_number(),707				&config,708			);709710			// calculate the number of the next recalculation block,711			// this value is set for the stakers to whom the recalculation will be performed712			let next_recalc_block = current_recalc_block + config.recalculation_interval;713714			let mut storage_iterator = Self::get_next_calculated_key()715				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));716717			PreviousCalculatedRecord::<T>::set(None);718719			{720				// Address handled in the last payout loop iteration (below)721				let last_id = RefCell::new(None);722				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration723				let mut last_staked_calculated_block = Default::default();724				// Reward balance for the address in the iteration725				let income_acc = RefCell::new(BalanceOf::<T>::default());726				// Staked balance for the address in the iteration (before stake is recalculated)727				let amount_acc = RefCell::new(BalanceOf::<T>::default());728729				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout730				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout731				// loop switches to handling the next staker address:732				//   1. Transfer full reward amount to the payee733				//   2. Lock the reward in staking lock734				//   3. Update TotalStaked amount735				//   4. Issue StakingRecalculation event736				let flush_stake = || -> DispatchResult {737					if let Some(last_id) = &*last_id.borrow() {738						if !income_acc.borrow().is_zero() {739							<<T as Config>::Currency as Mutate<T::AccountId>>::transfer(740								&T::TreasuryAccountId::get(),741								last_id,742								*income_acc.borrow(),743								frame_support::traits::tokens::Preservation::Protect,744							)?;745746							Self::add_freeze_balance(last_id, *income_acc.borrow())?;747							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {748								*staked = staked749									.checked_add(&*income_acc.borrow())750									.ok_or(ArithmeticError::Overflow)?;751								Ok(())752							})?;753754							Self::deposit_event(Event::StakingRecalculation(755								last_id.clone(),756								*amount_acc.borrow(),757								*income_acc.borrow(),758							));759						}760761						*income_acc.borrow_mut() = BalanceOf::<T>::default();762						*amount_acc.borrow_mut() = BalanceOf::<T>::default();763					}764					Ok(())765				};766767				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation768				// iterations in one extrinsic call769				//770				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)771				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out772				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)773				while let Some((774					(current_id, staked_block),775					(amount, next_recalc_block_for_stake),776				)) = storage_iterator.next()777				{778					// last_id is not equal current_id when we switch to handling a new staker address779					// or just start handling the very first address. In the latter case last_id will be None and780					// flush_stake will do nothing781					if last_id.borrow().as_ref() != Some(&current_id) {782						if stakers_number > 0 {783							flush_stake()?;784							*last_id.borrow_mut() = Some(current_id.clone());785							stakers_number -= 1;786						}787						// Break out if we reached the address limit788						else {789							if let Some(staker) = &*last_id.borrow() {790								// Save the last calculated record to pick up in the next extrinsic call791								PreviousCalculatedRecord::<T>::set(Some((792									staker.clone(),793									last_staked_calculated_block,794								)));795							}796							break;797						};798					};799800					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount801					if current_recalc_block >= next_recalc_block_for_stake {802						*amount_acc.borrow_mut() += amount;803						Self::recalculate_and_insert_stake(804							&current_id,805							staked_block,806							next_recalc_block,807							amount,808							((current_recalc_block - next_recalc_block_for_stake)809								/ config.recalculation_interval)810								.into() + 1,811							&mut *income_acc.borrow_mut(),812						);813					}814					last_staked_calculated_block = staked_block;815				}816				flush_stake()?;817			}818819			Ok(())820		}821822		///  Migrates lock state into freeze one823		///824		///  # Arguments825		///826		/// * `origin`: Must be `Signed`.827		/// * `stakers`: Accounts to be upgraded.828		#[pallet::call_index(9)]829		#[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]830		pub fn upgrade_accounts(831			origin: OriginFor<T>,832			stakers: Vec<T::AccountId>,833		) -> DispatchResult {834			ensure_signed(origin)?;835836			stakers.into_iter().try_for_each(|s| -> Result<_, DispatchError> {837				if let Some(lock) = Self::get_locked_balance(&s) {838					839					if let Some(_) = Self::get_freezed_balance(&s) {840						return Err(Error::<T>::InconsistencyState.into())841					}842					843					<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(844						LOCK_IDENTIFIER,845						&s,846					);847848					Self::set_freeze_unchecked(&s, lock.amount);849					Ok(())850				} else {851					Ok(())852				}853			})?;854			855			Ok(())856		}857	}858}859860impl<T: Config> Pallet<T> {861	/// The account address of the app promotion pot.862	///863	/// This actually does computation. If you need to keep using it, then make sure you cache the864	/// value and only call this once.865	pub fn account_id() -> T::AccountId {866		T::PalletId::get().into_account_truncating()867	}868869	/// Unstakes the balance for the staker.870	///871	/// - `staker`: staker account.872	/// - `amount`: amount of unstaked funds.873	fn unstake_partial_internal(874		staker_id: T::AccountId,875		unstaked_balance: BalanceOf<T>,876	) -> DispatchResult {877		if unstaked_balance == Default::default() {878			return Ok(());879		}880881		let config = <PalletConfiguration<T>>::get();882883		// calculate block number where the sum would be free884		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;885886		let mut pendings = <PendingUnstake<T>>::get(unpending_block);887888		// checks that we can do unstake in the block889		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);890891		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();892893		let total_staked = stakes894			.iter()895			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {896				acc + *balance897			});898899		ensure!(900			unstaked_balance <= total_staked,901			<Error<T>>::InsufficientStakedBalance902		);903904		<TotalStaked<T>>::set(905			<TotalStaked<T>>::get()906				.checked_sub(&unstaked_balance)907				.ok_or(ArithmeticError::Underflow)?,908		);909910		stakes.sort_by_key(|(block, _)| *block);911912		let mut acc_amount = unstaked_balance;913		let mut will_deleted_stakes_count = 0u8;914915		let changed_stakes = stakes916			.into_iter()917			.map_while(|(block, (balance_per_block, _))| {918				if acc_amount == <BalanceOf<T>>::default() {919					return None;920				}921				if acc_amount < balance_per_block {922					let res = (block, balance_per_block - acc_amount);923					acc_amount = <BalanceOf<T>>::default();924					return Some(res);925				} else {926					acc_amount -= balance_per_block;927					will_deleted_stakes_count += 1;928					return Some((block, <BalanceOf<T>>::default()));929				}930			})931			.collect::<Vec<_>>();932933		pendings934			.try_push((staker_id.clone(), unstaked_balance))935			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;936937		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {938			*stakes = stakes939				.checked_sub(will_deleted_stakes_count)940				.ok_or(ArithmeticError::Underflow)?;941			Ok(())942		})?;943944		changed_stakes945			.into_iter()946			.for_each(|(staked_block, current_stake_state)| {947				if current_stake_state == Default::default() {948					<Staked<T>>::remove((&staker_id, staked_block));949				} else {950					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {951						*old_stake_state = current_stake_state952					});953				}954			});955956		<PendingUnstake<T>>::insert(unpending_block, pendings);957958		Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));959960		Ok(())961	}962963	/// Adds the balance to locked by the pallet.964	///965	/// - `staker`: staker account.966	/// - `amount`: amount of added locked funds.967	// fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {968	// 	Self::get_locked_balance(staker)969	// 		.map_or(<BalanceOf<T>>::default(), |l| l.amount)970	// 		.checked_add(&amount)971	// 		.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))972	// 		.ok_or(ArithmeticError::Overflow.into())973	// }974975	/// Adds the balance to freezed by the pallet.976	///977	/// - `staker`: staker account.978	/// - `amount`: amount of added freezed funds.979	fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {980		Self::get_freezed_balance(staker)981			.unwrap_or_default()982			.checked_add(&amount)983			.map(|freeze| Self::set_freeze_unchecked(staker, freeze))984			.ok_or(ArithmeticError::Overflow.into())985	}986987	/// Sets the new state of a balance locked by the pallet.988	///989	/// - `staker`: staker account.990	/// - `amount`: amount of locked funds.991	// fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {992	// 	if amount.is_zero() {993	// 		<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(994	// 			LOCK_IDENTIFIER,995	// 			&staker,996	// 		);997	// 	} else {998	// 		<<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(999	// 			LOCK_IDENTIFIER,1000	// 			staker,1001	// 			amount,1002	// 			WithdrawReasons::all(),1003	// 		)1004	// 	}1005	// }10061007	/// Sets the new state of a balance freezed by the pallet.1008	///1009	/// - `staker`: staker account.1010	/// - `amount`: amount of freezed funds.1011	fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {1012		if amount.is_zero() {1013			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(1014				&T::FreezeIdentifier::get(),1015				&staker,1016			);1017		} else {1018			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(1019				&T::FreezeIdentifier::get(),1020				staker,1021				amount,1022			);1023		}1024	}10251026	/// Returns the balance locked by the pallet for the staker.1027	///1028	/// - `staker`: staker account.1029	pub fn get_locked_balance(1030		staker: impl EncodeLike<T::AccountId>,1031	) -> Option<BalanceLock<BalanceOf<T>>> {1032		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)1033			.into_iter()1034			.find(|l| l.id == LOCK_IDENTIFIER)1035	}10361037	/// Returns the balance freezed by the pallet for the staker.1038	///1039	/// - `staker`: staker account.1040	pub fn get_freezed_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {1041		let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(1042			&T::FreezeIdentifier::get(),1043			staker,1044		);10451046		if res == Zero::zero() {1047			None1048		} else {1049			Some(res)1050		}1051	}10521053	/// Returns the total staked balance for the staker.1054	///1055	/// - `staker`: staker account.1056	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {1057		let staked = Staked::<T>::iter_prefix((staker,))1058			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {1059				acc + amount1060			});1061		if staked != <BalanceOf<T>>::default() {1062			Some(staked)1063		} else {1064			None1065		}1066	}10671068	/// Returns all relay block numbers when stake was made,1069	/// the amount of the stake.1070	///1071	/// - `staker`: staker account.1072	pub fn total_staked_by_id_per_block(1073		staker: impl EncodeLike<T::AccountId>,1074	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {1075		let mut staked = Staked::<T>::iter_prefix((staker,))1076			.map(|(block, (amount, _))| (block, amount))1077			.collect::<Vec<_>>();1078		staked.sort_by_key(|(block, _)| *block);1079		if !staked.is_empty() {1080			Some(staked)1081		} else {1082			None1083		}1084	}10851086	/// Returns the total staked balance for the staker.1087	/// If `staker` is `None`, returns the total amount staked.1088	/// - `staker`: staker account.1089	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1090		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1091			Self::total_staked_by_id(s.as_sub())1092		})1093	}10941095	/// Returns all relay block numbers when stake was made,1096	/// the amount of the stake.1097	///1098	/// - `staker`: staker account.1099	pub fn cross_id_total_staked_per_block(1100		staker: T::CrossAccountId,1101	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1102		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1103	}11041105	fn recalculate_and_insert_stake(1106		staker: &T::AccountId,1107		staked_block: T::BlockNumber,1108		next_recalc_block: T::BlockNumber,1109		base: BalanceOf<T>,1110		iters: u32,1111		income_acc: &mut BalanceOf<T>,1112	) {1113		let income = Self::calculate_income(base, iters);11141115		base.checked_add(&income).map(|res| {1116			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1117			*income_acc += income;1118		});1119	}11201121	fn calculate_income<I>(base: I, iters: u32) -> I1122	where1123		I: EncodeLike<BalanceOf<T>> + Balance,1124	{1125		let config = <PalletConfiguration<T>>::get();1126		let mut income = base;11271128		(0..iters).for_each(|_| income += config.interval_income * income);11291130		income - base1131	}11321133	/// Get relay block number rounded down to multiples of config.recalculation_interval.1134	/// We need it to reward stakers in integer parts of recalculation_interval1135	fn get_current_recalc_block(1136		current_relay_block: T::BlockNumber,1137		config: &PalletConfiguration<T>,1138	) -> T::BlockNumber {1139		(current_relay_block / config.recalculation_interval) * config.recalculation_interval1140	}11411142	fn get_next_calculated_key() -> Option<Vec<u8>> {1143		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))1144	}1145}11461147impl<T: Config> Pallet<T>1148where1149	<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1150{1151	/// Returns the amount reserved by the pending.1152	/// If `staker` is `None`, returns the total pending.1153	///1154	/// -`staker`: staker account.1155	///1156	/// Since user funds are not transferred anywhere by staking, overflow protection is provided1157	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1158	/// the staker must have more funds on his account than the maximum set for `Balance` type.1159	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1160		staker.map_or(1161			PendingUnstake::<T>::iter_values()1162				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1163				.sum(),1164			|s| {1165				PendingUnstake::<T>::iter_values()1166					.flatten()1167					.filter_map(|(id, amount)| {1168						if id == *s.as_sub() {1169							Some(amount)1170						} else {1171							None1172						}1173					})1174					.sum()1175			},1176		)1177	}11781179	/// Returns all parachain block numbers when unreserve is expected,1180	/// the amount of the unreserved funds.1181	///1182	/// - `staker`: staker account.1183	pub fn cross_id_pending_unstake_per_block(1184		staker: T::CrossAccountId,1185	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1186		let mut unsorted_res = vec![];1187		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1188			pendings.into_iter().for_each(|(id, amount)| {1189				if id == *staker.as_sub() {1190					unsorted_res.push((block, amount));1191				};1192			})1193		});11941195		unsorted_res.sort_by_key(|(block, _)| *block);1196		unsorted_res1197	}11981199	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1200		let config = <PalletConfiguration<T>>::get();12011202		// calculate block number where the sum would be free1203		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;12041205		let mut pendings = <PendingUnstake<T>>::get(block);12061207		// checks that we can do unstake in the block1208		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);12091210		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1211			.map(|(_, (amount, _))| amount)1212			.sum();12131214		if total_staked.is_zero() {1215			return Ok(());1216		}12171218		pendings1219			.try_push((staker_id.clone(), total_staked))1220			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;12211222		<PendingUnstake<T>>::insert(block, pendings);12231224		TotalStaked::<T>::set(1225			TotalStaked::<T>::get()1226				.checked_sub(&total_staked)1227				.ok_or(ArithmeticError::Underflow)?,1228		);12291230		StakesPerAccount::<T>::remove(&staker_id);12311232		Self::deposit_event(Event::Unstake(staker_id, total_staked));12331234		Ok(())1235	}1236}