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

difftreelog

feat add testUtils to dev unique helper

Daniel Shiposha2022-10-11parent: #4ce643d.patch.diff
in: master

1 file changed

modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {stringToU8a} from '@polkadot/util';5import {encodeAddress, mnemonicGenerate} from '@polkadot/util-crypto';6import {UniqueHelper, MoonbeamHelper, ChainHelperBase, AcalaHelper, RelayHelper, WestmintHelper} from './unique';7import {ApiPromise, Keyring, WsProvider} from '@polkadot/api';8import * as defs from '../../interfaces/definitions';9import {IKeyringPair} from '@polkadot/types/types';10import {EventRecord} from '@polkadot/types/interfaces';11import {ICrossAccountId} from './types';12import {FrameSystemEventRecord} from '@polkadot/types/lookup';13import {VoidFn} from '@polkadot/api/types';14import {FrameSystemEventRecord} from '@polkadot/types/lookup';1516export class SilentLogger {17  log(_msg: any, _level: any): void { }18  level = {19    ERROR: 'ERROR' as const,20    WARNING: 'WARNING' as const,21    INFO: 'INFO' as const,22  };23}2425export class SilentConsole {26  // TODO: Remove, this is temporary: Filter unneeded API output27  // (Jaco promised it will be removed in the next version)28  consoleErr: any;29  consoleLog: any;30  consoleWarn: any;3132  constructor() {33    this.consoleErr = console.error;34    this.consoleLog = console.log;35    this.consoleWarn = console.warn;36  }3738  enable() {  39    const outFn = (printer: any) => (...args: any[]) => {40      for (const arg of args) {41        if (typeof arg !== 'string')42          continue;43        if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')44          return;45      }46      printer(...args);47    };48  49    console.error = outFn(this.consoleErr.bind(console));50    console.log = outFn(this.consoleLog.bind(console));51    console.warn = outFn(this.consoleWarn.bind(console));52  }5354  disable() {55    console.error = this.consoleErr;56    console.log = this.consoleLog;57    console.warn = this.consoleWarn;58  }59}6061export class DevUniqueHelper extends UniqueHelper {62  /**63   * Arrange methods for tests64   */65  arrange: ArrangeGroup;66  wait: WaitGroup;67  admin: AdminGroup;6869  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {70    options.helperBase = options.helperBase ?? DevUniqueHelper;7172    super(logger, options);73    this.arrange = new ArrangeGroup(this);74    this.wait = new WaitGroup(this);75    this.admin = new AdminGroup(this);76  }7778  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {79    const wsProvider = new WsProvider(wsEndpoint);80    this.api = new ApiPromise({81      provider: wsProvider,82      signedExtensions: {83        ContractHelpers: {84          extrinsic: {},85          payload: {},86        },87        FakeTransactionFinalizer: {88          extrinsic: {},89          payload: {},90        },91      },92      rpc: {93        unique: defs.unique.rpc,94        appPromotion: defs.appPromotion.rpc,95        rmrk: defs.rmrk.rpc,96        eth: {97          feeHistory: {98            description: 'Dummy',99            params: [],100            type: 'u8',101          },102          maxPriorityFeePerGas: {103            description: 'Dummy',104            params: [],105            type: 'u8',106          },107        },108      },109    });110    await this.api.isReadyOrError;111    this.network = await UniqueHelper.detectNetwork(this.api);112  }113}114115export class DevRelayHelper extends RelayHelper {}116117export class DevWestmintHelper extends WestmintHelper {118  wait: WaitGroup;119120  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {121    options.helperBase = options.helperBase ?? DevWestmintHelper;122123    super(logger, options);124    this.wait = new WaitGroup(this);125  }126}127128export class DevMoonbeamHelper extends MoonbeamHelper {129  account: MoonbeamAccountGroup;130  wait: WaitGroup;131132  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {133    options.helperBase = options.helperBase ?? DevMoonbeamHelper;134135    super(logger, options);136    this.account = new MoonbeamAccountGroup(this);137    this.wait = new WaitGroup(this);138  }139}140141export class DevMoonriverHelper extends DevMoonbeamHelper {}142143export class DevAcalaHelper extends AcalaHelper {144  wait: WaitGroup;145146  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {147    options.helperBase = options.helperBase ?? DevAcalaHelper;148149    super(logger, options);150    this.wait = new WaitGroup(this);151  }152}153154export class DevKaruraHelper extends DevAcalaHelper {}155156class ArrangeGroup {157  helper: DevUniqueHelper;158159  scheduledIdSlider = 0;160161  constructor(helper: DevUniqueHelper) {162    this.helper = helper;163  }164165  /**166   * Generates accounts with the specified UNQ token balance 167   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.168   * @param donor donor account for balances169   * @returns array of newly created accounts170   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 171   */172  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {173    let nonce = await this.helper.chain.getNonce(donor.address);174    const wait = new WaitGroup(this.helper);175    const ss58Format = this.helper.chain.getChainProperties().ss58Format;176    const tokenNominal = this.helper.balance.getOneTokenNominal();177    const transactions = [];178    const accounts: IKeyringPair[] = [];179    for (const balance of balances) {180      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);181      accounts.push(recipient);182      if (balance !== 0n) {183        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);184        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));185        nonce++;186      }187    }188189    await Promise.all(transactions).catch(_e => {});190    191    //#region TODO remove this region, when nonce problem will be solved192    const checkBalances = async () => {193      let isSuccess = true;194      for (let i = 0; i < balances.length; i++) {195        const balance = await this.helper.balance.getSubstrate(accounts[i].address);196        if (balance !== balances[i] * tokenNominal) {197          isSuccess = false;198          break;199        }200      }201      return isSuccess;202    };203204    let accountsCreated = false;205    const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;206    // checkBalances retry up to 5-50 blocks207    for (let index = 0; index < maxBlocksChecked; index++) {208      accountsCreated = await checkBalances();209      if(accountsCreated) break;210      await wait.newBlocks(1);211    }212213    if (!accountsCreated) throw Error('Accounts generation failed');214    //#endregion215216    return accounts;217  };218219  // TODO combine this method and createAccounts into one220  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {  221    const createAsManyAsCan = async () => {222      let transactions: any = [];223      const accounts: IKeyringPair[] = [];224      let nonce = await this.helper.chain.getNonce(donor.address);225      const tokenNominal = this.helper.balance.getOneTokenNominal();226      for (let i = 0; i < accountsToCreate; i++) {227        if (i === 500) { // if there are too many accounts to create228          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 229          transactions = []; //230          nonce = await this.helper.chain.getNonce(donor.address); // update nonce 231        }232        const recepient = this.helper.util.fromSeed(mnemonicGenerate());233        accounts.push(recepient);234        if (withBalance !== 0n) {235          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);236          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));237          nonce++;238        }239      }240      241      const fullfilledAccounts = [];242      await Promise.allSettled(transactions);243      for (const account of accounts) {244        const accountBalance = await this.helper.balance.getSubstrate(account.address);245        if (accountBalance === withBalance * tokenNominal) {246          fullfilledAccounts.push(account);247        }248      }249      return fullfilledAccounts;250    };251252    253    const crowd: IKeyringPair[] = [];254    // do up to 5 retries255    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {256      const asManyAsCan = await createAsManyAsCan();257      crowd.push(...asManyAsCan);258      accountsToCreate -= asManyAsCan.length;259    }260261    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);262263    return crowd;264  };265266  isDevNode = async () => {267    let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();268    if (blockNumber == 0) {269      await this.helper.wait.newBlocks(1); 270      blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();271    }272    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);273    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber - 1])]);274    const findCreationDate = async (block: any) => {275      const humanBlock = block.toHuman();276      let date;277      humanBlock.block.extrinsics.forEach((ext: any) => {278        if(ext.method.section === 'timestamp') {279          date = Number(ext.method.args.now.replaceAll(',', ''));280        }281      });282      return date;283    };284    const block1date = await findCreationDate(block1);285    const block2date = await findCreationDate(block2);286    if(block2date! - block1date! < 9000) return true;287  };288  289  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {290    const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);291    let balance = await this.helper.balance.getSubstrate(address); 292    293    await promise();294    295    balance -= await this.helper.balance.getSubstrate(address);296    297    return balance;298  }299300  calculatePalletAddress(palletId: any) {301    const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));302    return encodeAddress(address);303  }304305  async makeScheduledIds(num: number): Promise<string[]> {306    await this.helper.wait.noScheduledTasks();307308    function makeId(slider: number) {309      const scheduledIdSize = 32;310      const hexId = slider.toString(16);311      const prefixSize = scheduledIdSize - hexId.length;312313      const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;314315      return scheduledId;  316    }317318    const ids = [];319    for (let i = 0; i < num; i++) {320      ids.push(makeId(this.scheduledIdSlider));321      this.scheduledIdSlider += 1;322    }323324    return ids;325  }326327  async makeScheduledId(): Promise<string> {328    return (await this.makeScheduledIds(1))[0];329  }330331  async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {332    const capture = new EventCapture(this.helper, eventSection, eventMethod);333    await capture.startCapture();334335    return capture;336  }337}338339class MoonbeamAccountGroup {340  helper: MoonbeamHelper;341342  keyring: Keyring;343  _alithAccount: IKeyringPair;344  _baltatharAccount: IKeyringPair;345  _dorothyAccount: IKeyringPair;346347  constructor(helper: MoonbeamHelper) {348    this.helper = helper;349350    this.keyring = new Keyring({type: 'ethereum'});351    const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';352    const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';353    const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';354355    this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');356    this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');357    this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');358  }359360  alithAccount() {361    return this._alithAccount;362  }363364  baltatharAccount() {365    return this._baltatharAccount;366  }367368  dorothyAccount() {369    return this._dorothyAccount;370  }371372  create() {373    return this.keyring.addFromUri(mnemonicGenerate());374  }375}376377class WaitGroup {378  helper: ChainHelperBase;379380  constructor(helper: ChainHelperBase) {381    this.helper = helper;382  }383384  /**385   * Wait for specified number of blocks386   * @param blocksCount number of blocks to wait387   * @returns 388   */389  async newBlocks(blocksCount = 1): Promise<void> {390    // eslint-disable-next-line no-async-promise-executor391    const promise = new Promise<void>(async (resolve) => {392      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {393        if (blocksCount > 0) {394          blocksCount--;395        } else {396          unsubscribe();397          resolve();398        }399      });400    });401    return promise;402  }403404  async forParachainBlockNumber(blockNumber: bigint) {405    // eslint-disable-next-line no-async-promise-executor406    return new Promise<void>(async (resolve) => {407      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {408        if (data.number.toNumber() >= blockNumber) {409          unsubscribe();410          resolve();411        }412      });413    });414  }415  416  async forRelayBlockNumber(blockNumber: bigint) {417    // eslint-disable-next-line no-async-promise-executor418    return new Promise<void>(async (resolve) => {419      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {420        if (data.value.relayParentNumber.toNumber() >= blockNumber) {421          // @ts-ignore422          unsubscribe();423          resolve();424        }425      });426    });427  }428429  async noScheduledTasks() {430    const api = this.helper.getApi();431    432    // eslint-disable-next-line no-async-promise-executor433    const promise = new Promise<void>(async resolve => {434      const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {435        const areThereScheduledTasks = await api.query.scheduler.lookup.entries();436437        if(areThereScheduledTasks.length == 0) {438          unsubscribe();439          resolve();440        }441      }); 442    });443444    return promise;445  }446447  async event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {448    // eslint-disable-next-line no-async-promise-executor449    const promise = new Promise<EventRecord | null>(async (resolve) => {450      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {451        const blockNumber = header.number.toHuman();452        const blockHash = header.hash;453        const eventIdStr = `${eventSection}.${eventMethod}`;454        const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;455  456        this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);457  458        const apiAt = await this.helper.getApi().at(blockHash);459        const eventRecords = (await apiAt.query.system.events()) as any;460  461        const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {462          return r.event.section == eventSection && r.event.method == eventMethod;463        });464  465        if (neededEvent) {466          unsubscribe();467          resolve(neededEvent);468        } else if (maxBlocksToWait > 0) {469          maxBlocksToWait--;470        } else {471          this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);472          unsubscribe();473          resolve(null);474        }475      });476    });477    return promise;478  }479}480481class EventCapture {482  helper: DevUniqueHelper;483  eventSection: string;484  eventMethod: string;485  events: EventRecord[] = [];486  unsubscribe: VoidFn | null = null;487488  constructor(489    helper: DevUniqueHelper,490    eventSection: string,491    eventMethod: string,492  ) {493    this.helper = helper;494    this.eventSection = eventSection;495    this.eventMethod = eventMethod;496  }497498  async startCapture() {499    this.stopCapture();500    this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {501      const newEvents = eventRecords.filter(r => {502        return r.event.section == this.eventSection && r.event.method == this.eventMethod;503      });504505      this.events.push(...newEvents);506    })) as any;507  }508509  stopCapture() {510    if (this.unsubscribe !== null) {511      this.unsubscribe();512    }513  }514515  extractCapturedEvents() {516    return this.events;517  }518}519520class AdminGroup {521  helper: UniqueHelper;522523  constructor(helper: UniqueHelper) {524    this.helper = helper;525  }526527  async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {528    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);529    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {530      return {531        staker: e.event.data[0].toString(),532        stake: e.event.data[1].toBigInt(),533        payout: e.event.data[2].toBigInt(),534      };535    });536  }537}
after · tests/src/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {stringToU8a} from '@polkadot/util';5import {encodeAddress, mnemonicGenerate} from '@polkadot/util-crypto';6import {UniqueHelper, MoonbeamHelper, ChainHelperBase, AcalaHelper, RelayHelper, WestmintHelper} from './unique';7import {ApiPromise, Keyring, WsProvider} from '@polkadot/api';8import * as defs from '../../interfaces/definitions';9import {IKeyringPair} from '@polkadot/types/types';10import {EventRecord} from '@polkadot/types/interfaces';11import {ICrossAccountId, TSigner} from './types';12import {FrameSystemEventRecord} from '@polkadot/types/lookup';13import {VoidFn} from '@polkadot/api/types';1415export class SilentLogger {16  log(_msg: any, _level: any): void { }17  level = {18    ERROR: 'ERROR' as const,19    WARNING: 'WARNING' as const,20    INFO: 'INFO' as const,21  };22}2324export class SilentConsole {25  // TODO: Remove, this is temporary: Filter unneeded API output26  // (Jaco promised it will be removed in the next version)27  consoleErr: any;28  consoleLog: any;29  consoleWarn: any;3031  constructor() {32    this.consoleErr = console.error;33    this.consoleLog = console.log;34    this.consoleWarn = console.warn;35  }3637  enable() {  38    const outFn = (printer: any) => (...args: any[]) => {39      for (const arg of args) {40        if (typeof arg !== 'string')41          continue;42        if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')43          return;44      }45      printer(...args);46    };47  48    console.error = outFn(this.consoleErr.bind(console));49    console.log = outFn(this.consoleLog.bind(console));50    console.warn = outFn(this.consoleWarn.bind(console));51  }5253  disable() {54    console.error = this.consoleErr;55    console.log = this.consoleLog;56    console.warn = this.consoleWarn;57  }58}5960export class DevUniqueHelper extends UniqueHelper {61  /**62   * Arrange methods for tests63   */64  arrange: ArrangeGroup;65  wait: WaitGroup;66  admin: AdminGroup;67  testUtils: TestUtilGroup;6869  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {70    options.helperBase = options.helperBase ?? DevUniqueHelper;7172    super(logger, options);73    this.arrange = new ArrangeGroup(this);74    this.wait = new WaitGroup(this);75    this.admin = new AdminGroup(this);76    this.testUtils = new TestUtilGroup(this);77  }7879  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {80    const wsProvider = new WsProvider(wsEndpoint);81    this.api = new ApiPromise({82      provider: wsProvider,83      signedExtensions: {84        ContractHelpers: {85          extrinsic: {},86          payload: {},87        },88        FakeTransactionFinalizer: {89          extrinsic: {},90          payload: {},91        },92      },93      rpc: {94        unique: defs.unique.rpc,95        appPromotion: defs.appPromotion.rpc,96        rmrk: defs.rmrk.rpc,97        eth: {98          feeHistory: {99            description: 'Dummy',100            params: [],101            type: 'u8',102          },103          maxPriorityFeePerGas: {104            description: 'Dummy',105            params: [],106            type: 'u8',107          },108        },109      },110    });111    await this.api.isReadyOrError;112    this.network = await UniqueHelper.detectNetwork(this.api);113  }114}115116export class DevRelayHelper extends RelayHelper {}117118export class DevWestmintHelper extends WestmintHelper {119  wait: WaitGroup;120121  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {122    options.helperBase = options.helperBase ?? DevWestmintHelper;123124    super(logger, options);125    this.wait = new WaitGroup(this);126  }127}128129export class DevMoonbeamHelper extends MoonbeamHelper {130  account: MoonbeamAccountGroup;131  wait: WaitGroup;132133  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {134    options.helperBase = options.helperBase ?? DevMoonbeamHelper;135136    super(logger, options);137    this.account = new MoonbeamAccountGroup(this);138    this.wait = new WaitGroup(this);139  }140}141142export class DevMoonriverHelper extends DevMoonbeamHelper {}143144export class DevAcalaHelper extends AcalaHelper {145  wait: WaitGroup;146147  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {148    options.helperBase = options.helperBase ?? DevAcalaHelper;149150    super(logger, options);151    this.wait = new WaitGroup(this);152  }153}154155export class DevKaruraHelper extends DevAcalaHelper {}156157class ArrangeGroup {158  helper: DevUniqueHelper;159160  scheduledIdSlider = 0;161162  constructor(helper: DevUniqueHelper) {163    this.helper = helper;164  }165166  /**167   * Generates accounts with the specified UNQ token balance 168   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.169   * @param donor donor account for balances170   * @returns array of newly created accounts171   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 172   */173  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {174    let nonce = await this.helper.chain.getNonce(donor.address);175    const wait = new WaitGroup(this.helper);176    const ss58Format = this.helper.chain.getChainProperties().ss58Format;177    const tokenNominal = this.helper.balance.getOneTokenNominal();178    const transactions = [];179    const accounts: IKeyringPair[] = [];180    for (const balance of balances) {181      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);182      accounts.push(recipient);183      if (balance !== 0n) {184        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);185        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));186        nonce++;187      }188    }189190    await Promise.all(transactions).catch(_e => {});191    192    //#region TODO remove this region, when nonce problem will be solved193    const checkBalances = async () => {194      let isSuccess = true;195      for (let i = 0; i < balances.length; i++) {196        const balance = await this.helper.balance.getSubstrate(accounts[i].address);197        if (balance !== balances[i] * tokenNominal) {198          isSuccess = false;199          break;200        }201      }202      return isSuccess;203    };204205    let accountsCreated = false;206    const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;207    // checkBalances retry up to 5-50 blocks208    for (let index = 0; index < maxBlocksChecked; index++) {209      accountsCreated = await checkBalances();210      if(accountsCreated) break;211      await wait.newBlocks(1);212    }213214    if (!accountsCreated) throw Error('Accounts generation failed');215    //#endregion216217    return accounts;218  };219220  // TODO combine this method and createAccounts into one221  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {  222    const createAsManyAsCan = async () => {223      let transactions: any = [];224      const accounts: IKeyringPair[] = [];225      let nonce = await this.helper.chain.getNonce(donor.address);226      const tokenNominal = this.helper.balance.getOneTokenNominal();227      for (let i = 0; i < accountsToCreate; i++) {228        if (i === 500) { // if there are too many accounts to create229          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 230          transactions = []; //231          nonce = await this.helper.chain.getNonce(donor.address); // update nonce 232        }233        const recepient = this.helper.util.fromSeed(mnemonicGenerate());234        accounts.push(recepient);235        if (withBalance !== 0n) {236          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);237          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));238          nonce++;239        }240      }241      242      const fullfilledAccounts = [];243      await Promise.allSettled(transactions);244      for (const account of accounts) {245        const accountBalance = await this.helper.balance.getSubstrate(account.address);246        if (accountBalance === withBalance * tokenNominal) {247          fullfilledAccounts.push(account);248        }249      }250      return fullfilledAccounts;251    };252253    254    const crowd: IKeyringPair[] = [];255    // do up to 5 retries256    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {257      const asManyAsCan = await createAsManyAsCan();258      crowd.push(...asManyAsCan);259      accountsToCreate -= asManyAsCan.length;260    }261262    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);263264    return crowd;265  };266267  isDevNode = async () => {268    let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();269    if (blockNumber == 0) {270      await this.helper.wait.newBlocks(1); 271      blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();272    }273    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);274    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber - 1])]);275    const findCreationDate = async (block: any) => {276      const humanBlock = block.toHuman();277      let date;278      humanBlock.block.extrinsics.forEach((ext: any) => {279        if(ext.method.section === 'timestamp') {280          date = Number(ext.method.args.now.replaceAll(',', ''));281        }282      });283      return date;284    };285    const block1date = await findCreationDate(block1);286    const block2date = await findCreationDate(block2);287    if(block2date! - block1date! < 9000) return true;288  };289  290  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {291    const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);292    let balance = await this.helper.balance.getSubstrate(address); 293    294    await promise();295    296    balance -= await this.helper.balance.getSubstrate(address);297    298    return balance;299  }300301  calculatePalletAddress(palletId: any) {302    const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));303    return encodeAddress(address);304  }305306  async makeScheduledIds(num: number): Promise<string[]> {307    await this.helper.wait.noScheduledTasks();308309    function makeId(slider: number) {310      const scheduledIdSize = 32;311      const hexId = slider.toString(16);312      const prefixSize = scheduledIdSize - hexId.length;313314      const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;315316      return scheduledId;  317    }318319    const ids = [];320    for (let i = 0; i < num; i++) {321      ids.push(makeId(this.scheduledIdSlider));322      this.scheduledIdSlider += 1;323    }324325    return ids;326  }327328  async makeScheduledId(): Promise<string> {329    return (await this.makeScheduledIds(1))[0];330  }331332  async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {333    const capture = new EventCapture(this.helper, eventSection, eventMethod);334    await capture.startCapture();335336    return capture;337  }338}339340class MoonbeamAccountGroup {341  helper: MoonbeamHelper;342343  keyring: Keyring;344  _alithAccount: IKeyringPair;345  _baltatharAccount: IKeyringPair;346  _dorothyAccount: IKeyringPair;347348  constructor(helper: MoonbeamHelper) {349    this.helper = helper;350351    this.keyring = new Keyring({type: 'ethereum'});352    const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';353    const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';354    const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';355356    this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');357    this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');358    this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');359  }360361  alithAccount() {362    return this._alithAccount;363  }364365  baltatharAccount() {366    return this._baltatharAccount;367  }368369  dorothyAccount() {370    return this._dorothyAccount;371  }372373  create() {374    return this.keyring.addFromUri(mnemonicGenerate());375  }376}377378class WaitGroup {379  helper: ChainHelperBase;380381  constructor(helper: ChainHelperBase) {382    this.helper = helper;383  }384385  /**386   * Wait for specified number of blocks387   * @param blocksCount number of blocks to wait388   * @returns 389   */390  async newBlocks(blocksCount = 1): Promise<void> {391    // eslint-disable-next-line no-async-promise-executor392    const promise = new Promise<void>(async (resolve) => {393      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {394        if (blocksCount > 0) {395          blocksCount--;396        } else {397          unsubscribe();398          resolve();399        }400      });401    });402    return promise;403  }404405  async forParachainBlockNumber(blockNumber: bigint) {406    // eslint-disable-next-line no-async-promise-executor407    return new Promise<void>(async (resolve) => {408      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {409        if (data.number.toNumber() >= blockNumber) {410          unsubscribe();411          resolve();412        }413      });414    });415  }416  417  async forRelayBlockNumber(blockNumber: bigint) {418    // eslint-disable-next-line no-async-promise-executor419    return new Promise<void>(async (resolve) => {420      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {421        if (data.value.relayParentNumber.toNumber() >= blockNumber) {422          // @ts-ignore423          unsubscribe();424          resolve();425        }426      });427    });428  }429430  async noScheduledTasks() {431    const api = this.helper.getApi();432    433    // eslint-disable-next-line no-async-promise-executor434    const promise = new Promise<void>(async resolve => {435      const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {436        const areThereScheduledTasks = await api.query.scheduler.lookup.entries();437438        if(areThereScheduledTasks.length == 0) {439          unsubscribe();440          resolve();441        }442      }); 443    });444445    return promise;446  }447448  async event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {449    // eslint-disable-next-line no-async-promise-executor450    const promise = new Promise<EventRecord | null>(async (resolve) => {451      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {452        const blockNumber = header.number.toHuman();453        const blockHash = header.hash;454        const eventIdStr = `${eventSection}.${eventMethod}`;455        const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;456  457        this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);458  459        const apiAt = await this.helper.getApi().at(blockHash);460        const eventRecords = (await apiAt.query.system.events()) as any;461  462        const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {463          return r.event.section == eventSection && r.event.method == eventMethod;464        });465  466        if (neededEvent) {467          unsubscribe();468          resolve(neededEvent);469        } else if (maxBlocksToWait > 0) {470          maxBlocksToWait--;471        } else {472          this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);473          unsubscribe();474          resolve(null);475        }476      });477    });478    return promise;479  }480}481482class TestUtilGroup {483  helper: DevUniqueHelper;484485  constructor(helper: DevUniqueHelper) {486    this.helper = helper;487  }488489  async setTestValue(signer: TSigner, testVal: number) {490    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValue', [testVal], true);491  }492493  async incTestValue(signer: TSigner) {494    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.incTestValue', [], true);495  }496497  async setTestValueAndRollback(signer: TSigner, testVal: number) {498    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);499  }500501  async testValue() {502    return (await this.helper.callRpc('api.query.testUtils.testValue', [])).toNumber();503  }504505  async justTakeFee(signer: TSigner) {506    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.justTakeFee', [], true);507  }508509  async selfCancelingInc(signer: TSigner, scheduledId: string, maxTestVal: number) {510    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.selfCancelingInc', [scheduledId, maxTestVal], true);511  }512}513514class EventCapture {515  helper: DevUniqueHelper;516  eventSection: string;517  eventMethod: string;518  events: EventRecord[] = [];519  unsubscribe: VoidFn | null = null;520521  constructor(522    helper: DevUniqueHelper,523    eventSection: string,524    eventMethod: string,525  ) {526    this.helper = helper;527    this.eventSection = eventSection;528    this.eventMethod = eventMethod;529  }530531  async startCapture() {532    this.stopCapture();533    this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {534      const newEvents = eventRecords.filter(r => {535        return r.event.section == this.eventSection && r.event.method == this.eventMethod;536      });537538      this.events.push(...newEvents);539    })) as any;540  }541542  stopCapture() {543    if (this.unsubscribe !== null) {544      this.unsubscribe();545    }546  }547548  extractCapturedEvents() {549    return this.events;550  }551}552553class AdminGroup {554  helper: UniqueHelper;555556  constructor(helper: UniqueHelper) {557    this.helper = helper;558  }559560  async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {561    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);562    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {563      return {564        staker: e.event.data[0].toString(),565        stake: e.event.data[1].toBigInt(),566        payout: e.event.data[2].toBigInt(),567      };568    });569  }570}