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

difftreelog

fix unstake

PraetorP2022-09-02parent: #123bef5.patch.diff
in: master

2 files changed

modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -358,7 +358,7 @@
 			let block = <frame_system::Pallet<T>>::block_number() + T::PendingInterval::get();
 			let mut pendings = <PendingUnstake<T>>::get(block);
 
-			ensure!(pendings.is_full(), Error::<T>::PendingForBlockOverflow);
+			ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);
 
 			let mut total_stakes = 0u64;
 
@@ -370,7 +370,7 @@
 				.sum();
 
 			if total_staked.is_zero() {
-				return Ok(None.into());
+				return Ok(None.into()); // TO-DO
 			}
 
 			pendings
@@ -387,7 +387,7 @@
 				TotalStaked::<T>::get()
 					.checked_sub(&total_staked)
 					.ok_or(ArithmeticError::Underflow)?,
-			); // when error we should recover initial stake state for the staker
+			);
 
 			StakesPerAccount::<T>::remove(&staker_id);
 
@@ -474,46 +474,46 @@
 			let next_recalc_block = current_recalc_block + T::RecalculationInterval::get();
 
 			let mut storage_iterator = Self::get_next_calculated_key()
-				.map_or(Staked::<T>::iter().skip(0), |key| {
-					Staked::<T>::iter_from(key).skip(1)
+				.map_or(Staked::<T>::iter(), |key| {
+					Staked::<T>::iter_from(key)
 				});
 
 			NextCalculatedRecord::<T>::set(None);
 
 			{
 				let mut stakers_number = stakers_number.unwrap_or(20);
-				let mut current_id = admin_id;
+				let mut last_id = admin_id;
 				let mut income_acc = BalanceOf::<T>::default();
 
-				while let Some(((id, staked_block), (amount, next_recalc_block_for_stake))) =
+				while let Some(((current_id, staked_block), (amount, next_recalc_block_for_stake))) =
 					storage_iterator.next()
 				{
-					if current_id != id {
+					if last_id != current_id {
 						if income_acc != BalanceOf::<T>::default() {
 							<T::Currency as Currency<T::AccountId>>::transfer(
 								&T::TreasuryAccountId::get(),
-								&current_id,
+								&last_id,
 								income_acc,
 								ExistenceRequirement::KeepAlive,
 							)
-							.and_then(|_| Self::add_lock_balance(&current_id, income_acc))?;
+							.and_then(|_| Self::add_lock_balance(&last_id, income_acc))?;
 
 							Self::deposit_event(Event::StakingRecalculation(
-								current_id, amount, income_acc,
+								last_id, amount, income_acc,
 							));
 						}
 
 						if stakers_number == 0 {
-							NextCalculatedRecord::<T>::set(Some((id, staked_block)));
+							NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));
 							break;
 						}
 						stakers_number -= 1;
 						income_acc = BalanceOf::<T>::default();
-						current_id = id;
+						last_id = current_id;
 					};
 					if current_recalc_block >= next_recalc_block_for_stake {
 						Self::recalculate_and_insert_stake(
-							&current_id,
+							&last_id,
 							staked_block,
 							next_recalc_block,
 							amount,
modifiedtests/src/app-promotion.test.tsdiffbeforeafterboth
before · tests/src/app-promotion.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  normalizeAccountId,20  getModuleNames,21  Pallets,22} from './util/helpers';2324import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {usingPlaygrounds} from './util/playgrounds';2728import {encodeAddress} from '@polkadot/util-crypto';29import {stringToU8a} from '@polkadot/util';30import {ApiPromise} from '@polkadot/api';31import {SponsoringMode, contractHelpers, createEthAccountWithBalance, deployFlipper, itWeb3, transferBalanceToEth} from './eth/util/helpers';32chai.use(chaiAsPromised);33const expect = chai.expect;3435let alice: IKeyringPair;36let palletAdmin: IKeyringPair;37let nominal: bigint;38let promotionStartBlock: number | null = null;39const palletAddress = calculatePalleteAddress('appstake');40let accounts: IKeyringPair[] = [];4142before(async function () {43  await usingPlaygrounds(async (helper, privateKeyWrapper) => {44    if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();45    alice = privateKeyWrapper('//Alice');46    palletAdmin = privateKeyWrapper('//Charlie'); // TODO use custom address47    await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address})));48    nominal = helper.balance.getOneTokenNominal();49    await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);50    await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);51    if (!promotionStartBlock) {52      promotionStartBlock = (await helper.api!.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();53    }54    await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.startAppPromotion(promotionStartBlock!)));55    accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests56  });57});5859after(async function () {60  await usingPlaygrounds(async (helper) => {61    await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.stopAppPromotion()));62  });63});6465describe('app-promotions.stake extrinsic', () => {66  it('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async () => {67    await usingPlaygrounds(async (helper) => {68      const [staker, recepient] = [accounts.pop()!, accounts.pop()!];69      const totalStakedBefore = await helper.staking.getTotalStaked();7071      // Minimum stake amount is 100:72      await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.eventually.rejected;73      await helper.staking.stake(staker, 100n * nominal);7475      // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...76      // ...so he can not transfer 90077      expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});78      await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejected;79      80      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(100n * nominal);81      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);82      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);83      // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo? 84      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased 8586      87      await helper.staking.stake(staker, 200n * nominal);88      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(300n * nominal);89      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);90      expect((await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map((x) => x[1])).to.be.deep.equal([100n * nominal, 200n * nominal]);91    });92  });9394  it('should allow to stake with nonce', async () => {95    await usingPlaygrounds(async (helper) => {96      const staker = accounts.pop()!;97      const transactions = [];98      for (let nonce = 0; nonce < 9; nonce++) {99        transactions.push(helper.signTransaction(staker, helper.api?.tx.promotion.stake(100n * nominal), 'Staker stakes with nonce', {nonce}));100      }101      await Promise.allSettled(transactions);102103      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(900n * nominal);104    });105  });106  107  it('should reject transaction if stake amount is more than total free balance minus frozen', async () => {108    await usingPlaygrounds(async helper => { 109      const staker = accounts.pop()!;110111      // Can't stake full balance because Alice needs to pay some fee112      await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.eventually.rejected;113      await helper.staking.stake(staker, 500n * nominal);114115      // Can't stake 500 tkn because Alice has Less than 500 transferable;116      await expect(helper.staking.stake(staker, 500n * nominal)).to.be.eventually.rejected; 117      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);118    });119  });120  121  it('for different accounts in one block is possible', async () => {122    await usingPlaygrounds(async helper => {123      const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];124      125      const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));126      await expect(Promise.all(crowdStartsToStake)).to.be.eventually.fulfilled;127128      const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));129      expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);130    });131  });132133  it('should allow to create maximum 10 stakes for account', async () => {134135  });136});137138describe('unstake balance extrinsic', () => {  139  it('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async () => {140    await usingPlaygrounds(async helper => {141      const [staker, recepient] = [accounts.pop()!, accounts.pop()!];142      const totalStakedBefore = await helper.staking.getTotalStaked();143      await helper.staking.stake(staker, 900n * nominal);144      await helper.staking.unstake(staker);145146      // Right after unstake balance is reserved147      // Staker can not transfer 148      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 900n * nominal, miscFrozen: 0n, feeFrozen: 0n});149      await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejected;150      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);151      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);152      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);153    });154  });155156  it('should unlock balance after unlocking period ends and subtract it from "pendingUnstake"', async () => {157    await usingPlaygrounds(async (helper) => {158      const staker = accounts.pop()!;159      await helper.staking.stake(staker, 100n * nominal);160      await helper.staking.unstake(staker);161162      // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n163      await waitForRelayBlock(helper.api!, 20);164      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n * nominal, miscFrozen: 0n, feeFrozen: 0n});165      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);166167      // staker can transfer:168      await helper.balance.transferToSubstrate(staker, alice.address, 998n * nominal);169      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);170    });171  });172173  it('should successfully unstake multiple stakes', async () => {174    await usingPlaygrounds(async helper => {175      const staker = accounts.pop()!;176      await helper.staking.stake(staker, 100n * nominal);177      await helper.staking.stake(staker, 200n * nominal);178      await helper.staking.stake(staker, 300n * nominal);179180      // staked: [100, 200, 300]; unstaked: 0181      let pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});182      let unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);183      let stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);184      expect(pendingUnstake).to.be.deep.equal(0n);185      expect(unstakedPerBlock).to.be.deep.equal([]);186      expect(stakedPerBlock).to.be.deep.equal([100n * nominal, 200n * nominal, 300n * nominal]);187     188      // Can unstake multiple stakes189      await helper.staking.unstake(staker);190      pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});191      unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);192      stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);193      expect(pendingUnstake).to.be.equal(600n * nominal);194      expect(stakedPerBlock).to.be.deep.equal([]);195      expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);196197      expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});198      await waitForRelayBlock(helper.api!, 20);199      expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});200      expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);201    });202  });203204  it('should not have any effects if no active stakes', async () => {205    await usingPlaygrounds(async (helper) => {206      const staker = accounts.pop()!;207      208      // unstake has no effect if no stakes at all209      await helper.staking.unstake(staker);210      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);211      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(0n);212      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper213214      // TODO stake() unstake() waitUnstaked() unstake();215216      // can't unstake if there are only pendingUnstakes217      await helper.staking.stake(staker, 100n * nominal);218      await helper.staking.unstake(staker);219      await helper.staking.unstake(staker);220221      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);222      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(100n * nominal);223      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);224    });225  });226227  it('should keep different unlocking block for each unlocking stake', async () => {228    await usingPlaygrounds(async (helper) => {229      const staker = accounts.pop()!;230      await helper.staking.stake(staker, 100n * nominal);231      await helper.staking.unstake(staker);232      await helper.staking.stake(staker, 120n * nominal);233      await helper.staking.unstake(staker);234235      const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});236      expect(unstakingPerBlock).has.length(2);237      expect(unstakingPerBlock[0][1]).to.equal(100n * nominal);238      expect(unstakingPerBlock[1][1]).to.equal(120n * nominal);239    });240  });241242  it('should be possible for different accounts in one block', async () => {243    await usingPlaygrounds(async (helper) => {244      const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];245246      await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));247      await Promise.all(stakers.map(staker => helper.staking.unstake(staker)));248249      await Promise.all(stakers.map(async (staker) => {250        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);251        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);252      }));253    });254  });255256  // TODO for different accounts in one block is possible257});258259describe('Admin adress', () => {260  it('can be set by sudo only', async () => {261    await usingPlaygrounds(async (helper) => {262      const nonAdmin = accounts.pop()!;263      // nonAdmin can not set admin not from himself nor as a sudo264      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.eventually.rejected;265      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.eventually.rejected;266267      // Alice can268      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;269    });270  });271  272  it('can be any valid CrossAccountId', async () => {273    // We are not going to set an eth address as a sponsor,274    // but we do want to check, it doesn't break anything;275    await usingPlaygrounds(async (helper) => {276      const account = accounts.pop()!;277      const ethAccount = helper.address.substrateToEth(account.address); 278      // Alice sets Ethereum address as a sudo. Then Substrate address back...279      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Ethereum: ethAccount})))).to.be.eventually.fulfilled;280      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;281      282      // ...It doesn't break anything;283      const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});284      await expect(helper.signTransaction(account, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;285    });286  });287288  it('can be reassigned', async () => {289    await usingPlaygrounds(async (helper) => {290      const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];291      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});292      293      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.eventually.fulfilled;294      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.eventually.fulfilled;295      await expect(helper.signTransaction(oldAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;296      297      await expect(helper.signTransaction(newAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;298    });299  });300});301302describe('App-promotion collection sponsoring', () => {303  before(async function () {304    await usingPlaygrounds(async (helper) => {305      const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address}));306      await helper.signTransaction(alice, tx);307    });308  });309310  it('should actually sponsor transactions', async () => {311    await usingPlaygrounds(async (helper) => {312      const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];313      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});314      const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});315      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId));316      const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);317318      await token.transfer(tokenSender, {Substrate: receiver.address});319      expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});320      const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);321322      // senders balance the same, transaction has sponsored323      expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);324      expect (palletBalanceBefore > palletBalanceAfter).to.be.true;325    });326  });327328  it('can not be set by non admin', async () => {329    await usingPlaygrounds(async (helper) => {330      const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];331332      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});333      334      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;335      expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');336    });337  });338339  it('should set pallet address as confirmed admin', async () => {340    await usingPlaygrounds(async (helper) => {341      const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];342      343      // Can set sponsoring for collection without sponsor344      const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});345      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.eventually.fulfilled;346      expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});347348      // Can set sponsoring for collection with unconfirmed sponsor349      const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});350      expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});351      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.eventually.fulfilled;352      expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});353354      // Can set sponsoring for collection with confirmed sponsor355      const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});356      await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);357      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.eventually.fulfilled;358      expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});359    });360  });361362  it('can be overwritten by collection owner', async () => {    363    await usingPlaygrounds(async (helper) => {364      const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];365      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});366      const collectionId = collection.collectionId;367      368      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionId))).to.be.eventually.fulfilled;369      370      // Collection limits still can be changed by the owner371      expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;372      expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);373      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});374375      // Collection sponsor can be changed too376      expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;377      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});378    });379  });380  381  it('should not overwrite collection limits set by the owner earlier', async () => {382    await usingPlaygrounds(async (helper) => {383      const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};384      const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});385386      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.eventually.fulfilled;387      expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);388    });389  });390  391  it('should reject transaction if collection doesn\'t exist', async () => {392    await usingPlaygrounds(async (helper) => {393      const collectionOwner = accounts.pop()!;394      395      // collection has never existed396      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(999999999))).to.be.eventually.rejected;397      // collection has been burned398      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});399      await collection.burn(collectionOwner);400401      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;402    });403  });404});405406describe('app-promotion stopSponsoringCollection', () => {407  it('can not be called by non-admin', async () => {    408    await usingPlaygrounds(async (helper) => {409      const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];410      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});411      412      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;413      414      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;415      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});416    });417  });418419  it('should set sponsoring as disabled', async () => {420    await usingPlaygrounds(async (helper) => {421      const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];422      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});423      const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});424      425      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId));426      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId));427      428      expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');429430      // Transactions are not sponsored anymore:431      const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);432      await token.transfer(collectionOwner, {Substrate: recepient.address});433      const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);434      expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);435    });436  });437438  it('should not affect collection which is not sponsored by pallete', async () => {439    await usingPlaygrounds(async (helper) => {440      const collectionOwner = accounts.pop()!;441      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});442      await collection.confirmSponsorship(collectionOwner);443      444      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;445      446      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});447    });448  });449450  it('should reject transaction if collection does not exist', async () => {    451    await usingPlaygrounds(async (helper) => {452      const collectionOwner = accounts.pop()!;453      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});454      455      await collection.burn(collectionOwner);456      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;457      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(999999999))).to.be.eventually.rejected;458    });459  });460});461462describe('app-promotion contract sponsoring', () => {463  itWeb3('should set palletes address as a sponsor', async ({api, web3, privateKeyWrapper}) => {464    await usingPlaygrounds(async (helper) => {465      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();466      const flipper = await deployFlipper(web3, contractOwner);467      const contractMethods = contractHelpers(web3, contractOwner);468469      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));470      471      expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;  472      expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  473      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({474        confirmed: {475          substrate: palletAddress,476        },477      });478    });479  });480481  itWeb3('should overwrite sponsoring mode and existed sponsor', async ({api, web3, privateKeyWrapper}) => {482    await usingPlaygrounds(async (helper) => {483      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();484      const flipper = await deployFlipper(web3, contractOwner);485      const contractMethods = contractHelpers(web3, contractOwner);486487      await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;488489      // Contract is self sponsored490      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({491        confirmed: {492          ethereum: flipper.options.address.toLowerCase(),493        },494      });495496      // set promotion sponsoring497      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));498499      // new sponsor is pallet address500      expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;  501      expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  502      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({503        confirmed: {504          substrate: palletAddress,505        },506      });507    });508  });509510  itWeb3('can be overwritten by contract owner', async ({api, web3, privateKeyWrapper}) => {511    await usingPlaygrounds(async (helper) => {      512      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();513      const flipper = await deployFlipper(web3, contractOwner);514      const contractMethods = contractHelpers(web3, contractOwner);515516      // contract sponsored by pallet517      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));518519      // owner sets self sponsoring520      await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;521522      expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;  523      expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  524      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({525        confirmed: {526          ethereum: flipper.options.address.toLowerCase(),527        },528      });529    });530  });531532  itWeb3('can not be set by non admin', async ({api, web3, privateKeyWrapper}) => {533    await usingPlaygrounds(async (helper) => {      534      const nonAdmin = accounts.pop()!;535      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();536      const flipper = await deployFlipper(web3, contractOwner);537      const contractMethods = contractHelpers(web3, contractOwner);538539      await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;540541      // nonAdmin calls sponsorConract542      await expect(helper.signTransaction(nonAdmin, api.tx.promotion.sponsorConract(flipper.options.address))).to.be.rejected;543544      // contract still self-sponsored 545      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({546        confirmed: {547          ethereum: flipper.options.address.toLowerCase(),548        },549      });550    });551552    itWeb3('should be rejected for non-contract address', async ({api, web3, privateKeyWrapper}) => {553      await usingPlaygrounds(async (helper) => {554555      });556    });557  });558559  itWeb3('should actually sponsor transactions', async ({api, web3, privateKeyWrapper}) => {560    await usingPlaygrounds(async (helper) => {      561      const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);562      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();563      const flipper = await deployFlipper(web3, contractOwner);564      const contractHelper = contractHelpers(web3, contractOwner);565      await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});566      await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});567      await transferBalanceToEth(api, alice, flipper.options.address, 1000n);568569      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));570      await flipper.methods.flip().send({from: caller});571      expect(await flipper.methods.getValue().call()).to.be.true;572573      const callerBalance = await helper.balance.getEthereum(caller);574      const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);575576      expect(callerBalance).to.be.equal(1000n * nominal);577      expect(1000n * nominal > contractBalanceAfter).to.be.true;578    });579  });580});581582describe('app-promotion stopSponsoringContract', () => {  583  itWeb3('should remove pallet address from contract sponsors', async ({api, web3, privateKeyWrapper}) => {584    await usingPlaygrounds(async (helper) => {      585      const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);586      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();587      const flipper = await deployFlipper(web3, contractOwner);588      await transferBalanceToEth(api, alice, flipper.options.address);589      const contractHelper = contractHelpers(web3, contractOwner);590      await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});591      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));592      await helper.signTransaction(palletAdmin, api.tx.promotion.stopSponsoringContract(flipper.options.address));593594      expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;  595      expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  596      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({597        disabled: null,598      });599600      await flipper.methods.flip().send({from: caller});601      expect(await flipper.methods.getValue().call()).to.be.true;602603      const callerBalance = await helper.balance.getEthereum(caller);604      const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);605606      // caller payed for call607      expect(1000n * nominal > callerBalance).to.be.true;608      expect(contractBalanceAfter).to.be.equal(1000n * nominal);609    });610  });611612  itWeb3('can not be called by non-admin', async ({api, web3, privateKeyWrapper}) => {613    await usingPlaygrounds(async (helper) => {      614      const nonAdmin = accounts.pop()!;615      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();616      const flipper = await deployFlipper(web3, contractOwner);617618      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));619      await expect(helper.signTransaction(nonAdmin, api.tx.promotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;620    });621  });622623  itWeb3('should not affect a contract which is not sponsored by pallete', async ({api, web3, privateKeyWrapper}) => {624    await usingPlaygrounds(async (helper) => {      625      const nonAdmin = accounts.pop()!;626      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();627      const flipper = await deployFlipper(web3, contractOwner);628      const contractHelper = contractHelpers(web3, contractOwner);629      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;630631      await expect(helper.signTransaction(nonAdmin, api.tx.promotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;632    });633  });634});635636describe('app-promotion rewards', () => {637  it('can not be called by non admin', async () => {638    await usingPlaygrounds(async (helper) => {639      const nonAdmin = accounts.pop()!;640      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.payoutStakers(50))).to.be.rejected;641    });642  });643644  it('should credit 0.05% for staking period', async () => {    645    // TODO flaky test646    await usingPlaygrounds(async helper => {647      const staker = accounts.pop()!;648      649      await helper.staking.stake(staker, 100n * nominal);650      await helper.staking.stake(staker, 200n * nominal);651      await waitForRelayBlock(helper.api!, 30);652      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));653654      const totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);655      expect(totalStakedPerBlock).to.be.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n)]);656    });657  });658659  it('shoud be paid for more than one period if payments was missed', async () => {660    await usingPlaygrounds(async (helper) => {661      const staker = accounts.pop()!;662663      await helper.staking.stake(staker, 100n * nominal);664      await helper.staking.stake(staker, 200n * nominal);665666      await waitForRelayBlock(helper.api!, 55);667      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));668      const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});669      expect(stakedPerBlock[0][1]).to.be.equal(calculateIncome(100n * nominal, 10n, 2));670      expect(stakedPerBlock[1][1]).to.be.equal(calculateIncome(200n * nominal, 10n, 2));671672      const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);673      const frozenBalanceShouldBe = calculateIncome(300n * nominal, 10n, 2);674675      expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});676    });677  });678  679  it('should not be credited for unstaked (reserved) balance', async () => {680    expect.fail('Test not implemented');681    await usingPlaygrounds(async helper => {682      const staker = accounts.pop()!;683    });684  });685  686  it('should bring compound interest', async () => {687    // TODO flaky test688    await usingPlaygrounds(async helper => {689      const staker = accounts.pop()!;690            691      await helper.staking.stake(staker, 100n * nominal);692      await helper.staking.stake(staker, 200n * nominal);693      await helper.staking.stake(staker, 300n * nominal);694      695      await waitForRelayBlock(helper.api!, 34);696      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));697      let totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);698      expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n), calculateIncome(300n * nominal, 10n)]);699      700      await waitForRelayBlock(helper.api!, 20);701      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));702      totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);703      expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n, 2), calculateIncome(200n * nominal, 10n, 2), calculateIncome(300n * nominal, 10n, 2)]);      704    });705  });706707  it.skip('can handle 40.000 rewards', async () => {708    await usingPlaygrounds(async (helper) => {709      const [donor] = await helper.arrange.createAccounts([7_000_000n], alice);710      const crowdStakes = async () => {711        // each account in the crowd stakes 2 times712        const crowd = await helper.arrange.createCrowd(500, 300n, donor);713        await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));714        await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));715        // 716      };717718      for (let i = 0; i < 40; i++) {719        await crowdStakes();720      }721722      // TODO pay rewards for some period723    });724  });725});726727async function waitForRelayBlock(api: ApiPromise, blocks = 1): Promise<void> {728  const current_block = (await api.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();729  return new Promise<void>(async (resolve, reject) => {730    const unsubscribe = await api.query.parachainSystem.validationData(async (data) => {731      // console.log(`${current_block} || ${data.value.relayParentNumber.toNumber()}`);732      if (data.value.relayParentNumber.toNumber() - current_block >= blocks) {733        unsubscribe();734        resolve();735      }736    });737  });738}739740function calculatePalleteAddress(palletId: any) {741  const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));742  return encodeAddress(address);743}744745function calculateIncome(base: bigint, calcPeriod: bigint, iter = 0): bigint {746  const DAY = 7200n;747  const ACCURACY = 1_000_000_000n;748  const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;749  750  if (iter > 1) {751    return calculateIncome(income, calcPeriod, iter - 1);752  } else return income;753}
after · tests/src/app-promotion.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  normalizeAccountId,20  getModuleNames,21  Pallets,22} from './util/helpers';2324import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {usingPlaygrounds} from './util/playgrounds';2728import {encodeAddress} from '@polkadot/util-crypto';29import {stringToU8a} from '@polkadot/util';30import {ApiPromise} from '@polkadot/api';31import {SponsoringMode, contractHelpers, createEthAccountWithBalance, deployFlipper, itWeb3, transferBalanceToEth} from './eth/util/helpers';32chai.use(chaiAsPromised);33const expect = chai.expect;3435let alice: IKeyringPair;36let palletAdmin: IKeyringPair;37let nominal: bigint;38let promotionStartBlock: number | null = null;39const palletAddress = calculatePalleteAddress('appstake');40let accounts: IKeyringPair[] = [];4142before(async function () {43  await usingPlaygrounds(async (helper, privateKeyWrapper) => {44    if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();45    alice = privateKeyWrapper('//Alice');46    palletAdmin = privateKeyWrapper('//Charlie'); // TODO use custom address47    await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address})));48    nominal = helper.balance.getOneTokenNominal();49    await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);50    await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);51    if (!promotionStartBlock) {52      promotionStartBlock = (await helper.api!.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();53    }54    accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests55  });56});5758after(async function () {59  await usingPlaygrounds(async (helper) => {60  });61});6263describe('app-promotions.stake extrinsic', () => {64  it('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async () => {65    await usingPlaygrounds(async (helper) => {66      const [staker, recepient] = [accounts.pop()!, accounts.pop()!];67      const totalStakedBefore = await helper.staking.getTotalStaked();6869      // Minimum stake amount is 100:70      await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.eventually.rejected;71      await helper.staking.stake(staker, 100n * nominal);7273      // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...74      // ...so he can not transfer 90075      expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});76      await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejected;77      78      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(100n * nominal);79      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);80      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);81      // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo? 82      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased 8384      85      await helper.staking.stake(staker, 200n * nominal);86      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(300n * nominal);87      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);88      expect((await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map((x) => x[1])).to.be.deep.equal([100n * nominal, 200n * nominal]);89    });90  });9192  it('should allow to stake with nonce', async () => {93    await usingPlaygrounds(async (helper) => {94      const staker = accounts.pop()!;95      const transactions = [];96      for (let nonce = 0; nonce < 9; nonce++) {97        transactions.push(helper.signTransaction(staker, helper.api?.tx.promotion.stake(100n * nominal), 'Staker stakes with nonce', {nonce}));98      }99      await Promise.allSettled(transactions);100101      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(900n * nominal);102    });103  });104  105  it('should reject transaction if stake amount is more than total free balance minus frozen', async () => {106    await usingPlaygrounds(async helper => { 107      const staker = accounts.pop()!;108109      // Can't stake full balance because Alice needs to pay some fee110      await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.eventually.rejected;111      await helper.staking.stake(staker, 500n * nominal);112113      // Can't stake 500 tkn because Alice has Less than 500 transferable;114      await expect(helper.staking.stake(staker, 500n * nominal)).to.be.eventually.rejected; 115      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);116    });117  });118  119  it('for different accounts in one block is possible', async () => {120    await usingPlaygrounds(async helper => {121      const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];122      123      const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));124      await expect(Promise.all(crowdStartsToStake)).to.be.eventually.fulfilled;125126      const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));127      expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);128    });129  });130131  it('should allow to create maximum 10 stakes for account', async () => {132133  });134});135136describe('unstake balance extrinsic', () => {  137  it('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async () => {138    await usingPlaygrounds(async helper => {139      const [staker, recepient] = [accounts.pop()!, accounts.pop()!];140      const totalStakedBefore = await helper.staking.getTotalStaked();141      await helper.staking.stake(staker, 900n * nominal);142      await helper.staking.unstake(staker);143144      // Right after unstake balance is reserved145      // Staker can not transfer 146      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 900n * nominal, miscFrozen: 0n, feeFrozen: 0n});147      await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejected;148      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);149      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);150      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);151    });152  });153154  it('should unlock balance after unlocking period ends and subtract it from "pendingUnstake"', async () => {155    await usingPlaygrounds(async (helper) => {156      const staker = accounts.pop()!;157      await helper.staking.stake(staker, 100n * nominal);158      await helper.staking.unstake(staker);159160      // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n161      await waitForRelayBlock(helper.api!, 20);162      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n * nominal, miscFrozen: 0n, feeFrozen: 0n});163      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);164165      // staker can transfer:166      await helper.balance.transferToSubstrate(staker, alice.address, 998n * nominal);167      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);168    });169  });170171  it('should successfully unstake multiple stakes', async () => {172    await usingPlaygrounds(async helper => {173      const staker = accounts.pop()!;174      await helper.staking.stake(staker, 100n * nominal);175      await helper.staking.stake(staker, 200n * nominal);176      await helper.staking.stake(staker, 300n * nominal);177178      // staked: [100, 200, 300]; unstaked: 0179      let pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});180      let unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);181      let stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);182      expect(pendingUnstake).to.be.deep.equal(0n);183      expect(unstakedPerBlock).to.be.deep.equal([]);184      expect(stakedPerBlock).to.be.deep.equal([100n * nominal, 200n * nominal, 300n * nominal]);185     186      // Can unstake multiple stakes187      await helper.staking.unstake(staker);188      pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});189      unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);190      stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);191      expect(pendingUnstake).to.be.equal(600n * nominal);192      expect(stakedPerBlock).to.be.deep.equal([]);193      expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);194195      expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});196      await waitForRelayBlock(helper.api!, 20);197      expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});198      expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);199    });200  });201202  it('should not have any effects if no active stakes', async () => {203    await usingPlaygrounds(async (helper) => {204      const staker = accounts.pop()!;205      206      // unstake has no effect if no stakes at all207      await helper.staking.unstake(staker);208      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);209      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(0n);210      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper211212      // TODO stake() unstake() waitUnstaked() unstake();213214      // can't unstake if there are only pendingUnstakes215      await helper.staking.stake(staker, 100n * nominal);216      await helper.staking.unstake(staker);217      await helper.staking.unstake(staker);218219      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);220      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(100n * nominal);221      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);222    });223  });224225  it('should keep different unlocking block for each unlocking stake', async () => {226    await usingPlaygrounds(async (helper) => {227      const staker = accounts.pop()!;228      await helper.staking.stake(staker, 100n * nominal);229      await helper.staking.unstake(staker);230      await helper.staking.stake(staker, 120n * nominal);231      await helper.staking.unstake(staker);232233      const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});234      expect(unstakingPerBlock).has.length(2);235      expect(unstakingPerBlock[0][1]).to.equal(100n * nominal);236      expect(unstakingPerBlock[1][1]).to.equal(120n * nominal);237    });238  });239240  it('should be possible for different accounts in one block', async () => {241    await usingPlaygrounds(async (helper) => {242      const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];243244      await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));245      await Promise.all(stakers.map(staker => helper.staking.unstake(staker)));246247      await Promise.all(stakers.map(async (staker) => {248        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);249        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);250      }));251    });252  });253254  // TODO for different accounts in one block is possible255});256257describe('Admin adress', () => {258  it('can be set by sudo only', async () => {259    await usingPlaygrounds(async (helper) => {260      const nonAdmin = accounts.pop()!;261      // nonAdmin can not set admin not from himself nor as a sudo262      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.eventually.rejected;263      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.eventually.rejected;264265      // Alice can266      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;267    });268  });269  270  it('can be any valid CrossAccountId', async () => {271    // We are not going to set an eth address as a sponsor,272    // but we do want to check, it doesn't break anything;273    await usingPlaygrounds(async (helper) => {274      const account = accounts.pop()!;275      const ethAccount = helper.address.substrateToEth(account.address); 276      // Alice sets Ethereum address as a sudo. Then Substrate address back...277      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Ethereum: ethAccount})))).to.be.eventually.fulfilled;278      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;279      280      // ...It doesn't break anything;281      const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});282      await expect(helper.signTransaction(account, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;283    });284  });285286  it('can be reassigned', async () => {287    await usingPlaygrounds(async (helper) => {288      const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];289      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});290      291      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.eventually.fulfilled;292      await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.eventually.fulfilled;293      await expect(helper.signTransaction(oldAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;294      295      await expect(helper.signTransaction(newAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;296    });297  });298});299300describe('App-promotion collection sponsoring', () => {301  before(async function () {302    await usingPlaygrounds(async (helper) => {303      const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.setAdminAddress({Substrate: palletAdmin.address}));304      await helper.signTransaction(alice, tx);305    });306  });307308  it('should actually sponsor transactions', async () => {309    await usingPlaygrounds(async (helper) => {310      const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];311      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});312      const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});313      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId));314      const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);315316      await token.transfer(tokenSender, {Substrate: receiver.address});317      expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});318      const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);319320      // senders balance the same, transaction has sponsored321      expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);322      expect (palletBalanceBefore > palletBalanceAfter).to.be.true;323    });324  });325326  it('can not be set by non admin', async () => {327    await usingPlaygrounds(async (helper) => {328      const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];329330      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});331      332      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;333      expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');334    });335  });336337  it('should set pallet address as confirmed admin', async () => {338    await usingPlaygrounds(async (helper) => {339      const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];340      341      // Can set sponsoring for collection without sponsor342      const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});343      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.eventually.fulfilled;344      expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});345346      // Can set sponsoring for collection with unconfirmed sponsor347      const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});348      expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});349      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.eventually.fulfilled;350      expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});351352      // Can set sponsoring for collection with confirmed sponsor353      const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});354      await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);355      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.eventually.fulfilled;356      expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});357    });358  });359360  it('can be overwritten by collection owner', async () => {    361    await usingPlaygrounds(async (helper) => {362      const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];363      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});364      const collectionId = collection.collectionId;365      366      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionId))).to.be.eventually.fulfilled;367      368      // Collection limits still can be changed by the owner369      expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;370      expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);371      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});372373      // Collection sponsor can be changed too374      expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;375      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});376    });377  });378  379  it('should not overwrite collection limits set by the owner earlier', async () => {380    await usingPlaygrounds(async (helper) => {381      const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};382      const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});383384      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.eventually.fulfilled;385      expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);386    });387  });388  389  it('should reject transaction if collection doesn\'t exist', async () => {390    await usingPlaygrounds(async (helper) => {391      const collectionOwner = accounts.pop()!;392      393      // collection has never existed394      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(999999999))).to.be.eventually.rejected;395      // collection has been burned396      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});397      await collection.burn(collectionOwner);398399      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;400    });401  });402});403404describe('app-promotion stopSponsoringCollection', () => {405  it('can not be called by non-admin', async () => {    406    await usingPlaygrounds(async (helper) => {407      const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];408      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});409      410      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;411      412      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;413      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});414    });415  });416417  it('should set sponsoring as disabled', async () => {418    await usingPlaygrounds(async (helper) => {419      const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];420      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});421      const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});422      423      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.sponsorCollection(collection.collectionId));424      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId));425      426      expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');427428      // Transactions are not sponsored anymore:429      const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);430      await token.transfer(collectionOwner, {Substrate: recepient.address});431      const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);432      expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);433    });434  });435436  it('should not affect collection which is not sponsored by pallete', async () => {437    await usingPlaygrounds(async (helper) => {438      const collectionOwner = accounts.pop()!;439      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});440      await collection.confirmSponsorship(collectionOwner);441      442      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;443      444      expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});445    });446  });447448  it('should reject transaction if collection does not exist', async () => {    449    await usingPlaygrounds(async (helper) => {450      const collectionOwner = accounts.pop()!;451      const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});452      453      await collection.burn(collectionOwner);454      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;455      await expect(helper.signTransaction(palletAdmin, helper.api!.tx.promotion.stopSponsoringCollection(999999999))).to.be.eventually.rejected;456    });457  });458});459460describe('app-promotion contract sponsoring', () => {461  itWeb3('should set palletes address as a sponsor', async ({api, web3, privateKeyWrapper}) => {462    await usingPlaygrounds(async (helper) => {463      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();464      const flipper = await deployFlipper(web3, contractOwner);465      const contractMethods = contractHelpers(web3, contractOwner);466467      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));468      469      expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;  470      expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  471      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({472        confirmed: {473          substrate: palletAddress,474        },475      });476    });477  });478479  itWeb3('should overwrite sponsoring mode and existed sponsor', async ({api, web3, privateKeyWrapper}) => {480    await usingPlaygrounds(async (helper) => {481      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();482      const flipper = await deployFlipper(web3, contractOwner);483      const contractMethods = contractHelpers(web3, contractOwner);484485      await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;486487      // Contract is self sponsored488      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({489        confirmed: {490          ethereum: flipper.options.address.toLowerCase(),491        },492      });493494      // set promotion sponsoring495      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));496497      // new sponsor is pallet address498      expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;  499      expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  500      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({501        confirmed: {502          substrate: palletAddress,503        },504      });505    });506  });507508  itWeb3('can be overwritten by contract owner', async ({api, web3, privateKeyWrapper}) => {509    await usingPlaygrounds(async (helper) => {      510      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();511      const flipper = await deployFlipper(web3, contractOwner);512      const contractMethods = contractHelpers(web3, contractOwner);513514      // contract sponsored by pallet515      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));516517      // owner sets self sponsoring518      await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;519520      expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;  521      expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  522      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({523        confirmed: {524          ethereum: flipper.options.address.toLowerCase(),525        },526      });527    });528  });529530  itWeb3('can not be set by non admin', async ({api, web3, privateKeyWrapper}) => {531    await usingPlaygrounds(async (helper) => {      532      const nonAdmin = accounts.pop()!;533      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();534      const flipper = await deployFlipper(web3, contractOwner);535      const contractMethods = contractHelpers(web3, contractOwner);536537      await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;538539      // nonAdmin calls sponsorConract540      await expect(helper.signTransaction(nonAdmin, api.tx.promotion.sponsorConract(flipper.options.address))).to.be.rejected;541542      // contract still self-sponsored 543      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({544        confirmed: {545          ethereum: flipper.options.address.toLowerCase(),546        },547      });548    });549550    itWeb3('should be rejected for non-contract address', async ({api, web3, privateKeyWrapper}) => {551      await usingPlaygrounds(async (helper) => {552553      });554    });555  });556557  itWeb3('should actually sponsor transactions', async ({api, web3, privateKeyWrapper}) => {558    await usingPlaygrounds(async (helper) => {      559      const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);560      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();561      const flipper = await deployFlipper(web3, contractOwner);562      const contractHelper = contractHelpers(web3, contractOwner);563      await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});564      await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});565      await transferBalanceToEth(api, alice, flipper.options.address, 1000n);566567      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));568      await flipper.methods.flip().send({from: caller});569      expect(await flipper.methods.getValue().call()).to.be.true;570571      const callerBalance = await helper.balance.getEthereum(caller);572      const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);573574      expect(callerBalance).to.be.equal(1000n * nominal);575      expect(1000n * nominal > contractBalanceAfter).to.be.true;576    });577  });578});579580describe('app-promotion stopSponsoringContract', () => {  581  itWeb3('should remove pallet address from contract sponsors', async ({api, web3, privateKeyWrapper}) => {582    await usingPlaygrounds(async (helper) => {      583      const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);584      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();585      const flipper = await deployFlipper(web3, contractOwner);586      await transferBalanceToEth(api, alice, flipper.options.address);587      const contractHelper = contractHelpers(web3, contractOwner);588      await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});589      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));590      await helper.signTransaction(palletAdmin, api.tx.promotion.stopSponsoringContract(flipper.options.address));591592      expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;  593      expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  594      expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({595        disabled: null,596      });597598      await flipper.methods.flip().send({from: caller});599      expect(await flipper.methods.getValue().call()).to.be.true;600601      const callerBalance = await helper.balance.getEthereum(caller);602      const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);603604      // caller payed for call605      expect(1000n * nominal > callerBalance).to.be.true;606      expect(contractBalanceAfter).to.be.equal(1000n * nominal);607    });608  });609610  itWeb3('can not be called by non-admin', async ({api, web3, privateKeyWrapper}) => {611    await usingPlaygrounds(async (helper) => {      612      const nonAdmin = accounts.pop()!;613      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();614      const flipper = await deployFlipper(web3, contractOwner);615616      await helper.signTransaction(palletAdmin, api.tx.promotion.sponsorConract(flipper.options.address));617      await expect(helper.signTransaction(nonAdmin, api.tx.promotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;618    });619  });620621  itWeb3('should not affect a contract which is not sponsored by pallete', async ({api, web3, privateKeyWrapper}) => {622    await usingPlaygrounds(async (helper) => {      623      const nonAdmin = accounts.pop()!;624      const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();625      const flipper = await deployFlipper(web3, contractOwner);626      const contractHelper = contractHelpers(web3, contractOwner);627      await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;628629      await expect(helper.signTransaction(nonAdmin, api.tx.promotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;630    });631  });632});633634describe('app-promotion rewards', () => {635  it('can not be called by non admin', async () => {636    await usingPlaygrounds(async (helper) => {637      const nonAdmin = accounts.pop()!;638      await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.payoutStakers(50))).to.be.rejected;639    });640  });641642  it('should credit 0.05% for staking period', async () => {    643    // TODO flaky test644    await usingPlaygrounds(async helper => {645      const staker = accounts.pop()!;646      647      await helper.staking.stake(staker, 100n * nominal);648      await helper.staking.stake(staker, 200n * nominal);649      await waitForRelayBlock(helper.api!, 30);650      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));651652      const totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);653      expect(totalStakedPerBlock).to.be.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n)]);654    });655  });656657  it('shoud be paid for more than one period if payments was missed', async () => {658    await usingPlaygrounds(async (helper) => {659      const staker = accounts.pop()!;660661      await helper.staking.stake(staker, 100n * nominal);662      await helper.staking.stake(staker, 200n * nominal);663664      await waitForRelayBlock(helper.api!, 55);665      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));666      const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});667      expect(stakedPerBlock[0][1]).to.be.equal(calculateIncome(100n * nominal, 10n, 2));668      expect(stakedPerBlock[1][1]).to.be.equal(calculateIncome(200n * nominal, 10n, 2));669670      const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);671      const frozenBalanceShouldBe = calculateIncome(300n * nominal, 10n, 2);672673      expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});674    });675  });676  677  it('should not be credited for unstaked (reserved) balance', async () => {678    expect.fail('Test not implemented');679    await usingPlaygrounds(async helper => {680      const staker = accounts.pop()!;681    });682  });683  684  it('should bring compound interest', async () => {685    // TODO flaky test686    await usingPlaygrounds(async helper => {687      const staker = accounts.pop()!;688            689      await helper.staking.stake(staker, 100n * nominal);690      await helper.staking.stake(staker, 200n * nominal);691      await helper.staking.stake(staker, 300n * nominal);692      693      await waitForRelayBlock(helper.api!, 34);694      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));695      let totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);696      expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n), calculateIncome(300n * nominal, 10n)]);697      698      await waitForRelayBlock(helper.api!, 20);699      await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));700      totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);701      expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n, 2), calculateIncome(200n * nominal, 10n, 2), calculateIncome(300n * nominal, 10n, 2)]);      702    });703  });704705  it.skip('can handle 40.000 rewards', async () => {706    await usingPlaygrounds(async (helper) => {707      const [donor] = await helper.arrange.createAccounts([7_000_000n], alice);708      const crowdStakes = async () => {709        // each account in the crowd stakes 2 times710        const crowd = await helper.arrange.createCrowd(500, 300n, donor);711        await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));712        await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));713        // 714      };715716      for (let i = 0; i < 40; i++) {717        await crowdStakes();718      }719720      // TODO pay rewards for some period721    });722  });723});724725async function waitForRelayBlock(api: ApiPromise, blocks = 1): Promise<void> {726  const current_block = (await api.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();727  return new Promise<void>(async (resolve, reject) => {728    const unsubscribe = await api.query.parachainSystem.validationData(async (data) => {729      // console.log(`${current_block} || ${data.value.relayParentNumber.toNumber()}`);730      if (data.value.relayParentNumber.toNumber() - current_block >= blocks) {731        unsubscribe();732        resolve();733      }734    });735  });736}737738function calculatePalleteAddress(palletId: any) {739  const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));740  return encodeAddress(address);741}742743function calculateIncome(base: bigint, calcPeriod: bigint, iter = 0): bigint {744  const DAY = 7200n;745  const ACCURACY = 1_000_000_000n;746  const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;747  748  if (iter > 1) {749    return calculateIncome(income, calcPeriod, iter - 1);750  } else return income;751}