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

difftreelog

fix runtime benchmarks, `payout_stakers` logic, bencmarkr for payout_stakers

PraetorP2022-09-06parent: #ebc4cdb.patch.diff
in: master

15 files changed

modifiedpallets/app-promotion/Cargo.tomldiffbeforeafterboth
--- a/pallets/app-promotion/Cargo.toml
+++ b/pallets/app-promotion/Cargo.toml
@@ -20,18 +20,23 @@
     'frame-benchmarking',
     'frame-support/runtime-benchmarks',
     'frame-system/runtime-benchmarks',
+    # 'pallet-unique/runtime-benchmarks',
 ]
 std = [
     'codec/std',
-    'serde/std',
+    'frame-benchmarking/std',
     'frame-support/std',
     'frame-system/std',
     'pallet-balances/std',
     'pallet-timestamp/std',
     'pallet-randomness-collective-flip/std',
+    'pallet-evm/std',
+    'sp-io/std',
     'sp-std/std',
     'sp-runtime/std',
-    'frame-benchmarking/std',
+    'sp-core/std',
+    'serde/std',
+
 ]
 
 ################################################################################
@@ -108,24 +113,24 @@
 # local dependencies
 [dependencies.up-data-structs]
 default-features = false
-path =  "../../primitives/data-structs"
+path = "../../primitives/data-structs"
 
 [dependencies.pallet-common]
 default-features = false
-path =  "../common"
+path = "../common"
 
 [dependencies.pallet-unique]
 default-features = false
-path =  "../unique"
+path = "../unique"
 
 [dependencies.pallet-evm-contract-helpers]
 default-features = false
-path =  "../evm-contract-helpers"
+path = "../evm-contract-helpers"
 
 [dev-dependencies]
 [dependencies.pallet-evm-migration]
 default-features = false
-path =  "../evm-migration"
+path = "../evm-migration"
 
 
 ################################################################################
modifiedpallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth
before · pallets/app-promotion/src/benchmarking.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#![cfg(feature = "runtime-benchmarks")]1819use super::*;20use crate::Pallet as PromototionPallet;2122use sp_runtime::traits::Bounded;23use sp_std::vec;2425use frame_benchmarking::{benchmarks, account};2627use frame_system::{Origin, RawOrigin};28use pallet_unique::benchmarking::create_nft_collection;29use pallet_evm_migration::Pallet as EvmMigrationPallet;3031// trait BenchmarkingConfig: Config + pallet_unique::Config { }3233// impl<T: Config + pallet_unique::Config> BenchmarkingConfig for T { }3435const SEED: u32 = 0;36benchmarks! {37	where_clause{38		where T:  Config + pallet_unique::Config + pallet_evm_migration::Config ,39		T::BlockNumber: From<u32> + Into<u32>,40		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>41	}42	// start_app_promotion {4344	// } : {PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), None)?}4546	// stop_app_promotion{47	// 	PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), Some(25.into()))?;48	// } : {PromototionPallet::<T>::stop_app_promotion(RawOrigin::Root.into())?}4950	set_admin_address {51		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);52		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());53	} : {PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin))?}5455	payout_stakers{56		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);57		let share = Perbill::from_rational(1u32, 100);58		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;59		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());60		let staker: T::AccountId = account("caller", 0, SEED);61		let stakers: Vec<T::AccountId> = (0..100).map(|index| account("staker", index, SEED)).collect();62		stakers.iter().for_each(|staker| {63			<T as Config>::Currency::make_free_balance_be(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());64		});65		let _ = <T as Config>::Currency::make_free_balance_be(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());66		let _ = PromototionPallet::<T>::stake(RawOrigin::Signed(staker.clone()).into(), share * <T as Config>::Currency::total_balance(&staker))?;67	} : {PromototionPallet::<T>::payout_stakers(RawOrigin::Signed(pallet_admin.clone()).into(), Some(1))?}6869	stake {70		let caller = account::<T::AccountId>("caller", 0, SEED);71		let share = Perbill::from_rational(1u32, 10);72		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());73	} : {PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))?}7475	unstake {76		let caller = account::<T::AccountId>("caller", 0, SEED);77		let share = Perbill::from_rational(1u32, 20);78		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());79		(0..10).map(|_| PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))).collect::<Result<Vec<_>, _>>()?;8081	} : {PromototionPallet::<T>::unstake(RawOrigin::Signed(caller.clone()).into())?}8283	// recalculate_and_insert_stake{84	// 	let caller = account::<T::AccountId>("caller", 0, SEED);85	// 	let share = Perbill::from_rational(1u32, 10);86	// 	let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());87	// 	let _ = PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))?;88	// 	let block = <T::RelayBlockNumberProvider as BlockNumberProvider>::current_block_number();89	// 	let mut acc = <BalanceOf<T>>::default();90	// } : {PromototionPallet::<T>::recalculate_and_insert_stake(&caller, block, share * <T as Config>::Currency::total_balance(&caller), &mut acc)}9192	sponsor_collection {93		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);94		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;95		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());96		let caller: T::AccountId = account("caller", 0, SEED);97		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());98		let collection = create_nft_collection::<T>(caller.clone())?;99	} : {PromototionPallet::<T>::sponsor_collection(RawOrigin::Signed(pallet_admin.clone()).into(), collection)?}100101	stop_sponsoring_collection {102		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);103		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;104		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());105		let caller: T::AccountId = account("caller", 0, SEED);106		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());107		let collection = create_nft_collection::<T>(caller.clone())?;108		PromototionPallet::<T>::sponsor_collection(RawOrigin::Signed(pallet_admin.clone()).into(), collection)?;109	} : {PromototionPallet::<T>::stop_sponsoring_collection(RawOrigin::Signed(pallet_admin.clone()).into(), collection)?}110111	sponsor_contract {112		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);113		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;114115		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());116		let address = H160::from_low_u64_be(SEED as u64);117		let data: Vec<u8> = (0..20 as u8).collect();118		<EvmMigrationPallet<T>>::begin(RawOrigin::Root.into(), address)?;119		<EvmMigrationPallet<T>>::finish(RawOrigin::Root.into(), address, data)?;120	} : {PromototionPallet::<T>::sponsor_conract(RawOrigin::Signed(pallet_admin.clone()).into(), address)?}121122	stop_sponsoring_contract {123		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);124		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;125126		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());127		let address = H160::from_low_u64_be(SEED as u64);128		let data: Vec<u8> = (0..20 as u8).collect();129		<EvmMigrationPallet<T>>::begin(RawOrigin::Root.into(), address)?;130		<EvmMigrationPallet<T>>::finish(RawOrigin::Root.into(), address, data)?;131		PromototionPallet::<T>::sponsor_conract(RawOrigin::Signed(pallet_admin.clone()).into(), address)?;132	} : {PromototionPallet::<T>::stop_sponsoring_contract(RawOrigin::Signed(pallet_admin.clone()).into(), address)?}133}
after · pallets/app-promotion/src/benchmarking.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#![cfg(feature = "runtime-benchmarks")]1819use super::*;20use crate::Pallet as PromototionPallet;2122use sp_runtime::traits::Bounded;23use sp_std::vec;2425use frame_benchmarking::{benchmarks, account};2627use frame_system::{Origin, RawOrigin};28use pallet_unique::benchmarking::create_nft_collection;29use pallet_evm_migration::Pallet as EvmMigrationPallet;3031const SEED: u32 = 0;3233benchmarks! {34	where_clause{35		where T:  Config + pallet_unique::Config + pallet_evm_migration::Config ,36		T::BlockNumber: From<u32> + Into<u32>,37		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>38	}39	// start_app_promotion {4041	// } : {PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), None)?}4243	// stop_app_promotion{44	// 	PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), Some(25.into()))?;45	// } : {PromototionPallet::<T>::stop_app_promotion(RawOrigin::Root.into())?}4647	set_admin_address {48		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);49		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());50	} : {PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin))?}5152	payout_stakers{53		let b in 1..101;5455		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);56		let share = Perbill::from_rational(1u32, 20);57		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;58		<T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());5960		let staker: T::AccountId = account("caller", 0, SEED);61		<T as Config>::Currency::make_free_balance_be(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());62		let stakers: Vec<T::AccountId> = (0..b).map(|index| account("staker", index, SEED)).collect();63		stakers.iter().for_each(|staker| {64			<T as Config>::Currency::make_free_balance_be(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());65		});66		(0..10).try_for_each(|_| {67			stakers.iter()68				.map(|staker| {69				70					PromototionPallet::<T>::stake(RawOrigin::Signed(staker.clone()).into(), Into::<BalanceOf<T>>::into(100u128) * T::Nominal::get())71				}).collect::<Result<Vec<_>, _>>()?;72			<frame_system::Pallet<T>>::finalize();73			Result::<(), sp_runtime::DispatchError>::Ok(())74		})?;7576		// let _ = <T as Config>::Currency::make_free_balance_be(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());77		// let _ = PromototionPallet::<T>::stake(RawOrigin::Signed(staker.clone()).into(), share * <T as Config>::Currency::total_balance(&staker))?;78	} : {PromototionPallet::<T>::payout_stakers(RawOrigin::Signed(pallet_admin.clone()).into(), Some(b as u8))?}7980	stake {81		let caller = account::<T::AccountId>("caller", 0, SEED);82		let share = Perbill::from_rational(1u32, 10);83		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());84	} : {PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))?}8586	unstake {87		let caller = account::<T::AccountId>("caller", 0, SEED);88		let share = Perbill::from_rational(1u32, 20);89		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());90		(0..10).map(|_| {91			<frame_system::Pallet<T>>::finalize();92			PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))93		}).collect::<Result<Vec<_>, _>>()?;9495	} : {PromototionPallet::<T>::unstake(RawOrigin::Signed(caller.clone()).into())?}9697	// recalculate_and_insert_stake{98	// 	let caller = account::<T::AccountId>("caller", 0, SEED);99	// 	let share = Perbill::from_rational(1u32, 10);100	// 	let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());101	// 	let _ = PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))?;102	// 	let block = <T::RelayBlockNumberProvider as BlockNumberProvider>::current_block_number();103	// 	let mut acc = <BalanceOf<T>>::default();104	// } : {PromototionPallet::<T>::recalculate_and_insert_stake(&caller, block, share * <T as Config>::Currency::total_balance(&caller), &mut acc)}105106	sponsor_collection {107		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);108		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;109		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());110		let caller: T::AccountId = account("caller", 0, SEED);111		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());112		let collection = create_nft_collection::<T>(caller.clone())?;113	} : {PromototionPallet::<T>::sponsor_collection(RawOrigin::Signed(pallet_admin.clone()).into(), collection)?}114115	stop_sponsoring_collection {116		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);117		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;118		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());119		let caller: T::AccountId = account("caller", 0, SEED);120		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());121		let collection = create_nft_collection::<T>(caller.clone())?;122		PromototionPallet::<T>::sponsor_collection(RawOrigin::Signed(pallet_admin.clone()).into(), collection)?;123	} : {PromototionPallet::<T>::stop_sponsoring_collection(RawOrigin::Signed(pallet_admin.clone()).into(), collection)?}124125	sponsor_contract {126		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);127		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;128129		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());130		let address = H160::from_low_u64_be(SEED as u64);131		let data: Vec<u8> = (0..20 as u8).collect();132		<EvmMigrationPallet<T>>::begin(RawOrigin::Root.into(), address)?;133		<EvmMigrationPallet<T>>::finish(RawOrigin::Root.into(), address, data)?;134	} : {PromototionPallet::<T>::sponsor_conract(RawOrigin::Signed(pallet_admin.clone()).into(), address)?}135136	stop_sponsoring_contract {137		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);138		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;139140		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());141		let address = H160::from_low_u64_be(SEED as u64);142		let data: Vec<u8> = (0..20 as u8).collect();143		<EvmMigrationPallet<T>>::begin(RawOrigin::Root.into(), address)?;144		<EvmMigrationPallet<T>>::finish(RawOrigin::Root.into(), address, data)?;145		PromototionPallet::<T>::sponsor_conract(RawOrigin::Signed(pallet_admin.clone()).into(), address)?;146	} : {PromototionPallet::<T>::stop_sponsoring_contract(RawOrigin::Signed(pallet_admin.clone()).into(), address)?}147}
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -157,7 +157,7 @@
 		/// No permission to perform an action
 		NoPermission,
 		/// Insufficient funds to perform an action
-		NotSufficientFounds,
+		NotSufficientFunds,
 		PendingForBlockOverflow,
 		/// An error related to the fact that an invalid argument was passed to perform an action
 		InvalidArgument,
@@ -285,14 +285,23 @@
 			<<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(
 				&staker_id,
 				amount,
-				WithdrawReasons::all(),
+				WithdrawReasons::RESERVE,
 				balance - amount,
 			)?;
 
 			Self::add_lock_balance(&staker_id, amount)?;
 
 			let block_number = T::RelayBlockNumberProvider::current_block_number();
-			let recalc_block = (block_number / T::RecalculationInterval::get() + 2u32.into())
+
+			let recalculate_after_interval: T::BlockNumber =
+				if block_number % T::RecalculationInterval::get() == 0u32.into() {
+					1u32.into()
+				} else {
+					2u32.into()
+				};
+
+			let recalc_block = (block_number / T::RecalculationInterval::get()
+				+ recalculate_after_interval)
 				* T::RecalculationInterval::get();
 
 			<Staked<T>>::insert((&staker_id, block_number), {
@@ -428,7 +437,7 @@
 			T::ContractHandler::remove_contract_sponsor(contract_id)
 		}
 
-		#[pallet::weight(0)]
+		#[pallet::weight(T::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]
 		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {
 			let admin_id = ensure_signed(admin)?;
 
@@ -495,6 +504,74 @@
 			// 	}
 			// }
 
+			// {
+			// 	let mut stakers_number = stakers_number.unwrap_or(20);
+			// 	let last_id = RefCell::new(None);
+			// 	let income_acc = RefCell::new(BalanceOf::<T>::default());
+			// 	let amount_acc = RefCell::new(BalanceOf::<T>::default());
+
+			// 	let flush_stake = || -> DispatchResult {
+			// 		if let Some(last_id) = &*last_id.borrow() {
+			// 			if !income_acc.borrow().is_zero() {
+			// 				<T::Currency as Currency<T::AccountId>>::transfer(
+			// 					&T::TreasuryAccountId::get(),
+			// 					last_id,
+			// 					*income_acc.borrow(),
+			// 					ExistenceRequirement::KeepAlive,
+			// 				)
+			// 				.and_then(|_| {
+			// 					Self::add_lock_balance(last_id, *income_acc.borrow());
+			// 					<TotalStaked<T>>::try_mutate(|staked| {
+			// 						staked
+			// 							.checked_add(&*income_acc.borrow())
+			// 							.ok_or(ArithmeticError::Overflow.into())
+			// 					})
+			// 				})?;
+
+			// 				Self::deposit_event(Event::StakingRecalculation(
+			// 					last_id.clone(),
+			// 					*amount_acc.borrow(),
+			// 					*income_acc.borrow(),
+			// 				));
+			// 			}
+
+			// 			*income_acc.borrow_mut() = BalanceOf::<T>::default();
+			// 			*amount_acc.borrow_mut() = BalanceOf::<T>::default();
+			// 		}
+			// 		Ok(())
+			// 	};
+
+			// 	while let Some((
+			// 		(current_id, staked_block),
+			// 		(amount, next_recalc_block_for_stake),
+			// 	)) = storage_iterator.next()
+			// 	{
+			// 		if stakers_number == 0 {
+			// 			NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));
+			// 			break;
+			// 		}
+			// 		stakers_number -= 1;
+			// 		if last_id.borrow().as_ref() != Some(&current_id) {
+			// 			flush_stake()?;
+			// 		};
+			// 		*last_id.borrow_mut() = Some(current_id.clone());
+			// 		if current_recalc_block >= next_recalc_block_for_stake {
+			// 			*amount_acc.borrow_mut() += amount;
+			// 			Self::recalculate_and_insert_stake(
+			// 				&current_id,
+			// 				staked_block,
+			// 				next_recalc_block,
+			// 				amount,
+			// 				((current_recalc_block - next_recalc_block_for_stake)
+			// 					/ T::RecalculationInterval::get())
+			// 				.into() + 1,
+			// 				&mut *income_acc.borrow_mut(),
+			// 			);
+			// 		}
+			// 	}
+			// 	flush_stake()?;
+			// }
+
 			{
 				let mut stakers_number = stakers_number.unwrap_or(20);
 				let last_id = RefCell::new(None);
@@ -510,7 +587,14 @@
 								*income_acc.borrow(),
 								ExistenceRequirement::KeepAlive,
 							)
-							.and_then(|_| Self::add_lock_balance(last_id, *income_acc.borrow()))?;
+							.and_then(|_| {
+								Self::add_lock_balance(last_id, *income_acc.borrow())?;
+								<TotalStaked<T>>::try_mutate(|staked| {
+									staked
+										.checked_add(&*income_acc.borrow())
+										.ok_or(ArithmeticError::Overflow.into())
+								})
+							})?;
 
 							Self::deposit_event(Event::StakingRecalculation(
 								last_id.clone(),
@@ -534,11 +618,11 @@
 						NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));
 						break;
 					}
-					stakers_number -= 1;
 					if last_id.borrow().as_ref() != Some(&current_id) {
 						flush_stake()?;
+						*last_id.borrow_mut() = Some(current_id.clone());
+						stakers_number -= 1;
 					};
-					*last_id.borrow_mut() = Some(current_id.clone());
 					if current_recalc_block >= next_recalc_block_for_stake {
 						*amount_acc.borrow_mut() += amount;
 						Self::recalculate_and_insert_stake(
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, ensure,
-};
+use frame_support::{traits::LockableCurrency, WeakBoundedVec, Parameter, dispatch::DispatchResult};
 
 use pallet_balances::{BalanceLock, Config as BalancesConfig, Pallet as PalletBalances};
 use pallet_common::CollectionHandle;
modifiedpallets/app-promotion/src/weights.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/weights.rs
+++ b/pallets/app-promotion/src/weights.rs
@@ -3,7 +3,7 @@
 //! Autogenerated weights for pallet_app_promotion
 //!
 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-09-01, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-09-06, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
 //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
 
 // Executed Command:
@@ -35,7 +35,7 @@
 /// Weight functions needed for pallet_app_promotion.
 pub trait WeightInfo {
 	fn set_admin_address() -> Weight;
-	fn payout_stakers() -> Weight;
+	fn payout_stakers(b: u32, ) -> Weight;
 	fn stake() -> Weight;
 	fn unstake() -> Weight;
 	fn sponsor_collection() -> Weight;
@@ -47,66 +47,70 @@
 /// Weights for pallet_app_promotion using the Substrate node and recommended hardware.
 pub struct SubstrateWeight<T>(PhantomData<T>);
 impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
-	// Storage: Promotion Admin (r:0 w:1)
+	// Storage: AppPromotion Admin (r:0 w:1)
 	fn set_admin_address() -> Weight {
-		(515_000 as Weight)
+		(5_297_000 as Weight)
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
-	// Storage: Promotion Admin (r:1 w:0)
+	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: ParachainSystem ValidationData (r:1 w:0)
-	// Storage: Promotion NextCalculatedRecord (r:1 w:1)
-	// Storage: Promotion Staked (r:2 w:0)
-	fn payout_stakers() -> Weight {
-		(8_475_000 as Weight)
-			.saturating_add(T::DbWeight::get().reads(5 as Weight))
+	// Storage: AppPromotion NextCalculatedRecord (r:1 w:1)
+	// Storage: AppPromotion Staked (r:2 w:0)
+	fn payout_stakers(b: u32, ) -> Weight {
+		(8_045_000 as Weight)
+			// Standard Error: 19_000
+			.saturating_add((4_778_000 as Weight).saturating_mul(b as Weight))
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
 	// Storage: System Account (r:1 w:1)
-	// Storage: Promotion StakesPerAccount (r:1 w:1)
+	// Storage: AppPromotion StakesPerAccount (r:1 w:1)
 	// Storage: Balances Locks (r:1 w:1)
 	// Storage: ParachainSystem ValidationData (r:1 w:0)
-	// Storage: Promotion Staked (r:1 w:1)
-	// Storage: Promotion TotalStaked (r:1 w:1)
+	// Storage: AppPromotion Staked (r:1 w:1)
+	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	fn stake() -> Weight {
-		(12_266_000 as Weight)
+		(17_623_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(6 as Weight))
 			.saturating_add(T::DbWeight::get().writes(5 as Weight))
 	}
-	// Storage: Promotion Staked (r:2 w:1)
-	// Storage: ParachainSystem ValidationData (r:1 w:0)
-	// Storage: Promotion PendingUnstake (r:1 w:1)
-	// Storage: Promotion TotalStaked (r:1 w:1)
-	// Storage: Promotion StakesPerAccount (r:0 w:1)
+	// Storage: AppPromotion PendingUnstake (r:1 w:1)
+	// Storage: AppPromotion Staked (r:2 w:1)
+	// Storage: Balances Locks (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: AppPromotion TotalStaked (r:1 w:1)
+	// Storage: AppPromotion StakesPerAccount (r:0 w:1)
 	fn unstake() -> Weight {
-		(10_663_000 as Weight)
-			.saturating_add(T::DbWeight::get().reads(5 as Weight))
-			.saturating_add(T::DbWeight::get().writes(4 as Weight))
+		(27_190_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(6 as Weight))
+			.saturating_add(T::DbWeight::get().writes(6 as Weight))
 	}
-	// Storage: Promotion Admin (r:1 w:0)
+	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn sponsor_collection() -> Weight {
-		(10_879_000 as Weight)
+		(11_351_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
-	// Storage: Promotion Admin (r:1 w:0)
+	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn stop_sponsoring_collection() -> Weight {
-		(10_548_000 as Weight)
+		(10_687_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
-	// Storage: Promotion Admin (r:1 w:0)
+	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:0 w:1)
 	fn sponsor_contract() -> Weight {
-		(2_130_000 as Weight)
+		(2_332_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
-	// Storage: Promotion Admin (r:1 w:0)
+	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:1 w:1)
 	fn stop_sponsoring_contract() -> Weight {
-		(3_509_000 as Weight)
+		(3_712_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
@@ -114,66 +118,70 @@
 
 // For backwards compatibility and tests
 impl WeightInfo for () {
-	// Storage: Promotion Admin (r:0 w:1)
+	// Storage: AppPromotion Admin (r:0 w:1)
 	fn set_admin_address() -> Weight {
-		(515_000 as Weight)
+		(5_297_000 as Weight)
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
-	// Storage: Promotion Admin (r:1 w:0)
+	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: ParachainSystem ValidationData (r:1 w:0)
-	// Storage: Promotion NextCalculatedRecord (r:1 w:1)
-	// Storage: Promotion Staked (r:2 w:0)
-	fn payout_stakers() -> Weight {
-		(8_475_000 as Weight)
-			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
+	// Storage: AppPromotion NextCalculatedRecord (r:1 w:1)
+	// Storage: AppPromotion Staked (r:2 w:0)
+	fn payout_stakers(b: u32, ) -> Weight {
+		(8_045_000 as Weight)
+			// Standard Error: 19_000
+			.saturating_add((4_778_000 as Weight).saturating_mul(b as Weight))
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
 	// Storage: System Account (r:1 w:1)
-	// Storage: Promotion StakesPerAccount (r:1 w:1)
+	// Storage: AppPromotion StakesPerAccount (r:1 w:1)
 	// Storage: Balances Locks (r:1 w:1)
 	// Storage: ParachainSystem ValidationData (r:1 w:0)
-	// Storage: Promotion Staked (r:1 w:1)
-	// Storage: Promotion TotalStaked (r:1 w:1)
+	// Storage: AppPromotion Staked (r:1 w:1)
+	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	fn stake() -> Weight {
-		(12_266_000 as Weight)
+		(17_623_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(6 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(5 as Weight))
 	}
-	// Storage: Promotion Staked (r:2 w:1)
-	// Storage: ParachainSystem ValidationData (r:1 w:0)
-	// Storage: Promotion PendingUnstake (r:1 w:1)
-	// Storage: Promotion TotalStaked (r:1 w:1)
-	// Storage: Promotion StakesPerAccount (r:0 w:1)
+	// Storage: AppPromotion PendingUnstake (r:1 w:1)
+	// Storage: AppPromotion Staked (r:2 w:1)
+	// Storage: Balances Locks (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: AppPromotion TotalStaked (r:1 w:1)
+	// Storage: AppPromotion StakesPerAccount (r:0 w:1)
 	fn unstake() -> Weight {
-		(10_663_000 as Weight)
-			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
+		(27_190_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(6 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(6 as Weight))
 	}
-	// Storage: Promotion Admin (r:1 w:0)
+	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn sponsor_collection() -> Weight {
-		(10_879_000 as Weight)
+		(11_351_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
-	// Storage: Promotion Admin (r:1 w:0)
+	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn stop_sponsoring_collection() -> Weight {
-		(10_548_000 as Weight)
+		(10_687_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
-	// Storage: Promotion Admin (r:1 w:0)
+	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:0 w:1)
 	fn sponsor_contract() -> Weight {
-		(2_130_000 as Weight)
+		(2_332_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
-	// Storage: Promotion Admin (r:1 w:0)
+	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:1 w:1)
 	fn stop_sponsoring_contract() -> Weight {
-		(3_509_000 as Weight)
+		(3_712_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
modifiedpallets/common/Cargo.tomldiffbeforeafterboth
--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -40,4 +40,7 @@
     "up-data-structs/std",
     "pallet-evm/std",
 ]
-runtime-benchmarks = ["frame-benchmarking"]
+runtime-benchmarks = [
+    "frame-benchmarking/runtime-benchmarks",
+    "up-data-structs/runtime-benchmarks",
+]
modifiedruntime/common/config/pallets/app_promotion.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/app_promotion.rs
+++ b/runtime/common/config/pallets/app_promotion.rs
@@ -22,7 +22,7 @@
 use frame_support::{parameter_types, PalletId};
 use sp_arithmetic::Perbill;
 use up_common::{
-	constants::{ UNIQUE, RELAY_DAYS},
+	constants::{UNIQUE, RELAY_DAYS},
 	types::Balance,
 };
 
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -680,7 +680,7 @@
                     list_benchmark!(list, extra, pallet_unique, Unique);
                     list_benchmark!(list, extra, pallet_structure, Structure);
                     list_benchmark!(list, extra, pallet_inflation, Inflation);
-                    list_benchmark!(list, extra, pallet_app_promotion, Promotion);
+                    list_benchmark!(list, extra, pallet_app_promotion, AppPromotion);
                     list_benchmark!(list, extra, pallet_fungible, Fungible);
                     list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);
 
@@ -736,7 +736,7 @@
                     add_benchmark!(params, batches, pallet_unique, Unique);
                     add_benchmark!(params, batches, pallet_structure, Structure);
                     add_benchmark!(params, batches, pallet_inflation, Inflation);
-                    add_benchmark!(params, batches, pallet_app_promotion, Promotion);
+                    add_benchmark!(params, batches, pallet_app_promotion, AppPromotion);
                     add_benchmark!(params, batches, pallet_fungible, Fungible);
                     add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);
 
modifiedtests/src/interfaces/augment-api-consts.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-consts.ts
+++ b/tests/src/interfaces/augment-api-consts.ts
@@ -16,10 +16,6 @@
 declare module '@polkadot/api-base/types/consts' {
   interface AugmentedConsts<ApiType extends ApiTypes> {
     appPromotion: {
-      /**
-       * In chain blocks.
-       **/
-      day: u32 & AugmentedConst<ApiType>;
       intervalIncome: Perbill & AugmentedConst<ApiType>;
       nominal: u128 & AugmentedConst<ApiType>;
       /**
modifiedtests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -27,7 +27,7 @@
       /**
        * Insufficient funds to perform an action
        **/
-      NotSufficientFounds: AugmentedError<ApiType>;
+      NotSufficientFunds: AugmentedError<ApiType>;
       PendingForBlockOverflow: AugmentedError<ApiType>;
       /**
        * Generic error
modifiedtests/src/interfaces/augment-api-events.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-events.ts
+++ b/tests/src/interfaces/augment-api-events.ts
@@ -16,7 +16,10 @@
 declare module '@polkadot/api-base/types/events' {
   interface AugmentedEvents<ApiType extends ApiTypes> {
     appPromotion: {
+      SetAdmin: AugmentedEvent<ApiType, [AccountId32]>;
+      Stake: AugmentedEvent<ApiType, [AccountId32, u128]>;
       StakingRecalculation: AugmentedEvent<ApiType, [AccountId32, u128, u128]>;
+      Unstake: AugmentedEvent<ApiType, [AccountId32, u128]>;
       /**
        * Generic event
        **/
modifiedtests/src/interfaces/augment-api-query.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -36,10 +36,6 @@
        * Amount of stakes for an Account
        **/
       stakesPerAccount: AugmentedQuery<ApiType, (arg: AccountId32 | string | Uint8Array) => Observable<u8>, [AccountId32]> & QueryableStorageEntry<ApiType, [AccountId32]>;
-      /**
-       * A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`.
-       **/
-      startBlock: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
       totalStaked: AugmentedQuery<ApiType, () => Observable<u128>, []> & QueryableStorageEntry<ApiType, []>;
       /**
        * Generic query
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -844,17 +844,23 @@
 export interface PalletAppPromotionError extends Enum {
   readonly isAdminNotSet: boolean;
   readonly isNoPermission: boolean;
-  readonly isNotSufficientFounds: boolean;
+  readonly isNotSufficientFunds: boolean;
   readonly isPendingForBlockOverflow: boolean;
   readonly isInvalidArgument: boolean;
-  readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFounds' | 'PendingForBlockOverflow' | 'InvalidArgument';
+  readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFunds' | 'PendingForBlockOverflow' | 'InvalidArgument';
 }
 
 /** @name PalletAppPromotionEvent */
 export interface PalletAppPromotionEvent extends Enum {
   readonly isStakingRecalculation: boolean;
   readonly asStakingRecalculation: ITuple<[AccountId32, u128, u128]>;
-  readonly type: 'StakingRecalculation';
+  readonly isStake: boolean;
+  readonly asStake: ITuple<[AccountId32, u128]>;
+  readonly isUnstake: boolean;
+  readonly asUnstake: ITuple<[AccountId32, u128]>;
+  readonly isSetAdmin: boolean;
+  readonly asSetAdmin: AccountId32;
+  readonly type: 'StakingRecalculation' | 'Stake' | 'Unstake' | 'SetAdmin';
 }
 
 /** @name PalletBalancesAccountData */
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -1061,7 +1061,10 @@
    **/
   PalletAppPromotionEvent: {
     _enum: {
-      StakingRecalculation: '(AccountId32,u128,u128)'
+      StakingRecalculation: '(AccountId32,u128,u128)',
+      Stake: '(AccountId32,u128)',
+      Unstake: '(AccountId32,u128)',
+      SetAdmin: 'AccountId32'
     }
   },
   /**
@@ -3102,7 +3105,7 @@
    * Lookup415: pallet_app_promotion::pallet::Error<T>
    **/
   PalletAppPromotionError: {
-    _enum: ['AdminNotSet', 'NoPermission', 'NotSufficientFounds', 'PendingForBlockOverflow', 'InvalidArgument']
+    _enum: ['AdminNotSet', 'NoPermission', 'NotSufficientFunds', 'PendingForBlockOverflow', 'InvalidArgument']
   },
   /**
    * Lookup418: pallet_evm::pallet::Error<T>
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -1202,7 +1202,13 @@
   interface PalletAppPromotionEvent extends Enum {
     readonly isStakingRecalculation: boolean;
     readonly asStakingRecalculation: ITuple<[AccountId32, u128, u128]>;
-    readonly type: 'StakingRecalculation';
+    readonly isStake: boolean;
+    readonly asStake: ITuple<[AccountId32, u128]>;
+    readonly isUnstake: boolean;
+    readonly asUnstake: ITuple<[AccountId32, u128]>;
+    readonly isSetAdmin: boolean;
+    readonly asSetAdmin: AccountId32;
+    readonly type: 'StakingRecalculation' | 'Stake' | 'Unstake' | 'SetAdmin';
   }
 
   /** @name PalletEvmEvent (104) */
@@ -3290,10 +3296,10 @@
   interface PalletAppPromotionError extends Enum {
     readonly isAdminNotSet: boolean;
     readonly isNoPermission: boolean;
-    readonly isNotSufficientFounds: boolean;
+    readonly isNotSufficientFunds: boolean;
     readonly isPendingForBlockOverflow: boolean;
     readonly isInvalidArgument: boolean;
-    readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFounds' | 'PendingForBlockOverflow' | 'InvalidArgument';
+    readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFunds' | 'PendingForBlockOverflow' | 'InvalidArgument';
   }
 
   /** @name PalletEvmError (418) */