git.delta.rocks / unique-network / refs/commits / 91c34acacac8

difftreelog

Merge pull request #882 from UniqueNetwork/feature/app-promo-unstake-behaviour

Yaroslav Bolyukin2023-02-15parents: #9f4fc06 #803eec0.patch.diff
in: master
Feature/app promo unstake behaviour

14 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5782,7 +5782,7 @@
 
 [[package]]
 name = "pallet-app-promotion"
-version = "0.1.4"
+version = "0.1.5"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
modifiedpallets/app-promotion/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/app-promotion/CHANGELOG.md
+++ b/pallets/app-promotion/CHANGELOG.md
@@ -4,6 +4,12 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.5] - 2023-02-14
+
+### Added
+
+- `unstake_partial` extrinsic.
+
 ## [0.1.4] - 2023-01-31
 
 ### 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.1.4'
+version = '0.1.5'
 
 [package.metadata.docs.rs]
 targets = ['x86_64-unknown-linux-gnu']
modifiedpallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/benchmarking.rs
+++ b/pallets/app-promotion/src/benchmarking.rs
@@ -65,7 +65,7 @@
 			let staker = account::<T::AccountId>("staker", index, SEED);
 			<T as Config>::Currency::make_free_balance_be(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 			PromototionPallet::<T>::stake(RawOrigin::Signed(staker.clone()).into(), Into::<BalanceOf<T>>::into(100u128) * T::Nominal::get())?;
-			PromototionPallet::<T>::unstake(RawOrigin::Signed(staker.clone()).into()).map_err(|e| e.error)?;
+			PromototionPallet::<T>::unstake_all(RawOrigin::Signed(staker.clone()).into())?;
 			Result::<(), sp_runtime::DispatchError>::Ok(())
 		})?;
 		let block_number = <frame_system::Pallet<T>>::current_block_number() + T::PendingInterval::get();
@@ -115,7 +115,7 @@
 		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 	} : _(RawOrigin::Signed(caller.clone()), share * <T as Config>::Currency::total_balance(&caller))
 
-	unstake {
+	unstake_all {
 		let caller = account::<T::AccountId>("caller", 0, SEED);
 		let share = Perbill::from_rational(1u32, 20);
 		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
@@ -130,6 +130,21 @@
 
 	} : _(RawOrigin::Signed(caller.clone()))
 
+	unstake_partial {
+		let caller = account::<T::AccountId>("caller", 0, SEED);
+		let share = Perbill::from_rational(1u32, 20);
+		let _ = <T as Config>::Currency::make_free_balance_be(&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());
+			T::RelayBlockNumberProvider::set_block_number((2*i).into());
+			assert_eq!(<frame_system::Pallet<T>>::block_number(), i.into());
+			assert_eq!(T::RelayBlockNumberProvider::current_block_number(), (2*i).into());
+			PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), Into::<BalanceOf<T>>::into(100u128) * T::Nominal::get())
+		}).collect::<Result<Vec<_>, _>>()?;
+
+	} : _(RawOrigin::Signed(caller.clone()), Into::<BalanceOf<T>>::into(1000u128) * T::Nominal::get())
+
 	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()))?;
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -72,7 +72,7 @@
 	traits::{
 		Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,
 	},
-	ensure,
+	ensure, BoundedVec,
 };
 
 use weights::WeightInfo;
@@ -156,7 +156,7 @@
 	pub struct Pallet<T>(_);
 
 	#[pallet::event]
-	#[pallet::generate_deposit(fn deposit_event)]
+	#[pallet::generate_deposit(pub(super) fn deposit_event)]
 	pub enum Event<T: Config> {
 		/// Staking recalculation was performed
 		///
@@ -208,6 +208,8 @@
 		SponsorNotSet,
 		/// Errors caused by incorrect actions with a locked balance.
 		IncorrectLockedBalanceOperation,
+		/// Errors caused by insufficient staked balance.
+		InsufficientStakedBalance,
 	}
 
 	/// Stores the total staked amount.
@@ -489,53 +491,30 @@
 		}
 
 		/// Unstakes all stakes.
-		/// Moves the sum of all stakes to the `reserved` state.
 		/// After the end of `PendingInterval` this sum becomes completely
 		/// free for further use.
 		#[pallet::call_index(2)]
-		#[pallet::weight(<T as Config>::WeightInfo::unstake())]
-		pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {
+		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]
+		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {
 			let staker_id = ensure_signed(staker)?;
-			let config = <PalletConfiguration<T>>::get();
 
-			// calculate block number where the sum would be free
-			let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;
+			Self::unstake_all_internal(staker_id)
+		}
 
-			let mut pendings = <PendingUnstake<T>>::get(block);
-
-			// checks that we can do unreserve stakes in the block
-			ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);
-
-			let mut total_stakes = 0u64;
-
-			let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))
-				.map(|(_, (amount, _))| {
-					total_stakes += 1;
-					amount
-				})
-				.sum();
+		/// Unstakes the amount of balance for the staker.
+		/// After the end of `PendingInterval` this sum becomes completely
+		/// free for further use.
+		///
+		///  # Arguments
+		///
+		/// * `staker`: staker account.
+		/// * `amount`: amount of unstaked funds.
+		#[pallet::call_index(8)]
+		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]
+		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {
+			let staker_id = ensure_signed(staker)?;
 
-			if total_staked.is_zero() {
-				return Ok(None::<Weight>.into()); // TO-DO
-			}
-
-			pendings
-				.try_push((staker_id.clone(), total_staked))
-				.map_err(|_| Error::<T>::PendingForBlockOverflow)?;
-
-			<PendingUnstake<T>>::insert(block, pendings);
-
-			TotalStaked::<T>::set(
-				TotalStaked::<T>::get()
-					.checked_sub(&total_staked)
-					.ok_or(ArithmeticError::Underflow)?,
-			);
-
-			StakesPerAccount::<T>::remove(&staker_id);
-
-			Self::deposit_event(Event::Unstake(staker_id, total_staked));
-
-			Ok(None::<Weight>.into())
+			Self::unstake_partial_internal(staker_id, amount)
 		}
 
 		/// Sets the pallet to be the sponsor for the collection.
@@ -809,6 +788,100 @@
 		T::PalletId::get().into_account_truncating()
 	}
 
+	/// Unstakes the balance for the staker.
+	///
+	/// - `staker`: staker account.
+	/// - `amount`: amount of unstaked funds.
+	fn unstake_partial_internal(
+		staker_id: T::AccountId,
+		unstaked_balance: BalanceOf<T>,
+	) -> DispatchResult {
+		if unstaked_balance == Default::default() {
+			return Ok(());
+		}
+
+		let config = <PalletConfiguration<T>>::get();
+
+		// calculate block number where the sum would be free
+		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;
+
+		let mut pendings = <PendingUnstake<T>>::get(unpending_block);
+
+		// checks that we can do unstake in the block
+		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);
+
+		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();
+
+		let total_staked = stakes
+			.iter()
+			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {
+				acc + *balance
+			});
+
+		ensure!(
+			unstaked_balance <= total_staked,
+			<Error<T>>::InsufficientStakedBalance
+		);
+
+		<TotalStaked<T>>::set(
+			<TotalStaked<T>>::get()
+				.checked_sub(&unstaked_balance)
+				.ok_or(ArithmeticError::Underflow)?,
+		);
+
+		stakes.sort_by_key(|(block, _)| *block);
+
+		let mut acc_amount = unstaked_balance;
+		let mut will_deleted_stakes_count = 0u8;
+
+		let changed_stakes = stakes
+			.into_iter()
+			.map_while(|(block, (balance_per_block, _))| {
+				if acc_amount == <BalanceOf<T>>::default() {
+					return None;
+				}
+				if acc_amount < balance_per_block {
+					let res = (block, balance_per_block - acc_amount);
+					acc_amount = <BalanceOf<T>>::default();
+					return Some(res);
+				} else {
+					acc_amount -= balance_per_block;
+					will_deleted_stakes_count += 1;
+					return Some((block, <BalanceOf<T>>::default()));
+				}
+			})
+			.collect::<Vec<_>>();
+
+		pendings
+			.try_push((staker_id.clone(), unstaked_balance))
+			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;
+
+		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {
+			*stakes = stakes
+				.checked_sub(will_deleted_stakes_count)
+				.ok_or(ArithmeticError::Underflow)?;
+			Ok(())
+		})?;
+
+		changed_stakes
+			.into_iter()
+			.for_each(|(staked_block, current_stake_state)| {
+				if current_stake_state == Default::default() {
+					<Staked<T>>::remove((&staker_id, staked_block));
+				} else {
+					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {
+						*old_stake_state = current_stake_state
+					});
+				}
+			});
+
+		<PendingUnstake<T>>::insert(unpending_block, pendings);
+
+		Self::deposit_event(Event::Unstake(staker_id, total_staked));
+
+		Ok(())
+	}
+
 	/// Adds the balance to locked by the pallet.
 	///
 	/// - `staker`: staker account.
@@ -1005,4 +1078,47 @@
 		unsorted_res.sort_by_key(|(block, _)| *block);
 		unsorted_res
 	}
+
+	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {
+		let config = <PalletConfiguration<T>>::get();
+
+		// calculate block number where the sum would be free
+		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;
+
+		let mut pendings = <PendingUnstake<T>>::get(block);
+
+		// checks that we can do unstake in the block
+		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);
+
+		let mut total_stakes = 0u64;
+
+		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))
+			.map(|(_, (amount, _))| {
+				total_stakes += 1;
+				amount
+			})
+			.sum();
+
+		if total_staked.is_zero() {
+			return Ok(());
+		}
+
+		pendings
+			.try_push((staker_id.clone(), total_staked))
+			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;
+
+		<PendingUnstake<T>>::insert(block, pendings);
+
+		TotalStaked::<T>::set(
+			TotalStaked::<T>::get()
+				.checked_sub(&total_staked)
+				.ok_or(ArithmeticError::Underflow)?,
+		);
+
+		StakesPerAccount::<T>::remove(&staker_id);
+
+		Self::deposit_event(Event::Unstake(staker_id, total_staked));
+
+		Ok(())
+	}
 }
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-12-25, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2023-02-15, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
 //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
 
 // Executed Command:
@@ -38,7 +38,8 @@
 	fn set_admin_address() -> Weight;
 	fn payout_stakers(b: u32, ) -> Weight;
 	fn stake() -> Weight;
-	fn unstake() -> Weight;
+	fn unstake_all() -> Weight;
+	fn unstake_partial() -> Weight;
 	fn sponsor_collection() -> Weight;
 	fn stop_sponsoring_collection() -> Weight;
 	fn sponsor_contract() -> Weight;
@@ -49,18 +50,19 @@
 pub struct SubstrateWeight<T>(PhantomData<T>);
 impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
 	// Storage: AppPromotion PendingUnstake (r:1 w:0)
+	// Storage: Balances Locks (r:1 w:1)
 	// Storage: System Account (r:1 w:1)
 	fn on_initialize(b: u32, ) -> Weight {
-		Weight::from_ref_time(3_079_948 as u64)
-			// Standard Error: 30_376
-			.saturating_add(Weight::from_ref_time(6_343_630 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(2_592_346 as u64)
+			// Standard Error: 23_629
+			.saturating_add(Weight::from_ref_time(7_523_802 as u64).saturating_mul(b as u64))
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
-			.saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(b as u64)))
-			.saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(b as u64)))
+			.saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(b as u64)))
+			.saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(b as u64)))
 	}
 	// Storage: AppPromotion Admin (r:0 w:1)
 	fn set_admin_address() -> Weight {
-		Weight::from_ref_time(6_653_000 as u64)
+		Weight::from_ref_time(6_209_000 as u64)
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
@@ -72,9 +74,9 @@
 	// Storage: Balances Locks (r:1 w:1)
 	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	fn payout_stakers(b: u32, ) -> Weight {
-		Weight::from_ref_time(74_048_000 as u64)
-			// Standard Error: 33_223
-			.saturating_add(Weight::from_ref_time(57_702_092 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(64_917_000 as u64)
+			// Standard Error: 34_206
+			.saturating_add(Weight::from_ref_time(51_518_500 as u64).saturating_mul(b as u64))
 			.saturating_add(T::DbWeight::get().reads(7 as u64))
 			.saturating_add(T::DbWeight::get().reads((12 as u64).saturating_mul(b as u64)))
 			.saturating_add(T::DbWeight::get().writes(3 as u64))
@@ -88,47 +90,55 @@
 	// Storage: AppPromotion Staked (r:1 w:1)
 	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	fn stake() -> Weight {
-		Weight::from_ref_time(20_314_000 as u64)
+		Weight::from_ref_time(18_208_000 as u64)
 			.saturating_add(T::DbWeight::get().reads(7 as u64))
 			.saturating_add(T::DbWeight::get().writes(5 as u64))
 	}
 	// Storage: Configuration AppPromomotionConfigurationOverride (r:1 w:0)
 	// Storage: AppPromotion PendingUnstake (r:1 w:1)
 	// Storage: AppPromotion Staked (r:11 w:10)
-	// 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 {
-		Weight::from_ref_time(64_582_000 as u64)
-			.saturating_add(T::DbWeight::get().reads(16 as u64))
-			.saturating_add(T::DbWeight::get().writes(15 as u64))
+	fn unstake_all() -> Weight {
+		Weight::from_ref_time(45_018_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(14 as u64))
+			.saturating_add(T::DbWeight::get().writes(13 as u64))
+	}
+	// Storage: Configuration AppPromomotionConfigurationOverride (r:1 w:0)
+	// Storage: AppPromotion PendingUnstake (r:1 w:1)
+	// Storage: AppPromotion Staked (r:11 w:10)
+	// Storage: AppPromotion TotalStaked (r:1 w:1)
+	// Storage: AppPromotion StakesPerAccount (r:1 w:1)
+	fn unstake_partial() -> Weight {
+		Weight::from_ref_time(49_066_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(15 as u64))
+			.saturating_add(T::DbWeight::get().writes(13 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn sponsor_collection() -> Weight {
-		Weight::from_ref_time(16_364_000 as u64)
+		Weight::from_ref_time(15_039_000 as u64)
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn stop_sponsoring_collection() -> Weight {
-		Weight::from_ref_time(15_710_000 as u64)
+		Weight::from_ref_time(14_692_000 as u64)
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:0 w:1)
 	fn sponsor_contract() -> Weight {
-		Weight::from_ref_time(12_669_000 as u64)
+		Weight::from_ref_time(11_810_000 as u64)
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:1 w:1)
 	fn stop_sponsoring_contract() -> Weight {
-		Weight::from_ref_time(14_406_000 as u64)
+		Weight::from_ref_time(13_570_000 as u64)
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
@@ -137,18 +147,19 @@
 // For backwards compatibility and tests
 impl WeightInfo for () {
 	// Storage: AppPromotion PendingUnstake (r:1 w:0)
+	// Storage: Balances Locks (r:1 w:1)
 	// Storage: System Account (r:1 w:1)
 	fn on_initialize(b: u32, ) -> Weight {
-		Weight::from_ref_time(3_079_948 as u64)
-			// Standard Error: 30_376
-			.saturating_add(Weight::from_ref_time(6_343_630 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(2_592_346 as u64)
+			// Standard Error: 23_629
+			.saturating_add(Weight::from_ref_time(7_523_802 as u64).saturating_mul(b as u64))
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
-			.saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(b as u64)))
-			.saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(b as u64)))
+			.saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(b as u64)))
+			.saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(b as u64)))
 	}
 	// Storage: AppPromotion Admin (r:0 w:1)
 	fn set_admin_address() -> Weight {
-		Weight::from_ref_time(6_653_000 as u64)
+		Weight::from_ref_time(6_209_000 as u64)
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
@@ -160,9 +171,9 @@
 	// Storage: Balances Locks (r:1 w:1)
 	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	fn payout_stakers(b: u32, ) -> Weight {
-		Weight::from_ref_time(74_048_000 as u64)
-			// Standard Error: 33_223
-			.saturating_add(Weight::from_ref_time(57_702_092 as u64).saturating_mul(b as u64))
+		Weight::from_ref_time(64_917_000 as u64)
+			// Standard Error: 34_206
+			.saturating_add(Weight::from_ref_time(51_518_500 as u64).saturating_mul(b as u64))
 			.saturating_add(RocksDbWeight::get().reads(7 as u64))
 			.saturating_add(RocksDbWeight::get().reads((12 as u64).saturating_mul(b as u64)))
 			.saturating_add(RocksDbWeight::get().writes(3 as u64))
@@ -176,47 +187,55 @@
 	// Storage: AppPromotion Staked (r:1 w:1)
 	// Storage: AppPromotion TotalStaked (r:1 w:1)
 	fn stake() -> Weight {
-		Weight::from_ref_time(20_314_000 as u64)
+		Weight::from_ref_time(18_208_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(7 as u64))
 			.saturating_add(RocksDbWeight::get().writes(5 as u64))
 	}
 	// Storage: Configuration AppPromomotionConfigurationOverride (r:1 w:0)
 	// Storage: AppPromotion PendingUnstake (r:1 w:1)
 	// Storage: AppPromotion Staked (r:11 w:10)
-	// 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 {
-		Weight::from_ref_time(64_582_000 as u64)
-			.saturating_add(RocksDbWeight::get().reads(16 as u64))
-			.saturating_add(RocksDbWeight::get().writes(15 as u64))
+	fn unstake_all() -> Weight {
+		Weight::from_ref_time(45_018_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(14 as u64))
+			.saturating_add(RocksDbWeight::get().writes(13 as u64))
 	}
+	// Storage: Configuration AppPromomotionConfigurationOverride (r:1 w:0)
+	// Storage: AppPromotion PendingUnstake (r:1 w:1)
+	// Storage: AppPromotion Staked (r:11 w:10)
+	// Storage: AppPromotion TotalStaked (r:1 w:1)
+	// Storage: AppPromotion StakesPerAccount (r:1 w:1)
+	fn unstake_partial() -> Weight {
+		Weight::from_ref_time(49_066_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(15 as u64))
+			.saturating_add(RocksDbWeight::get().writes(13 as u64))
+	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn sponsor_collection() -> Weight {
-		Weight::from_ref_time(16_364_000 as u64)
+		Weight::from_ref_time(15_039_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn stop_sponsoring_collection() -> Weight {
-		Weight::from_ref_time(15_710_000 as u64)
+		Weight::from_ref_time(14_692_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:0 w:1)
 	fn sponsor_contract() -> Weight {
-		Weight::from_ref_time(12_669_000 as u64)
+		Weight::from_ref_time(11_810_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
 	// Storage: AppPromotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:1 w:1)
 	fn stop_sponsoring_contract() -> Weight {
-		Weight::from_ref_time(14_406_000 as u64)
+		Weight::from_ref_time(13_570_000 as u64)
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -24,7 +24,10 @@
 	CommonCollectionOperations,
 };
 use sp_std::prelude::*;
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited};
+use up_data_structs::{
+	CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited,
+	PropertyPermission,
+};
 
 const SEED: u32 = 1;
 
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -25,7 +25,10 @@
 	benchmarking::{create_collection_raw, property_key, property_value},
 };
 use sp_std::prelude::*;
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited};
+use up_data_structs::{
+	CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited,
+	PropertyPermission,
+};
 
 const SEED: u32 = 1;
 
modifiedtests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth
after · tests/src/sub/appPromotion/appPromotion.test.ts
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/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {19  itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip, LOCKING_PERIOD, UNLOCKING_PERIOD,20} from '../../util';21import {DevUniqueHelper} from '../../util/playgrounds/unique.dev';22import {itEth, expect, SponsoringMode} from '../../eth/util';2324let donor: IKeyringPair;25let palletAdmin: IKeyringPair;26let nominal: bigint;27let palletAddress: string;28let accounts: IKeyringPair[];29let usedAccounts: IKeyringPair[] = [];3031function getAccount(accountsNumber: number) {32  const accs = accounts.splice(0, accountsNumber);33  usedAccounts.push(...accs);34  return accs;35}36// App promotion periods:37// LOCKING_PERIOD = 12 blocks of relay38// UNLOCKING_PERIOD = 6 blocks of parachain3940describe('App promotion', () => {41  before(async function () {42    await usingPlaygrounds(async (helper, privateKey) => {43      requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);44      donor = await privateKey({filename: __filename});45      palletAddress = helper.arrange.calculatePalletAddress('appstake');46      palletAdmin = await privateKey('//PromotionAdmin');47      nominal = helper.balance.getOneTokenNominal();4849      const accountBalances = new Array(200).fill(1000n);50      accounts = await helper.arrange.createAccounts(accountBalances, donor); // create accounts-pool to speed up tests51    });52  });5354  afterEach(async () => {55    await usingPlaygrounds(async (helper) => {56      let unstakeTxs = [];57      for (const account of usedAccounts) {58        if (unstakeTxs.length === 3) {59          await Promise.all(unstakeTxs);60          unstakeTxs = [];61        }62        unstakeTxs.push(helper.staking.unstakeAll(account));63      }64      await Promise.all(unstakeTxs);65      usedAccounts = [];66    });67  });6869  describe('stake extrinsic', () => {70    itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {71      const [staker, recepient] = getAccount(2);72      const totalStakedBefore = await helper.staking.getTotalStaked();7374      // Minimum stake amount is 100:75      await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;76      await helper.staking.stake(staker, 100n * nominal);7778      // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...79      // ...so he can not transfer 90080      expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});81      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: 100n * nominal, reasons: 'All'}]);82      await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');8384      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);85      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);86      // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?87      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased888990      await helper.staking.stake(staker, 200n * nominal);91      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);92      const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});93      expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);94      expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);95    });9697    [98      {unstake: 'unstakeAll' as const},99      {unstake: 'unstakePartial' as const},100    ].map(testCase => {101      itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {102        const [staker] = await helper.arrange.createAccounts([2000n], donor);103        const ONE_STAKE = 100n * nominal;104        for (let i = 0; i < 10; i++) {105          await helper.staking.stake(staker, ONE_STAKE);106        }107108        // can have 10 stakes109        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);110        expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);111112        await expect(helper.staking.stake(staker, ONE_STAKE)).to.be.rejectedWith('appPromotion.NoPermission');113114        // After unstake can stake again115116        // CASE 1: unstakeAll117        if (testCase.unstake === 'unstakeAll') {118          await helper.staking.unstakeAll(staker);119          expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);120          await helper.staking.stake(staker, 100n * nominal);121          expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);122        }123        // CASE 2: unstakePartial124        else {125          await helper.staking.unstakePartial(staker, ONE_STAKE);126          expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);127          await helper.staking.stake(staker, 100n * nominal);128          expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(10);129          await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');130          await helper.staking.unstakePartial(staker, 150n * nominal);131          expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);132          expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(850n * nominal);133        }134      });135    });136137    itSub('should allow to stake() if balance is locked with different id', async ({helper}) => {138      const [staker] = getAccount(1);139140      // staker has tokens locked with vesting id:141      await helper.balance.vestedTransfer(donor, staker.address, {start: 0n, period: 1n, periodCount: 1n, perPeriod: 200n * nominal});142      expect(await helper.balance.getSubstrateFull(staker.address))143        .to.deep.contain({free: 1200n * nominal, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal, reserved: 0n});144145      // Locked balance can be staked. staker can stake 1200 tokens (minus fee):146      await helper.staking.stake(staker, 1000n * nominal);147      await helper.staking.stake(staker, 199n * nominal);148      // check balances149      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}, {id: 'appstake', amount: 1199n * nominal, reasons: 'All'}]);150      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 1199n * nominal, feeFrozen: 1199n * nominal});151      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);152      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(1199n * nominal);153154      // staker can unstake155      await helper.staking.unstakeAll(staker);156      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1199n * nominal);157      const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});158      await helper.wait.forParachainBlockNumber(pendingUnstake.block);159160      // check balances161      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}]);162      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal});163      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);164      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);165166      // staker can transfer balances now167      await helper.balance.transferToSubstrate(staker, donor.address, 900n * nominal);168    });169170    itSub('should not allow to stake(), if stake amount is more than total free balance minus locked by staking', async ({helper}) => {171      const [staker] = getAccount(1);172173      // Can't stake full balance because Alice needs to pay some fee174      await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected; // With('Arithmetic')175      await helper.staking.stake(staker, 500n * nominal);176177      // Can't stake 500 tkn because Alice has Less than 500 transferable;178      await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejected; // With('Arithmetic');179      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);180    });181182    itSub('for different accounts in one block is possible', async ({helper}) => {183      const crowd = getAccount(4);184185      const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));186      await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;187188      const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));189      expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);190    });191  });192193  describe('Unstaking', () => {194    [195      {method: 'unstakeAll' as const},196      {method: 'unstakePartial' as const},197    ].map(testCase => {198      itSub(`[${testCase.method}] should move tokens to "pendingUnstake" and subtract it from totalStaked`, async ({helper}) => {199        const [staker, recepient] = getAccount(2);200        const totalStakedBefore = await helper.staking.getTotalStaked();201        const STAKE_AMOUNT = 900n * nominal;202203        await helper.staking.stake(staker, STAKE_AMOUNT);204        testCase.method === 'unstakeAll'205          ? await helper.staking.unstakeAll(staker)206          : await helper.staking.unstakePartial(staker, STAKE_AMOUNT);207208        // Right after unstake tokens are still locked209        expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);210        expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: STAKE_AMOUNT, reasons: 'All'}]);211        expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: STAKE_AMOUNT, feeFrozen: STAKE_AMOUNT});212        // Staker can not transfer213        await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');214        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(STAKE_AMOUNT);215        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);216        expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);217      });218    });219220    [221      {method: 'unstakeAll' as const},222      {method: 'unstakePartial' as const},223    ].map(testCase => {224      itSub(`[${testCase.method}] should unlock balance after unlocking period ends and remove it from "pendingUnstake"`, async ({helper}) => {225        const [staker] = getAccount(1);226        await helper.staking.stake(staker, 100n * nominal);227        testCase.method === 'unstakeAll'228          ? await helper.staking.unstakeAll(staker)229          : await helper.staking.unstakePartial(staker, 100n * nominal);230        const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});231232        // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n233        await helper.wait.forParachainBlockNumber(pendingUnstake.block);234        expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});235        expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);236237        // staker can transfer:238        await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);239        expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);240      });241    });242243    [244      {method: 'unstakeAll' as const},245      {method: 'unstakePartial' as const},246    ].map(testCase => {247      itSub(`[${testCase.method}] should successfully unstake multiple stakes`, async ({helper}) => {248        const [staker] = getAccount(1);249        await helper.staking.stake(staker, 100n * nominal);250        await helper.staking.stake(staker, 200n * nominal);251        await helper.staking.stake(staker, 300n * nominal);252253        // staked: [100, 200, 300]; unstaked: 0254        let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});255        let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});256        let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});257        expect(totalPendingUnstake).to.be.deep.equal(0n);258        expect(pendingUnstake).to.be.deep.equal([]);259        expect(stakes[0].amount).to.equal(100n * nominal);260        expect(stakes[1].amount).to.equal(200n * nominal);261        expect(stakes[2].amount).to.equal(300n * nominal);262263        // Can unstake multiple stakes264        testCase.method === 'unstakeAll'265          ? await helper.staking.unstakeAll(staker)266          : await helper.staking.unstakePartial(staker, 600n * nominal);267268        pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});269        totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});270        stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});271        expect(totalPendingUnstake).to.be.equal(600n * nominal);272        expect(stakes).to.be.deep.equal([]);273        expect(pendingUnstake[0].amount).to.equal(600n * nominal);274275        expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});276        expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);277        await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);278        expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});279        expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);280      });281    });282283    [284      {method: 'unstakeAll' as const},285      {method: 'unstakePartial' as const},286    ].map(testCase => {287      itSub(`[${testCase.method}] should not have any effects if no active stakes`, async ({helper}) => {288        const [staker] = getAccount(1);289290        // unstake has no effect if no stakes at all291        testCase.method === 'unstakeAll'292          ? await helper.staking.unstakeAll(staker)293          : await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');294295        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);296        expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper297298        // TODO stake() unstake() waitUnstaked() unstake();299300        // can't unstake if there are only pendingUnstakes301        await helper.staking.stake(staker, 100n * nominal);302303        if (testCase.method === 'unstakeAll') {304          await helper.staking.unstakeAll(staker);305          await helper.staking.unstakeAll(staker);306        } else {307          await helper.staking.unstakePartial(staker, 100n * nominal);308          await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');309        }310311        expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);312        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);313        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);314      });315    });316317    [318      {method: 'unstakeAll' as const},319      {method: 'unstakePartial' as const},320    ].map(testCase => {321      itSub(`[${testCase.method}] should create different pending-unlock for each unlocking stake`, async ({helper}) => {322        const [staker] = getAccount(1);323        await helper.staking.stake(staker, 100n * nominal);324        testCase.method === 'unstakeAll'325          ? await helper.staking.unstakeAll(staker)326          : await helper.staking.unstakePartial(staker, 100n * nominal);327        await helper.staking.stake(staker, 120n * nominal);328        testCase.method === 'unstakeAll'329          ? await helper.staking.unstakeAll(staker)330          : await helper.staking.unstakePartial(staker, 120n * nominal);331332        const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});333        expect(unstakingPerBlock).has.length(2);334        expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);335        expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);336        expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.equal(0);337      });338    });339340    [341      {method: 'unstakeAll' as const},342      {method: 'unstakePartial' as const},343    ].map(testCase => {344      itSub(`[${testCase.method}] should be possible for 3 accounts in one block`, async ({helper}) => {345        const stakers = getAccount(3);346347        await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));348        await Promise.all(stakers.map(staker => {349          return testCase.method === 'unstakeAll'350            ? helper.staking.unstakeAll(staker)351            : helper.staking.unstakePartial(staker, 100n * nominal);352        }));353354        await Promise.all(stakers.map(async (staker) => {355          expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);356          expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);357        }));358      });359    });360361    itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {362      if (!await helper.arrange.isDevNode()) {363        const stakers = getAccount(10);364365        await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));366        const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => {367          return i % 2 === 0368            ? helper.staking.unstakeAll(staker)369            : helper.staking.unstakePartial(staker, 100n * nominal);370        }));371372        const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');373        expect(successfulUnstakes).to.have.length(3);374      }375    });376377    itSub('Cannot partially unstake more than staked', async ({helper}) => {378      const [staker] = getAccount(1);379      // Staker stakes 300:380      await helper.staking.stake(staker, 100n * nominal);381      await helper.staking.stake(staker, 200n * nominal);382383      // cannot usntake 300.00000...1384      await expect(helper.staking.unstakePartial(staker, 300n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');385      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(2);386387      await helper.staking.unstakePartial(staker, 150n * nominal);388      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);389      await expect(helper.staking.unstakePartial(staker, 150n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');390      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);391392      // nothing broken, can unstake full amount:393      await helper.staking.unstakePartial(staker, 150n * nominal);394      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(0);395    });396397    itSub('Can partially unstake arbitrary amount', async ({helper}) => {398      const [staker] = getAccount(1);399      await helper.staking.stake(staker, 100n * nominal);400      await helper.staking.stake(staker, 200n * nominal);401402      // 0. Staker cannot unstake negative amount403      await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;404405      // 1. Staker can unstake 0 wei406      await helper.staking.unstakePartial(staker, 0n);407      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);408      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal);409      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);410411      // 2. Staker can unstake 1 wei412      await helper.staking.unstakePartial(staker, 1n);413      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);414      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal - 1n);415      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1n);416      // 2.1 The oldest stake decreased:417      let [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});418      expect(stake1.amount).to.eq(100n * nominal - 1n);419      expect(stake2.amount).to.eq(200n * nominal);420421      // 3. Staker can unstake all but 1 wei422      await helper.staking.unstakePartial(staker, 100n * nominal - 2n);423      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);424      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(200n * nominal + 1n);425      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(100n * nominal - 1n);426      [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});427      expect(stake1.amount).to.eq(1n);428      expect(stake2.amount).to.eq(200n * nominal);429    });430431    itSub('can mix different type of unstakes', async ({helper}) => {432      const [staker] = getAccount(1);433      await helper.staking.stake(staker, 100n * nominal);434      await helper.staking.stake(staker, 200n * nominal);435436      await helper.staking.unstakePartial(staker, 50n * nominal);437      await helper.staking.unstakeAll(staker);438      expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);439      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);440      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(300n * nominal);441442      const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});443      await helper.wait.forParachainBlockNumber(unstake2.block);444445      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([]);446      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});447      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);448      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);449      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);450      expect(await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).to.deep.eq([]);451    });452  });453454  describe('collection sponsoring', () => {455    itSub('should actually sponsor transactions', async ({helper}) => {456      const api = helper.getApi();457      const [collectionOwner, tokenSender, receiver] = getAccount(3);458      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});459      const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});460      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));461      const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);462463      await token.transfer(tokenSender, {Substrate: receiver.address});464      expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});465      const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);466467      // senders balance the same, transaction has sponsored468      expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);469      expect (palletBalanceBefore > palletBalanceAfter).to.be.true;470    });471472    itSub('can not be set by non admin', async ({helper}) => {473      const api = helper.getApi();474      const [collectionOwner, nonAdmin] = getAccount(2);475476      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});477478      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;479      expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');480    });481482    itSub('should set pallet address as confirmed admin', async ({helper}) => {483      const api = helper.getApi();484      const [collectionOwner, oldSponsor] = getAccount(2);485486      // Can set sponsoring for collection without sponsor487      const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});488      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;489      expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});490491      // Can set sponsoring for collection with unconfirmed sponsor492      const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});493      expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});494      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;495      expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});496497      // Can set sponsoring for collection with confirmed sponsor498      const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});499      await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);500      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;501      expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});502    });503504    itSub('can be overwritten by collection owner', async ({helper}) => {505      const api = helper.getApi();506      const [collectionOwner, newSponsor] = getAccount(2);507      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});508      const collectionId = collection.collectionId;509510      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;511512      // Collection limits still can be changed by the owner513      expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;514      expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);515      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});516517      // Collection sponsor can be changed too518      expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;519      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});520    });521522    itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {523      const api = helper.getApi();524      const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};525      const collectionWithLimits = await helper.nft.mintCollection(getAccount(1)[0], {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});526527      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;528      expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);529    });530531    itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {532      const api = helper.getApi();533      const [collectionOwner] = getAccount(1);534535      // collection has never existed536      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;537      // collection has been burned538      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});539      await collection.burn(collectionOwner);540541      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;542    });543  });544545  describe('stopSponsoringCollection', () => {546    itSub('can not be called by non-admin', async ({helper}) => {547      const api = helper.getApi();548      const [collectionOwner, nonAdmin] = getAccount(2);549      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});550551      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;552553      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;554      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});555    });556557    itSub('should set sponsoring as disabled', async ({helper}) => {558      const api = helper.getApi();559      const [collectionOwner, recepient] = getAccount(2);560      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});561      const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});562563      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));564      await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));565566      expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');567568      // Transactions are not sponsored anymore:569      const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);570      await token.transfer(collectionOwner, {Substrate: recepient.address});571      const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);572      expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);573    });574575    itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {576      const api = helper.getApi();577      const [collectionOwner] = getAccount(1);578      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});579      await collection.confirmSponsorship(collectionOwner);580581      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;582583      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});584    });585586    itSub('should reject transaction if collection does not exist', async ({helper}) => {587      const [collectionOwner] = getAccount(1);588      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});589590      await collection.burn(collectionOwner);591      await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');592      await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');593    });594  });595596  describe('contract sponsoring', () => {597    itEth('should set palletes address as a sponsor', async ({helper}) => {598      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();599      const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);600      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);601602      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);603604      expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;605      expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);606      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({607        confirmed: {608          substrate: palletAddress,609        },610      });611    });612613    itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {614      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();615      const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);616      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);617618      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;619620      // Contract is self sponsored621      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({622        confirmed: {623          ethereum: flipper.options.address.toLowerCase(),624        },625      });626627      // set promotion sponsoring628      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);629630      // new sponsor is pallet address631      expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;632      expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);633      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({634        confirmed: {635          substrate: palletAddress,636        },637      });638    });639640    itEth('can be overwritten by contract owner', async ({helper}) => {641      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();642      const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);643      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);644645      // contract sponsored by pallet646      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);647648      // owner sets self sponsoring649      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;650651      expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;652      expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);653      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({654        confirmed: {655          ethereum: flipper.options.address.toLowerCase(),656        },657      });658    });659660    itEth('can not be set by non admin', async ({helper}) => {661      const [nonAdmin] = getAccount(1);662      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();663      const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);664      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);665666      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;667668      // nonAdmin calls sponsorContract669      await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');670671      // contract still self-sponsored672      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({673        confirmed: {674          ethereum: flipper.options.address.toLowerCase(),675        },676      });677    });678679    itEth('should actually sponsor transactions', async ({helper}) => {680      // Contract caller681      const caller = await helper.eth.createAccountWithBalance(donor, 1000n);682      const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);683684      // Deploy flipper685      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();686      const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);687      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);688689      // Owner sets to sponsor every tx690      await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});691      await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});692      await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);693694      // Set promotion to the Flipper695      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);696697      // Caller calls Flipper698      await flipper.methods.flip().send({from: caller});699      expect(await flipper.methods.getValue().call()).to.be.true;700701      // The contracts and caller balances have not changed702      const callerBalance = await helper.balance.getEthereum(caller);703      const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);704      expect(callerBalance).to.be.equal(1000n * nominal);705      expect(1000n * nominal === contractBalanceAfter).to.be.true;706707      // The pallet balance has decreased708      const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);709      expect(palletBalanceAfter < palletBalanceBefore).to.be.true;710    });711  });712713  describe('stopSponsoringContract', () => {714    itEth('should remove pallet address from contract sponsors', async ({helper}) => {715      const caller = await helper.eth.createAccountWithBalance(donor, 1000n);716      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();717      const flipper = await helper.eth.deployFlipper(contractOwner);718      await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);719      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);720721      await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});722      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);723      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);724725      expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;726      expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);727      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({728        disabled: null,729      });730731      await flipper.methods.flip().send({from: caller});732      expect(await flipper.methods.getValue().call()).to.be.true;733734      const callerBalance = await helper.balance.getEthereum(caller);735      const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);736737      // caller payed for call738      expect(1000n * nominal > callerBalance).to.be.true;739      expect(contractBalanceAfter).to.be.equal(100n * nominal);740    });741742    itEth('can not be called by non-admin', async ({helper}) => {743      const [nonAdmin] = getAccount(1);744      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();745      const flipper = await helper.eth.deployFlipper(contractOwner);746747      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);748      await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))749        .to.be.rejectedWith(/appPromotion\.NoPermission/);750    });751752    itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {753      const [nonAdmin] = getAccount(1);754      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();755      const flipper = await helper.eth.deployFlipper(contractOwner);756      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);757      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;758759      await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');760    });761  });762763  describe('payoutStakers', () => {764    itSub('can not be called by non admin', async ({helper}) => {765      const [nonAdmin] = getAccount(1);766      await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');767    });768769    itSub('should increase total staked', async ({helper}) => {770      const [staker] = getAccount(1);771      const totalStakedBefore = await helper.staking.getTotalStaked();772      await helper.staking.stake(staker, 100n * nominal);773774      // Wait for rewards and pay775      const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});776      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));777      const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);778779      const totalStakedAfter = await helper.staking.getTotalStaked();780      expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);781      // staker can unstake782      await helper.staking.unstakeAll(staker);783      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));784    });785786    itSub('should credit 0.05% for staking period', async ({helper}) => {787      const [staker] = getAccount(1);788789      await waitPromotionPeriodDoesntEnd(helper);790791      await helper.staking.stake(staker, 100n * nominal);792      await helper.staking.stake(staker, 200n * nominal);793794      // wait rewards are available:795      const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});796      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));797798      const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)?.payout;799      expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal));800801      const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});802      const income1 = calculateIncome(100n * nominal);803      const income2 = calculateIncome(200n * nominal);804      expect(totalStakedPerBlock[0].amount).to.equal(income1);805      expect(totalStakedPerBlock[1].amount).to.equal(income2);806807      const stakerBalance = await helper.balance.getSubstrateFull(staker.address);808      expect(stakerBalance).to.contain({miscFrozen: income1 + income2, feeFrozen: income1 + income2, reserved: 0n});809      expect(stakerBalance.free / nominal).to.eq(999n);810    });811812    itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {813      const [staker] = getAccount(1);814815      await helper.staking.stake(staker, 100n * nominal);816      // wait for two rewards are available:817      let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});818      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);819820      await helper.admin.payoutStakers(palletAdmin, 100);821      [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});822      const frozenBalanceShouldBe = calculateIncome(100n * nominal, 2);823      expect(stake.amount).to.be.equal(frozenBalanceShouldBe);824825      const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);826827      expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});828    });829830    itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {831      // staker unstakes before rewards been payed832      const [staker] = getAccount(1);833      await helper.staking.stake(staker, 100n * nominal);834      const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});835      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);836      await helper.staking.unstakeAll(staker);837838      // so he did not receive any rewards839      const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);840      await helper.admin.payoutStakers(palletAdmin, 100);841      const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);842843      expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);844    });845846    itSub('should bring compound interest', async ({helper}) => {847      const [staker] = getAccount(1);848849      await helper.staking.stake(staker, 100n * nominal);850851      let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});852      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));853854      await helper.admin.payoutStakers(palletAdmin, 100);855      [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});856      expect(stake.amount).to.equal(calculateIncome(100n * nominal));857858      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);859      await helper.admin.payoutStakers(palletAdmin, 100);860      [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});861      expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));862    });863864    itSub('can calculate reward for tiny stake', async ({helper}) => {865      const [staker] = getAccount(1);866      await helper.staking.stake(staker, 100n * nominal);867      await helper.staking.stake(staker, 100n * nominal);868      await helper.staking.unstakePartial(staker, 100n * nominal - 1n);869870      const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});871      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));872873      const payouts = await helper.admin.payoutStakers(palletAdmin, 100);874      const stakerPayout = payouts.find(p => p.staker === staker.address);875      expect(stakerPayout!.stake).to.eq(100n * nominal + 1n);876    });877878    itSub('can eventually pay all rewards', async ({helper}) => {879      const stakers = getAccount(30);880      // Create 30 stakes:881      await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));882883      let unstakingTxs = [];884      for (const staker of stakers) {885        if (unstakingTxs.length == 3) {886          await Promise.all(unstakingTxs);887          unstakingTxs = [];888        }889        unstakingTxs.push(helper.staking.unstakePartial(staker, 100n * nominal - 1n));890      }891892      const [staker] = getAccount(1);893      await helper.staking.stake(staker, 100n * nominal);894      const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});895      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));896897      let payouts;898      do {899        payouts = await helper.admin.payoutStakers(palletAdmin, 20);900      } while (payouts.length !== 0);901    });902  });903});904905906function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {907  const DAY = 7200n;908  const ACCURACY = 1_000_000_000n;909  // 5n / 10_000n = 0.05% p/day910  const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;911912  if (iter > 1) {913    return calculateIncome(income, iter - 1, calcPeriod);914  } else return income;915}916917function rewardAvailableInBlock(stakedInBlock: bigint) {918  if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;919  return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);920}921922// Wait while promotion period less than specified block, to avoid boundary cases923// 0 if this should be the beginning of the period.924async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {925  const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();926  const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;927928  if (currentPeriodBlock > waitBlockLessThan) {929    await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);930  }931}
modifiedtests/src/util/globalSetup.tsdiffbeforeafterboth
--- a/tests/src/util/globalSetup.ts
+++ b/tests/src/util/globalSetup.ts
@@ -29,8 +29,8 @@
         const api = helper.getApi();
         await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
         const nominal = helper.balance.getOneTokenNominal();
-        await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 1000n * nominal);
-        await helper.balance.transferToSubstrate(superuser, palletAddress, 1000n * nominal);
+        await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 10000n * nominal);
+        await helper.balance.transferToSubstrate(superuser, palletAddress, 10000n * nominal);
         await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [api.tx.configuration
           .setAppPromotionConfigurationOverride({
             recalculationInterval: LOCKING_PERIOD,
modifiedtests/src/util/index.tsdiffbeforeafterboth
--- a/tests/src/util/index.ts
+++ b/tests/src/util/index.ts
@@ -94,7 +94,7 @@
 };
 
 export const MINIMUM_DONOR_FUND = 100_000n;
-export const DONOR_FUNDING = 1_000_000n;
+export const DONOR_FUNDING = 2_000_000n;
 
 // App-promotion periods:
 export const LOCKING_PERIOD = 12n; // 12 blocks of relay
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -20,7 +20,8 @@
         event: IEvent;
       }[];
   },
-  moduleError?: string;
+  blockHash: string,
+  moduleError?: string | object;
 }
 
 export interface ISubscribeBlockEventsData {
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -214,7 +214,7 @@
       accounts.push(recipient);
       if (balance !== 0n) {
         const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);
-        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));
+        transactions.push(this.helper.signTransaction(donor, tx, {nonce, era: 0}, 'account generation'));
         nonce++;
       }
     }
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -6,7 +6,8 @@
 /* eslint-disable no-prototype-builtins */
 
 import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';
-import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';
+import {SignerOptions} from '@polkadot/api/types/submittable';
+import {ApiInterfaceEvents} from '@polkadot/api/types';
 import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';
 import {IKeyringPair} from '@polkadot/types/types';
 import {hexToU8a} from '@polkadot/util/hex';
@@ -561,7 +562,7 @@
           if (status === this.transactionStatus.SUCCESS) {
             this.logger.log(`${label} successful`);
             unsub();
-            resolve({result, status});
+            resolve({result, status, blockHash: result.status.asInBlock.toHuman()});
           } else if (status === this.transactionStatus.FAIL) {
             let moduleError = null;
 
@@ -672,8 +673,15 @@
       params,
     } as IUniqueHelperLog;
 
+    let errorMessage = '';
+
     if(result.status !== this.transactionStatus.SUCCESS) {
-      if (result.moduleError) log.moduleError = result.moduleError;
+      if (result.moduleError) {
+        errorMessage = typeof result.moduleError === 'string'
+          ? result.moduleError
+          : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;
+        log.moduleError = errorMessage;
+      }
       else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;
     }
     if(events.length > 0) log.events = events;
@@ -681,7 +689,7 @@
     this.chainLog.push(log);
 
     if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {
-      if (result.moduleError) throw Error(`${result.moduleError}`);
+      if (result.moduleError) throw Error(`${errorMessage}`);
       else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));
     }
     return result;
@@ -2657,20 +2665,45 @@
   }
 
   /**
-   * Unstake tokens for App Promotion
+   * Unstake all staked tokens
    * @param signer keyring of signer
    * @param amountToUnstake amount of tokens to unstake
    * @param label extra label for log
-   * @returns block number where balances will be unlocked
+   * @returns block hash where unstake happened
    */
-  async unstake(signer: TSigner, label?: string): Promise<number> {
+  async unstakeAll(signer: TSigner, label?: string): Promise<string> {
     if(typeof label === 'undefined') label = `${signer.address}`;
-    const _unstakeResult = await this.helper.executeExtrinsic(
-      signer, 'api.tx.appPromotion.unstake',
+    const unstakeResult = await this.helper.executeExtrinsic(
+      signer, 'api.tx.appPromotion.unstakeAll',
       [], true,
     );
-    // TODO extract block number fron events
-    return 1;
+    return unstakeResult.blockHash;
+  }
+
+  /**
+   * Unstake the part of a staked tokens
+   * @param signer keyring of signer
+   * @param amount amount of tokens to unstake
+   * @param label extra label for log
+   * @returns block hash where unstake happened
+   */
+  async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {
+    if(typeof label === 'undefined') label = `${signer.address}`;
+    const unstakeResult = await this.helper.executeExtrinsic(
+      signer, 'api.tx.appPromotion.unstakePartial',
+      [amount], true,
+    );
+    return unstakeResult.blockHash;
+  }
+
+  /**
+   * Get total number of active stakes
+   * @param address substrate address
+   * @returns {number}
+   */
+  async getStakesNumber(address: ICrossAccountId): Promise<number> {
+    if (address.Ethereum) throw Error('only substrate address');
+    return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();
   }
 
   /**