difftreelog
Fix flaky test
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[];29let usedAccounts: IKeyringPair[] = [];3031function getAccount(accountsNumber: number) {32 const accs = accounts.splice(0, accountsNumber);33 usedAccounts.push(...accs);34 return accs;35}36// App promotion periods:37// LOCKING_PERIOD = 12 blocks of relay38// UNLOCKING_PERIOD = 6 blocks of parachain3940describe('App promotion', () => {41 before(async function () {42 await usingPlaygrounds(async (helper, privateKey) => {43 requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);44 donor = await privateKey({filename: __filename});45 palletAddress = helper.arrange.calculatePalletAddress('appstake');46 palletAdmin = await privateKey('//PromotionAdmin');47 nominal = helper.balance.getOneTokenNominal();4849 const accountBalances = new Array(200).fill(1000n);50 accounts = await helper.arrange.createAccounts(accountBalances, donor); // create accounts-pool to speed up tests51 });52 });5354 afterEach(async () => {55 await usingPlaygrounds(async (helper) => {56 let unstakeTxs = [];57 for (const account of usedAccounts) {58 if (unstakeTxs.length === 3) {59 await Promise.all(unstakeTxs);60 unstakeTxs = [];61 }62 unstakeTxs.push(helper.staking.unstakeAll(account));63 }64 await Promise.all(unstakeTxs);65 usedAccounts = [];66 });67 });6869 describe('stake extrinsic', () => {70 itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {71 const [staker, recepient] = getAccount(2);72 const totalStakedBefore = await helper.staking.getTotalStaked();7374 // Minimum stake amount is 100:75 await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;76 await helper.staking.stake(staker, 100n * nominal);7778 // Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...79 // ...so he can not transfer 90080 expect(await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});81 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: 100n * nominal, reasons: 'All'}]);82 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');8384 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);85 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);86 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?87 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased888990 await helper.staking.stake(staker, 200n * nominal);91 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);92 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});93 expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);94 expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);95 });9697 [98 {unstake: 'unstakeAll' as const},99 {unstake: 'unstakePartial' as const},100 ].map(testCase => {101 itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {102 const [staker] = await helper.arrange.createAccounts([2000n], donor);103 const ONE_STAKE = 100n * nominal;104 for (let i = 0; i < 10; i++) {105 await helper.staking.stake(staker, ONE_STAKE);106 }107108 // can have 10 stakes109 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);110 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);111112 await expect(helper.staking.stake(staker, ONE_STAKE)).to.be.rejectedWith('appPromotion.NoPermission');113114 // After unstake can stake again115116 // CASE 1: unstakeAll117 if (testCase.unstake === 'unstakeAll') {118 await helper.staking.unstakeAll(staker);119 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);120 await helper.staking.stake(staker, 100n * nominal);121 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);122 }123 // CASE 2: unstakePartial124 else {125 await helper.staking.unstakePartial(staker, ONE_STAKE);126 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);127 await helper.staking.stake(staker, 100n * nominal);128 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(10);129 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');130 await helper.staking.unstakePartial(staker, 150n * nominal);131 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(9);132 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(850n * nominal);133 }134 });135 });136137 itSub('should allow to stake() if balance is locked with different id', async ({helper}) => {138 const [staker] = getAccount(1);139140 // staker has tokens locked with vesting id:141 await helper.balance.vestedTransfer(donor, staker.address, {start: 0n, period: 1n, periodCount: 1n, perPeriod: 200n * nominal});142 expect(await helper.balance.getSubstrateFull(staker.address))143 .to.deep.contain({free: 1200n * nominal, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal, reserved: 0n});144145 // Locked balance can be staked. staker can stake 1200 tokens (minus fee):146 await helper.staking.stake(staker, 1000n * nominal);147 await helper.staking.stake(staker, 199n * nominal);148 // check balances149 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}, {id: 'appstake', amount: 1199n * nominal, reasons: 'All'}]);150 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 1199n * nominal, feeFrozen: 1199n * nominal});151 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);152 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(1199n * nominal);153154 // staker can unstake155 await helper.staking.unstakeAll(staker);156 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1199n * nominal);157 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});158 await helper.wait.forParachainBlockNumber(pendingUnstake.block);159160 // check balances161 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}]);162 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 200n * nominal, feeFrozen: 200n * nominal});163 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);164 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);165166 // staker can transfer balances now167 await helper.balance.transferToSubstrate(staker, donor.address, 900n * nominal);168 });169170 itSub('should not allow to stake(), if stake amount is more than total free balance minus locked by staking', async ({helper}) => {171 const [staker] = getAccount(1);172173 // Can't stake full balance because Alice needs to pay some fee174 await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected; // With('Arithmetic')175 await helper.staking.stake(staker, 500n * nominal);176177 // Can't stake 500 tkn because Alice has Less than 500 transferable;178 await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejected; // With('Arithmetic');179 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);180 });181182 itSub('for different accounts in one block is possible', async ({helper}) => {183 const crowd = getAccount(4);184185 const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));186 await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;187188 const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));189 expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);190 });191 });192193 describe('Unstaking', () => {194 [195 {method: 'unstakeAll' as const},196 {method: 'unstakePartial' as const},197 ].map(testCase => {198 itSub(`[${testCase.method}] should move tokens to "pendingUnstake" and subtract it from totalStaked`, async ({helper}) => {199 const [staker, recepient] = getAccount(2);200 const totalStakedBefore = await helper.staking.getTotalStaked();201 const STAKE_AMOUNT = 900n * nominal;202203 await helper.staking.stake(staker, STAKE_AMOUNT);204 testCase.method === 'unstakeAll'205 ? await helper.staking.unstakeAll(staker)206 : await helper.staking.unstakePartial(staker, STAKE_AMOUNT);207208 // Right after unstake tokens are still locked209 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);210 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: STAKE_AMOUNT, reasons: 'All'}]);211 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: STAKE_AMOUNT, feeFrozen: STAKE_AMOUNT});212 // Staker can not transfer213 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');214 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(STAKE_AMOUNT);215 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);216 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);217 });218 });219220 [221 {method: 'unstakeAll' as const},222 {method: 'unstakePartial' as const},223 ].map(testCase => {224 itSub(`[${testCase.method}] should unlock balance after unlocking period ends and remove it from "pendingUnstake"`, async ({helper}) => {225 const [staker] = getAccount(1);226 await helper.staking.stake(staker, 100n * nominal);227 testCase.method === 'unstakeAll'228 ? await helper.staking.unstakeAll(staker)229 : await helper.staking.unstakePartial(staker, 100n * nominal);230 const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});231232 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n233 await helper.wait.forParachainBlockNumber(pendingUnstake.block);234 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});235 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);236237 // staker can transfer:238 await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);239 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);240 });241 });242243 [244 {method: 'unstakeAll' as const},245 {method: 'unstakePartial' as const},246 ].map(testCase => {247 itSub(`[${testCase.method}] should successfully unstake multiple stakes`, async ({helper}) => {248 const [staker] = getAccount(1);249 await helper.staking.stake(staker, 100n * nominal);250 await helper.staking.stake(staker, 200n * nominal);251 await helper.staking.stake(staker, 300n * nominal);252253 // staked: [100, 200, 300]; unstaked: 0254 let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});255 let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});256 let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});257 expect(totalPendingUnstake).to.be.deep.equal(0n);258 expect(pendingUnstake).to.be.deep.equal([]);259 expect(stakes[0].amount).to.equal(100n * nominal);260 expect(stakes[1].amount).to.equal(200n * nominal);261 expect(stakes[2].amount).to.equal(300n * nominal);262263 // Can unstake multiple stakes264 testCase.method === 'unstakeAll'265 ? await helper.staking.unstakeAll(staker)266 : await helper.staking.unstakePartial(staker, 600n * nominal);267268 pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});269 totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});270 stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});271 expect(totalPendingUnstake).to.be.equal(600n * nominal);272 expect(stakes).to.be.deep.equal([]);273 expect(pendingUnstake[0].amount).to.equal(600n * nominal);274275 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});276 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);277 await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);278 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});279 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);280 });281 });282283 [284 {method: 'unstakeAll' as const},285 {method: 'unstakePartial' as const},286 ].map(testCase => {287 itSub(`[${testCase.method}] should not have any effects if no active stakes`, async ({helper}) => {288 const [staker] = getAccount(1);289290 // unstake has no effect if no stakes at all291 testCase.method === 'unstakeAll'292 ? await helper.staking.unstakeAll(staker)293 : await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');294295 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);296 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper297298 // TODO stake() unstake() waitUnstaked() unstake();299300 // can't unstake if there are only pendingUnstakes301 await helper.staking.stake(staker, 100n * nominal);302303 if (testCase.method === 'unstakeAll') {304 await helper.staking.unstakeAll(staker);305 await helper.staking.unstakeAll(staker);306 } else {307 await helper.staking.unstakePartial(staker, 100n * nominal);308 await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');309 }310311 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);312 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);313 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);314 });315 });316317 [318 {method: 'unstakeAll' as const},319 {method: 'unstakePartial' as const},320 ].map(testCase => {321 itSub(`[${testCase.method}] should create different pending-unlock for each unlocking stake`, async ({helper}) => {322 const [staker] = getAccount(1);323 await helper.staking.stake(staker, 100n * nominal);324 testCase.method === 'unstakeAll'325 ? await helper.staking.unstakeAll(staker)326 : await helper.staking.unstakePartial(staker, 100n * nominal);327 await helper.staking.stake(staker, 120n * nominal);328 testCase.method === 'unstakeAll'329 ? await helper.staking.unstakeAll(staker)330 : await helper.staking.unstakePartial(staker, 120n * nominal);331332 const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});333 expect(unstakingPerBlock).has.length(2);334 expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);335 expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);336 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.equal(0);337 });338 });339340 [341 {method: 'unstakeAll' as const},342 {method: 'unstakePartial' as const},343 ].map(testCase => {344 itSub(`[${testCase.method}] should be possible for 3 accounts in one block`, async ({helper}) => {345 const stakers = getAccount(3);346347 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));348 await Promise.all(stakers.map(staker => {349 return testCase.method === 'unstakeAll'350 ? helper.staking.unstakeAll(staker)351 : helper.staking.unstakePartial(staker, 100n * nominal);352 }));353354 await Promise.all(stakers.map(async (staker) => {355 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);356 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);357 }));358 });359 });360361 itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {362 if (!await helper.arrange.isDevNode()) {363 const stakers = getAccount(10);364365 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));366 const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => {367 return i % 2 === 0368 ? helper.staking.unstakeAll(staker)369 : helper.staking.unstakePartial(staker, 100n * nominal);370 }));371372 const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');373 expect(successfulUnstakes).to.have.length(3);374 }375 });376377 itSub('Cannot partially unstake more than staked', async ({helper}) => {378 const [staker] = getAccount(1);379 // Staker stakes 300:380 await helper.staking.stake(staker, 100n * nominal);381 await helper.staking.stake(staker, 200n * nominal);382383 // cannot usntake 300.00000...1384 await expect(helper.staking.unstakePartial(staker, 300n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');385 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(2);386387 await helper.staking.unstakePartial(staker, 150n * nominal);388 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);389 await expect(helper.staking.unstakePartial(staker, 150n * nominal + 1n)).to.be.rejectedWith('appPromotion.InsufficientStakedBalance');390 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(1);391392 // nothing broken, can unstake full amount:393 await helper.staking.unstakePartial(staker, 150n * nominal);394 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).eq(0);395 });396397 itSub('Can partially unstake arbitrary amount', async ({helper}) => {398 const [staker] = getAccount(1);399 await helper.staking.stake(staker, 100n * nominal);400 await helper.staking.stake(staker, 200n * nominal);401402 // 0. Staker cannot unstake negative amount403 await expect(helper.staking.unstakePartial(staker, -1n)).to.be.rejected;404405 // 1. Staker can unstake 0 wei406 await helper.staking.unstakePartial(staker, 0n);407 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);408 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal);409 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);410411 // 2. Staker can unstake 1 wei412 await helper.staking.unstakePartial(staker, 1n);413 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);414 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(300n * nominal - 1n);415 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(1n);416 // 2.1 The oldest stake decreased:417 let [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});418 expect(stake1.amount).to.eq(100n * nominal - 1n);419 expect(stake2.amount).to.eq(200n * nominal);420421 // 3. Staker can unstake all but 1 wei422 await helper.staking.unstakePartial(staker, 100n * nominal - 2n);423 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(2);424 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(200n * nominal + 1n);425 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(100n * nominal - 1n);426 [stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});427 expect(stake1.amount).to.eq(1n);428 expect(stake2.amount).to.eq(200n * nominal);429 });430431 itSub('can mix different type of unstakes', async ({helper}) => {432 const [staker] = getAccount(1);433 await helper.staking.stake(staker, 100n * nominal);434 await helper.staking.stake(staker, 200n * nominal);435436 await helper.staking.unstakePartial(staker, 50n * nominal);437 await helper.staking.unstakeAll(staker);438 expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);439 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);440 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(300n * nominal);441442 const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});443 await helper.wait.forParachainBlockNumber(unstake2.block);444445 expect(await helper.balance.getLocked(staker.address)).to.deep.eq([]);446 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});447 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);448 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);449 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.eq(0n);450 expect(await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).to.deep.eq([]);451 });452 });453454 describe('collection sponsoring', () => {455 itSub('should actually sponsor transactions', async ({helper}) => {456 const api = helper.getApi();457 const [collectionOwner, tokenSender, receiver] = getAccount(3);458 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});459 const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});460 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));461 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);462463 await token.transfer(tokenSender, {Substrate: receiver.address});464 expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});465 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);466467 // senders balance the same, transaction has sponsored468 expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);469 expect (palletBalanceBefore > palletBalanceAfter).to.be.true;470 });471472 itSub('can not be set by non admin', async ({helper}) => {473 const api = helper.getApi();474 const [collectionOwner, nonAdmin] = getAccount(2);475476 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});477478 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;479 expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');480 });481482 itSub('should set pallet address as confirmed admin', async ({helper}) => {483 const api = helper.getApi();484 const [collectionOwner, oldSponsor] = getAccount(2);485486 // Can set sponsoring for collection without sponsor487 const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});488 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;489 expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});490491 // Can set sponsoring for collection with unconfirmed sponsor492 const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});493 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});494 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;495 expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});496497 // Can set sponsoring for collection with confirmed sponsor498 const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});499 await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);500 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;501 expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});502 });503504 itSub('can be overwritten by collection owner', async ({helper}) => {505 const api = helper.getApi();506 const [collectionOwner, newSponsor] = getAccount(2);507 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});508 const collectionId = collection.collectionId;509510 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;511512 // Collection limits still can be changed by the owner513 expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;514 expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);515 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});516517 // Collection sponsor can be changed too518 expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;519 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});520 });521522 itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {523 const api = helper.getApi();524 const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};525 const collectionWithLimits = await helper.nft.mintCollection(getAccount(1)[0], {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});526527 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;528 expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);529 });530531 itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {532 const api = helper.getApi();533 const [collectionOwner] = getAccount(1);534535 // collection has never existed536 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;537 // collection has been burned538 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});539 await collection.burn(collectionOwner);540541 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;542 });543 });544545 describe('stopSponsoringCollection', () => {546 itSub('can not be called by non-admin', async ({helper}) => {547 const api = helper.getApi();548 const [collectionOwner, nonAdmin] = getAccount(2);549 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});550551 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;552553 await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;554 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});555 });556557 itSub('should set sponsoring as disabled', async ({helper}) => {558 const api = helper.getApi();559 const [collectionOwner, recepient] = getAccount(2);560 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});561 const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});562563 await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));564 await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));565566 expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');567568 // Transactions are not sponsored anymore:569 const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);570 await token.transfer(collectionOwner, {Substrate: recepient.address});571 const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);572 expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);573 });574575 itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {576 const api = helper.getApi();577 const [collectionOwner] = getAccount(1);578 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});579 await collection.confirmSponsorship(collectionOwner);580581 await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;582583 expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});584 });585586 itSub('should reject transaction if collection does not exist', async ({helper}) => {587 const [collectionOwner] = getAccount(1);588 const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});589590 await collection.burn(collectionOwner);591 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');592 await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');593 });594 });595596 describe('contract sponsoring', () => {597 itEth('should set palletes address as a sponsor', async ({helper}) => {598 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();599 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);600 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);601602 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);603604 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;605 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);606 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({607 confirmed: {608 substrate: palletAddress,609 },610 });611 });612613 itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {614 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();615 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);616 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);617618 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;619620 // Contract is self sponsored621 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({622 confirmed: {623 ethereum: flipper.options.address.toLowerCase(),624 },625 });626627 // set promotion sponsoring628 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);629630 // new sponsor is pallet address631 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;632 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);633 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({634 confirmed: {635 substrate: palletAddress,636 },637 });638 });639640 itEth('can be overwritten by contract owner', async ({helper}) => {641 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();642 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);643 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);644645 // contract sponsored by pallet646 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);647648 // owner sets self sponsoring649 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;650651 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;652 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);653 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({654 confirmed: {655 ethereum: flipper.options.address.toLowerCase(),656 },657 });658 });659660 itEth('can not be set by non admin', async ({helper}) => {661 const [nonAdmin] = getAccount(1);662 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();663 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);664 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);665666 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;667668 // nonAdmin calls sponsorContract669 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');670671 // contract still self-sponsored672 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({673 confirmed: {674 ethereum: flipper.options.address.toLowerCase(),675 },676 });677 });678679 itEth('should actually sponsor transactions', async ({helper}) => {680 // Contract caller681 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);682 const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);683684 // Deploy flipper685 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();686 const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);687 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);688689 // Owner sets to sponsor every tx690 await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});691 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});692 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);693694 // Set promotion to the Flipper695 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);696697 // Caller calls Flipper698 await flipper.methods.flip().send({from: caller});699 expect(await flipper.methods.getValue().call()).to.be.true;700701 // The contracts and caller balances have not changed702 const callerBalance = await helper.balance.getEthereum(caller);703 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);704 expect(callerBalance).to.be.equal(1000n * nominal);705 expect(1000n * nominal === contractBalanceAfter).to.be.true;706707 // The pallet balance has decreased708 const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);709 expect(palletBalanceAfter < palletBalanceBefore).to.be.true;710 });711 });712713 describe('stopSponsoringContract', () => {714 itEth('should remove pallet address from contract sponsors', async ({helper}) => {715 const caller = await helper.eth.createAccountWithBalance(donor, 1000n);716 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();717 const flipper = await helper.eth.deployFlipper(contractOwner);718 await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);719 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);720721 await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});722 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);723 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);724725 expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;726 expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);727 expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({728 disabled: null,729 });730731 await flipper.methods.flip().send({from: caller});732 expect(await flipper.methods.getValue().call()).to.be.true;733734 const callerBalance = await helper.balance.getEthereum(caller);735 const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);736737 // caller payed for call738 expect(1000n * nominal > callerBalance).to.be.true;739 expect(contractBalanceAfter).to.be.equal(100n * nominal);740 });741742 itEth('can not be called by non-admin', async ({helper}) => {743 const [nonAdmin] = getAccount(1);744 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();745 const flipper = await helper.eth.deployFlipper(contractOwner);746747 await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);748 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))749 .to.be.rejectedWith(/appPromotion\.NoPermission/);750 });751752 itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {753 const [nonAdmin] = getAccount(1);754 const contractOwner = (await helper.eth.createAccountWithBalance(donor, 1000n)).toLowerCase();755 const flipper = await helper.eth.deployFlipper(contractOwner);756 const contractHelper = await helper.ethNativeContract.contractHelpers(contractOwner);757 await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;758759 await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');760 });761 });762763 describe('payoutStakers', () => {764 itSub('can not be called by non admin', async ({helper}) => {765 const [nonAdmin] = getAccount(1);766 await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');767 });768769 itSub('should increase total staked', async ({helper}) => {770 const [staker] = getAccount(1);771 const totalStakedBefore = await helper.staking.getTotalStaked();772 await helper.staking.stake(staker, 100n * nominal);773774 // Wait for rewards and pay775 const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});776 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));777 const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);778779 const totalStakedAfter = await helper.staking.getTotalStaked();780 expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);781 // staker can unstake782 await helper.staking.unstakeAll(staker);783 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal));784 });785786 itSub('should credit 0.05% for staking period', async ({helper}) => {787 const [staker] = getAccount(1);788789 await waitPromotionPeriodDoesntEnd(helper);790791 await helper.staking.stake(staker, 100n * nominal);792 await helper.staking.stake(staker, 200n * nominal);793794 // wait rewards are available:795 const [_stake1, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});796 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));797798 const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)!.payout;799 expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal));800801 const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});802 const income1 = calculateIncome(100n * nominal);803 const income2 = calculateIncome(200n * nominal);804 expect(totalStakedPerBlock[0].amount).to.equal(income1);805 expect(totalStakedPerBlock[1].amount).to.equal(income2);806807 const stakerBalance = await helper.balance.getSubstrateFull(staker.address);808 expect(stakerBalance).to.contain({miscFrozen: income1 + income2, feeFrozen: income1 + income2, reserved: 0n});809 expect(stakerBalance.free / nominal).to.eq(999n);810 });811812 itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {813 const [staker] = getAccount(1);814815 await helper.staking.stake(staker, 100n * nominal);816 // wait for two rewards are available:817 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});818 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);819820 await helper.admin.payoutStakers(palletAdmin, 100);821 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});822 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 2);823 expect(stake.amount).to.be.equal(frozenBalanceShouldBe);824825 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);826827 expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});828 });829830 itSub('should not be credited for pending-unstaked tokens', async ({helper}) => {831 // staker unstakes before rewards been payed832 const [staker] = getAccount(1);833 await helper.staking.stake(staker, 100n * nominal);834 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});835 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);836 await helper.staking.unstakeAll(staker);837838 // so he did not receive any rewards839 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);840 await helper.admin.payoutStakers(palletAdmin, 100);841 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);842843 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);844 });845846 itSub('should bring compound interest', async ({helper}) => {847 const [staker] = getAccount(1);848849 await helper.staking.stake(staker, 100n * nominal);850851 let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});852 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));853854 await helper.admin.payoutStakers(palletAdmin, 100);855 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});856 expect(stake.amount).to.equal(calculateIncome(100n * nominal));857858 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);859 await helper.admin.payoutStakers(palletAdmin, 100);860 [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});861 expect(stake.amount).to.equal(calculateIncome(100n * nominal, 2));862 });863864 itSub('can calculate reward for tiny stake', async ({helper}) => {865 const [staker] = getAccount(1);866 await helper.staking.stake(staker, 100n * nominal);867 await helper.staking.stake(staker, 100n * nominal);868 await helper.staking.unstakePartial(staker, 100n * nominal - 1n);869870 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});871 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));872873 const stakerPayout = await payUntilRewardFor(staker.address, helper);874 expect(stakerPayout.stake).to.eq(100n * nominal + 1n);875 });876877 itSub('can eventually pay all rewards', async ({helper}) => {878 const stakers = getAccount(30);879 // Create 30 stakes:880 await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));881882 let unstakingTxs = [];883 for (const staker of stakers) {884 if (unstakingTxs.length == 3) {885 await Promise.all(unstakingTxs);886 unstakingTxs = [];887 }888 unstakingTxs.push(helper.staking.unstakePartial(staker, 100n * nominal - 1n));889 }890891 const [staker] = getAccount(1);892 await helper.staking.stake(staker, 100n * nominal);893 const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});894 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));895896 let payouts;897 do {898 payouts = await helper.admin.payoutStakers(palletAdmin, 20);899 } while (payouts.length !== 0);900 });901 });902903 describe('events', () => {904 [905 {method: 'unstakePartial' as const},906 {method: 'unstakeAll' as const},907 ].map(testCase => {908 itSub(testCase.method, async ({helper}) => {909 const unstakeParams = testCase.method === 'unstakePartial'910 ? [100n * nominal - 1n]911 : [];912 const [staker] = getAccount(1);913 await helper.staking.stake(staker, 100n * nominal);914 await helper.staking.stake(staker, 200n * nominal);915 const {result} = await helper.executeExtrinsic(staker, `api.tx.appPromotion.${testCase.method}`, unstakeParams);916917 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Unstake');918 const unstakerEvents = event?.event.data[0].toString();919 const unstakedEvents = BigInt(event?.event.data[1].toString());920 expect(unstakerEvents).to.eq(staker.address);921 expect(unstakedEvents).to.eq(testCase.method === 'unstakeAll' ? 300n * nominal : 100n * nominal - 1n);922 });923 });924925 itSub('stake', async ({helper}) => {926 const [staker] = getAccount(1);927 const {result} = await helper.executeExtrinsic(staker, 'api.tx.appPromotion.stake', [100n * nominal]);928929 const event = result.events.find(e => e.event.section === 'appPromotion' && e.event.method === 'Stake');930 const stakerEvents = event?.event.data[0].toString();931 const stakedEvents = BigInt(event?.event.data[1].toString());932 expect(stakerEvents).to.eq(staker.address);933 expect(stakedEvents).to.eq(100n * nominal);934 });935936 // Flaky937 itSub.skip('payoutStakers', async ({helper}) => {938 const [staker1, staker2] = getAccount(2);939 const STAKE1 = 100n * nominal;940 const STAKE2 = 200n * nominal;941 await helper.staking.stake(staker1, STAKE1);942 await helper.staking.stake(staker2, STAKE2);943944 const [stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker2.address});945 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));946947 const results = await helper.admin.payoutStakers(palletAdmin, 100);948 const stakersEvents = results.filter(ev => ev.staker === staker1.address || ev.staker === staker2.address);949 expect(stakersEvents).has.length(2);950 expect(stakersEvents).has.not.ordered.members([951 {staker: staker1.address, stake: STAKE1, payout: calculateIncome(STAKE1) - STAKE1},952 {staker: staker2.address, stake: STAKE2, payout: calculateIncome(STAKE2) - STAKE2},953 ]);954 });955 });956});957958959// Sometimes is is required to make a cycle in order for the payment to be calculated for a specific account960async function payUntilRewardFor(account: string, helper: DevUniqueHelper) {961 for (let i = 0; i < 3; i++) {962 const payouts = await helper.admin.payoutStakers(palletAdmin, 100);963 const accountPayout = payouts.find(p => p.staker === account);964 if (accountPayout) return accountPayout;965 }966 throw Error(`Cannot find payout for ${account}`);967}968969function calculateIncome(base: bigint, iter = 0, calcPeriod: bigint = UNLOCKING_PERIOD): bigint {970 const DAY = 7200n;971 const ACCURACY = 1_000_000_000n;972 // 5n / 10_000n = 0.05% p/day973 const income = base + base * (ACCURACY * (calcPeriod * 5n) / (10_000n * DAY)) / ACCURACY ;974975 if (iter > 1) {976 return calculateIncome(income, iter - 1, calcPeriod);977 } else return income;978}979980function rewardAvailableInBlock(stakedInBlock: bigint) {981 if (stakedInBlock % LOCKING_PERIOD === 0n) return stakedInBlock + LOCKING_PERIOD;982 return (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);983}984985// Wait while promotion period less than specified block, to avoid boundary cases986// 0 if this should be the beginning of the period.987async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {988 const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();989 const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;990991 if (currentPeriodBlock > waitBlockLessThan) {992 await helper.wait.forRelayBlockNumber(BigInt(relayBlockNumber) + LOCKING_PERIOD - currentPeriodBlock);993 }994}