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

difftreelog

source

tests/src/util/playgrounds/unique.dev.ts5.3 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        for (const arg of args) {38          if (typeof arg !== 'string')39            continue;40          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')41            return;42        }43      }44      printer(...args);45    };46  47    console.error = outFn(this.consoleErr.bind(console));48    console.log = outFn(this.consoleLog.bind(console));49    console.warn = outFn(this.consoleWarn.bind(console));50  }5152  disable() {53    console.error = this.consoleErr;54    console.log = this.consoleLog;55    console.warn = this.consoleWarn;56  }57}585960export class DevUniqueHelper extends UniqueHelper {61  /**62   * Arrange methods for tests63   */64  arrange: ArrangeGroup;6566  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {67    super(logger);68    this.arrange = new ArrangeGroup(this);69  }7071  async connect(wsEndpoint: string, listeners?: any): Promise<void> {72    const wsProvider = new WsProvider(wsEndpoint);73    this.api = new ApiPromise({74      provider: wsProvider,75      signedExtensions: {76        ContractHelpers: {77          extrinsic: {},78          payload: {},79        },80        FakeTransactionFinalizer: {81          extrinsic: {},82          payload: {},83        },84      },85      rpc: {86        unique: defs.unique.rpc,87        rmrk: defs.rmrk.rpc,88        eth: {89          feeHistory: {90            description: 'Dummy',91            params: [],92            type: 'u8',93          },94          maxPriorityFeePerGas: {95            description: 'Dummy',96            params: [],97            type: 'u8',98          },99        },100      },101    });102    await this.api.isReadyOrError;103    this.network = await UniqueHelper.detectNetwork(this.api);104  }105}106107class ArrangeGroup {108  helper: UniqueHelper;109110  constructor(helper: UniqueHelper) {111    this.helper = helper;112  }113114  /**115   * Generates accounts with the specified UNQ token balance 116   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.117   * @param donor donor account for balances118   * @returns array of newly created accounts119   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 120   */121  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {122    let nonce = await this.helper.chain.getNonce(donor.address);123    const tokenNominal = this.helper.balance.getOneTokenNominal();124    const transactions = [];125    const accounts: IKeyringPair[] = [];126    for (const balance of balances) {127      const recepient = this.helper.util.fromSeed(mnemonicGenerate());128      accounts.push(recepient);129      if (balance !== 0n) {130        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, balance * tokenNominal]);131        transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));132        nonce++;133      }134    }135136    await Promise.all(transactions).catch(e => {});137    138    //#region TODO remove this region, when nonce problem will be solved139    const checkBalances = async () => {140      let isSuccess = true;141      for (let i = 0; i < balances.length; i++) {142        const balance = await this.helper.balance.getSubstrate(accounts[i].address);143        if (balance !== balances[i] * tokenNominal) {144          isSuccess = false;145          break;146        }147      }148      return isSuccess;149    };150151    let accountsCreated = false;152    // checkBalances retry up to 5 blocks153    for (let index = 0; index < 5; index++) {154      console.log(await this.helper.chain.getLatestBlockNumber());155      accountsCreated = await checkBalances();156      if(accountsCreated) break;157      await this.waitNewBlocks(1);158    }159160    if (!accountsCreated) throw Error('Accounts generation failed');161    //#endregion162163    return accounts;164  };165166  /**167   * Wait for specified bnumber of blocks168   * @param blocksCount number of blocks to wait169   * @returns 170   */171  async waitNewBlocks(blocksCount = 1): Promise<void> {172    const promise = new Promise<void>(async (resolve) => {173      const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {174        if (blocksCount > 0) {175          blocksCount--;176        } else {177          unsubscribe();178          resolve();179        }180      });181    });182    return promise;183  }184}