git.delta.rocks / unique-network / refs/commits / 65414d643dd4

difftreelog

feat(app-promo) types for `Currency` trait support has been removed & bench fix

PraetorP2023-06-23parent: #c575769.patch.diff
in: master

8 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6129,13 +6129,12 @@
 
 [[package]]
 name = "pallet-app-promotion"
-version = "0.2.0"
+version = "0.2.1"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
  "frame-system",
  "log",
- "pallet-balances",
  "pallet-common",
  "pallet-configuration",
  "pallet-evm",
modifiedpallets/app-promotion/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/app-promotion/CHANGELOG.md
+++ b/pallets/app-promotion/CHANGELOG.md
@@ -3,6 +3,17 @@
 All notable changes to this project will be documented in this file.
 
 <!-- bureaucrate goes here -->
+
+## [0.2.1] - 2023-06-23
+
+### Changed
+
+- Removed types associated with support for `Currency` trait.
+
+### Fixed
+
+- Benchmarks.
+  
 ## [0.2.0] - 2023-05-19
 
 ### Changed
modifiedpallets/app-promotion/Cargo.tomldiffbeforeafterboth
--- a/pallets/app-promotion/Cargo.toml
+++ b/pallets/app-promotion/Cargo.toml
@@ -9,7 +9,7 @@
 license = 'GPLv3'
 name = 'pallet-app-promotion'
 repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.2.0'
+version = '0.2.1'
 
 [package.metadata.docs.rs]
 targets = ['x86_64-unknown-linux-gnu']
@@ -27,7 +27,6 @@
 	'frame-benchmarking/std',
 	'frame-support/std',
 	'frame-system/std',
-	'pallet-balances/std',
 	'pallet-evm/std',
 	'sp-core/std',
 	'sp-runtime/std',
@@ -48,7 +47,7 @@
 frame-benchmarking = { workspace = true, optional = true }
 frame-support = { workspace = true }
 frame-system = { workspace = true }
-pallet-balances = { features = ["insecure_zero_ed"], workspace = true }
+
 pallet-evm = { workspace = true }
 sp-core = { workspace = true }
 sp-runtime = { workspace = true }
modifiedpallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/benchmarking.rs
+++ b/pallets/app-promotion/src/benchmarking.rs
@@ -18,7 +18,7 @@
 
 use super::*;
 use crate::Pallet as PromototionPallet;
-
+use frame_support::traits::fungible::Unbalanced;
 use sp_runtime::traits::Bounded;
 
 use frame_benchmarking::{benchmarks, account};
@@ -63,9 +63,9 @@
 
 		(0..b).try_for_each(|index| {
 			let staker = account::<T::AccountId>("staker", index, SEED);
-			<T as Config>::Currency::set_balance(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+			<T as Config>::Currency::write_balance(&staker,  Into::<BalanceOf<T>>::into(10_000u128) * T::Nominal::get())?;
 			PromototionPallet::<T>::stake(RawOrigin::Signed(staker.clone()).into(), Into::<BalanceOf<T>>::into(100u128) * T::Nominal::get())?;
-			PromototionPallet::<T>::unstake_all(RawOrigin::Signed(staker.clone()).into())?;
+			PromototionPallet::<T>::unstake_all(RawOrigin::Signed(staker).into())?;
 			Result::<(), sp_runtime::DispatchError>::Ok(())
 		})?;
 		let block_number = <frame_system::Pallet<T>>::current_block_number() + T::PendingInterval::get();
@@ -82,13 +82,14 @@
 		let pallet_admin = account::<T::AccountId>("admin", 1, SEED);
 		let share = Perbill::from_rational(1u32, 20);
 		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;
-		<T as Config>::Currency::set_balance(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
-		<T as Config>::Currency::set_balance(&<T as pallet::Config>::TreasuryAccountId::get(),  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		<T as Config>::Currency::write_balance(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value())?;
+		<T as Config>::Currency::write_balance(&<T as pallet::Config>::TreasuryAccountId::get(),  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value())?;
 
 		let stakers: Vec<T::AccountId> = (0..b).map(|index| account("staker", index, SEED)).collect();
-		stakers.iter().for_each(|staker| {
-			<T as Config>::Currency::set_balance(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
-		});
+		stakers.iter().try_for_each(|staker| {
+			<T as Config>::Currency::write_balance(staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value())?;
+			Result::<(), sp_runtime::DispatchError>::Ok(())
+		})?;
 		(1..11).try_for_each(|i| {
 			<frame_system::Pallet<T>>::set_block_number(i.into());
 			T::RelayBlockNumberProvider::set_block_number((2*i).into());
@@ -102,7 +103,7 @@
 			Result::<(), sp_runtime::DispatchError>::Ok(())
 		})?;
 
-		let stakes = Staked::<T>::iter_prefix((&stakers[0],)).into_iter().collect::<Vec<_>>();
+		let stakes = Staked::<T>::iter_prefix((&stakers[0],)).collect::<Vec<_>>();
 		assert_eq!(stakes.len(), 10);
 
 		<frame_system::Pallet<T>>::set_block_number(15_000.into());
@@ -112,13 +113,13 @@
 	stake {
 		let caller = account::<T::AccountId>("caller", 0, SEED);
 		let share = Perbill::from_rational(1u32, 10);
-		let _ = <T as Config>::Currency::set_balance(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		let _ = <T as Config>::Currency::write_balance(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 	} : _(RawOrigin::Signed(caller.clone()), share * <T as Config>::Currency::total_balance(&caller))
 
 	unstake_all {
 		let caller = account::<T::AccountId>("caller", 0, SEED);
 		let share = Perbill::from_rational(1u32, 20);
-		let _ = <T as Config>::Currency::set_balance(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		let _ = <T as Config>::Currency::write_balance(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 		(1..11).map(|i| {
 			// used to change block number
 			<frame_system::Pallet<T>>::set_block_number(i.into());
@@ -133,7 +134,7 @@
 	unstake_partial {
 		let caller = account::<T::AccountId>("caller", 0, SEED);
 		let share = Perbill::from_rational(1u32, 20);
-		let _ = <T as Config>::Currency::set_balance(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		let _ = <T as Config>::Currency::write_balance(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 		(1..11).map(|i| {
 			// used to change block number
 			<frame_system::Pallet<T>>::set_block_number(i.into());
@@ -148,19 +149,19 @@
 	sponsor_collection {
 		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
 		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;
-		let _ = <T as Config>::Currency::set_balance(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		let _ = <T as Config>::Currency::write_balance(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 		let caller: T::AccountId = account("caller", 0, SEED);
-		let _ = <T as Config>::Currency::set_balance(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
-		let collection = create_nft_collection::<T>(caller.clone())?;
+		let _ = <T as Config>::Currency::write_balance(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		let collection = create_nft_collection::<T>(caller)?;
 	} : _(RawOrigin::Signed(pallet_admin.clone()), collection)
 
 	stop_sponsoring_collection {
 		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
 		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;
-		let _ = <T as Config>::Currency::set_balance(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		let _ = <T as Config>::Currency::write_balance(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 		let caller: T::AccountId = account("caller", 0, SEED);
-		let _ = <T as Config>::Currency::set_balance(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
-		let collection = create_nft_collection::<T>(caller.clone())?;
+		let _ = <T as Config>::Currency::write_balance(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		let collection = create_nft_collection::<T>(caller)?;
 		PromototionPallet::<T>::sponsor_collection(RawOrigin::Signed(pallet_admin.clone()).into(), collection)?;
 	} : _(RawOrigin::Signed(pallet_admin.clone()), collection)
 
@@ -168,9 +169,9 @@
 		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
 		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;
 
-		let _ = <T as Config>::Currency::set_balance(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		let _ = <T as Config>::Currency::write_balance(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 		let address = H160::from_low_u64_be(SEED as u64);
-		let data: Vec<u8> = (0..20 as u8).collect();
+		let data: Vec<u8> = (0..20).collect();
 		<EvmMigrationPallet<T>>::begin(RawOrigin::Root.into(), address)?;
 		<EvmMigrationPallet<T>>::finish(RawOrigin::Root.into(), address, data)?;
 	} : _(RawOrigin::Signed(pallet_admin.clone()), address)
@@ -179,9 +180,9 @@
 		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
 		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;
 
-		let _ = <T as Config>::Currency::set_balance(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		let _ = <T as Config>::Currency::write_balance(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 		let address = H160::from_low_u64_be(SEED as u64);
-		let data: Vec<u8> = (0..20 as u8).collect();
+		let data: Vec<u8> = (0..20).collect();
 		<EvmMigrationPallet<T>>::begin(RawOrigin::Root.into(), address)?;
 		<EvmMigrationPallet<T>>::finish(RawOrigin::Root.into(), address, data)?;
 		PromototionPallet::<T>::sponsor_contract(RawOrigin::Signed(pallet_admin.clone()).into(), address)?;
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
before · pallets/app-promotion/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # App Promotion pallet18//!19//! The pallet implements the mechanics of staking and sponsoring collections/contracts.20//!21//! - [`Config`]22//! - [`Pallet`]23//! - [`Error`]24//! - [`Event`]25//!26//! ## Overview27//! The App Promotion pallet allows fund holders to stake at a certain daily rate of return.28//! The mechanics implemented in the pallet allow it to act as a sponsor for collections / contracts,29//! the list of which is set by the pallet administrator.30//!31//!32//! ## Interface33//! The pallet provides interfaces for funds, collection/contract operations (see [types] module).3435//!36//! ### Dispatchable Functions37//! - [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.38//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.39//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.40//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.41//! - [`stop_sponsoring_collection`][`Pallet::stop_sponsoring_collection`] - removes the pallet as the sponsor for the collection.42//! - [`sponsor_contract`][`Pallet::sponsor_contract`] - sets the pallet to be the sponsor for the contract.43//! - [`stop_sponsoring_contract`][`Pallet::stop_sponsoring_contract`] - removes the pallet as the sponsor for the contract.44//! - [`payout_stakers`][`Pallet::payout_stakers`] - recalculates interest for the specified number of stakers.45//!4647// #![recursion_limit = "1024"]48#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57	vec::{Vec},58	vec,59	iter::Sum,60	borrow::ToOwned,61	cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71	dispatch::{DispatchResult},72	traits::{73		Get, LockableCurrency,74		tokens::Balance,75		fungible::{Inspect, InspectFreeze, Mutate, MutateFreeze},76	},77	ensure, BoundedVec,78};7980use weights::WeightInfo;8182pub use pallet::*;83use pallet_evm::account::CrossAccountId;84use sp_runtime::{85	Perbill,86	traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},87	ArithmeticError, DispatchError,88};8990pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";9192const PENDING_LIMIT_PER_BLOCK: u32 = 3;9394type BalanceOf<T> =95	<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;9697#[frame_support::pallet]98pub mod pallet {99	use super::*;100	use frame_support::{101		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId, weights::Weight,102	};103	use frame_system::pallet_prelude::*;104	use sp_runtime::DispatchError;105106	#[pallet::config]107	pub trait Config:108		frame_system::Config + pallet_evm::Config + pallet_configuration::Config109	{110		/// Type to interact with the native token111		type Currency: MutateFreeze<Self::AccountId>112			+ Mutate<Self::AccountId>113			+ ExtendedLockableCurrency<114				Self::AccountId,115				Balance = <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,116			>;117118		/// Type for interacting with collections119		type CollectionHandler: CollectionHandler<120			AccountId = Self::AccountId,121			CollectionId = CollectionId,122		>;123124		/// Type for interacting with conrtacts125		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;126127		/// `AccountId` for treasury128		type TreasuryAccountId: Get<Self::AccountId>;129130		/// The app's pallet id, used for deriving its sovereign account address.131		#[pallet::constant]132		type PalletId: Get<PalletId>;133134		/// Freeze identifier used by the pallet135		#[pallet::constant]136		type FreezeIdentifier: Get<137			<<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id,138		>;139140		/// In relay blocks.141		#[pallet::constant]142		type RecalculationInterval: Get<Self::BlockNumber>;143144		/// In parachain blocks.145		#[pallet::constant]146		type PendingInterval: Get<Self::BlockNumber>;147148		/// Rate of return for interval in blocks defined in `RecalculationInterval`.149		#[pallet::constant]150		type IntervalIncome: Get<Perbill>;151152		/// Decimals for the `Currency`.153		#[pallet::constant]154		type Nominal: Get<BalanceOf<Self>>;155156		/// Maintenance mode status.157		type IsMaintenanceModeEnabled: Get<bool>;158159		/// Weight information for extrinsics in this pallet.160		type WeightInfo: WeightInfo;161162		// The relay block number provider163		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;164165		/// Events compatible with [`frame_system::Config::Event`].166		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;167	}168169	#[pallet::pallet]170	pub struct Pallet<T>(_);171172	#[pallet::event]173	#[pallet::generate_deposit(pub(super) fn deposit_event)]174	pub enum Event<T: Config> {175		/// Staking recalculation was performed176		///177		/// # Arguments178		/// * AccountId: account of the staker.179		/// * Balance : recalculation base180		/// * Balance : total income181		StakingRecalculation(182			/// An recalculated staker183			T::AccountId,184			/// Base on which interest is calculated185			BalanceOf<T>,186			/// Amount of accrued interest187			BalanceOf<T>,188		),189190		/// Staking was performed191		///192		/// # Arguments193		/// * AccountId: account of the staker194		/// * Balance : staking amount195		Stake(T::AccountId, BalanceOf<T>),196197		/// Unstaking was performed198		///199		/// # Arguments200		/// * AccountId: account of the staker201		/// * Balance : unstaking amount202		Unstake(T::AccountId, BalanceOf<T>),203204		/// The admin was set205		///206		/// # Arguments207		/// * AccountId: account address of the admin208		SetAdmin(T::AccountId),209	}210211	#[pallet::error]212	pub enum Error<T> {213		/// Error due to action requiring admin to be set.214		AdminNotSet,215		/// No permission to perform an action.216		NoPermission,217		/// Insufficient funds to perform an action.218		NotSufficientFunds,219		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.220		PendingForBlockOverflow,221		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.222		SponsorNotSet,223		/// Errors caused by insufficient staked balance.224		InsufficientStakedBalance,225		/// Errors caused by incorrect state of a staker in context of the pallet.226		InconsistencyState,227	}228229	/// Stores the total staked amount.230	#[pallet::storage]231	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;232233	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.234	#[pallet::storage]235	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;236237	/// Stores the amount of tokens staked by account in the blocknumber.238	///239	/// * **Key1** - Staker account.240	/// * **Key2** - Relay block number when the stake was made.241	/// * **(Balance, BlockNumber)** - Balance of the stake.242	/// The number of the relay block in which we must perform the interest recalculation243	#[pallet::storage]244	pub type Staked<T: Config> = StorageNMap<245		Key = (246			Key<Blake2_128Concat, T::AccountId>,247			Key<Twox64Concat, T::BlockNumber>,248		),249		Value = (BalanceOf<T>, T::BlockNumber),250		QueryKind = ValueQuery,251	>;252253	/// Stores number of stake records for an `Account`.254	///255	/// * **Key** - Staker account.256	/// * **Value** - Amount of stakes.257	#[pallet::storage]258	pub type StakesPerAccount<T: Config> =259		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;260261	/// Pending unstake records for an `Account`.262	///263	/// * **Key** - Staker account.264	/// * **Value** - Amount of stakes.265	#[pallet::storage]266	pub type PendingUnstake<T: Config> = StorageMap<267		_,268		Twox64Concat,269		T::BlockNumber,270		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,271		ValueQuery,272	>;273274	/// Stores a key for record for which the revenue recalculation was performed.275	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.276	#[pallet::storage]277	#[pallet::getter(fn get_next_calculated_record)]278	pub type PreviousCalculatedRecord<T: Config> =279		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;280281	#[pallet::hooks]282	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {283		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize284		/// implies the execution of a strictly limited number of relatively lightweight operations.285		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.286		fn on_initialize(current_block_number: T::BlockNumber) -> Weight287		where288			<T as frame_system::Config>::BlockNumber: From<u32>,289		{290			if T::IsMaintenanceModeEnabled::get() {291				return T::DbWeight::get().reads_writes(1, 0);292			}293294			let block_pending = PendingUnstake::<T>::take(current_block_number);295			let counter = block_pending.len() as u32;296297			if !block_pending.is_empty() {298				block_pending.into_iter().for_each(|(staker, amount)| {299					if let Some(b) = Self::get_frozen_balance(&staker) {300						let new_state = b.checked_sub(&amount).unwrap_or_default();301302						// In this case, setting a new state for the frozen funds cannot fail303						// because the state change goes in the direction of decreasing the frozen funds304						// and the validity of this transition is ensured by the fact305						// that we cannot (in the current implementation) unfreeze more funds306						// than were originally frozen by the pallet. Either way, `on_initialize()` cannot fail.307						Self::set_freeze_unchecked(&staker, new_state);308					};309				});310			}311312			<T as Config>::WeightInfo::on_initialize(counter)313		}314	}315316	#[pallet::call]317	impl<T: Config> Pallet<T>318	where319		T::BlockNumber: From<u32> + Into<u32>,320		<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,321	{322		/// Sets an address as the the admin.323		///324		/// # Permissions325		///326		/// * Sudo327		///328		/// # Arguments329		///330		/// * `admin`: account of the new admin.331		#[pallet::call_index(0)]332		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]333		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {334			ensure_root(origin)?;335336			<Admin<T>>::set(Some(admin.as_sub().to_owned()));337338			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));339340			Ok(())341		}342343		/// Stakes the amount of native tokens.344		/// Sets `amount` to the locked state.345		/// The maximum number of stakes for a staker is 10.346		///347		/// # Arguments348		///349		/// * `amount`: in native tokens.350		#[pallet::call_index(1)]351		#[pallet::weight(<T as Config>::WeightInfo::stake())]352		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {353			let staker_id = ensure_signed(staker)?;354355			ensure!(356				StakesPerAccount::<T>::get(&staker_id) < 10,357				Error::<T>::NoPermission358			);359360			ensure!(361				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),362				ArithmeticError::Underflow363			);364			let config = <PalletConfiguration<T>>::get();365366			let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);367368			// checks that we can freeze `amount` on the `staker` account.369			ensure!(370				amount371					<= match Self::get_frozen_balance(&staker_id) {372						Some(frozen_by_pallet) => balance373							.checked_sub(&frozen_by_pallet)374							.ok_or(ArithmeticError::Underflow)?,375						None => balance,376					},377				ArithmeticError::Underflow378			);379380			Self::add_freeze_balance(&staker_id, amount)?;381382			let block_number = T::RelayBlockNumberProvider::current_block_number();383384			// Calculation of the number of recalculation periods,385			// after how much the first interest calculation should be performed for the stake386			let recalculate_after_interval: T::BlockNumber =387				if block_number % config.recalculation_interval == 0u32.into() {388					1u32.into()389				} else {390					2u32.into()391				};392393			// Сalculation of the number of the relay block394			// in which it is necessary to accrue remuneration for the stake.395			let recalc_block = (block_number / config.recalculation_interval396				+ recalculate_after_interval)397				* config.recalculation_interval;398399			<Staked<T>>::insert((&staker_id, block_number), {400				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));401				balance_and_recalc_block.0 = balance_and_recalc_block402					.0403					.checked_add(&amount)404					.ok_or(ArithmeticError::Overflow)?;405				balance_and_recalc_block.1 = recalc_block;406				balance_and_recalc_block407			});408409			<TotalStaked<T>>::set(410				<TotalStaked<T>>::get()411					.checked_add(&amount)412					.ok_or(ArithmeticError::Overflow)?,413			);414415			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);416417			Self::deposit_event(Event::Stake(staker_id, amount));418419			Ok(())420		}421422		/// Unstakes all stakes.423		/// After the end of `PendingInterval` this sum becomes completely424		/// free for further use.425		#[pallet::call_index(2)]426		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]427		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {428			let staker_id = ensure_signed(staker)?;429430			Self::unstake_all_internal(staker_id)431		}432433		/// Unstakes the amount of balance for the staker.434		/// After the end of `PendingInterval` this sum becomes completely435		/// free for further use.436		///437		///  # Arguments438		///439		/// * `staker`: staker account.440		/// * `amount`: amount of unstaked funds.441		#[pallet::call_index(8)]442		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]443		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {444			let staker_id = ensure_signed(staker)?;445446			Self::unstake_partial_internal(staker_id, amount)447		}448449		/// Sets the pallet to be the sponsor for the collection.450		///451		/// # Permissions452		///453		/// * Pallet admin454		///455		/// # Arguments456		///457		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`458		#[pallet::call_index(3)]459		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]460		pub fn sponsor_collection(461			admin: OriginFor<T>,462			collection_id: CollectionId,463		) -> DispatchResult {464			let admin_id = ensure_signed(admin)?;465			ensure!(466				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,467				Error::<T>::NoPermission468			);469470			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)471		}472473		/// Removes the pallet as the sponsor for the collection.474		/// Returns [`NoPermission`][`Error::NoPermission`]475		/// if the pallet wasn't the sponsor.476		///477		/// # Permissions478		///479		/// * Pallet admin480		///481		/// # Arguments482		///483		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`484		#[pallet::call_index(4)]485		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]486		pub fn stop_sponsoring_collection(487			admin: OriginFor<T>,488			collection_id: CollectionId,489		) -> DispatchResult {490			let admin_id = ensure_signed(admin)?;491492			ensure!(493				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,494				Error::<T>::NoPermission495			);496497			ensure!(498				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?499					== Self::account_id(),500				<Error<T>>::NoPermission501			);502			T::CollectionHandler::remove_collection_sponsor(collection_id)503		}504505		/// Sets the pallet to be the sponsor for the contract.506		///507		/// # Permissions508		///509		/// * Pallet admin510		///511		/// # Arguments512		///513		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`514		#[pallet::call_index(5)]515		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]516		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {517			let admin_id = ensure_signed(admin)?;518519			ensure!(520				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,521				Error::<T>::NoPermission522			);523524			T::ContractHandler::set_sponsor(525				T::CrossAccountId::from_sub(Self::account_id()),526				contract_id,527			)528		}529530		/// Removes the pallet as the sponsor for the contract.531		/// Returns [`NoPermission`][`Error::NoPermission`]532		/// if the pallet wasn't the sponsor.533		///534		/// # Permissions535		///536		/// * Pallet admin537		///538		/// # Arguments539		///540		/// * `contract_id`: the contract address that is sponsored by `pallet_id`541		#[pallet::call_index(6)]542		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]543		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {544			let admin_id = ensure_signed(admin)?;545546			ensure!(547				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,548				Error::<T>::NoPermission549			);550551			ensure!(552				T::ContractHandler::sponsor(contract_id)?553					.ok_or(<Error<T>>::SponsorNotSet)?554					.as_sub() == &Self::account_id(),555				<Error<T>>::NoPermission556			);557			T::ContractHandler::remove_contract_sponsor(contract_id)558		}559560		/// Recalculates interest for the specified number of stakers.561		/// If all stakers are not recalculated, the next call of the extrinsic562		/// will continue the recalculation, from those stakers for whom this563		/// was not perform in last call.564		///565		/// # Permissions566		///567		/// * Pallet admin568		///569		/// # Arguments570		///571		/// * `stakers_number`: the number of stakers for which recalculation will be performed572		#[pallet::call_index(7)]573		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]574		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {575			let admin_id = ensure_signed(admin)?;576577			ensure!(578				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,579				Error::<T>::NoPermission580			);581			let config = <PalletConfiguration<T>>::get();582583			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);584585			ensure!(586				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,587				Error::<T>::NoPermission588			);589590			// calculate the number of the current recalculation block,591			// this is necessary in order to understand which stakers we should calculate interest592			let current_recalc_block = Self::get_current_recalc_block(593				T::RelayBlockNumberProvider::current_block_number(),594				&config,595			);596597			// calculate the number of the next recalculation block,598			// this value is set for the stakers to whom the recalculation will be performed599			let next_recalc_block = current_recalc_block + config.recalculation_interval;600601			let storage_iterator =602				Self::get_next_calculated_key().map_or(Staked::<T>::iter(), Staked::<T>::iter_from);603604			PreviousCalculatedRecord::<T>::set(None);605606			{607				// Address handled in the last payout loop iteration (below)608				let last_id = RefCell::new(None);609				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration610				let mut last_staked_calculated_block = Default::default();611				// Reward balance for the address in the iteration612				let income_acc = RefCell::new(BalanceOf::<T>::default());613				// Staked balance for the address in the iteration (before stake is recalculated)614				let amount_acc = RefCell::new(BalanceOf::<T>::default());615616				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout617				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout618				// loop switches to handling the next staker address:619				//   1. Transfer full reward amount to the payee620				//   2. Lock the reward in staking lock621				//   3. Update TotalStaked amount622				//   4. Issue StakingRecalculation event623				let flush_stake = || -> DispatchResult {624					if let Some(last_id) = &*last_id.borrow() {625						if !income_acc.borrow().is_zero() {626							// TO-DO: When moving to ED>0, reconsider the value of preservation627							<<T as Config>::Currency as Mutate<T::AccountId>>::transfer(628								&T::TreasuryAccountId::get(),629								last_id,630								*income_acc.borrow(),631								frame_support::traits::tokens::Preservation::Protect,632							)?;633634							Self::add_freeze_balance(last_id, *income_acc.borrow())?;635							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {636								*staked = staked637									.checked_add(&*income_acc.borrow())638									.ok_or(ArithmeticError::Overflow)?;639								Ok(())640							})?;641642							Self::deposit_event(Event::StakingRecalculation(643								last_id.clone(),644								*amount_acc.borrow(),645								*income_acc.borrow(),646							));647						}648649						*income_acc.borrow_mut() = BalanceOf::<T>::default();650						*amount_acc.borrow_mut() = BalanceOf::<T>::default();651					}652					Ok(())653				};654655				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation656				// iterations in one extrinsic call657				//658				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)659				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out660				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)661				for ((current_id, staked_block), (amount, next_recalc_block_for_stake)) in662					storage_iterator663				{664					// last_id is not equal current_id when we switch to handling a new staker address665					// or just start handling the very first address. In the latter case last_id will be None and666					// flush_stake will do nothing667					if last_id.borrow().as_ref() != Some(&current_id) {668						if stakers_number > 0 {669							flush_stake()?;670							*last_id.borrow_mut() = Some(current_id.clone());671							stakers_number -= 1;672						}673						// Break out if we reached the address limit674						else {675							if let Some(staker) = &*last_id.borrow() {676								// Save the last calculated record to pick up in the next extrinsic call677								PreviousCalculatedRecord::<T>::set(Some((678									staker.clone(),679									last_staked_calculated_block,680								)));681							}682							break;683						};684					};685686					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount687					if current_recalc_block >= next_recalc_block_for_stake {688						*amount_acc.borrow_mut() += amount;689						Self::recalculate_and_insert_stake(690							&current_id,691							staked_block,692							next_recalc_block,693							amount,694							((current_recalc_block - next_recalc_block_for_stake)695								/ config.recalculation_interval)696								.into() + 1,697							&mut *income_acc.borrow_mut(),698						);699					}700					last_staked_calculated_block = staked_block;701				}702				flush_stake()?;703			}704705			Ok(())706		}707708		///  Migrates lock state into freeze one709		///710		/// # Permissions711		///712		/// * Sudo713		///714		///   # Arguments715		///716		/// * `origin`: Must be `Root`.717		/// * `stakers`: Accounts to be upgraded.718		#[pallet::call_index(9)]719		#[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]720		pub fn upgrade_accounts(721			origin: OriginFor<T>,722			stakers: Vec<T::AccountId>,723		) -> DispatchResult {724			ensure_root(origin)?;725726			stakers727				.into_iter()728				.try_for_each(|s| -> Result<_, DispatchError> {729					if let Some(BalanceLock { amount, .. }) = Self::get_locked_balance(&s) {730						if Self::get_frozen_balance(&s).is_some() {731							return Err(Error::<T>::InconsistencyState.into());732						}733734						<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(735							LOCK_IDENTIFIER,736							&s,737						);738739						Self::set_freeze_with_result(&s, amount)?;740						Ok(())741					} else {742						Ok(())743					}744				})?;745746			Ok(())747		}748749		/// Called for blocks that, for some reason, have not been unstacked750		///751		/// # Permissions752		///753		/// * Sudo754		///755		///   # Arguments756		///757		/// * `origin`: Must be `Root`.758		/// * `pending_blocks`: Block numbers that will be processed.759		#[pallet::call_index(10)]760		#[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]761		pub fn force_unstake(762			origin: OriginFor<T>,763			pending_blocks: Vec<T::BlockNumber>,764		) -> DispatchResult {765			ensure_root(origin)?;766767			ensure!(768				pending_blocks769					.iter()770					.all(|b| *b < <frame_system::Pallet<T>>::block_number()),771				<Error<T>>::NoPermission772			);773774			let mut pendings =775				Vec::with_capacity(PENDING_LIMIT_PER_BLOCK as usize * pending_blocks.len());776			pending_blocks777				.into_iter()778				.for_each(|b| pendings.append(&mut PendingUnstake::<T>::take(b).into_inner()));779780			pendings781				.into_iter()782				.try_for_each(|(staker, amount)| -> Result<(), DispatchError> {783					if let Some(b) = Self::get_frozen_balance(&staker) {784						let new_state = b.checked_sub(&amount).unwrap_or_default();785						Self::set_freeze_with_result(&staker, new_state)?;786					}787788					Ok(())789				})?;790791			Ok(())792		}793	}794}795796impl<T: Config> Pallet<T> {797	/// The account address of the app promotion pot.798	///799	/// This actually does computation. If you need to keep using it, then make sure you cache the800	/// value and only call this once.801	pub fn account_id() -> T::AccountId {802		T::PalletId::get().into_account_truncating()803	}804805	/// Unstakes the balance for the staker.806	///807	/// - `staker`: staker account.808	/// - `amount`: amount of unstaked funds.809	fn unstake_partial_internal(810		staker_id: T::AccountId,811		unstaked_balance: BalanceOf<T>,812	) -> DispatchResult {813		if unstaked_balance == Default::default() {814			return Ok(());815		}816817		let config = <PalletConfiguration<T>>::get();818819		// calculate block number where the sum would be free820		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;821822		let mut pendings = <PendingUnstake<T>>::get(unpending_block);823824		// checks that we can do unstake in the block825		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);826827		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();828829		let total_staked = stakes830			.iter()831			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {832				acc + *balance833			});834835		ensure!(836			unstaked_balance <= total_staked,837			<Error<T>>::InsufficientStakedBalance838		);839840		<TotalStaked<T>>::set(841			<TotalStaked<T>>::get()842				.checked_sub(&unstaked_balance)843				.ok_or(ArithmeticError::Underflow)?,844		);845846		stakes.sort_by_key(|(block, _)| *block);847848		let mut acc_amount = unstaked_balance;849		let mut will_deleted_stakes_count = 0u8;850851		let changed_stakes = stakes852			.into_iter()853			.map_while(|(block, (balance_per_block, _))| {854				if acc_amount == <BalanceOf<T>>::default() {855					return None;856				}857				if acc_amount < balance_per_block {858					let res = (block, balance_per_block - acc_amount);859					acc_amount = <BalanceOf<T>>::default();860					Some(res)861				} else {862					acc_amount -= balance_per_block;863					will_deleted_stakes_count += 1;864					Some((block, <BalanceOf<T>>::default()))865				}866			})867			.collect::<Vec<_>>();868869		pendings870			.try_push((staker_id.clone(), unstaked_balance))871			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;872873		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {874			*stakes = stakes875				.checked_sub(will_deleted_stakes_count)876				.ok_or(ArithmeticError::Underflow)?;877			Ok(())878		})?;879880		changed_stakes881			.into_iter()882			.for_each(|(staked_block, current_stake_state)| {883				if current_stake_state == Default::default() {884					<Staked<T>>::remove((&staker_id, staked_block));885				} else {886					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {887						*old_stake_state = current_stake_state888					});889				}890			});891892		<PendingUnstake<T>>::insert(unpending_block, pendings);893894		Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));895896		Ok(())897	}898899	/// Adds the balance to frozen by the pallet.900	///901	/// - `staker`: staker account.902	/// - `amount`: amount of added frozen funds.903	fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {904		Self::get_frozen_balance(staker)905			.unwrap_or_default()906			.checked_add(&amount)907			.map(|freeze| Self::set_freeze_with_result(staker, freeze))908			.ok_or::<DispatchError>(ArithmeticError::Overflow.into())?909	}910911	/// Sets the new state of a balance frozen by the pallet.912	///913	/// - `staker`: staker account.914	/// - `amount`: amount of frozen funds.915	fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {916		let _ = Self::set_freeze_with_result(staker, amount);917	}918919	/// Sets the new state of a balance frozen by the pallet.920	///921	/// - `staker`: staker account.922	/// - `amount`: amount of frozen funds.923	fn set_freeze_with_result(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {924		if amount.is_zero() {925			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(926				&T::FreezeIdentifier::get(),927				staker,928			)929		} else {930			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(931				&T::FreezeIdentifier::get(),932				staker,933				amount,934			)935		}936	}937938	/// Returns the balance locked by the pallet for the staker.939	///940	/// - `staker`: staker account.941	pub fn get_locked_balance(942		staker: impl EncodeLike<T::AccountId>,943	) -> Option<BalanceLock<BalanceOf<T>>> {944		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)945			.into_iter()946			.find(|l| l.id == LOCK_IDENTIFIER)947	}948949	/// Returns the balance frozen by the pallet for the staker.950	///951	/// - `staker`: staker account.952	pub fn get_frozen_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {953		let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(954			&T::FreezeIdentifier::get(),955			staker,956		);957958		if res == Zero::zero() {959			None960		} else {961			Some(res)962		}963	}964965	/// Returns the total staked balance for the staker.966	///967	/// - `staker`: staker account.968	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {969		let staked = Staked::<T>::iter_prefix((staker,))970			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {971				acc + amount972			});973		if staked != <BalanceOf<T>>::default() {974			Some(staked)975		} else {976			None977		}978	}979980	/// Returns all relay block numbers when stake was made,981	/// the amount of the stake.982	///983	/// - `staker`: staker account.984	pub fn total_staked_by_id_per_block(985		staker: impl EncodeLike<T::AccountId>,986	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {987		let mut staked = Staked::<T>::iter_prefix((staker,))988			.map(|(block, (amount, _))| (block, amount))989			.collect::<Vec<_>>();990		staked.sort_by_key(|(block, _)| *block);991		if !staked.is_empty() {992			Some(staked)993		} else {994			None995		}996	}997998	/// Returns the total staked balance for the staker.999	/// If `staker` is `None`, returns the total amount staked.1000	/// - `staker`: staker account.1001	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1002		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1003			Self::total_staked_by_id(s.as_sub())1004		})1005	}10061007	/// Returns all relay block numbers when stake was made,1008	/// the amount of the stake.1009	///1010	/// - `staker`: staker account.1011	pub fn cross_id_total_staked_per_block(1012		staker: T::CrossAccountId,1013	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1014		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1015	}10161017	fn recalculate_and_insert_stake(1018		staker: &T::AccountId,1019		staked_block: T::BlockNumber,1020		next_recalc_block: T::BlockNumber,1021		base: BalanceOf<T>,1022		iters: u32,1023		income_acc: &mut BalanceOf<T>,1024	) {1025		let income = Self::calculate_income(base, iters);10261027		if let Some(res) = base.checked_add(&income) {1028			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1029			*income_acc += income;1030		};1031	}10321033	fn calculate_income<I>(base: I, iters: u32) -> I1034	where1035		I: EncodeLike<BalanceOf<T>> + Balance,1036	{1037		let config = <PalletConfiguration<T>>::get();1038		let mut income = base;10391040		(0..iters).for_each(|_| income += config.interval_income * income);10411042		income - base1043	}10441045	/// Get relay block number rounded down to multiples of config.recalculation_interval.1046	/// We need it to reward stakers in integer parts of recalculation_interval1047	fn get_current_recalc_block(1048		current_relay_block: T::BlockNumber,1049		config: &PalletConfiguration<T>,1050	) -> T::BlockNumber {1051		(current_relay_block / config.recalculation_interval) * config.recalculation_interval1052	}10531054	fn get_next_calculated_key() -> Option<Vec<u8>> {1055		Self::get_next_calculated_record().map(Staked::<T>::hashed_key_for)1056	}1057}10581059impl<T: Config> Pallet<T>1060where1061	<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1062{1063	/// Returns the amount reserved by the pending.1064	/// If `staker` is `None`, returns the total pending.1065	///1066	/// -`staker`: staker account.1067	///1068	/// Since user funds are not transferred anywhere by staking, overflow protection is provided1069	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1070	/// the staker must have more funds on his account than the maximum set for `Balance` type.1071	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1072		staker.map_or(1073			PendingUnstake::<T>::iter_values()1074				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1075				.sum(),1076			|s| {1077				PendingUnstake::<T>::iter_values()1078					.flatten()1079					.filter_map(|(id, amount)| {1080						if id == *s.as_sub() {1081							Some(amount)1082						} else {1083							None1084						}1085					})1086					.sum()1087			},1088		)1089	}10901091	/// Returns all parachain block numbers when unreserve is expected,1092	/// the amount of the unreserved funds.1093	///1094	/// - `staker`: staker account.1095	pub fn cross_id_pending_unstake_per_block(1096		staker: T::CrossAccountId,1097	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1098		let mut unsorted_res = vec![];1099		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1100			pendings.into_iter().for_each(|(id, amount)| {1101				if id == *staker.as_sub() {1102					unsorted_res.push((block, amount));1103				};1104			})1105		});11061107		unsorted_res.sort_by_key(|(block, _)| *block);1108		unsorted_res1109	}11101111	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1112		let config = <PalletConfiguration<T>>::get();11131114		// calculate block number where the sum would be free1115		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;11161117		let mut pendings = <PendingUnstake<T>>::get(block);11181119		// checks that we can do unstake in the block1120		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);11211122		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1123			.map(|(_, (amount, _))| amount)1124			.sum();11251126		if total_staked.is_zero() {1127			return Ok(());1128		}11291130		pendings1131			.try_push((staker_id.clone(), total_staked))1132			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;11331134		<PendingUnstake<T>>::insert(block, pendings);11351136		TotalStaked::<T>::set(1137			TotalStaked::<T>::get()1138				.checked_sub(&total_staked)1139				.ok_or(ArithmeticError::Underflow)?,1140		);11411142		StakesPerAccount::<T>::remove(&staker_id);11431144		Self::deposit_event(Event::Unstake(staker_id, total_staked));11451146		Ok(())1147	}1148}
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::{vec::Vec, vec, iter::Sum, borrow::ToOwned, cell::RefCell};57use sp_core::H160;58use codec::EncodeLike;59pub use types::*;6061use up_data_structs::CollectionId;6263use frame_support::{64	dispatch::{DispatchResult},65	traits::{66		Get,67		tokens::Balance,68		fungible::{Inspect, InspectFreeze, Mutate, MutateFreeze},69	},70	ensure, BoundedVec,71};7273use weights::WeightInfo;7475pub use pallet::*;76use pallet_evm::account::CrossAccountId;77use sp_runtime::{78	Perbill,79	traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},80	ArithmeticError, DispatchError,81};8283const PENDING_LIMIT_PER_BLOCK: u32 = 3;8485type BalanceOf<T> =86	<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;8788#[frame_support::pallet]89pub mod pallet {90	use super::*;91	use frame_support::{92		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId, weights::Weight,93	};94	use frame_system::pallet_prelude::*;95	use sp_runtime::DispatchError;9697	#[pallet::config]98	pub trait Config:99		frame_system::Config + pallet_evm::Config + pallet_configuration::Config100	{101		/// Type to interact with the native token102		type Currency: MutateFreeze<Self::AccountId> + Mutate<Self::AccountId>;103104		/// Type for interacting with collections105		type CollectionHandler: CollectionHandler<106			AccountId = Self::AccountId,107			CollectionId = CollectionId,108		>;109110		/// Type for interacting with conrtacts111		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;112113		/// `AccountId` for treasury114		type TreasuryAccountId: Get<Self::AccountId>;115116		/// The app's pallet id, used for deriving its sovereign account address.117		#[pallet::constant]118		type PalletId: Get<PalletId>;119120		/// Freeze identifier used by the pallet121		#[pallet::constant]122		type FreezeIdentifier: Get<123			<<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id,124		>;125126		/// In relay blocks.127		#[pallet::constant]128		type RecalculationInterval: Get<Self::BlockNumber>;129130		/// In parachain blocks.131		#[pallet::constant]132		type PendingInterval: Get<Self::BlockNumber>;133134		/// Rate of return for interval in blocks defined in `RecalculationInterval`.135		#[pallet::constant]136		type IntervalIncome: Get<Perbill>;137138		/// Decimals for the `Currency`.139		#[pallet::constant]140		type Nominal: Get<BalanceOf<Self>>;141142		/// Maintenance mode status.143		type IsMaintenanceModeEnabled: Get<bool>;144145		/// Weight information for extrinsics in this pallet.146		type WeightInfo: WeightInfo;147148		// The relay block number provider149		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;150151		/// Events compatible with [`frame_system::Config::Event`].152		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;153	}154155	#[pallet::pallet]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 insufficient staked balance.210		InsufficientStakedBalance,211		/// Errors caused by incorrect state of a staker in context of the pallet.212		InconsistencyState,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::hooks]268	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {269		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize270		/// implies the execution of a strictly limited number of relatively lightweight operations.271		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.272		fn on_initialize(current_block_number: T::BlockNumber) -> Weight273		where274			<T as frame_system::Config>::BlockNumber: From<u32>,275		{276			if T::IsMaintenanceModeEnabled::get() {277				return T::DbWeight::get().reads_writes(1, 0);278			}279280			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					if let Some(b) = Self::get_frozen_balance(&staker) {286						let new_state = b.checked_sub(&amount).unwrap_or_default();287288						// In this case, setting a new state for the frozen funds cannot fail289						// because the state change goes in the direction of decreasing the frozen funds290						// and the validity of this transition is ensured by the fact291						// that we cannot (in the current implementation) unfreeze more funds292						// than were originally frozen by the pallet. Either way, `on_initialize()` cannot fail.293						Self::set_freeze_unchecked(&staker, new_state);294					};295				});296			}297298			<T as Config>::WeightInfo::on_initialize(counter)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 Inspect<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 = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);353354			// checks that we can freeze `amount` on the `staker` account.355			ensure!(356				amount357					<= match Self::get_frozen_balance(&staker_id) {358						Some(frozen_by_pallet) => balance359							.checked_sub(&frozen_by_pallet)360							.ok_or(ArithmeticError::Underflow)?,361						None => balance,362					},363				ArithmeticError::Underflow364			);365366			Self::add_freeze_balance(&staker_id, amount)?;367368			let block_number = T::RelayBlockNumberProvider::current_block_number();369370			// Calculation of the number of recalculation periods,371			// after how much the first interest calculation should be performed for the stake372			let recalculate_after_interval: T::BlockNumber =373				if block_number % config.recalculation_interval == 0u32.into() {374					1u32.into()375				} else {376					2u32.into()377				};378379			// Сalculation of the number of the relay block380			// in which it is necessary to accrue remuneration for the stake.381			let recalc_block = (block_number / config.recalculation_interval382				+ recalculate_after_interval)383				* config.recalculation_interval;384385			<Staked<T>>::insert((&staker_id, block_number), {386				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));387				balance_and_recalc_block.0 = balance_and_recalc_block388					.0389					.checked_add(&amount)390					.ok_or(ArithmeticError::Overflow)?;391				balance_and_recalc_block.1 = recalc_block;392				balance_and_recalc_block393			});394395			<TotalStaked<T>>::set(396				<TotalStaked<T>>::get()397					.checked_add(&amount)398					.ok_or(ArithmeticError::Overflow)?,399			);400401			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);402403			Self::deposit_event(Event::Stake(staker_id, amount));404405			Ok(())406		}407408		/// Unstakes all stakes.409		/// After the end of `PendingInterval` this sum becomes completely410		/// free for further use.411		#[pallet::call_index(2)]412		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]413		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {414			let staker_id = ensure_signed(staker)?;415416			Self::unstake_all_internal(staker_id)417		}418419		/// Unstakes the amount of balance for the staker.420		/// After the end of `PendingInterval` this sum becomes completely421		/// free for further use.422		///423		///  # Arguments424		///425		/// * `staker`: staker account.426		/// * `amount`: amount of unstaked funds.427		#[pallet::call_index(8)]428		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]429		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {430			let staker_id = ensure_signed(staker)?;431432			Self::unstake_partial_internal(staker_id, amount)433		}434435		/// Sets the pallet to be the sponsor for the collection.436		///437		/// # Permissions438		///439		/// * Pallet admin440		///441		/// # Arguments442		///443		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`444		#[pallet::call_index(3)]445		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]446		pub fn sponsor_collection(447			admin: OriginFor<T>,448			collection_id: CollectionId,449		) -> DispatchResult {450			let admin_id = ensure_signed(admin)?;451			ensure!(452				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,453				Error::<T>::NoPermission454			);455456			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)457		}458459		/// Removes the pallet as the sponsor for the collection.460		/// Returns [`NoPermission`][`Error::NoPermission`]461		/// if the pallet wasn't the sponsor.462		///463		/// # Permissions464		///465		/// * Pallet admin466		///467		/// # Arguments468		///469		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`470		#[pallet::call_index(4)]471		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]472		pub fn stop_sponsoring_collection(473			admin: OriginFor<T>,474			collection_id: CollectionId,475		) -> DispatchResult {476			let admin_id = ensure_signed(admin)?;477478			ensure!(479				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,480				Error::<T>::NoPermission481			);482483			ensure!(484				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?485					== Self::account_id(),486				<Error<T>>::NoPermission487			);488			T::CollectionHandler::remove_collection_sponsor(collection_id)489		}490491		/// Sets the pallet to be the sponsor for the contract.492		///493		/// # Permissions494		///495		/// * Pallet admin496		///497		/// # Arguments498		///499		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`500		#[pallet::call_index(5)]501		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]502		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {503			let admin_id = ensure_signed(admin)?;504505			ensure!(506				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,507				Error::<T>::NoPermission508			);509510			T::ContractHandler::set_sponsor(511				T::CrossAccountId::from_sub(Self::account_id()),512				contract_id,513			)514		}515516		/// Removes the pallet as the sponsor for the contract.517		/// Returns [`NoPermission`][`Error::NoPermission`]518		/// if the pallet wasn't the sponsor.519		///520		/// # Permissions521		///522		/// * Pallet admin523		///524		/// # Arguments525		///526		/// * `contract_id`: the contract address that is sponsored by `pallet_id`527		#[pallet::call_index(6)]528		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]529		pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {530			let admin_id = ensure_signed(admin)?;531532			ensure!(533				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,534				Error::<T>::NoPermission535			);536537			ensure!(538				T::ContractHandler::sponsor(contract_id)?539					.ok_or(<Error<T>>::SponsorNotSet)?540					.as_sub() == &Self::account_id(),541				<Error<T>>::NoPermission542			);543			T::ContractHandler::remove_contract_sponsor(contract_id)544		}545546		/// Recalculates interest for the specified number of stakers.547		/// If all stakers are not recalculated, the next call of the extrinsic548		/// will continue the recalculation, from those stakers for whom this549		/// was not perform in last call.550		///551		/// # Permissions552		///553		/// * Pallet admin554		///555		/// # Arguments556		///557		/// * `stakers_number`: the number of stakers for which recalculation will be performed558		#[pallet::call_index(7)]559		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]560		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {561			let admin_id = ensure_signed(admin)?;562563			ensure!(564				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,565				Error::<T>::NoPermission566			);567			let config = <PalletConfiguration<T>>::get();568569			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);570571			ensure!(572				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,573				Error::<T>::NoPermission574			);575576			// calculate the number of the current recalculation block,577			// this is necessary in order to understand which stakers we should calculate interest578			let current_recalc_block = Self::get_current_recalc_block(579				T::RelayBlockNumberProvider::current_block_number(),580				&config,581			);582583			// calculate the number of the next recalculation block,584			// this value is set for the stakers to whom the recalculation will be performed585			let next_recalc_block = current_recalc_block + config.recalculation_interval;586587			let storage_iterator =588				Self::get_next_calculated_key().map_or(Staked::<T>::iter(), Staked::<T>::iter_from);589590			PreviousCalculatedRecord::<T>::set(None);591592			{593				// Address handled in the last payout loop iteration (below)594				let last_id = RefCell::new(None);595				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration596				let mut last_staked_calculated_block = Default::default();597				// Reward balance for the address in the iteration598				let income_acc = RefCell::new(BalanceOf::<T>::default());599				// Staked balance for the address in the iteration (before stake is recalculated)600				let amount_acc = RefCell::new(BalanceOf::<T>::default());601602				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout603				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout604				// loop switches to handling the next staker address:605				//   1. Transfer full reward amount to the payee606				//   2. Lock the reward in staking lock607				//   3. Update TotalStaked amount608				//   4. Issue StakingRecalculation event609				let flush_stake = || -> DispatchResult {610					if let Some(last_id) = &*last_id.borrow() {611						if !income_acc.borrow().is_zero() {612							// TO-DO: When moving to ED>0, reconsider the value of preservation613							<<T as Config>::Currency as Mutate<T::AccountId>>::transfer(614								&T::TreasuryAccountId::get(),615								last_id,616								*income_acc.borrow(),617								frame_support::traits::tokens::Preservation::Protect,618							)?;619620							Self::add_freeze_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				for ((current_id, staked_block), (amount, next_recalc_block_for_stake)) in648					storage_iterator649				{650					// last_id is not equal current_id when we switch to handling a new staker address651					// or just start handling the very first address. In the latter case last_id will be None and652					// flush_stake will do nothing653					if last_id.borrow().as_ref() != Some(&current_id) {654						if stakers_number > 0 {655							flush_stake()?;656							*last_id.borrow_mut() = Some(current_id.clone());657							stakers_number -= 1;658						}659						// Break out if we reached the address limit660						else {661							if let Some(staker) = &*last_id.borrow() {662								// Save the last calculated record to pick up in the next extrinsic call663								PreviousCalculatedRecord::<T>::set(Some((664									staker.clone(),665									last_staked_calculated_block,666								)));667							}668							break;669						};670					};671672					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount673					if current_recalc_block >= next_recalc_block_for_stake {674						*amount_acc.borrow_mut() += amount;675						Self::recalculate_and_insert_stake(676							&current_id,677							staked_block,678							next_recalc_block,679							amount,680							((current_recalc_block - next_recalc_block_for_stake)681								/ config.recalculation_interval)682								.into() + 1,683							&mut *income_acc.borrow_mut(),684						);685					}686					last_staked_calculated_block = staked_block;687				}688				flush_stake()?;689			}690691			Ok(())692		}693694		/// Called for blocks that, for some reason, have not been unstacked695		///696		/// # Permissions697		///698		/// * Sudo699		///700		///   # Arguments701		///702		/// * `origin`: Must be `Root`.703		/// * `pending_blocks`: Block numbers that will be processed.704		#[pallet::call_index(9)]705		#[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]706		pub fn force_unstake(707			origin: OriginFor<T>,708			pending_blocks: Vec<T::BlockNumber>,709		) -> DispatchResult {710			ensure_root(origin)?;711712			ensure!(713				pending_blocks714					.iter()715					.all(|b| *b < <frame_system::Pallet<T>>::block_number()),716				<Error<T>>::NoPermission717			);718719			let mut pendings =720				Vec::with_capacity(PENDING_LIMIT_PER_BLOCK as usize * pending_blocks.len());721			pending_blocks722				.into_iter()723				.for_each(|b| pendings.append(&mut PendingUnstake::<T>::take(b).into_inner()));724725			pendings726				.into_iter()727				.try_for_each(|(staker, amount)| -> Result<(), DispatchError> {728					if let Some(b) = Self::get_frozen_balance(&staker) {729						let new_state = b.checked_sub(&amount).unwrap_or_default();730						Self::set_freeze_with_result(&staker, new_state)?;731					}732733					Ok(())734				})?;735736			Ok(())737		}738	}739}740741impl<T: Config> Pallet<T> {742	/// The account address of the app promotion pot.743	///744	/// This actually does computation. If you need to keep using it, then make sure you cache the745	/// value and only call this once.746	pub fn account_id() -> T::AccountId {747		T::PalletId::get().into_account_truncating()748	}749750	/// Unstakes the balance for the staker.751	///752	/// - `staker`: staker account.753	/// - `amount`: amount of unstaked funds.754	fn unstake_partial_internal(755		staker_id: T::AccountId,756		unstaked_balance: BalanceOf<T>,757	) -> DispatchResult {758		if unstaked_balance == Default::default() {759			return Ok(());760		}761762		let config = <PalletConfiguration<T>>::get();763764		// calculate block number where the sum would be free765		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;766767		let mut pendings = <PendingUnstake<T>>::get(unpending_block);768769		// checks that we can do unstake in the block770		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);771772		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();773774		let total_staked = stakes775			.iter()776			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {777				acc + *balance778			});779780		ensure!(781			unstaked_balance <= total_staked,782			<Error<T>>::InsufficientStakedBalance783		);784785		<TotalStaked<T>>::set(786			<TotalStaked<T>>::get()787				.checked_sub(&unstaked_balance)788				.ok_or(ArithmeticError::Underflow)?,789		);790791		stakes.sort_by_key(|(block, _)| *block);792793		let mut acc_amount = unstaked_balance;794		let mut will_deleted_stakes_count = 0u8;795796		let changed_stakes = stakes797			.into_iter()798			.map_while(|(block, (balance_per_block, _))| {799				if acc_amount == <BalanceOf<T>>::default() {800					return None;801				}802				if acc_amount < balance_per_block {803					let res = (block, balance_per_block - acc_amount);804					acc_amount = <BalanceOf<T>>::default();805					Some(res)806				} else {807					acc_amount -= balance_per_block;808					will_deleted_stakes_count += 1;809					Some((block, <BalanceOf<T>>::default()))810				}811			})812			.collect::<Vec<_>>();813814		pendings815			.try_push((staker_id.clone(), unstaked_balance))816			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;817818		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {819			*stakes = stakes820				.checked_sub(will_deleted_stakes_count)821				.ok_or(ArithmeticError::Underflow)?;822			Ok(())823		})?;824825		changed_stakes826			.into_iter()827			.for_each(|(staked_block, current_stake_state)| {828				if current_stake_state == Default::default() {829					<Staked<T>>::remove((&staker_id, staked_block));830				} else {831					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {832						*old_stake_state = current_stake_state833					});834				}835			});836837		<PendingUnstake<T>>::insert(unpending_block, pendings);838839		Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));840841		Ok(())842	}843844	/// Adds the balance to frozen by the pallet.845	///846	/// - `staker`: staker account.847	/// - `amount`: amount of added frozen funds.848	fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {849		Self::get_frozen_balance(staker)850			.unwrap_or_default()851			.checked_add(&amount)852			.map(|freeze| Self::set_freeze_with_result(staker, freeze))853			.ok_or::<DispatchError>(ArithmeticError::Overflow.into())?854	}855856	/// Sets the new state of a balance frozen by the pallet.857	///858	/// - `staker`: staker account.859	/// - `amount`: amount of frozen funds.860	fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {861		let _ = Self::set_freeze_with_result(staker, amount);862	}863864	/// Sets the new state of a balance frozen by the pallet.865	///866	/// - `staker`: staker account.867	/// - `amount`: amount of frozen funds.868	fn set_freeze_with_result(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {869		if amount.is_zero() {870			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(871				&T::FreezeIdentifier::get(),872				staker,873			)874		} else {875			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(876				&T::FreezeIdentifier::get(),877				staker,878				amount,879			)880		}881	}882883	/// Returns the balance frozen by the pallet for the staker.884	///885	/// - `staker`: staker account.886	pub fn get_frozen_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {887		let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(888			&T::FreezeIdentifier::get(),889			staker,890		);891892		if res == Zero::zero() {893			None894		} else {895			Some(res)896		}897	}898899	/// Returns the total staked balance for the staker.900	///901	/// - `staker`: staker account.902	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {903		let staked = Staked::<T>::iter_prefix((staker,))904			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {905				acc + amount906			});907		if staked != <BalanceOf<T>>::default() {908			Some(staked)909		} else {910			None911		}912	}913914	/// Returns all relay block numbers when stake was made,915	/// the amount of the stake.916	///917	/// - `staker`: staker account.918	pub fn total_staked_by_id_per_block(919		staker: impl EncodeLike<T::AccountId>,920	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {921		let mut staked = Staked::<T>::iter_prefix((staker,))922			.map(|(block, (amount, _))| (block, amount))923			.collect::<Vec<_>>();924		staked.sort_by_key(|(block, _)| *block);925		if !staked.is_empty() {926			Some(staked)927		} else {928			None929		}930	}931932	/// Returns the total staked balance for the staker.933	/// If `staker` is `None`, returns the total amount staked.934	/// - `staker`: staker account.935	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {936		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {937			Self::total_staked_by_id(s.as_sub())938		})939	}940941	/// Returns all relay block numbers when stake was made,942	/// the amount of the stake.943	///944	/// - `staker`: staker account.945	pub fn cross_id_total_staked_per_block(946		staker: T::CrossAccountId,947	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {948		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()949	}950951	fn recalculate_and_insert_stake(952		staker: &T::AccountId,953		staked_block: T::BlockNumber,954		next_recalc_block: T::BlockNumber,955		base: BalanceOf<T>,956		iters: u32,957		income_acc: &mut BalanceOf<T>,958	) {959		let income = Self::calculate_income(base, iters);960961		if let Some(res) = base.checked_add(&income) {962			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));963			*income_acc += income;964		};965	}966967	fn calculate_income<I>(base: I, iters: u32) -> I968	where969		I: EncodeLike<BalanceOf<T>> + Balance,970	{971		let config = <PalletConfiguration<T>>::get();972		let mut income = base;973974		(0..iters).for_each(|_| income += config.interval_income * income);975976		income - base977	}978979	/// Get relay block number rounded down to multiples of config.recalculation_interval.980	/// We need it to reward stakers in integer parts of recalculation_interval981	fn get_current_recalc_block(982		current_relay_block: T::BlockNumber,983		config: &PalletConfiguration<T>,984	) -> T::BlockNumber {985		(current_relay_block / config.recalculation_interval) * config.recalculation_interval986	}987988	fn get_next_calculated_key() -> Option<Vec<u8>> {989		Self::get_next_calculated_record().map(Staked::<T>::hashed_key_for)990	}991}992993impl<T: Config> Pallet<T>994where995	<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,996{997	/// Returns the amount reserved by the pending.998	/// If `staker` is `None`, returns the total pending.999	///1000	/// -`staker`: staker account.1001	///1002	/// Since user funds are not transferred anywhere by staking, overflow protection is provided1003	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1004	/// the staker must have more funds on his account than the maximum set for `Balance` type.1005	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1006		staker.map_or(1007			PendingUnstake::<T>::iter_values()1008				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1009				.sum(),1010			|s| {1011				PendingUnstake::<T>::iter_values()1012					.flatten()1013					.filter_map(|(id, amount)| {1014						if id == *s.as_sub() {1015							Some(amount)1016						} else {1017							None1018						}1019					})1020					.sum()1021			},1022		)1023	}10241025	/// Returns all parachain block numbers when unreserve is expected,1026	/// the amount of the unreserved funds.1027	///1028	/// - `staker`: staker account.1029	pub fn cross_id_pending_unstake_per_block(1030		staker: T::CrossAccountId,1031	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1032		let mut unsorted_res = vec![];1033		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1034			pendings.into_iter().for_each(|(id, amount)| {1035				if id == *staker.as_sub() {1036					unsorted_res.push((block, amount));1037				};1038			})1039		});10401041		unsorted_res.sort_by_key(|(block, _)| *block);1042		unsorted_res1043	}10441045	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1046		let config = <PalletConfiguration<T>>::get();10471048		// calculate block number where the sum would be free1049		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;10501051		let mut pendings = <PendingUnstake<T>>::get(block);10521053		// checks that we can do unstake in the block1054		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);10551056		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1057			.map(|(_, (amount, _))| amount)1058			.sum();10591060		if total_staked.is_zero() {1061			return Ok(());1062		}10631064		pendings1065			.try_push((staker_id.clone(), total_staked))1066			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;10671068		<PendingUnstake<T>>::insert(block, pendings);10691070		TotalStaked::<T>::set(1071			TotalStaked::<T>::get()1072				.checked_sub(&total_staked)1073				.ok_or(ArithmeticError::Underflow)?,1074		);10751076		StakesPerAccount::<T>::remove(&staker_id);10771078		Self::deposit_event(Event::Unstake(staker_id, total_staked));10791080		Ok(())1081	}1082}
modifiedpallets/app-promotion/src/types.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/types.rs
+++ b/pallets/app-promotion/src/types.rs
@@ -1,7 +1,5 @@
-use codec::EncodeLike;
-use frame_support::{traits::LockableCurrency, WeakBoundedVec, Parameter, dispatch::DispatchResult};
+use frame_support::{dispatch::DispatchResult};
 
-use pallet_balances::{BalanceLock, Config as BalancesConfig, Pallet as PalletBalances};
 use pallet_common::CollectionHandle;
 
 use sp_runtime::{DispatchError, Perbill};
@@ -14,25 +12,6 @@
 const MAX_NUMBER_PAYOUTS: u8 = 100;
 pub(crate) const DEFAULT_NUMBER_PAYOUTS: u8 = 20;
 
-/// This trait was defined because `LockableCurrency`
-/// has no way to know the state of the lock for an account.
-pub trait ExtendedLockableCurrency<AccountId: Parameter>: LockableCurrency<AccountId> {
-	/// Returns lock balance for an account. Allows to determine the cause of the lock.
-	fn locks<KArg>(who: KArg) -> WeakBoundedVec<BalanceLock<Self::Balance>, Self::MaxLocks>
-	where
-		KArg: EncodeLike<AccountId>;
-}
-
-impl<T: BalancesConfig<I>, I: 'static> ExtendedLockableCurrency<T::AccountId>
-	for PalletBalances<T, I>
-{
-	fn locks<KArg>(who: KArg) -> WeakBoundedVec<BalanceLock<Self::Balance>, Self::MaxLocks>
-	where
-		KArg: EncodeLike<T::AccountId>,
-	{
-		Self::locks(who)
-	}
-}
 /// Trait for interacting with collections.
 pub trait CollectionHandler {
 	type CollectionId;
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -200,7 +200,7 @@
 			value: property_value(),
 		}).collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, owner.clone())?;
-	}: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?}
+	}: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?}
 
 	delete_token_properties {
 		let b in 0..MAX_PROPERTIES_PER_ITEM;
@@ -222,7 +222,7 @@
 			value: property_value(),
 		}).collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, owner.clone())?;
-		<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?;
+		<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?;
 		let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
 	}: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}
 
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -257,7 +257,7 @@
 			value: property_value(),
 		}).collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-	}: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?}
+	}: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?}
 
 	delete_token_properties {
 		let b in 0..MAX_PROPERTIES_PER_ITEM;
@@ -279,7 +279,7 @@
 			value: property_value(),
 		}).collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-		<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?;
+		<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?;
 		let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
 	}: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}