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

difftreelog

source

tests/src/util/globalSetup.ts4.6 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {5  usingPlaygrounds, Pallets, DONOR_FUNDING, MINIMUM_DONOR_FUND, LOCKING_PERIOD, UNLOCKING_PERIOD,6} from './index';7import * as path from 'path';8import {promises as fs} from 'fs';910// This function should be called before running test suites.11const globalSetup = async (): Promise<void> => {12  await usingPlaygrounds(async (helper, privateKey) => {13    try {14      // 1. Wait node producing blocks15      await helper.wait.newBlocks(1, 600_000);1617      // 2. Create donors for test files18      await fundFilenamesWithRetries(3)19        .then((result) => {20          if (!result) throw Error('Some problems with fundFilenamesWithRetries');21        });2223      // 3. Configure App Promotion24      const missingPallets = helper.fetchMissingPalletNames([Pallets.AppPromotion]);25      if (missingPallets.length === 0) {26        const superuser = await privateKey('//Alice');27        const palletAddress = helper.arrange.calculatePalletAddress('appstake');28        const palletAdmin = await privateKey('//PromotionAdmin');29        const api = helper.getApi();30        await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));31        const nominal = helper.balance.getOneTokenNominal();32        await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 1000n * nominal);33        await helper.balance.transferToSubstrate(superuser, palletAddress, 1000n * nominal);34        await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [api.tx.configuration35          .setAppPromotionConfigurationOverride({36            recalculationInterval: LOCKING_PERIOD,37            pendingInterval: UNLOCKING_PERIOD})], true);38      }39    } catch (error) {40      console.error(error);41      throw Error('Error during globalSetup');42    }43  });44};4546async function getFiles(rootPath: string): Promise<string[]> {47  const files = await fs.readdir(rootPath, {withFileTypes: true});48  const filenames: string[] = [];49  for (const entry of files) {50    const res = path.resolve(rootPath, entry.name);51    if (entry.isDirectory()) {52      filenames.push(...await getFiles(res));53    } else {54      filenames.push(res);55    }56  }57  return filenames;58}5960const fundFilenames = async () => {61  await usingPlaygrounds(async (helper, privateKey) => {62    const oneToken = helper.balance.getOneTokenNominal();63    const alice = await privateKey('//Alice');64    const nonce = await helper.chain.getNonce(alice.address);65    const filenames = await getFiles(path.resolve(__dirname, '..'));6667    // batching is actually undesireable, it takes away the time while all the transactions actually succeed68    const batchSize = 300;69    let balanceGrantedCounter = 0;70    for (let b = 0; b < filenames.length; b += batchSize) {71      const tx = [];72      let batchBalanceGrantedCounter = 0;73      for (let i = 0; batchBalanceGrantedCounter < batchSize && b + i < filenames.length; i++) {74        const f = filenames[b + i];75        if (!f.endsWith('.test.ts') && !f.endsWith('seqtest.ts') || f.includes('.outdated')) continue;76        const account = await privateKey({filename: f, ignoreFundsPresence: true});77        const aliceBalance = await helper.balance.getSubstrate(account.address);7879        if (aliceBalance < MINIMUM_DONOR_FUND * oneToken) {80          tx.push(helper.executeExtrinsic(81            alice,82            'api.tx.balances.transfer',83            [account.address, DONOR_FUNDING * oneToken],84            true,85            {nonce: nonce + balanceGrantedCounter++},86          ).then(() => true).catch(() => {console.error(`Transaction to ${path.basename(f)} registered as failed. Strange.`); return false;}));87          batchBalanceGrantedCounter++;88        }89      }9091      if(tx.length > 0) {92        console.log(`Granting funds to ${batchBalanceGrantedCounter} filename accounts.`);93        const result = await Promise.all(tx);94        if (result && result.lastIndexOf(false) > -1) throw new Error('The transactions actually probably succeeded, should check the balances.');95      }96    }9798    if (balanceGrantedCounter == 0) console.log('No account needs additional funding.');99  });100};101102const fundFilenamesWithRetries = (retriesLeft: number): Promise<boolean> => {103  if (retriesLeft <= 0) return Promise.resolve(false);104  return fundFilenames()105    .then(() => Promise.resolve(true))106    .catch(e => {107      console.error(e);108      console.error(`Some transactions might have failed. ${retriesLeft > 1 ? 'Retrying...' : 'Something is wrong.'}\n`);109      return fundFilenamesWithRetries(--retriesLeft);110    });111};112113globalSetup().catch(() => process.exit(1));