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

difftreelog

source

tests/src/util/playgrounds/unique.dev.ts5.2 KiBsourcehistory
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';91011export 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}192021export class SilentConsole {22  // TODO: Remove, this is temporary: Filter unneeded API output23  // (Jaco promised it will be removed in the next version)24  consoleErr: any;25  consoleLog: any;26  consoleWarn: any;2728  constructor() {29    this.consoleErr = console.error;30    this.consoleLog = console.log;31    this.consoleWarn = console.warn;32  }3334  enable() {  35    const outFn = (printer: any) => (...args: any[]) => {36      for (const arg of args) {37        if (typeof arg !== 'string')38          continue;39        if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis: UniqueApi/2, RmrkApi/1') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')40          return;41      }42      printer(...args);43    };44  45    console.error = outFn(this.consoleErr.bind(console));46    console.log = outFn(this.consoleLog.bind(console));47    console.warn = outFn(this.consoleWarn.bind(console));48  }4950  disable() {51    console.error = this.consoleErr;52    console.log = this.consoleLog;53    console.warn = this.consoleWarn;54  }55}565758export class DevUniqueHelper extends UniqueHelper {59  /**60   * Arrange methods for tests61   */62  arrange: ArrangeGroup;6364  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {65    super(logger);66    this.arrange = new ArrangeGroup(this);67  }6869  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {70    const wsProvider = new WsProvider(wsEndpoint);71    this.api = new ApiPromise({72      provider: wsProvider,73      signedExtensions: {74        ContractHelpers: {75          extrinsic: {},76          payload: {},77        },78        FakeTransactionFinalizer: {79          extrinsic: {},80          payload: {},81        },82      },83      rpc: {84        unique: defs.unique.rpc,85        rmrk: defs.rmrk.rpc,86        eth: {87          feeHistory: {88            description: 'Dummy',89            params: [],90            type: 'u8',91          },92          maxPriorityFeePerGas: {93            description: 'Dummy',94            params: [],95            type: 'u8',96          },97        },98      },99    });100    await this.api.isReadyOrError;101    this.network = await UniqueHelper.detectNetwork(this.api);102  }103}104105class ArrangeGroup {106  helper: UniqueHelper;107108  constructor(helper: UniqueHelper) {109    this.helper = helper;110  }111112  /**113   * Generates accounts with the specified UNQ token balance 114   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.115   * @param donor donor account for balances116   * @returns array of newly created accounts117   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 118   */119  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {120    let nonce = await this.helper.chain.getNonce(donor.address);121    const tokenNominal = this.helper.balance.getOneTokenNominal();122    const transactions = [];123    const accounts: IKeyringPair[] = [];124    for (const balance of balances) {125      const recepient = this.helper.util.fromSeed(mnemonicGenerate());126      accounts.push(recepient);127      if (balance !== 0n) {128        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, balance * tokenNominal]);129        transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));130        nonce++;131      }132    }133134    await Promise.all(transactions).catch(_e => {});135    136    //#region TODO remove this region, when nonce problem will be solved137    const checkBalances = async () => {138      let isSuccess = true;139      for (let i = 0; i < balances.length; i++) {140        const balance = await this.helper.balance.getSubstrate(accounts[i].address);141        if (balance !== balances[i] * tokenNominal) {142          isSuccess = false;143          break;144        }145      }146      return isSuccess;147    };148149    let accountsCreated = false;150    // checkBalances retry up to 5 blocks151    for (let index = 0; index < 5; index++) {152      accountsCreated = await checkBalances();153      if(accountsCreated) break;154      await this.waitNewBlocks(1);155    }156157    if (!accountsCreated) throw Error('Accounts generation failed');158    //#endregion159160    return accounts;161  };162 163  /**164   * Wait for specified bnumber of blocks165   * @param blocksCount number of blocks to wait166   * @returns 167   */168  async waitNewBlocks(blocksCount = 1): Promise<void> {169    // eslint-disable-next-line no-async-promise-executor170    const promise = new Promise<void>(async (resolve) => {171      const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {172        if (blocksCount > 0) {173          blocksCount--;174        } else {175          unsubscribe();176          resolve();177        }178      });179    });180    return promise;181  }182}