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

difftreelog

Tests: fix flakyness

Max Andreev2022-09-07parent: #25c9617.patch.diff
in: master

3 files changed

modifiedtests/src/app-promotion.test.tsdiffbeforeafterboth
--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -37,6 +37,9 @@
 let nominal: bigint;
 const palletAddress = calculatePalleteAddress('appstake');
 let accounts: IKeyringPair[] = [];
+const LOCKING_PERIOD = 20n; // 20 blocks of relay
+const UNLOCKING_PERIOD = 10n; // 20 blocks of parachain
+const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);
 
 before(async function () {
   await usingPlaygrounds(async (helper, privateKeyWrapper) => {
@@ -66,7 +69,6 @@
       expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});
       await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejected;
       
-      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(100n * nominal);
       expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);
       expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
       // it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo? 
@@ -74,7 +76,6 @@
 
       
       await helper.staking.stake(staker, 200n * nominal);
-      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(300n * nominal);
       expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);
       expect((await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map((x) => x[1])).to.be.deep.equal([100n * nominal, 200n * nominal]);
     });
@@ -83,7 +84,6 @@
   it('should allow to create maximum 10 stakes for account', async () => {
     await usingPlaygrounds(async (helper) => {
       const [staker] = await helper.arrange.createAccounts([2000n], alice);
-      console.log(staker.address);
       for (let i = 0; i < 10; i++) {
         await helper.staking.stake(staker, 100n * nominal);
       }
@@ -147,14 +147,14 @@
   });
 
   it('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async () => {
-    // TODO Flaky test
     await usingPlaygrounds(async (helper) => {
       const staker = accounts.pop()!;
       await helper.staking.stake(staker, 100n * nominal);
       await helper.staking.unstake(staker);
+      const unstakedInBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address}))[0][0];
 
       // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
-      await waitForRelayBlock(helper.api!, 20);
+      await helper.wait.forParachainBlockNumber(unstakedInBlock);
       expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});
       expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
 
@@ -181,6 +181,7 @@
      
       // Can unstake multiple stakes
       await helper.staking.unstake(staker);
+      const unstakingBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address}))[0][0];
       pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
       unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);
       stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);
@@ -189,7 +190,7 @@
       expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);
 
       expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});
-      await waitForRelayBlock(helper.api!, 20);
+      await helper.wait.forParachainBlockNumber(unstakingBlock);
       expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});
       expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
     });
@@ -202,7 +203,6 @@
       // unstake has no effect if no stakes at all
       await helper.staking.unstake(staker);
       expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);
-      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(0n);
       expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper
 
       // TODO stake() unstake() waitUnstaked() unstake();
@@ -213,7 +213,6 @@
       await helper.staking.unstake(staker);
 
       expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
-      expect(await helper.staking.getTotalStakingLocked({Substrate: staker.address})).to.be.equal(100n * nominal);
       expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
     });
   });
@@ -246,8 +245,6 @@
       }));
     });
   });
-
-  // TODO for different accounts in one block is possible
 });
 
 describe('Admin adress', () => {
@@ -636,13 +633,16 @@
   });
 
   it('should credit 0.05% for staking period', async () => {    
-    // TODO flaky test
     await usingPlaygrounds(async helper => {
       const staker = accounts.pop()!;
       
       await helper.staking.stake(staker, 100n * nominal);
       await helper.staking.stake(staker, 200n * nominal);
-      await waitForRelayBlock(helper.api!, 30);
+
+      // wair rewards are available:
+      const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[1][0];
+      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock));
+
       await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
 
       const totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
@@ -651,21 +651,20 @@
   });
 
   it('shoud be paid for more than one period if payments was missed', async () => {
-    // TODO flaky test
     await usingPlaygrounds(async (helper) => {
       const staker = accounts.pop()!;
 
       await helper.staking.stake(staker, 100n * nominal);
-      await helper.staking.stake(staker, 200n * nominal);
+      // wait for two rewards are available:
+      const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[0][0];
+      await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock) + LOCKING_PERIOD);
 
-      await waitForRelayBlock(helper.api!, 55);
       await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
       const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
-      expect(stakedPerBlock[0][1]).to.be.equal(calculateIncome(100n * nominal, 10n, 2));
-      expect(stakedPerBlock[1][1]).to.be.equal(calculateIncome(200n * nominal, 10n, 2));
+      const frozenBalanceShouldBe = calculateIncome(100n * nominal, 10n, 2);
+      expect(stakedPerBlock[0][1]).to.be.equal(frozenBalanceShouldBe);
 
       const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);
-      const frozenBalanceShouldBe = calculateIncome(300n * nominal, 10n, 2);
 
       expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});
     });
@@ -673,7 +672,7 @@
   
   it('should not be credited for unstaked (reserved) balance', async () => {
     await usingPlaygrounds(async helper => {
-      // staker unstakes before rewards has been initialized
+      // staker unstakes before rewards has been payed
       const staker = accounts.pop()!;
       await helper.staking.stake(staker, 100n * nominal);
       await waitForRelayBlock(helper.api!, 40);
@@ -709,6 +708,12 @@
     });
   });
 
+  it('can be paid 1000 rewards in a time', async () => {
+    await usingPlaygrounds(async (helper) => {
+      expect.fail('Test not implemented');
+    });
+  });
+
   it.skip('can handle 40.000 rewards', async () => {
     await usingPlaygrounds(async (helper) => {
       const [donor] = await helper.arrange.createAccounts([7_000_000n], alice);
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -17,7 +17,6 @@
   };
 }
 
-
 export class SilentConsole {
   // TODO: Remove, this is temporary: Filter unneeded API output
   // (Jaco promised it will be removed in the next version)
@@ -60,10 +59,12 @@
    * Arrange methods for tests
    */
   arrange: ArrangeGroup;
+  wait: WaitGroup;
 
   constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
     super(logger);
     this.arrange = new ArrangeGroup(this);
+    this.wait = new WaitGroup(this);
   }
 
   async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
@@ -152,7 +153,7 @@
     for (let index = 0; index < 5; index++) {
       accountsCreated = await checkBalances();
       if(accountsCreated) break;
-      await this.waitNewBlocks(1);
+      
     }
 
     if (!accountsCreated) throw Error('Accounts generation failed');
@@ -162,11 +163,10 @@
   };
 
   // TODO combine this method and createAccounts into one
-  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {
-    let transactions: any = [];
-    const accounts: IKeyringPair[] = [];
-
+  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {  
     const createAsManyAsCan = async () => {
+      let transactions: any = [];
+      const accounts: IKeyringPair[] = [];
       let nonce = await this.helper.chain.getNonce(donor.address);
       const tokenNominal = this.helper.balance.getOneTokenNominal();
       for (let i = 0; i < accountsToCreate; i++) {
@@ -226,13 +226,21 @@
     const block2date = await findCreationDate(block2);
     if(block2date! - block1date! < 9000) return true;
   };
+}
+
+class WaitGroup {
+  helper: UniqueHelper;
 
+  constructor(helper: UniqueHelper) {
+    this.helper = helper;
+  }
+
   /**
    * Wait for specified bnumber of blocks
    * @param blocksCount number of blocks to wait
    * @returns 
    */
-  async waitNewBlocks(blocksCount = 1): Promise<void> {
+  async newBlocks(blocksCount = 1): Promise<void> {
     // eslint-disable-next-line no-async-promise-executor
     const promise = new Promise<void>(async (resolve) => {
       const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {
@@ -246,4 +254,26 @@
     });
     return promise;
   }
+
+  async forParachainBlockNumber(blockNumber: bigint) {
+    return new Promise<void>(async (resolve) => {
+      const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {
+        if (data.number.toNumber() >= blockNumber) {
+          unsubscribe();
+          resolve();
+        }
+      });
+    });
+  }
+  
+  async forRelayBlockNumber(blockNumber: bigint) {
+    return new Promise<void>(async (resolve) => {
+      const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {
+        if (data.value.relayParentNumber.toNumber() >= blockNumber) {
+          unsubscribe();
+          resolve();
+        }
+      });
+    });
+  }
 }
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
1975 return true;1975 return true;
1976 }1976 }
19771977
1978 /**1978 /**
1979 * Unstake tokens for App Promotion1979 * Unstake tokens for App Promotion
1980 * @param signer keyring of signer1980 * @param signer keyring of signer
1981 * @param amountToUnstake amount of tokens to unstake1981 * @param amountToUnstake amount of tokens to unstake
1982 * @param label extra label for log1982 * @param label extra label for log
1983 * @returns 1983 * @returns block number where balances will be unlocked
1984 */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 events
1992 return true;1992 return 1;
1993 }1993 }
19941994
1995 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 }
1999
2000 async getTotalStakingLocked(address: ICrossAccountId): Promise<bigint> {
2001 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakingLocked', [address])).toBigInt();
2002 }
20031999
2004 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()]);