git.delta.rocks / unique-network / refs/commits / 666793cdc364

difftreelog

source

tests/src/util/playgrounds/unique.dev.ts33.9 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {stringToU8a} from '@polkadot/util';5import {blake2AsHex, encodeAddress, mnemonicGenerate} from '@polkadot/util-crypto';6import {UniqueHelper, MoonbeamHelper, ChainHelperBase, AcalaHelper, RelayHelper, WestmintHelper, AstarHelper} 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, IPovInfo, TSigner} from './types';12import {FrameSystemEventRecord, XcmV2TraitsError} from '@polkadot/types/lookup';13import {VoidFn} from '@polkadot/api/types';14import {Pallets} from '..';15import {spawnSync} from 'child_process';1617export class SilentLogger {18  log(_msg: any, _level: any): void { }19  level = {20    ERROR: 'ERROR' as const,21    WARNING: 'WARNING' as const,22    INFO: 'INFO' as const,23  };24}2526export class SilentConsole {27  // TODO: Remove, this is temporary: Filter unneeded API output28  // (Jaco promised it will be removed in the next version)29  consoleErr: any;30  consoleLog: any;31  consoleWarn: any;3233  constructor() {34    this.consoleErr = console.error;35    this.consoleLog = console.log;36    this.consoleWarn = console.warn;37  }3839  enable() {40    const outFn = (printer: any) => (...args: any[]) => {41      for(const arg of args) {42        if(typeof arg !== 'string')43          continue;44        if(arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')45          return;46      }47      printer(...args);48    };4950    console.error = outFn(this.consoleErr.bind(console));51    console.log = outFn(this.consoleLog.bind(console));52    console.warn = outFn(this.consoleWarn.bind(console));53  }5455  disable() {56    console.error = this.consoleErr;57    console.log = this.consoleLog;58    console.warn = this.consoleWarn;59  }60}6162export interface IEventHelper {63  section(): string;6465  method(): string;6667  bindEventRecord(e: FrameSystemEventRecord): void;6869  raw(): FrameSystemEventRecord;70}7172// eslint-disable-next-line @typescript-eslint/naming-convention73function EventHelper(section: string, method: string) {74  return class implements IEventHelper {75    eventRecord: FrameSystemEventRecord | null;76    _section: string;77    _method: string;7879    constructor() {80      this.eventRecord = null;81      this._section = section;82      this._method = method;83    }8485    section(): string {86      return this._section;87    }8889    method(): string {90      return this._method;91    }9293    bindEventRecord(e: FrameSystemEventRecord) {94      this.eventRecord = e;95    }9697    raw() {98      return this.eventRecord!;99    }100101    eventJsonData<T = any>(index: number) {102      return this.raw().event.data[index].toJSON() as T;103    }104105    eventData<T>(index: number) {106      return this.raw().event.data[index] as T;107    }108  };109}110111// eslint-disable-next-line @typescript-eslint/naming-convention112function EventSection(section: string) {113  return class Section {114    static section = section;115116    static Method(name: string) {117      return EventHelper(Section.section, name);118    }119  };120}121122export class Event {123  static Democracy = class extends EventSection('democracy') {124    static Started = class extends this.Method('Started') {125      referendumIndex() {126        return this.eventJsonData<number>(0);127      }128129      threshold() {130        return this.eventJsonData(1);131      }132    };133134    static Voted = class extends this.Method('Voted') {135      voter() {136        return this.eventJsonData(0);137      }138139      referendumIndex() {140        return this.eventJsonData<number>(1);141      }142143      vote() {144        return this.eventJsonData(2);145      }146    };147148    static Passed = class extends this.Method('Passed') {149      referendumIndex() {150        return this.eventJsonData<number>(0);151      }152    };153  };154155  static Scheduler = class extends EventSection('scheduler') {156    static PriorityChanged = class extends this.Method('PriorityChanged') {157      task() {158        return this.eventJsonData(0);159      }160161      priority() {162        return this.eventJsonData(1);163      }164    };165  };166167  static XcmpQueue = class extends EventSection('xcmpQueue') {168    static XcmpMessageSent = class extends this.Method('XcmpMessageSent') {169      messageHash() {170        return this.eventJsonData(0);171      }172    };173174    static Fail = class extends this.Method('Fail') {175      messageHash() {176        return this.eventJsonData(0);177      }178179      outcome() {180        return this.eventData<XcmV2TraitsError>(1);181      }182    };183  };184}185186export class DevUniqueHelper extends UniqueHelper {187  /**188   * Arrange methods for tests189   */190  arrange: ArrangeGroup;191  wait: WaitGroup;192  admin: AdminGroup;193  session: SessionGroup;194  testUtils: TestUtilGroup;195196  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {197    options.helperBase = options.helperBase ?? DevUniqueHelper;198199    super(logger, options);200    this.arrange = new ArrangeGroup(this);201    this.wait = new WaitGroup(this);202    this.admin = new AdminGroup(this);203    this.testUtils = new TestUtilGroup(this);204    this.session = new SessionGroup(this);205  }206207  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {208    const wsProvider = new WsProvider(wsEndpoint);209    this.api = new ApiPromise({210      provider: wsProvider,211      signedExtensions: {212        ContractHelpers: {213          extrinsic: {},214          payload: {},215        },216        CheckMaintenance: {217          extrinsic: {},218          payload: {},219        },220        DisableIdentityCalls: {221          extrinsic: {},222          payload: {},223        },224        FakeTransactionFinalizer: {225          extrinsic: {},226          payload: {},227        },228      },229      rpc: {230        unique: defs.unique.rpc,231        appPromotion: defs.appPromotion.rpc,232        povinfo: defs.povinfo.rpc,233        eth: {234          feeHistory: {235            description: 'Dummy',236            params: [],237            type: 'u8',238          },239          maxPriorityFeePerGas: {240            description: 'Dummy',241            params: [],242            type: 'u8',243          },244        },245      },246    });247    await this.api.isReadyOrError;248    this.network = await UniqueHelper.detectNetwork(this.api);249    this.wsEndpoint = wsEndpoint;250  }251}252253export class DevRelayHelper extends RelayHelper {254  wait: WaitGroup;255256  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {257    options.helperBase = options.helperBase ?? DevRelayHelper;258259    super(logger, options);260    this.wait = new WaitGroup(this);261  }262}263264export class DevWestmintHelper extends WestmintHelper {265  wait: WaitGroup;266267  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {268    options.helperBase = options.helperBase ?? DevWestmintHelper;269270    super(logger, options);271    this.wait = new WaitGroup(this);272  }273}274275export class DevStatemineHelper extends DevWestmintHelper {}276277export class DevStatemintHelper extends DevWestmintHelper {}278279export class DevMoonbeamHelper extends MoonbeamHelper {280  account: MoonbeamAccountGroup;281  wait: WaitGroup;282  fastDemocracy: MoonbeamFastDemocracyGroup;283284  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {285    options.helperBase = options.helperBase ?? DevMoonbeamHelper;286    options.notePreimagePallet = options.notePreimagePallet ?? 'preimage';287288    super(logger, options);289    this.account = new MoonbeamAccountGroup(this);290    this.wait = new WaitGroup(this);291    this.fastDemocracy = new MoonbeamFastDemocracyGroup(this);292  }293}294295export class DevMoonriverHelper extends DevMoonbeamHelper {296  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {297    options.notePreimagePallet = options.notePreimagePallet ?? 'preimage';298    super(logger, options);299  }300}301302export class DevAstarHelper extends AstarHelper {303  wait: WaitGroup;304305  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {306    options.helperBase = options.helperBase ?? DevAstarHelper;307308    super(logger, options);309    this.wait = new WaitGroup(this);310  }311}312313export class DevShidenHelper extends AstarHelper {314  wait: WaitGroup;315316  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {317    options.helperBase = options.helperBase ?? DevShidenHelper;318319    super(logger, options);320    this.wait = new WaitGroup(this);321  }322}323324export class DevAcalaHelper extends AcalaHelper {325  wait: WaitGroup;326327  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {328    options.helperBase = options.helperBase ?? DevAcalaHelper;329330    super(logger, options);331    this.wait = new WaitGroup(this);332  }333}334335export class DevKaruraHelper extends DevAcalaHelper {}336337export class ArrangeGroup {338  helper: DevUniqueHelper;339340  scheduledIdSlider = 0;341342  constructor(helper: DevUniqueHelper) {343    this.helper = helper;344  }345346  /**347   * Generates accounts with the specified UNQ token balance348   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.349   * @param donor donor account for balances350   * @returns array of newly created accounts351   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor);352   */353  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {354    let nonce = await this.helper.chain.getNonce(donor.address);355    const wait = new WaitGroup(this.helper);356    const ss58Format = this.helper.chain.getChainProperties().ss58Format;357    const tokenNominal = this.helper.balance.getOneTokenNominal();358    const transactions = [];359    const accounts: IKeyringPair[] = [];360    for(const balance of balances) {361      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);362      accounts.push(recipient);363      if(balance !== 0n) {364        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);365        transactions.push(this.helper.signTransaction(donor, tx, {nonce, era: 0}, 'account generation'));366        nonce++;367      }368    }369370    await Promise.all(transactions).catch(_e => {});371372    //#region TODO remove this region, when nonce problem will be solved373    const checkBalances = async () => {374      let isSuccess = true;375      for(let i = 0; i < balances.length; i++) {376        const balance = await this.helper.balance.getSubstrate(accounts[i].address);377        if(balance !== balances[i] * tokenNominal) {378          isSuccess = false;379          break;380        }381      }382      return isSuccess;383    };384385    let accountsCreated = false;386    const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;387    // checkBalances retry up to 5-50 blocks388    for(let index = 0; index < maxBlocksChecked; index++) {389      accountsCreated = await checkBalances();390      if(accountsCreated) break;391      await wait.newBlocks(1);392    }393394    if(!accountsCreated) throw Error('Accounts generation failed');395    //#endregion396397    return accounts;398  };399400  // TODO combine this method and createAccounts into one401  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {402    const createAsManyAsCan = async () => {403      let transactions: any = [];404      const accounts: IKeyringPair[] = [];405      let nonce = await this.helper.chain.getNonce(donor.address);406      const tokenNominal = this.helper.balance.getOneTokenNominal();407      const ss58Format = this.helper.chain.getChainProperties().ss58Format;408      for(let i = 0; i < accountsToCreate; i++) {409        if(i === 500) { // if there are too many accounts to create410          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled411          transactions = []; //412          nonce = await this.helper.chain.getNonce(donor.address); // update nonce413        }414        const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);415        accounts.push(recipient);416        if(withBalance !== 0n) {417          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, withBalance * tokenNominal]);418          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));419          nonce++;420        }421      }422423      const fullfilledAccounts = [];424      await Promise.allSettled(transactions);425      for(const account of accounts) {426        const accountBalance = await this.helper.balance.getSubstrate(account.address);427        if(accountBalance === withBalance * tokenNominal) {428          fullfilledAccounts.push(account);429        }430      }431      return fullfilledAccounts;432    };433434435    const crowd: IKeyringPair[] = [];436    // do up to 5 retries437    for(let index = 0; index < 5 && accountsToCreate !== 0; index++) {438      const asManyAsCan = await createAsManyAsCan();439      crowd.push(...asManyAsCan);440      accountsToCreate -= asManyAsCan.length;441    }442443    if(accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);444445    return crowd;446  };447448  isDevNode = async () => {449    let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();450    if(blockNumber == 0) {451      await this.helper.wait.newBlocks(1);452      blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();453    }454    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);455    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber - 1])]);456    const findCreationDate = (block: any) => {457      const humanBlock = block.toHuman();458      let date;459      humanBlock.block.extrinsics.forEach((ext: any) => {460        if(ext.method.section === 'timestamp') {461          date = Number(ext.method.args.now.replaceAll(',', ''));462        }463      });464      return date;465    };466    const block1date = await findCreationDate(block1);467    const block2date = await findCreationDate(block2);468    if(block2date! - block1date! < 9000) return true;469  };470471  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {472    const address = 'Substrate' in payer ? payer.Substrate : this.helper.address.ethToSubstrate(payer.Ethereum);473    let balance = await this.helper.balance.getSubstrate(address);474475    await promise();476477    balance -= await this.helper.balance.getSubstrate(address);478479    return balance;480  }481482  async calculatePoVInfo(txs: any[]): Promise<IPovInfo> {483    const rawPovInfo = await this.helper.callRpc('api.rpc.povinfo.estimateExtrinsicPoV', [txs]);484485    const kvJson: {[key: string]: string} = {};486487    for(const kv of rawPovInfo.keyValues) {488      kvJson[kv.key.toHex()] = kv.value.toHex();489    }490491    const kvStr = JSON.stringify(kvJson);492493    const chainql = spawnSync(494      'chainql',495      [496        `--tla-code=data=${kvStr}`,497        '-e', `function(data) cql.dump(cql.chain("${this.helper.getEndpoint()}").latest._meta, data, {omit_empty:true})`,498      ],499    );500501    if(!chainql.stdout) {502      throw Error('unable to get an output from the `chainql`');503    }504505    return {506      proofSize: rawPovInfo.proofSize.toNumber(),507      compactProofSize: rawPovInfo.compactProofSize.toNumber(),508      compressedProofSize: rawPovInfo.compressedProofSize.toNumber(),509      results: rawPovInfo.results,510      kv: JSON.parse(chainql.stdout.toString()),511    };512  }513514  calculatePalletAddress(palletId: any) {515    const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));516    return encodeAddress(address, this.helper.chain.getChainProperties().ss58Format);517  }518519  makeScheduledIds(num: number): string[] {520    function makeId(slider: number) {521      const scheduledIdSize = 64;522      const hexId = slider.toString(16);523      const prefixSize = scheduledIdSize - hexId.length;524525      const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;526527      return scheduledId;528    }529530    const ids = [];531    for(let i = 0; i < num; i++) {532      ids.push(makeId(this.scheduledIdSlider));533      this.scheduledIdSlider += 1;534    }535536    return ids;537  }538539  makeScheduledId(): string {540    return (this.makeScheduledIds(1))[0];541  }542543  async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {544    const capture = new EventCapture(this.helper, eventSection, eventMethod);545    await capture.startCapture();546547    return capture;548  }549550  makeXcmProgramWithdrawDeposit(beneficiary: Uint8Array, id: any, amount: bigint) {551    return {552      V2: [553        {554          WithdrawAsset: [555            {556              id,557              fun: {558                Fungible: amount,559              },560            },561          ],562        },563        {564          BuyExecution: {565            fees: {566              id,567              fun: {568                Fungible: amount,569              },570            },571            weightLimit: 'Unlimited',572          },573        },574        {575          DepositAsset: {576            assets: {577              Wild: 'All',578            },579            maxAssets: 1,580            beneficiary: {581              parents: 0,582              interior: {583                X1: {584                  AccountId32: {585                    network: 'Any',586                    id: beneficiary,587                  },588                },589              },590            },591          },592        },593      ],594    };595  }596597  makeXcmProgramReserveAssetDeposited(beneficiary: Uint8Array, id: any, amount: bigint) {598    return {599      V2: [600        {601          ReserveAssetDeposited: [602            {603              id,604              fun: {605                Fungible: amount,606              },607            },608          ],609        },610        {611          BuyExecution: {612            fees: {613              id,614              fun: {615                Fungible: amount,616              },617            },618            weightLimit: 'Unlimited',619          },620        },621        {622          DepositAsset: {623            assets: {624              Wild: 'All',625            },626            maxAssets: 1,627            beneficiary: {628              parents: 0,629              interior: {630                X1: {631                  AccountId32: {632                    network: 'Any',633                    id: beneficiary,634                  },635                },636              },637            },638          },639        },640      ],641    };642  }643}644645class MoonbeamAccountGroup {646  helper: MoonbeamHelper;647648  keyring: Keyring;649  _alithAccount: IKeyringPair;650  _baltatharAccount: IKeyringPair;651  _dorothyAccount: IKeyringPair;652653  constructor(helper: MoonbeamHelper) {654    this.helper = helper;655656    this.keyring = new Keyring({type: 'ethereum'});657    const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';658    const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';659    const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';660661    this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');662    this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');663    this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');664  }665666  alithAccount() {667    return this._alithAccount;668  }669670  baltatharAccount() {671    return this._baltatharAccount;672  }673674  dorothyAccount() {675    return this._dorothyAccount;676  }677678  create() {679    return this.keyring.addFromUri(mnemonicGenerate());680  }681}682683class MoonbeamFastDemocracyGroup {684  helper: DevMoonbeamHelper;685686  constructor(helper: DevMoonbeamHelper) {687    this.helper = helper;688  }689690  async executeProposal(proposalDesciption: string, encodedProposal: string) {691    const proposalHash = blake2AsHex(encodedProposal);692693    const alithAccount = this.helper.account.alithAccount();694    const baltatharAccount = this.helper.account.baltatharAccount();695    const dorothyAccount = this.helper.account.dorothyAccount();696697    const councilVotingThreshold = 2;698    const technicalCommitteeThreshold = 2;699    const fastTrackVotingPeriod = 3;700    const fastTrackDelayPeriod = 0;701702    console.log(`[democracy] executing '${proposalDesciption}' proposal`);703704    // >>> Propose external motion through council >>>705    console.log('\t* Propose external motion through council.......');706    const externalMotion = this.helper.democracy.externalProposeMajority({Inline: encodedProposal});707    const encodedMotion = externalMotion?.method.toHex() || '';708    const motionHash = blake2AsHex(encodedMotion);709    console.log('\t* Motion hash is %s', motionHash);710711    await this.helper.collective.council.propose(712      baltatharAccount,713      councilVotingThreshold,714      externalMotion,715      externalMotion.encodedLength,716    );717718    const councilProposalIdx = await this.helper.collective.council.proposalCount() - 1;719    await this.helper.collective.council.vote(dorothyAccount, motionHash, councilProposalIdx, true);720    await this.helper.collective.council.vote(baltatharAccount, motionHash, councilProposalIdx, true);721722    await this.helper.collective.council.close(723      dorothyAccount,724      motionHash,725      councilProposalIdx,726      {727        refTime: 1_000_000_000,728        proofSize: 1_000_000,729      },730      externalMotion.encodedLength,731    );732    console.log('\t* Propose external motion through council.......DONE');733    // <<< Propose external motion through council <<<734735    // >>> Fast track proposal through technical committee >>>736    console.log('\t* Fast track proposal through technical committee.......');737    const fastTrack = this.helper.democracy.fastTrack(proposalHash, fastTrackVotingPeriod, fastTrackDelayPeriod);738    const encodedFastTrack = fastTrack?.method.toHex() || '';739    const fastTrackHash = blake2AsHex(encodedFastTrack);740    console.log('\t* FastTrack hash is %s', fastTrackHash);741742    await this.helper.collective.techCommittee.propose(alithAccount, technicalCommitteeThreshold, fastTrack, fastTrack.encodedLength);743744    const techProposalIdx = await this.helper.collective.techCommittee.proposalCount() - 1;745    await this.helper.collective.techCommittee.vote(baltatharAccount, fastTrackHash, techProposalIdx, true);746    await this.helper.collective.techCommittee.vote(alithAccount, fastTrackHash, techProposalIdx, true);747748    await this.helper.collective.techCommittee.close(749      baltatharAccount,750      fastTrackHash,751      techProposalIdx,752      {753        refTime: 1_000_000_000,754        proofSize: 1_000_000,755      },756      fastTrack.encodedLength,757    );758    console.log('\t* Fast track proposal through technical committee.......DONE');759    // <<< Fast track proposal through technical committee <<<760761    const democracyStarted = await this.helper.wait.expectEvent(3, Event.Democracy.Started);762    const referendumIndex = democracyStarted.referendumIndex();763764    // >>> Referendum voting >>>765    console.log(`\t* Referendum #${referendumIndex} voting.......`);766    await this.helper.democracy.referendumVote(dorothyAccount, referendumIndex, {767      balance: 10_000_000_000_000_000_000n,768      vote: {aye: true, conviction: 1},769    });770    console.log(`\t* Referendum #${referendumIndex} voting.......DONE`);771    // <<< Referendum voting <<<772773    // Wait the proposal to pass774    await this.helper.wait.expectEvent(3, Event.Democracy.Passed, event => event.referendumIndex() == referendumIndex);775776    await this.helper.wait.newBlocks(1);777778    console.log(`[democracy] executing '${proposalDesciption}' proposal.......DONE`);779  }780}781782class WaitGroup {783  helper: ChainHelperBase;784785  constructor(helper: ChainHelperBase) {786    this.helper = helper;787  }788789  sleep(milliseconds: number) {790    return new Promise((resolve) => setTimeout(resolve, milliseconds));791  }792793  private async waitWithTimeout(promise: Promise<any>, timeout: number) {794    let isBlock = false;795    promise.then(() => isBlock = true).catch(() => isBlock = true);796    let totalTime = 0;797    const step = 100;798    while(!isBlock) {799      await this.sleep(step);800      totalTime += step;801      if(totalTime >= timeout) throw Error('Blocks production failed');802    }803    return promise;804  }805806  /**807   * Launch some async operation, or throw an error after some time. Note that it will still continue executing after the timeout.808   * @param promise async operation to race against the timeout809   * @param timeoutMS time after which to time out810   * @param timeoutError error message to throw811   * @returns promise of the same type the operation had812   */813  withTimeout<T>(814    promise: Promise<T>,815    timeoutMS = 30000,816    timeoutError = 'The operation has timed out!',817  ): Promise<T> {818    const timeout = new Promise<never>((_, reject) => {819      setTimeout(() => {820        reject(new Error(timeoutError));821      }, timeoutMS);822    });823824    return Promise.race<T>([promise, timeout]).catch(e => {throw new Error(e);});825  }826827  /**828   * Wait for specified number of blocks829   * @param blocksCount number of blocks to wait830   * @returns831   */832  async newBlocks(blocksCount = 1, timeout?: number): Promise<void> {833    timeout = timeout ?? blocksCount * 60_000;834    // eslint-disable-next-line no-async-promise-executor835    const promise = new Promise<void>(async (resolve) => {836      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {837        if(blocksCount > 0) {838          blocksCount--;839        } else {840          unsubscribe();841          resolve();842        }843      });844    });845    await this.waitWithTimeout(promise, timeout);846    return promise;847  }848849  /**850   * Wait for the specified number of sessions to pass.851   * Only applicable if the Session pallet is turned on.852   * @param sessionCount number of sessions to wait853   * @param blockTimeout time in ms until panicking that the chain has stopped producing blocks854   * @returns855   */856  async newSessions(sessionCount = 1, blockTimeout = 60000): Promise<void> {857    console.log(`Waiting for ${sessionCount} new session${sessionCount > 1 ? 's' : ''}.`858      + ' This might take a while -- check SessionPeriod in pallet_session::Config for session time.');859860    const expectedSessionIndex = await (this.helper as DevUniqueHelper).session.getIndex() + sessionCount;861    let currentSessionIndex = -1;862863    while(currentSessionIndex < expectedSessionIndex) {864      // eslint-disable-next-line no-async-promise-executor865      currentSessionIndex = await this.withTimeout(new Promise(async (resolve) => {866        await this.newBlocks(1);867        const res = await (this.helper as DevUniqueHelper).session.getIndex();868        resolve(res);869      }), blockTimeout, 'The chain has stopped producing blocks!');870    }871  }872873  async forParachainBlockNumber(blockNumber: bigint | number, timeout?: number) {874    timeout = timeout ?? 30 * 60 * 1000;875    // eslint-disable-next-line no-async-promise-executor876    const promise = new Promise<void>(async (resolve) => {877      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads((data: any) => {878        if(data.number.toNumber() >= blockNumber) {879          unsubscribe();880          resolve();881        }882      });883    });884    await this.waitWithTimeout(promise, timeout);885    return promise;886  }887888  async forRelayBlockNumber(blockNumber: bigint | number, timeout?: number) {889    timeout = timeout ?? 30 * 60 * 1000;890    // eslint-disable-next-line no-async-promise-executor891    const promise = new Promise<void>(async (resolve) => {892      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData((data: any) => {893        if(data.value.relayParentNumber.toNumber() >= blockNumber) {894          // @ts-ignore895          unsubscribe();896          resolve();897        }898      });899    });900    await this.waitWithTimeout(promise, timeout);901    return promise;902  }903904  noScheduledTasks() {905    const api = this.helper.getApi();906907    // eslint-disable-next-line no-async-promise-executor908    const promise = new Promise<void>(async resolve => {909      const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {910        const areThereScheduledTasks = await api.query.scheduler.lookup.entries();911912        if(areThereScheduledTasks.length == 0) {913          unsubscribe();914          resolve();915        }916      });917    });918919    return promise;920  }921922  event<T extends IEventHelper>(923    maxBlocksToWait: number,924    eventHelperType: new () => T,925    filter: (_: T) => boolean = () => true,926  ) {927    // eslint-disable-next-line no-async-promise-executor928    const promise = new Promise<T | null>(async (resolve) => {929      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {930        const eventHelper = new eventHelperType();931        const blockNumber = header.number.toHuman();932        const blockHash = header.hash;933        const eventIdStr = `${eventHelper.section()}.${eventHelper.method()}`;934        const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;935936        this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);937938        const apiAt = await this.helper.getApi().at(blockHash);939        const eventRecords = (await apiAt.query.system.events()) as any;940941        const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {942          if(943            r.event.section == eventHelper.section()944            && r.event.method == eventHelper.method()945          ) {946            eventHelper.bindEventRecord(r);947            return filter(eventHelper);948          } else {949            return false;950          }951        });952953        if(neededEvent) {954          unsubscribe();955          resolve(eventHelper);956        } else if(maxBlocksToWait > 0) {957          maxBlocksToWait--;958        } else {959          this.helper.logger.log(`Eligible event \`${eventIdStr}\` is NOT found`);960          unsubscribe();961          resolve(null);962        }963      });964    });965    return promise;966  }967968  async expectEvent<T extends IEventHelper>(969    maxBlocksToWait: number,970    eventHelperType: new () => T,971    filter: (e: T) => boolean = () => true,972  ) {973    const e = await this.event(maxBlocksToWait, eventHelperType, filter);974    if(e == null) {975      const eventHelper = new eventHelperType();976      throw Error(`The event '${eventHelper.section()}.${eventHelper.method()}' is expected`);977    } else {978      return e;979    }980  }981}982983class SessionGroup {984  helper: ChainHelperBase;985986  constructor(helper: ChainHelperBase) {987    this.helper = helper;988  }989990  //todo:collator documentation991  async getIndex(): Promise<number> {992    return (await this.helper.callRpc('api.query.session.currentIndex', [])).toNumber();993  }994995  newSessions(sessionCount = 1, blockTimeout = 24000): Promise<void> {996    return (this.helper as DevUniqueHelper).wait.newSessions(sessionCount, blockTimeout);997  }998999  setOwnKeys(signer: TSigner, key: string) {1000    return this.helper.executeExtrinsic(1001      signer,1002      'api.tx.session.setKeys',1003      [key, '0x0'],1004      true,1005    );1006  }10071008  setOwnKeysFromAddress(signer: TSigner) {1009    return this.setOwnKeys(signer, '0x' + Buffer.from(signer.addressRaw).toString('hex'));1010  }1011}10121013class TestUtilGroup {1014  helper: DevUniqueHelper;10151016  constructor(helper: DevUniqueHelper) {1017    this.helper = helper;1018  }10191020  async enable() {1021    if(this.helper.fetchMissingPalletNames([Pallets.TestUtils]).length != 0) {1022      return;1023    }10241025    const signer = this.helper.util.fromSeed('//Alice');1026    await this.helper.getSudo<DevUniqueHelper>().executeExtrinsic(signer, 'api.tx.testUtils.enable', [], true);1027  }10281029  async setTestValue(signer: TSigner, testVal: number) {1030    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValue', [testVal], true);1031  }10321033  async incTestValue(signer: TSigner) {1034    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.incTestValue', [], true);1035  }10361037  async setTestValueAndRollback(signer: TSigner, testVal: number) {1038    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);1039  }10401041  async testValue(blockIdx?: number) {1042    const api = blockIdx1043      ? await this.helper.getApi().at(await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockIdx]))1044      : this.helper.getApi();10451046    return (await api.query.testUtils.testValue()).toJSON();1047  }10481049  async justTakeFee(signer: TSigner) {1050    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.justTakeFee', [], true);1051  }10521053  async selfCancelingInc(signer: TSigner, scheduledId: string, maxTestVal: number) {1054    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.selfCancelingInc', [scheduledId, maxTestVal], true);1055  }1056}10571058class EventCapture {1059  helper: DevUniqueHelper;1060  eventSection: string;1061  eventMethod: string;1062  events: EventRecord[] = [];1063  unsubscribe: VoidFn | null = null;10641065  constructor(1066    helper: DevUniqueHelper,1067    eventSection: string,1068    eventMethod: string,1069  ) {1070    this.helper = helper;1071    this.eventSection = eventSection;1072    this.eventMethod = eventMethod;1073  }10741075  async startCapture() {1076    this.stopCapture();1077    this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {1078      const newEvents = eventRecords.filter(r => r.event.section == this.eventSection && r.event.method == this.eventMethod);10791080      this.events.push(...newEvents);1081    })) as any;1082  }10831084  stopCapture() {1085    if(this.unsubscribe !== null) {1086      this.unsubscribe();1087    }1088  }10891090  extractCapturedEvents() {1091    return this.events;1092  }1093}10941095class AdminGroup {1096  helper: UniqueHelper;10971098  constructor(helper: UniqueHelper) {1099    this.helper = helper;1100  }11011102  async payoutStakers(signer: IKeyringPair, stakersToPayout: number):  Promise<{staker: string, stake: bigint, payout: bigint}[]> {1103    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);1104    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => ({1105      staker: e.event.data[0].toString(),1106      stake: e.event.data[1].toBigInt(),1107      payout: e.event.data[2].toBigInt(),1108    }));1109  }1110}