git.delta.rocks / unique-network / refs/commits / 6c62f5a03f69

difftreelog

Split promotion tests to sequential and parallel

Maksandre2022-10-10parent: #d52c8f5.patch.diff
in: master
- add globalSetup script to set app promotion admin
- move calculatePalleteAddress helper to DevUniqueHelper

5 files changed

addedtests/globalSetup.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/globalSetup.ts
@@ -0,0 +1,18 @@
+import {Pallets, usingPlaygrounds} from './src/util/playgrounds/index';
+
+export async function mochaGlobalSetup() {
+  await usingPlaygrounds(async (helper, privateKey) => {
+    // Set up App Promotion admin
+    const missingPallets = helper.fetchMissingPalletNames([Pallets.AppPromotion]);
+    if (missingPallets.length === 0) {
+      const superuser = await privateKey('//Alice');
+      const palletAddress = helper.arrange.calculatePalleteAddress('appstake');
+      const palletAdmin = await privateKey('//PromotionAdmin');
+      const api = helper.getApi();
+      await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+      const nominal = helper.balance.getOneTokenNominal();
+      await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 1000n * nominal);
+      await helper.balance.transferToSubstrate(superuser, palletAddress, 1000n * nominal);
+    }
+  });
+}
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -21,7 +21,7 @@
   },
   "mocha": {
     "timeout": 9999999,
-    "require": "ts-node/register"
+    "require": ["ts-node/register", "./globalSetup.ts"]
   },
   "scripts": {
     "lint": "eslint --ext .ts,.js src/",
addedtests/src/app-promotion.seqtest.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/app-promotion.seqtest.ts
@@ -0,0 +1,83 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip} from './util/playgrounds';
+import {expect} from './eth/util/playgrounds';
+
+let superuser: IKeyringPair;
+let donor: IKeyringPair;
+let palletAdmin: IKeyringPair;
+let nominal: bigint;
+let palletAddress;
+let accounts: IKeyringPair[];
+
+
+describe('App promotion', () => {
+  before(async function () {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);
+      superuser = await privateKey('//Alice');
+      donor = await privateKey({filename: __filename});
+      palletAddress = helper.arrange.calculatePalleteAddress('appstake');
+      palletAdmin = await privateKey('//PromotionAdmin');
+      const api = helper.getApi();
+      await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+      nominal = helper.balance.getOneTokenNominal();
+      await helper.balance.transferToSubstrate(donor, palletAdmin.address, 1000n * nominal);
+      await helper.balance.transferToSubstrate(donor, palletAddress, 1000n * nominal);
+      accounts = await helper.arrange.createCrowd(100, 1000n, donor); // create accounts-pool to speed up tests
+    });
+  });
+
+  describe('admin adress', () => {
+    itSub('can be set by sudo only', async ({helper}) => {
+      const api = helper.getApi();
+      const nonAdmin = accounts.pop()!;
+      // nonAdmin can not set admin not from himself nor as a sudo
+      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
+      await expect(helper.signTransaction(nonAdmin, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
+    });
+    
+    itSub('can be any valid CrossAccountId', async ({helper}) => {
+      // We are not going to set an eth address as a sponsor,
+      // but we do want to check, it doesn't break anything;
+      const api = helper.getApi();
+      const account = accounts.pop()!;
+      const ethAccount = helper.address.substrateToEth(account.address); 
+      // Alice sets Ethereum address as a sudo. Then Substrate address back...
+      await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
+      await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
+        
+      // ...It doesn't break anything;
+      const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+      await expect(helper.signTransaction(account, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+    });
+  
+    itSub('can be reassigned', async ({helper}) => {
+      const api = helper.getApi();
+      const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
+      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+        
+      await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: oldAdmin.address})))).to.be.fulfilled;
+      await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: newAdmin.address})))).to.be.fulfilled;
+      await expect(helper.signTransaction(oldAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+        
+      await expect(helper.signTransaction(newAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
+    });
+  });
+});
+
modifiedtests/src/app-promotion.test.tsdiffbeforeafterboth
--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -16,17 +16,14 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip} from './util/playgrounds';
-import {encodeAddress} from '@polkadot/util-crypto';
-import {stringToU8a} from '@polkadot/util';
 import {DevUniqueHelper} from './util/playgrounds/unique.dev';
 import {itEth, expect, SponsoringMode} from './eth/util/playgrounds';
 
-let superuser: IKeyringPair;
 let donor: IKeyringPair;
 let palletAdmin: IKeyringPair;
 let nominal: bigint;
-const palletAddress = calculatePalleteAddress('appstake');
-let accounts: IKeyringPair[] = [];
+let palletAddress: string;
+let accounts: IKeyringPair[];
 const LOCKING_PERIOD = 20n; // 20 blocks of relay
 const UNLOCKING_PERIOD = 10n; // 10 blocks of parachain
 const rewardAvailableInBlock = (stakedInBlock: bigint) => {
@@ -38,11 +35,9 @@
   before(async function () {
     await usingPlaygrounds(async (helper, privateKey) => {
       requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);
-      superuser = await privateKey('//Alice');
       donor = await privateKey({filename: __filename});
-      [palletAdmin] = await helper.arrange.createAccounts([100n], donor);
-      const api = helper.getApi();
-      await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+      palletAddress = helper.arrange.calculatePalleteAddress('appstake');
+      palletAdmin = await privateKey('//PromotionAdmin');
       nominal = helper.balance.getOneTokenNominal();
       await helper.balance.transferToSubstrate(donor, palletAdmin.address, 1000n * nominal);
       await helper.balance.transferToSubstrate(donor, palletAddress, 1000n * nominal);
@@ -223,58 +218,10 @@
         expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
         expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
       }));
-    });
-  });
-  
-  describe('admin adress', () => {
-    itSub('can be set by sudo only', async ({helper}) => {
-      const api = helper.getApi();
-      const nonAdmin = accounts.pop()!;
-      // nonAdmin can not set admin not from himself nor as a sudo
-      await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
-      await expect(helper.signTransaction(nonAdmin, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
-  
-      // Alice can
-      await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
-    });
-    
-    itSub('can be any valid CrossAccountId', async ({helper}) => {
-      // We are not going to set an eth address as a sponsor,
-      // but we do want to check, it doesn't break anything;
-      const api = helper.getApi();
-      const account = accounts.pop()!;
-      const ethAccount = helper.address.substrateToEth(account.address); 
-      // Alice sets Ethereum address as a sudo. Then Substrate address back...
-      await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
-      await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
-        
-      // ...It doesn't break anything;
-      const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-      await expect(helper.signTransaction(account, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
     });
-  
-    itSub('can be reassigned', async ({helper}) => {
-      const api = helper.getApi();
-      const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
-      const collection  = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-        
-      await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: oldAdmin.address})))).to.be.fulfilled;
-      await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: newAdmin.address})))).to.be.fulfilled;
-      await expect(helper.signTransaction(oldAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
-        
-      await expect(helper.signTransaction(newAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
-    });
   });
   
   describe('collection sponsoring', () => {
-    before(async function () {
-      await usingPlaygrounds(async (helper) => {
-        const api = helper.getApi();
-        const tx = api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
-        await helper.signTransaction(superuser, tx);
-      });
-    });
-  
     itSub('should actually sponsor transactions', async ({helper}) => {
       const api = helper.getApi();
       const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
@@ -708,11 +655,6 @@
     });
   });
 });
-
-function calculatePalleteAddress(palletId: any) {
-  const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));
-  return encodeAddress(address);
-}
 
 function calculateIncome(base: bigint, calcPeriod: bigint, iter = 0): bigint {
   const DAY = 7200n;
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {mnemonicGenerate} from '@polkadot/util-crypto';5import {UniqueHelper} from './unique';6import {ApiPromise, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';8import {IKeyringPair} from '@polkadot/types/types';9import {ICrossAccountId} from './types';1011export class SilentLogger {12  log(_msg: any, _level: any): void { }13  level = {14    ERROR: 'ERROR' as const,15    WARNING: 'WARNING' as const,16    INFO: 'INFO' as const,17  };18}1920export class SilentConsole {21  // TODO: Remove, this is temporary: Filter unneeded API output22  // (Jaco promised it will be removed in the next version)23  consoleErr: any;24  consoleLog: any;25  consoleWarn: any;2627  constructor() {28    this.consoleErr = console.error;29    this.consoleLog = console.log;30    this.consoleWarn = console.warn;31  }3233  enable() {  34    const outFn = (printer: any) => (...args: any[]) => {35      for (const arg of args) {36        if (typeof arg !== 'string')37          continue;38        if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')39          return;40      }41      printer(...args);42    };43  44    console.error = outFn(this.consoleErr.bind(console));45    console.log = outFn(this.consoleLog.bind(console));46    console.warn = outFn(this.consoleWarn.bind(console));47  }4849  disable() {50    console.error = this.consoleErr;51    console.log = this.consoleLog;52    console.warn = this.consoleWarn;53  }54}555657export class DevUniqueHelper extends UniqueHelper {58  /**59   * Arrange methods for tests60   */61  arrange: ArrangeGroup;62  wait: WaitGroup;63  admin: AdminGroup;6465  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {66    options.helperBase = options.helperBase ?? DevUniqueHelper;6768    super(logger, options);69    this.arrange = new ArrangeGroup(this);70    this.wait = new WaitGroup(this);71    this.admin = new AdminGroup(this);72  }7374  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {75    const wsProvider = new WsProvider(wsEndpoint);76    this.api = new ApiPromise({77      provider: wsProvider,78      signedExtensions: {79        ContractHelpers: {80          extrinsic: {},81          payload: {},82        },83        FakeTransactionFinalizer: {84          extrinsic: {},85          payload: {},86        },87      },88      rpc: {89        unique: defs.unique.rpc,90        appPromotion: defs.appPromotion.rpc,91        rmrk: defs.rmrk.rpc,92        eth: {93          feeHistory: {94            description: 'Dummy',95            params: [],96            type: 'u8',97          },98          maxPriorityFeePerGas: {99            description: 'Dummy',100            params: [],101            type: 'u8',102          },103        },104      },105    });106    await this.api.isReadyOrError;107    this.network = await UniqueHelper.detectNetwork(this.api);108  }109}110111class ArrangeGroup {112  helper: DevUniqueHelper;113114  constructor(helper: DevUniqueHelper) {115    this.helper = helper;116  }117118  /**119   * Generates accounts with the specified UNQ token balance 120   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.121   * @param donor donor account for balances122   * @returns array of newly created accounts123   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 124   */125  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {126    let nonce = await this.helper.chain.getNonce(donor.address);127    const wait = new WaitGroup(this.helper);128    const ss58Format = this.helper.chain.getChainProperties().ss58Format;129    const tokenNominal = this.helper.balance.getOneTokenNominal();130    const transactions = [];131    const accounts: IKeyringPair[] = [];132    for (const balance of balances) {133      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);134      accounts.push(recipient);135      if (balance !== 0n) {136        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);137        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));138        nonce++;139      }140    }141142    await Promise.all(transactions).catch(_e => {});143    144    //#region TODO remove this region, when nonce problem will be solved145    const checkBalances = async () => {146      let isSuccess = true;147      for (let i = 0; i < balances.length; i++) {148        const balance = await this.helper.balance.getSubstrate(accounts[i].address);149        if (balance !== balances[i] * tokenNominal) {150          isSuccess = false;151          break;152        }153      }154      return isSuccess;155    };156157    let accountsCreated = false;158    // checkBalances retry up to 5 blocks159    for (let index = 0; index < 5; index++) {160      accountsCreated = await checkBalances();161      if(accountsCreated) break;162      await wait.newBlocks(1);163    }164165    if (!accountsCreated) throw Error('Accounts generation failed');166    //#endregion167168    return accounts;169  };170171  // TODO combine this method and createAccounts into one172  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {  173    const createAsManyAsCan = async () => {174      let transactions: any = [];175      const accounts: IKeyringPair[] = [];176      let nonce = await this.helper.chain.getNonce(donor.address);177      const tokenNominal = this.helper.balance.getOneTokenNominal();178      for (let i = 0; i < accountsToCreate; i++) {179        if (i === 500) { // if there are too many accounts to create180          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 181          transactions = []; //182          nonce = await this.helper.chain.getNonce(donor.address); // update nonce 183        }184        const recepient = this.helper.util.fromSeed(mnemonicGenerate());185        accounts.push(recepient);186        if (withBalance !== 0n) {187          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);188          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));189          nonce++;190        }191      }192      193      const fullfilledAccounts = [];194      await Promise.allSettled(transactions);195      for (const account of accounts) {196        const accountBalance = await this.helper.balance.getSubstrate(account.address);197        if (accountBalance === withBalance * tokenNominal) {198          fullfilledAccounts.push(account);199        }200      }201      return fullfilledAccounts;202    };203204    205    const crowd: IKeyringPair[] = [];206    // do up to 5 retries207    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {208      const asManyAsCan = await createAsManyAsCan();209      crowd.push(...asManyAsCan);210      accountsToCreate -= asManyAsCan.length;211    }212213    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);214215    return crowd;216  };217218  isDevNode = async () => {219    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);220    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);221    const findCreationDate = async (block: any) => {222      const humanBlock = block.toHuman();223      let date;224      humanBlock.block.extrinsics.forEach((ext: any) => {225        if(ext.method.section === 'timestamp') {226          date = Number(ext.method.args.now.replaceAll(',', ''));227        }228      });229      return date;230    };231    const block1date = await findCreationDate(block1);232    const block2date = await findCreationDate(block2);233    if(block2date! - block1date! < 9000) return true;234  };235  236  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {237    const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);238    let balance = await this.helper.balance.getSubstrate(address); 239    240    await promise();241    242    balance -= await this.helper.balance.getSubstrate(address);243    244    return balance;245  }246}247248class WaitGroup {249  helper: DevUniqueHelper;250251  constructor(helper: DevUniqueHelper) {252    this.helper = helper;253  }254255  /**256   * Wait for specified number of blocks257   * @param blocksCount number of blocks to wait258   * @returns 259   */260  async newBlocks(blocksCount = 1): Promise<void> {261    // eslint-disable-next-line no-async-promise-executor262    const promise = new Promise<void>(async (resolve) => {263      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {264        if (blocksCount > 0) {265          blocksCount--;266        } else {267          unsubscribe();268          resolve();269        }270      });271    });272    return promise;273  }274275  async forParachainBlockNumber(blockNumber: bigint) {276    // eslint-disable-next-line no-async-promise-executor277    return new Promise<void>(async (resolve) => {278      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {279        if (data.number.toNumber() >= blockNumber) {280          unsubscribe();281          resolve();282        }283      });284    });285  }286  287  async forRelayBlockNumber(blockNumber: bigint) {288    // eslint-disable-next-line no-async-promise-executor289    return new Promise<void>(async (resolve) => {290      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {291        if (data.value.relayParentNumber.toNumber() >= blockNumber) {292          // @ts-ignore293          unsubscribe();294          resolve();295        }296      });297    });298  }299}300301class AdminGroup {302  helper: UniqueHelper;303304  constructor(helper: UniqueHelper) {305    this.helper = helper;306  }307308  async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {309    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);310    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {311      return {312        staker: e.event.data[0].toString(),313        stake: e.event.data[1].toBigInt(),314        payout: e.event.data[2].toBigInt(),315      };316    });317  }318}