git.delta.rocks / unique-network / refs/commits / 0d4bed32f053

difftreelog

source

tests/src/util/playgrounds/unique.dev.ts9.0 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}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;6364  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {65    super(logger);66    this.arrange = new ArrangeGroup(this);67    this.wait = new WaitGroup(this);68  }6970  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {71    const wsProvider = new WsProvider(wsEndpoint);72    this.api = new ApiPromise({73      provider: wsProvider,74      signedExtensions: {75        ContractHelpers: {76          extrinsic: {},77          payload: {},78        },79        FakeTransactionFinalizer: {80          extrinsic: {},81          payload: {},82        },83      },84      rpc: {85        unique: defs.unique.rpc,86        appPromotion: defs.appPromotion.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 ss58Format = this.helper.chain.getChainProperties().ss58Format;124    const tokenNominal = this.helper.balance.getOneTokenNominal();125    const transactions = [];126    const accounts: IKeyringPair[] = [];127    for (const balance of balances) {128      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);129      accounts.push(recipient);130      if (balance !== 0n) {131        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);132        transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));133        nonce++;134      }135    }136137    await Promise.all(transactions).catch(_e => {});138    139    //#region TODO remove this region, when nonce problem will be solved140    const checkBalances = async () => {141      let isSuccess = true;142      for (let i = 0; i < balances.length; i++) {143        const balance = await this.helper.balance.getSubstrate(accounts[i].address);144        if (balance !== balances[i] * tokenNominal) {145          isSuccess = false;146          break;147        }148      }149      return isSuccess;150    };151152    let accountsCreated = false;153    // checkBalances retry up to 5 blocks154    for (let index = 0; index < 5; index++) {155      accountsCreated = await checkBalances();156      if(accountsCreated) break;157      158    }159160    if (!accountsCreated) throw Error('Accounts generation failed');161    //#endregion162163    return accounts;164  };165166  // TODO combine this method and createAccounts into one167  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {  168    const createAsManyAsCan = async () => {169      let transactions: any = [];170      const accounts: IKeyringPair[] = [];171      let nonce = await this.helper.chain.getNonce(donor.address);172      const tokenNominal = this.helper.balance.getOneTokenNominal();173      for (let i = 0; i < accountsToCreate; i++) {174        if (i === 500) { // if there are too many accounts to create175          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 176          transactions = []; //177          nonce = await this.helper.chain.getNonce(donor.address); // update nonce 178        }179        const recepient = this.helper.util.fromSeed(mnemonicGenerate());180        accounts.push(recepient);181        if (withBalance !== 0n) {182          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);183          transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));184          nonce++;185        }186      }187      188      const fullfilledAccounts = [];189      await Promise.allSettled(transactions);190      for (const account of accounts) {191        const accountBalance = await this.helper.balance.getSubstrate(account.address);192        if (accountBalance === withBalance * tokenNominal) {193          fullfilledAccounts.push(account);194        }195      }196      return fullfilledAccounts;197    };198199    200    const crowd: IKeyringPair[] = [];201    // do up to 5 retries202    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {203      const asManyAsCan = await createAsManyAsCan();204      crowd.push(...asManyAsCan);205      accountsToCreate -= asManyAsCan.length;206    }207208    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);209210    return crowd;211  };212213  isDevNode = async () => {214    const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));215    const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));216    const findCreationDate = async (block: any) => {217      const humanBlock = block.toHuman();218      let date;219      humanBlock.block.extrinsics.forEach((ext: any) => {220        if(ext.method.section === 'timestamp') {221          date = Number(ext.method.args.now.replaceAll(',', ''));222        }223      });224      return date;225    };226    const block1date = await findCreationDate(block1);227    const block2date = await findCreationDate(block2);228    if(block2date! - block1date! < 9000) return true;229  };230}231232class WaitGroup {233  helper: UniqueHelper;234235  constructor(helper: UniqueHelper) {236    this.helper = helper;237  }238239  /**240   * Wait for specified bnumber of blocks241   * @param blocksCount number of blocks to wait242   * @returns 243   */244  async newBlocks(blocksCount = 1): Promise<void> {245    // eslint-disable-next-line no-async-promise-executor246    const promise = new Promise<void>(async (resolve) => {247      const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {248        if (blocksCount > 0) {249          blocksCount--;250        } else {251          unsubscribe();252          resolve();253        }254      });255    });256    return promise;257  }258259  async forParachainBlockNumber(blockNumber: bigint) {260    // eslint-disable-next-line no-async-promise-executor261    return new Promise<void>(async (resolve) => {262      const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {263        if (data.number.toNumber() >= blockNumber) {264          unsubscribe();265          resolve();266        }267      });268    });269  }270  271  async forRelayBlockNumber(blockNumber: bigint) {272    // eslint-disable-next-line no-async-promise-executor273    return new Promise<void>(async (resolve) => {274      const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {275        if (data.value.relayParentNumber.toNumber() >= blockNumber) {276          // @ts-ignore277          unsubscribe();278          resolve();279        }280      });281    });282  }283}