difftreelog
Add tests for trash-stakes rewards
in: master
1 file changed
tests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth1// 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 [77 {unstake: 'unstakeAll' as const},78 {unstake: 'unstakePartial' as const},79 ].map(testCase => {80 itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {81 const [staker] = await helper.arrange.createAccounts([2000n], donor);82 const ONE_STAKE = 100n * nominal;83 for (let i = 0; i < 10; i++) {84 await helper.staking.stake(staker, ONE_STAKE);85 }8687 // can have 10 stakes88 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);89 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);9091 await expect(helper.staking.stake(staker, ONE_STAKE)).to.be.rejectedWith('appPromotion.NoPermission');9293 // After unstake can stake again9495 // CASE 1: unstakeAll96 if (testCase.unstake === 'unstakeAll') {97 await helper.staking.unstakeAll(staker);98 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);99 await helper.staking.stake(staker, 100n * nominal);100 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);101 }102 // CASE 2: unstakePartial103 else {104 await helper.staking.unstakePartial(staker, ONE_STAKE);105 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);106 await helper.staking.stake(staker, 100n * nominal);107 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(10);108 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');109 await helper.staking.unstakePartial(staker, 150n * nominal);110 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);111 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(850n * nominal);112 }113 });114 });115116 itSub('should allow to stake() if balance is locked with different id', async ({helper}) => {117 const staker = accounts.pop()!;118119 // staker has tokens locked with vesting id:120 await helper.balance.vestedTransfer(donor, staker.address, {start: 0n, period: 1n, periodCount: 1n, perPeriod: 200n * nominal});121 expect(await helper.balance.getSubstrateFull(staker.address))122 .to.deep.contain({free: 1200n * nominal, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal, reserved: 0n});123124 // Locked balance can be staked. staker can stake 1200 tokens (minus fee):125 await helper.staking.stake(staker, 1000n * nominal);126 await helper.staking.stake(staker, 199n * nominal);127 // check balances128 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}, {id: 'appstake', amount: 1199n * nominal, reasons: 'All'}]);129 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 1199n * nominal, feeFrozen: 1199n * nominal});130 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);131 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(1199n * nominal);132133 // staker can unstake134 await helper.staking.unstakeAll(staker);135 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1199n * nominal);136 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});137 await helper.wait.forParachainBlockNumber(pendingUnstake.block);138139 // check balances140 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}]);141 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal});142 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);143 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);144145 // staker can transfer balances now146 await helper.balance.transferToSubstrate(staker, donor.address, 900n * nominal);147 });148149 itSub('should not allow to stake(), if stake amount is more than total free balance minus locked by staking', async ({helper}) => {150 const staker = accounts.pop()!;151152 // Can't stake full balance because Alice needs to pay some fee153 await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected; // With('Arithmetic')154 await helper.staking.stake(staker, 500n * nominal);155156 // Can't stake 500 tkn because Alice has Less than 500 transferable;157 await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejected; // With('Arithmetic');158 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);159 });160161 itSub('for different accounts in one block is possible', async ({helper}) => {162 const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];163164 const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));165 await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;166167 const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));168 expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);169 });170 });171172 describe('Unstaking', () => {173 [174 {method: 'unstakeAll' as const},175 {method: 'unstakePartial' as const},176 ].map(testCase => {177 itSub(`[${testCase.method}] should move tokens to "pendingUnstake" and subtract it from totalStaked`, async ({helper}) => {178 const [staker, recepient] = [accounts.pop()!, accounts.pop()!];179 const totalStakedBefore = await helper.staking.getTotalStaked();180 const STAKE_AMOUNT = 900n * nominal;181182 await helper.staking.stake(staker, STAKE_AMOUNT);183 testCase.method === 'unstakeAll'184 ? await helper.staking.unstakeAll(staker)185 : await helper.staking.unstakePartial(staker, STAKE_AMOUNT);186187 // Right after unstake tokens are still locked188 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);189 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: STAKE_AMOUNT, reasons: 'All'}]);190 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: STAKE_AMOUNT, feeFrozen: STAKE_AMOUNT});191 // Staker can not transfer192 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');193 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(STAKE_AMOUNT);194 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);195 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);196 });197 });198199 [200 {method: 'unstakeAll' as const},201 {method: 'unstakePartial' as const},202 ].map(testCase => {203 itSub(`[${testCase.method}] should unlock balance after unlocking period ends and remove it from "pendingUnstake"`, async ({helper}) => {204 const staker = accounts.pop()!;205 await helper.staking.stake(staker, 100n * nominal);206 testCase.method === 'unstakeAll'207 ? await helper.staking.unstakeAll(staker)208 : await helper.staking.unstakePartial(staker, 100n * nominal);209 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});210211 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n212 await helper.wait.forParachainBlockNumber(pendingUnstake.block);213 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});214 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);215216 // staker can transfer:217 await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);218 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);219 });220 });221222 [223 {method: 'unstakeAll' as const},224 {method: 'unstakePartial' as const},225 ].map(testCase => {226 itSub(`[${testCase.method}] should successfully unstake multiple stakes`, async ({helper}) => {227 const staker = accounts.pop()!;228 await helper.staking.stake(staker, 100n * nominal);229 await helper.staking.stake(staker, 200n * nominal);230 await helper.staking.stake(staker, 300n * nominal);231232 // staked: [100, 200, 300]; unstaked: 0233 let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});234 let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});235 let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});236 expect(totalPendingUnstake).to.be.deep.equal(0n);237 expect(pendingUnstake).to.be.deep.equal([]);238 expect(stakes[0].amount).to.equal(100n * nominal);239 expect(stakes[1].amount).to.equal(200n * nominal);240 expect(stakes[2].amount).to.equal(300n * nominal);241242 // Can unstake multiple stakes243 testCase.method === 'unstakeAll'244 ? await helper.staking.unstakeAll(staker)245 : await helper.staking.unstakePartial(staker, 600n * nominal);246247 pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});248 totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});249 stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});250 expect(totalPendingUnstake).to.be.equal(600n * nominal);251 expect(stakes).to.be.deep.equal([]);252 expect(pendingUnstake[0].amount).to.equal(600n * nominal);253254 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});255 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);256 await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);257 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});258 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);259 });260 });261262 [263 {method: 'unstakeAll' as const},264 {method: 'unstakePartial' as const},265 ].map(testCase => {266 itSub(`[${testCase.method}] should not have any effects if no active stakes`, async ({helper}) => {267 const staker = accounts.pop()!;268269 // unstake has no effect if no stakes at all270 testCase.method === 'unstakeAll'271 ? await helper.staking.unstakeAll(staker)272 : await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');273274 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);275 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper276277 // TODO stake() unstake() waitUnstaked() unstake();278279 // can't unstake if there are only pendingUnstakes280 await helper.staking.stake(staker, 100n * nominal);281282 if (testCase.method === 'unstakeAll') {283 await helper.staking.unstakeAll(staker);284 await helper.staking.unstakeAll(staker);285 } else {286 await helper.staking.unstakePartial(staker, 100n * nominal);287 await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');288 }289290 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);291 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);292 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);293 });294 });295296 [297 {method: 'unstakeAll' as const},298 {method: 'unstakePartial' as const},299 ].map(testCase => {300 itSub(`[${testCase.method}] should create different pending-unlock for each unlocking stake`, async ({helper}) => {301 const staker = accounts.pop()!;302 await helper.staking.stake(staker, 100n * nominal);303 testCase.method === 'unstakeAll'304 ? await helper.staking.unstakeAll(staker)305 : await helper.staking.unstakePartial(staker, 100n * nominal);306 await helper.staking.stake(staker, 120n * nominal);307 testCase.method === 'unstakeAll'308 ? await helper.staking.unstakeAll(staker)309 : await helper.staking.unstakePartial(staker, 120n * nominal);310311 const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});312 expect(unstakingPerBlock).has.length(2);313 expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);314 expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);315 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.equal(0);316 });317 });318319 [320 {method: 'unstakeAll' as const},321 {method: 'unstakePartial' as const},322 ].map(testCase => {323 itSub(`[${testCase.method}] should be possible for 3 accounts in one block`, async ({helper}) => {324 const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];325326 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));327 await Promise.all(stakers.map(staker => {328 return testCase.method === 'unstakeAll'329 ? helper.staking.unstakeAll(staker)330 : helper.staking.unstakePartial(staker, 100n * nominal);331 }));332333 await Promise.all(stakers.map(async (staker) => {334 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);335 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);336 }));337 });338 });339340 itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {341 if (!await helper.arrange.isDevNode()) {342 const stakers = await helper.arrange.createAccounts([200n,200n,200n,200n,200n,200n,200n,200n,200n,200n], donor);343344 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));345 const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => {346 return i % 2 === 0347 ? helper.staking.unstakeAll(staker)348 : helper.staking.unstakePartial(staker, 100n * nominal);349 }));350351 const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');352 expect(successfulUnstakes).to.have.length(3);353 }354 });355356 itSub('Cannot partially unstake more than staked', async ({helper}) => {357 const staker = accounts.pop()!;358 // Staker stakes 300:359 await helper.staking.stake(staker, 100n * nominal);360 await helper.staking.stake(staker, 200n * nominal);361362 // cannot usntake 300.00000...1363 await expect(helper.staking.unstakePartial(staker, 300n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');364 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(2);365366 await helper.staking.unstakePartial(staker, 150n * nominal);367 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);368 await expect(helper.staking.unstakePartial(staker, 150n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');369 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);370371 // nothing broken, can unstake full amount:372 await helper.staking.unstakePartial(staker, 150n * nominal);373 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(0);374 });375376 itSub('Can partially unstake arbitrary amount', async ({helper}) => {377 const staker = accounts.pop()!;378 await helper.staking.stake(staker, 100n * nominal);379 await helper.staking.stake(staker, 200n * nominal);380381 // 0. Staker cannot unstake negative amount382 await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;383384 // 1. Staker can unstake 0 wei385 await helper.staking.unstakePartial(staker, 0n);386 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);387 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal);388 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);389390 // 2. Staker can unstake 1 wei391 await helper.staking.unstakePartial(staker, 1n);392 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);393 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal - 1n);394 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1n);395 // 2.1 The oldest stake decreased:396 let [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});397 expect(stake1.amount).to.eq(100n * nominal - 1n);398 expect(stake2.amount).to.eq(200n * nominal);399400 // 3. Staker can unstake all but 1 wei401 await helper.staking.unstakePartial(staker, 100n * nominal - 2n);402 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);403 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(200n * nominal + 1n);404 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(100n * nominal - 1n);405 [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});406 expect(stake1.amount).to.eq(1n);407 expect(stake2.amount).to.eq(200n * nominal);408 });409410 itSub('can mix different type of unstakes', async ({helper}) => {411 const staker = accounts.pop()!;412 await helper.staking.stake(staker, 100n * nominal);413 await helper.staking.stake(staker, 200n * nominal);414415 await helper.staking.unstakePartial(staker, 50n * nominal);416 await helper.staking.unstakeAll(staker);417 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);418 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);419 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(300n * nominal);420421 const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});422 await helper.wait.forParachainBlockNumber(unstake2.block);423424 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([]);425 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});426 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);427 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);428 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);429 expect(await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).to.deep.eq([]);430 });431 });432433 describe('collection sponsoring', () => {434 itSub('should actually sponsor transactions', async ({helper}) => {435 const api = helper.getApi();436 const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];437 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});438 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});439 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));440 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);441442 await token.transfer(tokenSender, {Substrate: receiver.address});443 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});444 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);445446 // senders balance the same, transaction has sponsored447 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);448 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;449 });450451 itSub('can not be set by non admin', async ({helper}) => {452 const api = helper.getApi();453 const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];454455 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});456457 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;458 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');459 });460461 itSub('should set pallet address as confirmed admin', async ({helper}) => {462 const api = helper.getApi();463 const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];464465 // Can set sponsoring for collection without sponsor466 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});467 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;468 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});469470 // Can set sponsoring for collection with unconfirmed sponsor471 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});472 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});473 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;474 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});475476 // Can set sponsoring for collection with confirmed sponsor477 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});478 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);479 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;480 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});481 });482483 itSub('can be overwritten by collection owner', async ({helper}) => {484 const api = helper.getApi();485 const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];486 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});487 const collectionId = collection.collectionId;488489 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;490491 // Collection limits still can be changed by the owner492 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;493 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);494 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});495496 // Collection sponsor can be changed too497 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;498 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});499 });500501 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {502 const api = helper.getApi();503 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};504 const collectionWithLimits = await helper.nft.mintCollection(accounts.pop()!, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});505506 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;507 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);508 });509510 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {511 const api = helper.getApi();512 const collectionOwner = accounts.pop()!;513514 // collection has never existed515 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;516 // collection has been burned517 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});518 await collection.burn(collectionOwner);519520 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;521 });522 });523524 describe('stopSponsoringCollection', () => {525 itSub('can not be called by non-admin', async ({helper}) => {526 const api = helper.getApi();527 const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];528 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});529530 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;531532 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;533 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});534 });535536 itSub('should set sponsoring as disabled', async ({helper}) => {537 const api = helper.getApi();538 const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];539 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});540 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});541542 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));543 await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));544545 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');546547 // Transactions are not sponsored anymore:548 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);549 await token.transfer(collectionOwner, {Substrate: recepient.address});550 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);551 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);552 });553554 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {555 const api = helper.getApi();556 const collectionOwner = accounts.pop()!;557 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});558 await collection.confirmSponsorship(collectionOwner);559560 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;561562 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});563 });564565 itSub('should reject transaction if collection does not exist', async ({helper}) => {566 const collectionOwner = accounts.pop()!;567 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});568569 await collection.burn(collectionOwner);570 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');571 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');572 });573 });574575 describe('contract sponsoring', () => {576 itEth('should set palletes address as a sponsor', async ({helper}) => {577 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();578 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);579 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);580581 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);582583 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;584 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);585 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({586 confirmed: {587 substrate: palletAddress,588 },589 });590 });591592 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {593 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();594 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);595 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);596597 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;598599 // Contract is self sponsored600 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({601 confirmed: {602 ethereum: flipper.options.address.toLowerCase(),603 },604 });605606 // set promotion sponsoring607 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);608609 // new sponsor is pallet address610 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;611 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);612 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({613 confirmed: {614 substrate: palletAddress,615 },616 });617 });618619 itEth('can be overwritten by contract owner', async ({helper}) => {620 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();621 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);622 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);623624 // contract sponsored by pallet625 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);626627 // owner sets self sponsoring628 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;629630 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;631 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);632 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({633 confirmed: {634 ethereum: flipper.options.address.toLowerCase(),635 },636 });637 });638639 itEth('can not be set by non admin', async ({helper}) => {640 const nonAdmin = accounts.pop()!;641 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();642 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);643 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);644645 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;646647 // nonAdmin calls sponsorContract648 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');649650 // contract still self-sponsored651 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({652 confirmed: {653 ethereum: flipper.options.address.toLowerCase(),654 },655 });656 });657658 itEth('should actually sponsor transactions', async ({helper}) => {659 // Contract caller660 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);661 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);662663 // Deploy flipper664 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();665 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);666 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);667668 // Owner sets to sponsor every tx669 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});670 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});671 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);672673 // Set promotion to the Flipper674 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);675676 // Caller calls Flipper677 await flipper.methods.flip().send({from: caller});678 expect(await flipper.methods.getValue().call()).to.be.true;679680 // The contracts and caller balances have not changed681 const callerBalance = await helper.balance.getEthereum(caller);682 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);683 expect(callerBalance).to.be.equal(1000n * nominal);684 expect(1000n * nominal === contractBalanceAfter).to.be.true;685686 // The pallet balance has decreased687 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);688 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;689 });690 });691692 describe('stopSponsoringContract', () => {693 itEth('should remove pallet address from contract sponsors', async ({helper}) => {694 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);695 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();696 const flipper = await helper.eth.deployFlipper(contractOwner);697 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);698 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);699700 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});701 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);702 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);703704 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;705 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);706 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({707 disabled: null,708 });709710 await flipper.methods.flip().send({from: caller});711 expect(await flipper.methods.getValue().call()).to.be.true;712713 const callerBalance = await helper.balance.getEthereum(caller);714 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);715716 // caller payed for call717 expect(1000n * nominal > callerBalance).to.be.true;718 expect(contractBalanceAfter).to.be.equal(100n * nominal);719 });720721 itEth('can not be called by non-admin', async ({helper}) => {722 const nonAdmin = accounts.pop()!;723 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();724 const flipper = await helper.eth.deployFlipper(contractOwner);725726 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);727 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))728 .to.be.rejectedWith(/appPromotion\.NoPermission/);729 });730731 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {732 const nonAdmin = accounts.pop()!;733 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();734 const flipper = await helper.eth.deployFlipper(contractOwner);735 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);736 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;737738 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');739 });740 });741742 describe('payoutStakers', () => {743 itSub('can not be called by non admin', async ({helper}) => {744 const nonAdmin = accounts.pop()!;745 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');746 });747748 itSub('should increase total staked', async ({helper}) => {749 const staker = accounts.pop()!;750 const totalStakedBefore = await helper.staking.getTotalStaked();751 await helper.staking.stake(staker, 100n * nominal);752753 // Wait for rewards and pay754 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});755 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));756 const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);757758 const totalStakedAfter = await helper.staking.getTotalStaked();759 expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);760 // staker can unstake761 await helper.staking.unstakeAll(staker);762 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));763 });764765 itSub('should credit 0.05% for staking period', async ({helper}) => {766 const staker = accounts.pop()!;767768 await waitPromotionPeriodDoesntEnd(helper);769770 await helper.staking.stake(staker, 100n * nominal);771 await helper.staking.stake(staker, 200n * nominal);772773 // wait rewards are available:774 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});775 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));776777 const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)?.payout;778 expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal));779780 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});781 const income1 = calculateIncome(100n * nominal);782 const income2 = calculateIncome(200n * nominal);783 expect(totalStakedPerBlock[0].amount).to.equal(income1);784 expect(totalStakedPerBlock[1].amount).to.equal(income2);785786 const stakerBalance = await helper.balance.getSubstrateFull(staker.address);787 expect(stakerBalance).to.contain({miscFrozen: income1 + income2, feeFrozen: income1 + income2, reserved: 0n});788 expect(stakerBalance.free / nominal).to.eq(999n);789 });790791 itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {792 const staker = accounts.pop()!;793794 await helper.staking.stake(staker, 100n * nominal);795 // wait for two rewards are available:796 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});797 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);798799 await helper.admin.payoutStakers(palletAdmin, 100);800 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});801 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 2);802 expect(stake.amount).to.be.equal(frozenBalanceShouldBe);803804 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);805806 expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});807 });808809 itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {810 // staker unstakes before rewards been payed811 const staker = accounts.pop()!;812 await helper.staking.stake(staker, 100n * nominal);813 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});814 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);815 await helper.staking.unstakeAll(staker);816817 // so he did not receive any rewards818 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);819 await helper.admin.payoutStakers(palletAdmin, 100);820 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);821822 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);823 });824825 itSub('should bring compound interest', async ({helper}) => {826 const staker = accounts.pop()!;827828 await helper.staking.stake(staker, 100n * nominal);829830 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});831 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));832833 await helper.admin.payoutStakers(palletAdmin, 100);834 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});835 expect(stake.amount).to.equal(calculateIncome(100n * nominal));836837 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);838 await helper.admin.payoutStakers(palletAdmin, 100);839 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});840 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));841 });842843 itSub('can calculate reward for tiny stake', async ({helper}) => {844 const staker = accounts.pop()!;845 await helper.staking.stake(staker, 100n * nominal);846 await helper.staking.stake(staker, 100n * nominal);847 await helper.staking.unstakePartial(staker, 100n * nominal - 1n);848849 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});850 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));851852 const payouts = await helper.admin.payoutStakers(palletAdmin, 100);853 const stakerPayout = payouts.find(p => p.staker === staker.address);854 expect(stakerPayout!.stake).to.eq(100n * nominal + 1n);855 });856857 itSub('can eventually pay all rewards', async ({helper}) => {858 const stakers = await helper.arrange.createAccounts(new Array(100).fill(200n), donor);859 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));860861 let unstakingTxs = [];862 for (const staker of stakers) {863 if (unstakingTxs.length == 3) {864 await Promise.all(unstakingTxs);865 unstakingTxs = [];866 }867 unstakingTxs.push(helper.staking.unstakePartial(staker, 100n * nominal - 1n));868 }869870 const [staker] = await helper.arrange.createAccounts([1000n], donor);871 await helper.staking.stake(staker, 100n * nominal);872 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});873 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));874875 let payouts;876 do {877 payouts = await helper.admin.payoutStakers(palletAdmin, 20);878 } while (payouts.length !== 0);879 });880 });881});882883884function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {885 const DAY = 7200n;886 const ACCURACY = 1_000_000_000n;887 // 5n / 10_000n = 0.05% p/day888 const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;889890 if (iter > 1) {891 return calculateIncome(income, iter - 1, calcPeriod);892 } else return income;893}894895function rewardAvailableInBlock(stakedInBlock: bigint) {896 if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;897 return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);898}899900// Wait while promotion period less than specified block, to avoid boundary cases901// 0 if this should be the beginning of the period.902async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {903 const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();904 const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;905906 if (currentPeriodBlock > waitBlockLessThan) {907 await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);908 }909}