difftreelog
Tests: fix flakyness
in: master
3 files changed
tests/src/app-promotion.test.tsdiffbeforeafterboth37let nominal: bigint;37let nominal: bigint;38const palletAddress = calculatePalleteAddress('appstake');38const palletAddress = calculatePalleteAddress('appstake');39let accounts: IKeyringPair[] = [];39let accounts: IKeyringPair[] = [];40const LOCKING_PERIOD = 20n; // 20 blocks of relay41const UNLOCKING_PERIOD = 10n; // 20 blocks of parachain42const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);404341before(async function () {44before(async function () {42 await usingPlaygrounds(async (helper, privateKeyWrapper) => {45 await usingPlaygrounds(async (helper, privateKeyWrapper) => {66 expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});69 expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});67 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejected;70 await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejected;68 71 69 expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(100n * nominal);70 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);72 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);71 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);73 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);72 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo? 74 // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo? 73 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased 75 expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased 747675 77 76 await helper.staking.stake(staker, 200n * nominal);78 await helper.staking.stake(staker, 200n * nominal);77 expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(300n * nominal);78 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);79 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);79 expect((await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map((x) => x[1])).to.be.deep.equal([100n * nominal, 200n * nominal]);80 expect((await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map((x) => x[1])).to.be.deep.equal([100n * nominal, 200n * nominal]);80 });81 });83 it('should allow to create maximum 10 stakes for account', async () => {84 it('should allow to create maximum 10 stakes for account', async () => {84 await usingPlaygrounds(async (helper) => {85 await usingPlaygrounds(async (helper) => {85 const [staker] = await helper.arrange.createAccounts([2000n], alice);86 const [staker] = await helper.arrange.createAccounts([2000n], alice);86 console.log(staker.address);87 for (let i = 0; i < 10; i++) {87 for (let i = 0; i < 10; i++) {88 await helper.staking.stake(staker, 100n * nominal);88 await helper.staking.stake(staker, 100n * nominal);89 }89 }147 });147 });148148149 it('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async () => {149 it('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async () => {150 // TODO Flaky test151 await usingPlaygrounds(async (helper) => {150 await usingPlaygrounds(async (helper) => {152 const staker = accounts.pop()!;151 const staker = accounts.pop()!;153 await helper.staking.stake(staker, 100n * nominal);152 await helper.staking.stake(staker, 100n * nominal);154 await helper.staking.unstake(staker);153 await helper.staking.unstake(staker);154 const unstakedInBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address}))[0][0];155155156 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n156 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n157 await waitForRelayBlock(helper.api!, 20);157 await helper.wait.forParachainBlockNumber(unstakedInBlock);158 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});158 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});159 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);159 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);160160181 181 182 // Can unstake multiple stakes182 // Can unstake multiple stakes183 await helper.staking.unstake(staker);183 await helper.staking.unstake(staker);184 const unstakingBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address}))[0][0];184 pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});185 pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});185 unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);186 unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);186 stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);187 stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);189 expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);190 expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);190191191 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});192 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});192 await waitForRelayBlock(helper.api!, 20);193 await helper.wait.forParachainBlockNumber(unstakingBlock);193 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});194 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});194 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);195 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);195 });196 });202 // unstake has no effect if no stakes at all203 // unstake has no effect if no stakes at all203 await helper.staking.unstake(staker);204 await helper.staking.unstake(staker);204 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);205 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);205 expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(0n);206 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper206 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper207207208 // TODO stake() unstake() waitUnstaked() unstake();208 // TODO stake() unstake() waitUnstaked() unstake();213 await helper.staking.unstake(staker);213 await helper.staking.unstake(staker);214214215 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);215 expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);216 expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(100n * nominal);217 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);216 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);218 });217 });219 });218 });247 });246 });248 });247 });249250 // TODO for different accounts in one block is possible251});248});252249253describe('Admin adress', () => {250describe('Admin adress', () => {636 });633 });637634638 it('should credit 0.05% for staking period', async () => { 635 it('should credit 0.05% for staking period', async () => { 639 // TODO flaky test640 await usingPlaygrounds(async helper => {636 await usingPlaygrounds(async helper => {641 const staker = accounts.pop()!;637 const staker = accounts.pop()!;642 638 643 await helper.staking.stake(staker, 100n * nominal);639 await helper.staking.stake(staker, 100n * nominal);644 await helper.staking.stake(staker, 200n * nominal);640 await helper.staking.stake(staker, 200n * nominal);641642 // wair rewards are available:643 const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[1][0];645 await waitForRelayBlock(helper.api!, 30);644 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock));645646 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));646 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));647647651 });651 });652652653 it('shoud be paid for more than one period if payments was missed', async () => {653 it('shoud be paid for more than one period if payments was missed', async () => {654 // TODO flaky test655 await usingPlaygrounds(async (helper) => {654 await usingPlaygrounds(async (helper) => {656 const staker = accounts.pop()!;655 const staker = accounts.pop()!;657656658 await helper.staking.stake(staker, 100n * nominal);657 await helper.staking.stake(staker, 100n * nominal);658 // wait for two rewards are available:659 await helper.staking.stake(staker, 200n * nominal);659 const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[0][0];660661 await waitForRelayBlock(helper.api!, 55);660 await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock) + LOCKING_PERIOD);661662 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));662 await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));663 const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});663 const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});664 expect(stakedPerBlock[0][1]).to.be.equal(calculateIncome(100n * nominal, 10n, 2));664 const frozenBalanceShouldBe = calculateIncome(100n * nominal, 10n, 2);665 expect(stakedPerBlock[1][1]).to.be.equal(calculateIncome(200n * nominal, 10n, 2));665 expect(stakedPerBlock[0][1]).to.be.equal(frozenBalanceShouldBe);666666667 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);667 const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);668 const frozenBalanceShouldBe = calculateIncome(300n * nominal, 10n, 2);669668670 expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});669 expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});671 });670 });672 });671 });673 672 674 it('should not be credited for unstaked (reserved) balance', async () => {673 it('should not be credited for unstaked (reserved) balance', async () => {675 await usingPlaygrounds(async helper => {674 await usingPlaygrounds(async helper => {676 // staker unstakes before rewards has been initialized675 // staker unstakes before rewards has been payed677 const staker = accounts.pop()!;676 const staker = accounts.pop()!;678 await helper.staking.stake(staker, 100n * nominal);677 await helper.staking.stake(staker, 100n * nominal);679 await waitForRelayBlock(helper.api!, 40);678 await waitForRelayBlock(helper.api!, 40);709 });708 });710 });709 });710711 it('can be paid 1000 rewards in a time', async () => {712 await usingPlaygrounds(async (helper) => {713 expect.fail('Test not implemented');714 });715 });711716712 it.skip('can handle 40.000 rewards', async () => {717 it.skip('can handle 40.000 rewards', async () => {713 await usingPlaygrounds(async (helper) => {718 await usingPlaygrounds(async (helper) => {tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth60 * Arrange methods for tests59 * Arrange methods for tests61 */60 */62 arrange: ArrangeGroup;61 arrange: ArrangeGroup;62 wait: WaitGroup;636364 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {64 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {65 super(logger);65 super(logger);66 this.arrange = new ArrangeGroup(this);66 this.arrange = new ArrangeGroup(this);67 this.wait = new WaitGroup(this);67 }68 }686969 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {70 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {152 for (let index = 0; index < 5; index++) {153 for (let index = 0; index < 5; index++) {153 accountsCreated = await checkBalances();154 accountsCreated = await checkBalances();154 if(accountsCreated) break;155 if(accountsCreated) break;155 await this.waitNewBlocks(1);156 156 }157 }157158158 if (!accountsCreated) throw Error('Accounts generation failed');159 if (!accountsCreated) throw Error('Accounts generation failed');163164164 // TODO combine this method and createAccounts into one165 // TODO combine this method and createAccounts into one165 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {166 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 167 const createAsManyAsCan = async () => {166 let transactions: any = [];168 let transactions: any = [];167 const accounts: IKeyringPair[] = [];169 const accounts: IKeyringPair[] = [];168169 const createAsManyAsCan = async () => {170 let nonce = await this.helper.chain.getNonce(donor.address);170 let nonce = await this.helper.chain.getNonce(donor.address);171 const tokenNominal = this.helper.balance.getOneTokenNominal();171 const tokenNominal = this.helper.balance.getOneTokenNominal();172 for (let i = 0; i < accountsToCreate; i++) {172 for (let i = 0; i < accountsToCreate; i++) {193 }193 }194 }194 }195 return fullfilledAccounts;195 return fullfilledAccounts;196 };196 };197197198 198 199 const crowd: IKeyringPair[] = [];199 const crowd: IKeyringPair[] = [];227 if(block2date! - block1date! < 9000) return true;227 if(block2date! - block1date! < 9000) return true;228 };228 };229230 /**231 * Wait for specified bnumber of blocks232 * @param blocksCount number of blocks to wait233 * @returns 234 */235 async waitNewBlocks(blocksCount = 1): Promise<void> {236 // eslint-disable-next-line no-async-promise-executor237 const promise = new Promise<void>(async (resolve) => {238 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {239 if (blocksCount > 0) {240 blocksCount--;241 } else {242 unsubscribe();243 resolve();244 }245 });246 });247 return promise;248 }249}229}230231class WaitGroup {232 helper: UniqueHelper;233234 constructor(helper: UniqueHelper) {235 this.helper = helper;236 }237238 /**239 * Wait for specified bnumber of blocks240 * @param blocksCount number of blocks to wait241 * @returns 242 */243 async newBlocks(blocksCount = 1): Promise<void> {244 // eslint-disable-next-line no-async-promise-executor245 const promise = new Promise<void>(async (resolve) => {246 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {247 if (blocksCount > 0) {248 blocksCount--;249 } else {250 unsubscribe();251 resolve();252 }253 });254 });255 return promise;256 }257258 async forParachainBlockNumber(blockNumber: bigint) {259 return new Promise<void>(async (resolve) => {260 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {261 if (data.number.toNumber() >= blockNumber) {262 unsubscribe();263 resolve();264 }265 });266 });267 }268 269 async forRelayBlockNumber(blockNumber: bigint) {270 return new Promise<void>(async (resolve) => {271 const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {272 if (data.value.relayParentNumber.toNumber() >= blockNumber) {273 unsubscribe();274 resolve();275 }276 });277 });278 }279}250280tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1975 return true;1975 return true;1976 }1976 }197719771978 /**1978 /**1979 * Unstake tokens for App Promotion1979 * Unstake tokens for App Promotion1980 * @param signer keyring of signer1980 * @param signer keyring of signer1981 * @param amountToUnstake amount of tokens to unstake1981 * @param amountToUnstake amount of tokens to unstake1982 * @param label extra label for log1982 * @param label extra label for log1983 * @returns 1983 * @returns block number where balances will be unlocked1984 */1984 */1985 async unstake(signer: TSigner, label?: string): Promise<boolean> {1985 async unstake(signer: TSigner, label?: string): Promise<number> {1986 if(typeof label === 'undefined') label = `${signer.address}`;1986 if(typeof label === 'undefined') label = `${signer.address}`;1987 const unstakeResult = await this.helper.executeExtrinsic(1987 const unstakeResult = await this.helper.executeExtrinsic(1988 signer, 'api.tx.appPromotion.unstake', 1988 signer, 'api.tx.appPromotion.unstake', 1989 [], true,1989 [], true,1990 );1990 );1991 // TODO extract info from unstakeResult1991 // TODO extract block number fron events1992 return true;1992 return 1;1993 }1993 }199419941995 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {1995 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {1996 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();1996 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();1997 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();1997 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();1998 }1998 }19992000 async getTotalStakingLocked(address: ICrossAccountId): Promise<bigint> {2001 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakingLocked', [address])).toBigInt();2002 }200319992004 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2000 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2005 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2001 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);