git.delta.rocks / unique-network / refs/commits / 2c586ed344ac

difftreelog

Move app promotion configuration to globalSetup

Max Andreev2022-12-13parent: #f09b3a8.patch.diff
in: master

2 files changed

modifiedtests/src/app-promotion.test.tsdiffbeforeafterboth
--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -31,7 +31,6 @@
   before(async function () {
     await usingPlaygrounds(async (helper, privateKey) => {
       requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);
-      const alice = await privateKey('//Alice');
       donor = await privateKey({filename: __filename});
       palletAddress = helper.arrange.calculatePalletAddress('appstake');
       palletAdmin = await privateKey('//PromotionAdmin');
@@ -40,8 +39,6 @@
       const accountBalances = new Array(100);
       accountBalances.fill(1000n);
       accounts = await helper.arrange.createAccounts(accountBalances, donor); // create accounts-pool to speed up tests
-      const api = helper.getApi();
-      await helper.executeExtrinsic(alice, 'api.tx.sudo.sudo', [api.tx.configuration.setAppPromotionConfigurationOverride({recalculationInterval: LOCKING_PERIOD, pendingInterval: UNLOCKING_PERIOD})], true);
     });
   });
 
modifiedtests/src/util/globalSetup.tsdiffbeforeafterboth
before · tests/src/util/globalSetup.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {usingPlaygrounds, Pallets, DONOR_FUNDING, MINIMUM_DONOR_FUND} from './index';5import * as path from 'path';6import {promises as fs} from 'fs';78// This function should be called before running test suites.9const globalSetup = async (): Promise<void> => {10  await usingPlaygrounds(async (helper, privateKey) => {11    try {12      // 1. Wait node producing blocks13      await helper.wait.newBlocks(1, 600_000);1415      // 2. Create donors for test files16      await fundFilenamesWithRetries(3)17        .then((result) => {18          if (!result) Promise.reject();19        });2021      // 3. Set up App Promotion admin 22      const missingPallets = helper.fetchMissingPalletNames([Pallets.AppPromotion]);23      if (missingPallets.length === 0) {24        const superuser = await privateKey('//Alice');25        const palletAddress = helper.arrange.calculatePalletAddress('appstake');26        const palletAdmin = await privateKey('//PromotionAdmin');27        const api = helper.getApi();28        await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));29        const nominal = helper.balance.getOneTokenNominal();30        await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 1000n * nominal);31        await helper.balance.transferToSubstrate(superuser, palletAddress, 1000n * nominal);32      }33    } catch (error) {34      console.error(error);35      Promise.reject();36    }37  });38};3940async function getFiles(rootPath: string): Promise<string[]> {41  const files = await fs.readdir(rootPath, {withFileTypes: true});42  const filenames: string[] = [];43  for (const entry of files) {44    const res = path.resolve(rootPath, entry.name);45    if (entry.isDirectory()) {46      filenames.push(...await getFiles(res));47    } else {48      filenames.push(res);49    }50  }51  return filenames;52}5354const fundFilenames = async () => {55  await usingPlaygrounds(async (helper, privateKey) => {56    const oneToken = helper.balance.getOneTokenNominal();57    const alice = await privateKey('//Alice');58    const nonce = await helper.chain.getNonce(alice.address);59    const filenames = await getFiles(path.resolve(__dirname, '..'));6061    // batching is actually undesireable, it takes away the time while all the transactions actually succeed62    const batchSize = 300;63    let balanceGrantedCounter = 0;64    for (let b = 0; b < filenames.length; b += batchSize) {65      const tx = [];66      let batchBalanceGrantedCounter = 0;67      for (let i = 0; batchBalanceGrantedCounter < batchSize && b + i < filenames.length; i++) {68        const f = filenames[b + i];69        if (!f.endsWith('.test.ts') && !f.endsWith('seqtest.ts') || f.includes('.outdated')) continue;70        const account = await privateKey({filename: f, ignoreFundsPresence: true});71        const aliceBalance = await helper.balance.getSubstrate(account.address);7273        if (aliceBalance < MINIMUM_DONOR_FUND * oneToken) {74          tx.push(helper.executeExtrinsic(75            alice, 76            'api.tx.balances.transfer',77            [account.address, DONOR_FUNDING * oneToken],78            true,79            {nonce: nonce + balanceGrantedCounter++},80          ).then(() => true).catch(() => {console.error(`Transaction to ${path.basename(f)} registered as failed. Strange.`); return false;}));81          batchBalanceGrantedCounter++;82        }83      }8485      if(tx.length > 0) {86        console.log(`Granting funds to ${batchBalanceGrantedCounter} filename accounts.`);87        const result = await Promise.all(tx);88        if (result && result.lastIndexOf(false) > -1) throw new Error('The transactions actually probably succeeded, should check the balances.');89      }90    }9192    if (balanceGrantedCounter == 0) console.log('No account needs additional funding.');93  });94};9596const fundFilenamesWithRetries = (retriesLeft: number): Promise<boolean> => {97  if (retriesLeft <= 0) return Promise.resolve(false);98  return fundFilenames()99    .then(() => Promise.resolve(true))100    .catch(e => {101      console.error(e);102      console.error(`Some transactions might have failed. ${retriesLeft > 1 ? 'Retrying...' : 'Something is wrong.'}\n`);103      return fundFilenamesWithRetries(--retriesLeft);104    });105};106107globalSetup().catch(() => process.exit(1));
after · tests/src/util/globalSetup.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {usingPlaygrounds, Pallets, DONOR_FUNDING, MINIMUM_DONOR_FUND} from './index';5import * as path from 'path';6import {promises as fs} from 'fs';78// This function should be called before running test suites.9const globalSetup = async (): Promise<void> => {10  await usingPlaygrounds(async (helper, privateKey) => {11    try {12      // 1. Wait node producing blocks13      await helper.wait.newBlocks(1, 600_000);1415      // 2. Create donors for test files16      await fundFilenamesWithRetries(3)17        .then((result) => {18          if (!result) Promise.reject();19        });2021      // 3. Configure App Promotion 22      const missingPallets = helper.fetchMissingPalletNames([Pallets.AppPromotion]);23      if (missingPallets.length === 0) {24        // TODO: move to config file25        const LOCKING_PERIOD = 8n; // 8 blocks of relay26        const UNLOCKING_PERIOD = 4n; // 4 blocks of parachain2728        const superuser = await privateKey('//Alice');29        const palletAddress = helper.arrange.calculatePalletAddress('appstake');30        const palletAdmin = await privateKey('//PromotionAdmin');31        const api = helper.getApi();32        await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));33        const nominal = helper.balance.getOneTokenNominal();34        await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 1000n * nominal);35        await helper.balance.transferToSubstrate(superuser, palletAddress, 1000n * nominal);36        await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [api.tx.configuration37          .setAppPromotionConfigurationOverride({38            recalculationInterval: LOCKING_PERIOD,39            pendingInterval: UNLOCKING_PERIOD})], true);40      }41    } catch (error) {42      console.error(error);43      Promise.reject();44    }45  });46};4748async function getFiles(rootPath: string): Promise<string[]> {49  const files = await fs.readdir(rootPath, {withFileTypes: true});50  const filenames: string[] = [];51  for (const entry of files) {52    const res = path.resolve(rootPath, entry.name);53    if (entry.isDirectory()) {54      filenames.push(...await getFiles(res));55    } else {56      filenames.push(res);57    }58  }59  return filenames;60}6162const fundFilenames = async () => {63  await usingPlaygrounds(async (helper, privateKey) => {64    const oneToken = helper.balance.getOneTokenNominal();65    const alice = await privateKey('//Alice');66    const nonce = await helper.chain.getNonce(alice.address);67    const filenames = await getFiles(path.resolve(__dirname, '..'));6869    // batching is actually undesireable, it takes away the time while all the transactions actually succeed70    const batchSize = 300;71    let balanceGrantedCounter = 0;72    for (let b = 0; b < filenames.length; b += batchSize) {73      const tx = [];74      let batchBalanceGrantedCounter = 0;75      for (let i = 0; batchBalanceGrantedCounter < batchSize && b + i < filenames.length; i++) {76        const f = filenames[b + i];77        if (!f.endsWith('.test.ts') && !f.endsWith('seqtest.ts') || f.includes('.outdated')) continue;78        const account = await privateKey({filename: f, ignoreFundsPresence: true});79        const aliceBalance = await helper.balance.getSubstrate(account.address);8081        if (aliceBalance < MINIMUM_DONOR_FUND * oneToken) {82          tx.push(helper.executeExtrinsic(83            alice, 84            'api.tx.balances.transfer',85            [account.address, DONOR_FUNDING * oneToken],86            true,87            {nonce: nonce + balanceGrantedCounter++},88          ).then(() => true).catch(() => {console.error(`Transaction to ${path.basename(f)} registered as failed. Strange.`); return false;}));89          batchBalanceGrantedCounter++;90        }91      }9293      if(tx.length > 0) {94        console.log(`Granting funds to ${batchBalanceGrantedCounter} filename accounts.`);95        const result = await Promise.all(tx);96        if (result && result.lastIndexOf(false) > -1) throw new Error('The transactions actually probably succeeded, should check the balances.');97      }98    }99100    if (balanceGrantedCounter == 0) console.log('No account needs additional funding.');101  });102};103104const fundFilenamesWithRetries = (retriesLeft: number): Promise<boolean> => {105  if (retriesLeft <= 0) return Promise.resolve(false);106  return fundFilenames()107    .then(() => Promise.resolve(true))108    .catch(e => {109      console.error(e);110      console.error(`Some transactions might have failed. ${retriesLeft > 1 ? 'Retrying...' : 'Something is wrong.'}\n`);111      return fundFilenamesWithRetries(--retriesLeft);112    });113};114115globalSetup().catch(() => process.exit(1));