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

difftreelog

Merge pull request #867 from UniqueNetwork/feature/appPromoReservationBalance

Yaroslav Bolyukin2023-02-02parents: #d6786e1 #2380650.patch.diff
in: master
Feature/app promo reservation balance

5 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5803,11 +5803,12 @@
 
 [[package]]
 name = "pallet-app-promotion"
-version = "0.1.3"
+version = "0.1.4"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
  "frame-system",
+ "log",
  "pallet-balances",
  "pallet-common",
  "pallet-configuration",
modifiedpallets/app-promotion/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/app-promotion/CHANGELOG.md
+++ b/pallets/app-promotion/CHANGELOG.md
@@ -4,6 +4,13 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.4] - 2023-01-31
+
+### Changed
+
+- Balance reservation when calling the unstake method is removed.
+  Now the locked balance (by AppPromo) does not change until the unlock interval expires.
+
 ## [0.1.3] - 2022-12-25
 
 ### Fixed
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.3'
+version = '0.1.4'
 
 [package.metadata.docs.rs]
 targets = ['x86_64-unknown-linux-gnu']
@@ -67,3 +67,6 @@
 # [dev-dependencies]
 
 ################################################################################
+# Other
+
+log = { version = "0.4.16", default-features = false }
\ No newline at end of file
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -97,7 +97,7 @@
 	use super::*;
 	use frame_support::{
 		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,
-		traits::ReservableCurrency,
+		traits::ReservableCurrency, weights::Weight,
 	};
 	use frame_system::pallet_prelude::*;
 
@@ -234,7 +234,7 @@
 		QueryKind = ValueQuery,
 	>;
 
-	/// Stores amount of stakes for an `Account`.
+	/// Stores number of stake records for an `Account`.
 	///
 	/// * **Key** - Staker account.
 	/// * **Value** - Amount of stakes.
@@ -242,7 +242,7 @@
 	pub type StakesPerAccount<T: Config> =
 		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;
 
-	/// Stores amount of stakes for an `Account`.
+	/// Pending unstake records for an `Account`.
 	///
 	/// * **Key** - Staker account.
 	/// * **Value** - Amount of stakes.
@@ -262,6 +262,10 @@
 	pub type PreviousCalculatedRecord<T: Config> =
 		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;
 
+	#[pallet::storage]
+	pub(crate) type UpgradedToReserves<T: Config> =
+		StorageValue<Value = bool, QueryKind = ValueQuery>;
+
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
 		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize
@@ -276,13 +280,104 @@
 
 			if !block_pending.is_empty() {
 				block_pending.into_iter().for_each(|(staker, amount)| {
+					Self::get_locked_balance(&staker).map(|b| {
+						let new_state = b.amount.checked_sub(&amount).unwrap_or_default();
+						Self::set_lock_unchecked(&staker, new_state);
+					});
+				});
+			}
+
+			<T as Config>::WeightInfo::on_initialize(counter)
+		}
+
+		fn on_runtime_upgrade() -> Weight {
+			let mut consumed_weight = Weight::zero();
+			let mut add_weight = |reads, writes, weight| {
+				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
+				consumed_weight += weight;
+			};
+
+			if <UpgradedToReserves<T>>::get() {
+				add_weight(1, 0, Weight::zero());
+				return consumed_weight;
+			} else {
+				add_weight(1, 1, Weight::zero());
+				<UpgradedToReserves<T>>::set(true);
+			}
+			<PendingUnstake<T>>::drain().for_each(|(_, v)| {
+				add_weight(1, 1, Weight::zero());
+				v.into_iter().for_each(|(staker, amount)| {
 					<<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(
 						&staker, amount,
 					);
+					add_weight(1, 1, Weight::zero());
 				});
+			});
+
+			consumed_weight
+		}
+
+		#[cfg(feature = "try-runtime")]
+		fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
+			use sp_std::collections::btree_map::BTreeMap;
+			if <UpgradedToReserves<T>>::get() {
+				return Ok(Default::default());
+			}
+			// Staker -> (total amount of reserved balance, reserved by promotion);
+			let mut pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =
+				BTreeMap::new();
+
+			<PendingUnstake<T>>::iter().for_each(|(_, v)| {
+				v.into_iter().for_each(|(staker, amount)| {
+					if let Some((_, reserved_balance)) = pre_state.get_mut(&staker) {
+						*reserved_balance += amount;
+					} else {
+						let total_reserve = <<T as Config>::Currency as ReservableCurrency<
+							T::AccountId,
+						>>::reserved_balance(&staker);
+						pre_state.insert(staker, (total_reserve, amount));
+					}
+				})
+			});
+
+			Ok(pre_state.encode())
+		}
+
+		#[cfg(feature = "try-runtime")]
+		fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {
+			use sp_std::collections::btree_map::BTreeMap;
+
+			if <UpgradedToReserves<T>>::get() {
+				return Ok(());
 			}
 
-			<T as Config>::WeightInfo::on_initialize(counter)
+			ensure!(
+				<PendingUnstake<T>>::iter().collect::<Vec<_>>().len() == 0,
+				"pendingUnstake storage isn't empty"
+			);
+
+			let mut is_ok = true;
+
+			let pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =
+				Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;
+			for (staker, (total_reserved, reserved_by_promo)) in pre_state.into_iter() {
+				let new_state_reserve = <<T as Config>::Currency as ReservableCurrency<
+					T::AccountId,
+				>>::reserved_balance(&staker);
+				if new_state_reserve != total_reserved - reserved_by_promo {
+					is_ok = false;
+					log::error!(
+								"Incorrect reserved balance for {:?}. New balance: {:?}. Before runtime upgrade: total reserve - {:?}, reserved by promo - {:?}",
+								staker, new_state_reserve, total_reserved, reserved_by_promo
+							);
+				}
+			}
+
+			if is_ok {
+				Ok(())
+			} else {
+				Err("Incorrect balance for some of stakers... See logs")
+			}
 		}
 	}
 
@@ -340,14 +435,16 @@
 				<<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);
 
 			// checks that we can lock `amount` on the `staker` account.
-			<<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(
-				&staker_id,
-				amount,
-				WithdrawReasons::all(),
-				balance
-					.checked_sub(&amount)
-					.ok_or(ArithmeticError::Underflow)?,
-			)?;
+			ensure!(
+				amount
+					<= match Self::get_locked_balance(&staker_id) {
+						Some(lock) => balance
+							.checked_sub(&lock.amount)
+							.ok_or(ArithmeticError::Underflow)?,
+						None => balance,
+					},
+				ArithmeticError::Underflow
+			);
 
 			Self::add_lock_balance(&staker_id, amount)?;
 
@@ -428,13 +525,6 @@
 
 			<PendingUnstake<T>>::insert(block, pendings);
 
-			Self::unlock_balance(&staker_id, total_staked)?;
-
-			<<T as Config>::Currency as ReservableCurrency<T::AccountId>>::reserve(
-				&staker_id,
-				total_staked,
-			)?;
-
 			TotalStaked::<T>::set(
 				TotalStaked::<T>::get()
 					.checked_sub(&total_staked)
@@ -717,26 +807,6 @@
 	/// value and only call this once.
 	pub fn account_id() -> T::AccountId {
 		T::PalletId::get().into_account_truncating()
-	}
-
-	/// Unlocks the balance that was locked by the pallet.
-	///
-	/// - `staker`: staker account.
-	/// - `amount`: amount of unlocked funds.
-	fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {
-		let locked_balance = Self::get_locked_balance(staker)
-			.map(|l| l.amount)
-			.ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;
-
-		// It is understood that we cannot unlock more funds than were locked by staking.
-		// Therefore, if implemented correctly, this error should not occur.
-		Self::set_lock_unchecked(
-			staker,
-			locked_balance
-				.checked_sub(&amount)
-				.ok_or(ArithmeticError::Underflow)?,
-		);
-		Ok(())
 	}
 
 	/// Adds the balance to locked by the pallet.
modifiedtests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth
before · 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[];29// App promotion periods:30// LOCKING_PERIOD = 12 blocks of relay31// UNLOCKING_PERIOD = 6 blocks of parachain3233describe('App promotion', () => {34  before(async function () {35    await usingPlaygrounds(async (helper, privateKey) => {36      requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);37      donor = await privateKey({filename: __filename});38      palletAddress = helper.arrange.calculatePalletAddress('appstake');39      palletAdmin = await privateKey('//PromotionAdmin');40      nominal = helper.balance.getOneTokenNominal();4142      const accountBalances = new Array(100);43      accountBalances.fill(1000n);44      accounts = await helper.arrange.createAccounts(accountBalances, donor); // create accounts-pool to speed up tests45    });46  });4748  describe('stake extrinsic', () => {49    itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {50      const [staker, recepient] = [accounts.pop()!, accounts.pop()!];51      const totalStakedBefore = await helper.staking.getTotalStaked();5253      // Minimum stake amount is 100:54      await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;55      await helper.staking.stake(staker, 100n * nominal);5657      // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...58      // ...so he can not transfer 90059      expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});60      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: 100n * nominal, reasons: 'All'}]);61      await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');6263      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);64      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);65      // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?66      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased676869      await helper.staking.stake(staker, 200n * nominal);70      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);71      const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});72      expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);73      expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);74    });7576    itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {77      const [staker] = await helper.arrange.createAccounts([2000n], donor);78      for (let i = 0; i < 10; i++) {79        await helper.staking.stake(staker, 100n * nominal);80      }8182      // can have 10 stakes83      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);84      expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);8586      await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');8788      // After unstake can stake again89      await helper.staking.unstake(staker);90      await helper.staking.stake(staker, 100n * nominal);91      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);92    });9394    itSub('should reject transaction if stake amount is more than total free balance minus frozen', async ({helper}) => {95      const staker = accounts.pop()!;9697      // Can't stake full balance because Alice needs to pay some fee98      await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected;99      await helper.staking.stake(staker, 500n * nominal);100101      // Can't stake 500 tkn because Alice has Less than 500 transferable;102      await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');103      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);104    });105106    itSub('for different accounts in one block is possible', async ({helper}) => {107      const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];108109      const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));110      await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;111112      const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));113      expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);114    });115  });116117  describe('unstake extrinsic', () => {118    itSub('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async ({helper}) => {119      const [staker, recepient] = [accounts.pop()!, accounts.pop()!];120      const totalStakedBefore = await helper.staking.getTotalStaked();121      await helper.staking.stake(staker, 900n * nominal);122      await helper.staking.unstake(staker);123124      // Right after unstake balance is reserved125      // Staker can not transfer126      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 900n * nominal, miscFrozen: 0n, feeFrozen: 0n});127      await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.InsufficientBalance');128      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);129      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);130      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);131    });132133    itSub('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async ({helper}) => {134      const staker = accounts.pop()!;135      await helper.staking.stake(staker, 100n * nominal);136      await helper.staking.unstake(staker);137      const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});138139      // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n140      await helper.wait.forParachainBlockNumber(pendingUnstake.block);141      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});142      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);143144      // staker can transfer:145      await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);146      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);147    });148149    itSub('should successfully unstake multiple stakes', async ({helper}) => {150      const staker = accounts.pop()!;151      await helper.staking.stake(staker, 100n * nominal);152      await helper.staking.stake(staker, 200n * nominal);153      await helper.staking.stake(staker, 300n * nominal);154155      // staked: [100, 200, 300]; unstaked: 0156      let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});157      let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});158      let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});159      expect(totalPendingUnstake).to.be.deep.equal(0n);160      expect(pendingUnstake).to.be.deep.equal([]);161      expect(stakes[0].amount).to.equal(100n * nominal);162      expect(stakes[1].amount).to.equal(200n * nominal);163      expect(stakes[2].amount).to.equal(300n * nominal);164165      // Can unstake multiple stakes166      await helper.staking.unstake(staker);167      pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});168      totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});169      stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});170      expect(totalPendingUnstake).to.be.equal(600n * nominal);171      expect(stakes).to.be.deep.equal([]);172      expect(pendingUnstake[0].amount).to.equal(600n * nominal);173174      expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});175      await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);176      expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});177      expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);178    });179180    itSub('should not have any effects if no active stakes', async ({helper}) => {181      const staker = accounts.pop()!;182183      // unstake has no effect if no stakes at all184      await helper.staking.unstake(staker);185      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);186      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper187188      // TODO stake() unstake() waitUnstaked() unstake();189190      // can't unstake if there are only pendingUnstakes191      await helper.staking.stake(staker, 100n * nominal);192      await helper.staking.unstake(staker);193      await helper.staking.unstake(staker);194195      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);196      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);197    });198199    itSub('should keep different unlocking block for each unlocking stake', async ({helper}) => {200      const staker = accounts.pop()!;201      await helper.staking.stake(staker, 100n * nominal);202      await helper.staking.unstake(staker);203      await helper.staking.stake(staker, 120n * nominal);204      await helper.staking.unstake(staker);205206      const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});207      expect(unstakingPerBlock).has.length(2);208      expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);209      expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);210    });211212    itSub('should be possible for different accounts in one block', async ({helper}) => {213      const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];214215      await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));216      await Promise.all(stakers.map(staker => helper.staking.unstake(staker)));217218      await Promise.all(stakers.map(async (staker) => {219        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);220        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);221      }));222    });223  });224225  describe('collection sponsoring', () => {226    itSub('should actually sponsor transactions', async ({helper}) => {227      const api = helper.getApi();228      const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];229      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});230      const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});231      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));232      const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);233234      await token.transfer(tokenSender, {Substrate: receiver.address});235      expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});236      const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);237238      // senders balance the same, transaction has sponsored239      expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);240      expect (palletBalanceBefore > palletBalanceAfter).to.be.true;241    });242243    itSub('can not be set by non admin', async ({helper}) => {244      const api = helper.getApi();245      const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];246247      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});248249      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;250      expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');251    });252253    itSub('should set pallet address as confirmed admin', async ({helper}) => {254      const api = helper.getApi();255      const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];256257      // Can set sponsoring for collection without sponsor258      const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});259      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;260      expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});261262      // Can set sponsoring for collection with unconfirmed sponsor263      const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});264      expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});265      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;266      expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});267268      // Can set sponsoring for collection with confirmed sponsor269      const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});270      await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);271      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;272      expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});273    });274275    itSub('can be overwritten by collection owner', async ({helper}) => {276      const api = helper.getApi();277      const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];278      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});279      const collectionId = collection.collectionId;280281      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;282283      // Collection limits still can be changed by the owner284      expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;285      expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);286      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});287288      // Collection sponsor can be changed too289      expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;290      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});291    });292293    itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {294      const api = helper.getApi();295      const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};296      const collectionWithLimits = await helper.nft.mintCollection(accounts.pop()!, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});297298      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;299      expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);300    });301302    itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {303      const api = helper.getApi();304      const collectionOwner = accounts.pop()!;305306      // collection has never existed307      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;308      // collection has been burned309      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});310      await collection.burn(collectionOwner);311312      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;313    });314  });315316  describe('stopSponsoringCollection', () => {317    itSub('can not be called by non-admin', async ({helper}) => {318      const api = helper.getApi();319      const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];320      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});321322      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;323324      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;325      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});326    });327328    itSub('should set sponsoring as disabled', async ({helper}) => {329      const api = helper.getApi();330      const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];331      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});332      const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});333334      await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));335      await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));336337      expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');338339      // Transactions are not sponsored anymore:340      const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);341      await token.transfer(collectionOwner, {Substrate: recepient.address});342      const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);343      expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);344    });345346    itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {347      const api = helper.getApi();348      const collectionOwner = accounts.pop()!;349      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});350      await collection.confirmSponsorship(collectionOwner);351352      await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;353354      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});355    });356357    itSub('should reject transaction if collection does not exist', async ({helper}) => {358      const collectionOwner = accounts.pop()!;359      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});360361      await collection.burn(collectionOwner);362      await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');363      await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');364    });365  });366367  describe('contract sponsoring', () => {368    itEth('should set palletes address as a sponsor', async ({helper}) => {369      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();370      const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);371      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);372373      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);374375      expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;376      expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);377      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({378        confirmed: {379          substrate: palletAddress,380        },381      });382    });383384    itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {385      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();386      const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);387      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);388389      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;390391      // Contract is self sponsored392      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({393        confirmed: {394          ethereum: flipper.options.address.toLowerCase(),395        },396      });397398      // set promotion sponsoring399      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);400401      // new sponsor is pallet address402      expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;403      expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);404      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({405        confirmed: {406          substrate: palletAddress,407        },408      });409    });410411    itEth('can be overwritten by contract owner', async ({helper}) => {412      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();413      const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);414      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);415416      // contract sponsored by pallet417      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);418419      // owner sets self sponsoring420      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;421422      expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;423      expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);424      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({425        confirmed: {426          ethereum: flipper.options.address.toLowerCase(),427        },428      });429    });430431    itEth('can not be set by non admin', async ({helper}) => {432      const nonAdmin = accounts.pop()!;433      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();434      const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);435      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);436437      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;438439      // nonAdmin calls sponsorContract440      await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');441442      // contract still self-sponsored443      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({444        confirmed: {445          ethereum: flipper.options.address.toLowerCase(),446        },447      });448    });449450    itEth('should actually sponsor transactions', async ({helper}) => {451      // Contract caller452      const caller = await helper.eth.createAccountWithBalance(donor, 1000n);453      const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);454455      // Deploy flipper456      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();457      const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);458      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);459460      // Owner sets to sponsor every tx461      await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});462      await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});463      await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);464465      // Set promotion to the Flipper466      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);467468      // Caller calls Flipper469      await flipper.methods.flip().send({from: caller});470      expect(await flipper.methods.getValue().call()).to.be.true;471472      // The contracts and caller balances have not changed473      const callerBalance = await helper.balance.getEthereum(caller);474      const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);475      expect(callerBalance).to.be.equal(1000n * nominal);476      expect(1000n * nominal === contractBalanceAfter).to.be.true;477478      // The pallet balance has decreased479      const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);480      expect(palletBalanceAfter < palletBalanceBefore).to.be.true;481    });482  });483484  describe('stopSponsoringContract', () => {485    itEth('should remove pallet address from contract sponsors', async ({helper}) => {486      const caller = await helper.eth.createAccountWithBalance(donor, 1000n);487      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();488      const flipper = await helper.eth.deployFlipper(contractOwner);489      await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);490      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);491492      await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});493      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);494      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);495496      expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;497      expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);498      expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({499        disabled: null,500      });501502      await flipper.methods.flip().send({from: caller});503      expect(await flipper.methods.getValue().call()).to.be.true;504505      const callerBalance = await helper.balance.getEthereum(caller);506      const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);507508      // caller payed for call509      expect(1000n * nominal > callerBalance).to.be.true;510      expect(contractBalanceAfter).to.be.equal(100n * nominal);511    });512513    itEth('can not be called by non-admin', async ({helper}) => {514      const nonAdmin = accounts.pop()!;515      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();516      const flipper = await helper.eth.deployFlipper(contractOwner);517518      await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);519      await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))520        .to.be.rejectedWith(/appPromotion\.NoPermission/);521    });522523    itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {524      const nonAdmin = accounts.pop()!;525      const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();526      const flipper = await helper.eth.deployFlipper(contractOwner);527      const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);528      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;529530      await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');531    });532  });533534  describe('payoutStakers', () => {535    itSub('can not be called by non admin', async ({helper}) => {536      const nonAdmin = accounts.pop()!;537      await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');538    });539540    itSub('should increase total staked', async ({helper}) => {541      const staker = accounts.pop()!;542      const totalStakedBefore = await helper.staking.getTotalStaked();543      await helper.staking.stake(staker, 100n * nominal);544545      // Wait for rewards and pay546      const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});547      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));548      const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);549550      const totalStakedAfter = await helper.staking.getTotalStaked();551      expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);552      // staker can unstake553      await helper.staking.unstake(staker);554      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));555    });556557    itSub('should credit 0.05% for staking period', async ({helper}) => {558      const staker = accounts.pop()!;559560      await waitPromotionPeriodDoesntEnd(helper);561562      await helper.staking.stake(staker, 100n * nominal);563      await helper.staking.stake(staker, 200n * nominal);564565      // wait rewards are available:566      const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});567      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));568569      const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)?.payout;570      expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal));571572      const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});573      const income1 = calculateIncome(100n * nominal);574      const income2 = calculateIncome(200n * nominal);575      expect(totalStakedPerBlock[0].amount).to.equal(income1);576      expect(totalStakedPerBlock[1].amount).to.equal(income2);577578      const stakerBalance = await helper.balance.getSubstrateFull(staker.address);579      expect(stakerBalance).to.contain({miscFrozen: income1 + income2, feeFrozen: income1 + income2, reserved: 0n});580      expect(stakerBalance.free / nominal).to.eq(999n);581    });582583    itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {584      const staker = accounts.pop()!;585586      await helper.staking.stake(staker, 100n * nominal);587      // wait for two rewards are available:588      let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});589      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);590591      await helper.admin.payoutStakers(palletAdmin, 100);592      [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});593      const frozenBalanceShouldBe = calculateIncome(100n * nominal, 2);594      expect(stake.amount).to.be.equal(frozenBalanceShouldBe);595596      const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);597598      expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});599    });600601    itSub('should not be credited for unstaked (reserved) balance', async ({helper}) => {602      // staker unstakes before rewards has been payed603      const staker = accounts.pop()!;604      await helper.staking.stake(staker, 100n * nominal);605      const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});606      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);607      await helper.staking.unstake(staker);608609      // so he did not receive any rewards610      const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);611      await helper.admin.payoutStakers(palletAdmin, 100);612      const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);613614      expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);615    });616617    itSub('should bring compound interest', async ({helper}) => {618      const staker = accounts.pop()!;619620      await helper.staking.stake(staker, 100n * nominal);621622      let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});623      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));624625      await helper.admin.payoutStakers(palletAdmin, 100);626      [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});627      expect(stake.amount).to.equal(calculateIncome(100n * nominal));628629      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);630      await helper.admin.payoutStakers(palletAdmin, 100);631      [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});632      expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));633    });634635    itSub.skip('can be paid 1000 rewards in a time', async ({helper}) => {636      // all other stakes should be unstaked637      const oneHundredStakers = await helper.arrange.createCrowd(100, 1050n, donor);638639      // stakers stakes 10 times each640      for (let i = 0; i < 10; i++) {641        await Promise.all(oneHundredStakers.map(staker => helper.staking.stake(staker, 100n * nominal)));642      }643      await helper.wait.newBlocks(40);644      await helper.admin.payoutStakers(palletAdmin, 100);645    });646647    itSub.skip('can handle 40.000 rewards', async ({helper}) => {648      const crowdStakes = async () => {649        // each account in the crowd stakes 2 times650        const crowd = await helper.arrange.createCrowd(500, 300n, donor);651        await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));652        await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));653        //654      };655656      for (let i = 0; i < 40; i++) {657        await crowdStakes();658      }659660      // TODO pay rewards for some period661    });662  });663});664665function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {666  const DAY = 7200n;667  const ACCURACY = 1_000_000_000n;668  // 5n / 10_000n = 0.05% p/day669  const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;670671  if (iter > 1) {672    return calculateIncome(income, iter - 1, calcPeriod);673  } else return income;674}675676function rewardAvailableInBlock(stakedInBlock: bigint) {677  if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;678  return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);679}680681// Wait while promotion period less than specified block, to avoid boundary cases682// 0 if this should be the beginning of the period.683async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {684  const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();685  const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;686687  if (currentPeriodBlock > waitBlockLessThan) {688    await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);689  }690}