git.delta.rocks / unique-network / refs/commits / 7c2f408f0bda

difftreelog

tests(parallelization): fix createAccounts failing to catch up on dev node + evm events

Fahrrader2022-10-13parent: #85e2544.patch.diff
in: master

6 files changed

modifiedtests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -378,7 +378,7 @@
     // Balance should be taken from flipper instead of caller
     // FIXME the comment is wrong! What check should be here?
     const balanceAfter = await helper.balance.getEthereum(flipper.options.address);
-    expect(balanceAfter).to.be.equals(originalFlipperBalance);
+    expect(balanceAfter).to.be.equal(originalFlipperBalance);
   });
 
   itEth('Sponsoring is set, an address that has UNQ can send a transaction and it works. User balance should not change', async ({helper}) => {
@@ -406,7 +406,7 @@
     const sponsorBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));
     const callerBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));
     expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
-    expect(callerBalanceAfter).to.be.equals(callerBalanceBefore);
+    expect(callerBalanceAfter).to.be.equal(callerBalanceBefore);
   });
 
   itEth('Sponsoring is limited, with setContractRateLimit. The limitation is working if transactions are sent more often, the sender pays the commission.', async ({helper}) => {
@@ -431,23 +431,24 @@
 
     await flipper.methods.flip().send({from: caller});
     expect(await flipper.methods.getValue().call()).to.be.true;
-    expect(await helper.balance.getEthereum(caller)).to.be.equals(originalCallerBalance);
+    expect(await helper.balance.getEthereum(caller)).to.be.equal(originalCallerBalance);
 
     const newFlipperBalance = await helper.balance.getEthereum(sponsor);
-    expect(newFlipperBalance).to.be.not.equals(originalFlipperBalance);
+    expect(newFlipperBalance).to.be.not.equal(originalFlipperBalance);
 
     await flipper.methods.flip().send({from: caller});
+    // todo:playgrounds fails rarely (expected 99893341659775672580n to equal 99912598679356033129n) (again, 99893341659775672580n)
     expect(await helper.balance.getEthereum(sponsor)).to.be.equal(newFlipperBalance);
-    expect(await helper.balance.getEthereum(caller)).to.be.not.equals(originalCallerBalance);
+    expect(await helper.balance.getEthereum(caller)).to.be.not.equal(originalCallerBalance);
   });
 
   // TODO: Find a way to calculate default rate limit
-  itEth('Default rate limit equals 7200', async ({helper}) => {
+  itEth('Default rate limit equal 7200', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const helpers = helper.ethNativeContract.contractHelpers(owner);
     const flipper = await helper.eth.deployFlipper(owner);
 
-    expect(await helpers.methods.sponsoringRateLimit(flipper.options.address).call()).to.be.equals('7200');
+    expect(await helpers.methods.sponsoringRateLimit(flipper.options.address).call()).to.be.equal('7200');
   });
 });
 
@@ -501,7 +502,7 @@
     const helpers = helper.ethNativeContract.contractHelpers(owner);
     const flipper = await helper.eth.deployFlipper(owner);
 
-    expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equals('115792089237316195423570985008687907853269984665640564039457584007913129639935');
+    expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equal('115792089237316195423570985008687907853269984665640564039457584007913129639935');
   });
 
   itEth('Set fee limit', async ({helper}) => {
@@ -510,7 +511,7 @@
     const flipper = await helper.eth.deployFlipper(owner);
 
     await helpers.methods.setSponsoringFeeLimit(flipper.options.address, 100).send();
-    expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equals('100');
+    expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equal('100');
   });
 
   itEth('Negative test - set fee limit by non-owner', async ({helper}) => {
modifiedtests/src/eth/fungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -294,9 +294,11 @@
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
     });
+    
     await collection.approveTokens(alice, {Ethereum: receiver}, 100n);
+    if (events.length == 0) await helper.wait.newBlocks(1);
+    const event = events[0];
 
-    const event = events[0];
     expect(event.event).to.be.equal('Approval');
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));
@@ -318,9 +320,11 @@
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
     });
+
     await collection.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver}, 51n);
+    if (events.length == 0) await helper.wait.newBlocks(1);
+    let event = events[0];
 
-    let event = events[0];
     expect(event.event).to.be.equal('Transfer');
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
@@ -347,9 +351,11 @@
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
     });
+    
     await collection.transfer(alice, {Ethereum:receiver}, 51n);
-
+    if (events.length == 0) await helper.wait.newBlocks(1);
     const event = events[0];
+
     expect(event.event).to.be.equal('Transfer');
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -385,9 +385,11 @@
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
     });
+
     const {tokenId} = await collection.mintToken(alice);
+    if (events.length == 0) await helper.wait.newBlocks(1);
+    const event = events[0];
 
-    const event = events[0];
     expect(event.event).to.be.equal('Transfer');
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
@@ -408,8 +410,9 @@
     });
 
     await token.burn(alice);
+    if (events.length == 0) await helper.wait.newBlocks(1);
+    const event = events[0];
 
-    const event = events[0];
     expect(event.event).to.be.equal('Transfer');
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
@@ -432,8 +435,9 @@
     });
 
     await token.approve(alice, {Ethereum: receiver});
+    if (events.length == 0) await helper.wait.newBlocks(1);
+    const event = events[0];
 
-    const event = events[0];
     expect(event.event).to.be.equal('Approval');
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));
@@ -458,8 +462,9 @@
     });
 
     await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver});
-    
+    if (events.length == 0) await helper.wait.newBlocks(1);
     const event = events[0];
+
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
     expect(event.returnValues.to).to.be.equal(receiver);
@@ -481,8 +486,9 @@
     });
 
     await token.transfer(alice, {Ethereum: receiver});
-    
+    if (events.length == 0) await helper.wait.newBlocks(1);
     const event = events[0];
+
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
     expect(event.returnValues.to).to.be.equal(receiver);
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -286,9 +286,11 @@
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
     });
+
     await tokenContract.methods.transfer(receiver, 1).send();
+    if (events.length == 0) await helper.wait.newBlocks(1);
+    const event = events[0];
 
-    const event = events[0];
     expect(event.address).to.equal(collectionAddress);
     expect(event.returnValues.from).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
     expect(event.returnValues.to).to.equal(receiver);
@@ -312,9 +314,11 @@
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
     });
+
     await tokenContract.methods.transfer(receiver, 1).send();
+    if (events.length == 0) await helper.wait.newBlocks(1);
+    const event = events[0];
 
-    const event = events[0];
     expect(event.address).to.equal(collectionAddress);
     expect(event.returnValues.from).to.equal(caller);
     expect(event.returnValues.to).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -311,6 +311,7 @@
     });
     await tokenContract.methods.burnFrom(caller, 1).send();
 
+    if (events.length == 0) await helper.wait.newBlocks(1);
     const event = events[0];
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.from).to.be.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
@@ -399,9 +400,11 @@
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
     });
-    expect(await token.approve(alice, {Ethereum: receiver}, 100n)).to.be.true;
 
+    expect(await token.approve(alice, {Ethereum: receiver}, 100n)).to.be.true;
+    if (events.length == 0) await helper.wait.newBlocks(1);
     const event = events[0];
+
     expect(event.event).to.be.equal('Approval');
     expect(event.address).to.be.equal(tokenAddress);
     expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));
@@ -425,6 +428,7 @@
     });
 
     expect(await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver},  51n)).to.be.true;
+    if (events.length == 0) await helper.wait.newBlocks(1);
 
     let event = events[0];
     expect(event.event).to.be.equal('Transfer');
@@ -455,8 +459,9 @@
     });
 
     expect(await token.transfer(alice, {Ethereum: receiver},  51n)).to.be.true;
+    if (events.length == 0) await helper.wait.newBlocks(1);
+    const event = events[0];
 
-    const event = events[0];
     expect(event.event).to.be.equal('Transfer');
     expect(event.address).to.be.equal(tokenAddress);
     expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
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} from './unique';7import {ApiPromise, WsProvider} from '@polkadot/api';8import * as defs from '../../interfaces/definitions';9import {IKeyringPair} from '@polkadot/types/types';10import {ICrossAccountId} from './types';1112export class SilentLogger {13  log(_msg: any, _level: any): void { }14  level = {15    ERROR: 'ERROR' as const,16    WARNING: 'WARNING' as const,17    INFO: 'INFO' as const,18  };19}2021export 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:') || 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;63  wait: WaitGroup;64  admin: AdminGroup;6566  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {67    options.helperBase = options.helperBase ?? DevUniqueHelper;6869    super(logger, options);70    this.arrange = new ArrangeGroup(this);71    this.wait = new WaitGroup(this);72    this.admin = new AdminGroup(this);73  }7475  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {76    const wsProvider = new WsProvider(wsEndpoint);77    this.api = new ApiPromise({78      provider: wsProvider,79      signedExtensions: {80        ContractHelpers: {81          extrinsic: {},82          payload: {},83        },84        FakeTransactionFinalizer: {85          extrinsic: {},86          payload: {},87        },88      },89      rpc: {90        unique: defs.unique.rpc,91        appPromotion: defs.appPromotion.rpc,92        rmrk: defs.rmrk.rpc,93        eth: {94          feeHistory: {95            description: 'Dummy',96            params: [],97            type: 'u8',98          },99          maxPriorityFeePerGas: {100            description: 'Dummy',101            params: [],102            type: 'u8',103          },104        },105      },106    });107    await this.api.isReadyOrError;108    this.network = await UniqueHelper.detectNetwork(this.api);109  }110}111112class ArrangeGroup {113  helper: DevUniqueHelper;114115  constructor(helper: DevUniqueHelper) {116    this.helper = helper;117  }118119  /**120   * Generates accounts with the specified UNQ token balance 121   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.122   * @param donor donor account for balances123   * @returns array of newly created accounts124   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 125   */126  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {127    let nonce = await this.helper.chain.getNonce(donor.address);128    const wait = new WaitGroup(this.helper);129    const ss58Format = this.helper.chain.getChainProperties().ss58Format;130    const tokenNominal = this.helper.balance.getOneTokenNominal();131    const transactions = [];132    const accounts: IKeyringPair[] = [];133    for (const balance of balances) {134      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);135      accounts.push(recipient);136      if (balance !== 0n) {137        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);138        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));139        nonce++;140      }141    }142143    await Promise.all(transactions).catch(_e => {});144    145    //#region TODO remove this region, when nonce problem will be solved146    const checkBalances = async () => {147      let isSuccess = true;148      for (let i = 0; i < balances.length; i++) {149        const balance = await this.helper.balance.getSubstrate(accounts[i].address);150        if (balance !== balances[i] * tokenNominal) {151          isSuccess = false;152          break;153        }154      }155      return isSuccess;156    };157158    let accountsCreated = false;159    // checkBalances retry up to 5 blocks160    for (let index = 0; index < 5; index++) {161      accountsCreated = await checkBalances();162      if(accountsCreated) break;163      await wait.newBlocks(1);164    }165166    if (!accountsCreated) throw Error('Accounts generation failed');167    //#endregion168169    return accounts;170  };171172  // TODO combine this method and createAccounts into one173  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {  174    const createAsManyAsCan = async () => {175      let transactions: any = [];176      const accounts: IKeyringPair[] = [];177      let nonce = await this.helper.chain.getNonce(donor.address);178      const tokenNominal = this.helper.balance.getOneTokenNominal();179      for (let i = 0; i < accountsToCreate; i++) {180        if (i === 500) { // if there are too many accounts to create181          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 182          transactions = []; //183          nonce = await this.helper.chain.getNonce(donor.address); // update nonce 184        }185        const recepient = this.helper.util.fromSeed(mnemonicGenerate());186        accounts.push(recepient);187        if (withBalance !== 0n) {188          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);189          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));190          nonce++;191        }192      }193      194      const fullfilledAccounts = [];195      await Promise.allSettled(transactions);196      for (const account of accounts) {197        const accountBalance = await this.helper.balance.getSubstrate(account.address);198        if (accountBalance === withBalance * tokenNominal) {199          fullfilledAccounts.push(account);200        }201      }202      return fullfilledAccounts;203    };204205    206    const crowd: IKeyringPair[] = [];207    // do up to 5 retries208    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {209      const asManyAsCan = await createAsManyAsCan();210      crowd.push(...asManyAsCan);211      accountsToCreate -= asManyAsCan.length;212    }213214    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);215216    return crowd;217  };218219  isDevNode = async () => {220    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);221    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);222    const findCreationDate = async (block: any) => {223      const humanBlock = block.toHuman();224      let date;225      humanBlock.block.extrinsics.forEach((ext: any) => {226        if(ext.method.section === 'timestamp') {227          date = Number(ext.method.args.now.replaceAll(',', ''));228        }229      });230      return date;231    };232    const block1date = await findCreationDate(block1);233    const block2date = await findCreationDate(block2);234    if(block2date! - block1date! < 9000) return true;235  };236  237  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {238    const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);239    let balance = await this.helper.balance.getSubstrate(address); 240    241    await promise();242    243    balance -= await this.helper.balance.getSubstrate(address);244    245    return balance;246  }247248  calculatePalletAddress(palletId: any) {249    const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));250    return encodeAddress(address);251  }252}253254class WaitGroup {255  helper: DevUniqueHelper;256257  constructor(helper: DevUniqueHelper) {258    this.helper = helper;259  }260261  /**262   * Wait for specified number of blocks263   * @param blocksCount number of blocks to wait264   * @returns 265   */266  async newBlocks(blocksCount = 1): Promise<void> {267    // eslint-disable-next-line no-async-promise-executor268    const promise = new Promise<void>(async (resolve) => {269      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {270        if (blocksCount > 0) {271          blocksCount--;272        } else {273          unsubscribe();274          resolve();275        }276      });277    });278    return promise;279  }280281  async forParachainBlockNumber(blockNumber: bigint) {282    // eslint-disable-next-line no-async-promise-executor283    return new Promise<void>(async (resolve) => {284      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {285        if (data.number.toNumber() >= blockNumber) {286          unsubscribe();287          resolve();288        }289      });290    });291  }292  293  async forRelayBlockNumber(blockNumber: bigint) {294    // eslint-disable-next-line no-async-promise-executor295    return new Promise<void>(async (resolve) => {296      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {297        if (data.value.relayParentNumber.toNumber() >= blockNumber) {298          // @ts-ignore299          unsubscribe();300          resolve();301        }302      });303    });304  }305}306307class AdminGroup {308  helper: UniqueHelper;309310  constructor(helper: UniqueHelper) {311    this.helper = helper;312  }313314  async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {315    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);316    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {317      return {318        staker: e.event.data[0].toString(),319        stake: e.event.data[1].toBigInt(),320        payout: e.event.data[2].toBigInt(),321      };322    });323  }324}
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} from './unique';7import {ApiPromise, WsProvider} from '@polkadot/api';8import * as defs from '../../interfaces/definitions';9import {IKeyringPair} from '@polkadot/types/types';10import {ICrossAccountId} from './types';1112export class SilentLogger {13  log(_msg: any, _level: any): void { }14  level = {15    ERROR: 'ERROR' as const,16    WARNING: 'WARNING' as const,17    INFO: 'INFO' as const,18  };19}2021export 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:') || 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;63  wait: WaitGroup;64  admin: AdminGroup;6566  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {67    options.helperBase = options.helperBase ?? DevUniqueHelper;6869    super(logger, options);70    this.arrange = new ArrangeGroup(this);71    this.wait = new WaitGroup(this);72    this.admin = new AdminGroup(this);73  }7475  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {76    const wsProvider = new WsProvider(wsEndpoint);77    this.api = new ApiPromise({78      provider: wsProvider,79      signedExtensions: {80        ContractHelpers: {81          extrinsic: {},82          payload: {},83        },84        FakeTransactionFinalizer: {85          extrinsic: {},86          payload: {},87        },88      },89      rpc: {90        unique: defs.unique.rpc,91        appPromotion: defs.appPromotion.rpc,92        rmrk: defs.rmrk.rpc,93        eth: {94          feeHistory: {95            description: 'Dummy',96            params: [],97            type: 'u8',98          },99          maxPriorityFeePerGas: {100            description: 'Dummy',101            params: [],102            type: 'u8',103          },104        },105      },106    });107    await this.api.isReadyOrError;108    this.network = await UniqueHelper.detectNetwork(this.api);109  }110}111112class ArrangeGroup {113  helper: DevUniqueHelper;114115  constructor(helper: DevUniqueHelper) {116    this.helper = helper;117  }118119  /**120   * Generates accounts with the specified UNQ token balance 121   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.122   * @param donor donor account for balances123   * @returns array of newly created accounts124   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 125   */126  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {127    let nonce = await this.helper.chain.getNonce(donor.address);128    const wait = new WaitGroup(this.helper);129    const ss58Format = this.helper.chain.getChainProperties().ss58Format;130    const tokenNominal = this.helper.balance.getOneTokenNominal();131    const transactions = [];132    const accounts: IKeyringPair[] = [];133    for (const balance of balances) {134      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);135      accounts.push(recipient);136      if (balance !== 0n) {137        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);138        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));139        nonce++;140      }141    }142143    await Promise.all(transactions).catch(_e => {});144    145    //#region TODO remove this region, when nonce problem will be solved146    const checkBalances = async () => {147      let isSuccess = true;148      for (let i = 0; i < balances.length; i++) {149        const balance = await this.helper.balance.getSubstrate(accounts[i].address);150        if (balance !== balances[i] * tokenNominal) {151          isSuccess = false;152          break;153        }154      }155      return isSuccess;156    };157158    let accountsCreated = false;159    const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;160    // checkBalances retry up to 5-50 blocks161    for (let index = 0; index < maxBlocksChecked; index++) {162      accountsCreated = await checkBalances();163      if(accountsCreated) break;164      await wait.newBlocks(1);165    }166167    if (!accountsCreated) throw Error('Accounts generation failed');168    //#endregion169170    return accounts;171  };172173  // TODO combine this method and createAccounts into one174  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {  175    const createAsManyAsCan = async () => {176      let transactions: any = [];177      const accounts: IKeyringPair[] = [];178      let nonce = await this.helper.chain.getNonce(donor.address);179      const tokenNominal = this.helper.balance.getOneTokenNominal();180      for (let i = 0; i < accountsToCreate; i++) {181        if (i === 500) { // if there are too many accounts to create182          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 183          transactions = []; //184          nonce = await this.helper.chain.getNonce(donor.address); // update nonce 185        }186        const recepient = this.helper.util.fromSeed(mnemonicGenerate());187        accounts.push(recepient);188        if (withBalance !== 0n) {189          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);190          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));191          nonce++;192        }193      }194      195      const fullfilledAccounts = [];196      await Promise.allSettled(transactions);197      for (const account of accounts) {198        const accountBalance = await this.helper.balance.getSubstrate(account.address);199        if (accountBalance === withBalance * tokenNominal) {200          fullfilledAccounts.push(account);201        }202      }203      return fullfilledAccounts;204    };205206    207    const crowd: IKeyringPair[] = [];208    // do up to 5 retries209    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {210      const asManyAsCan = await createAsManyAsCan();211      crowd.push(...asManyAsCan);212      accountsToCreate -= asManyAsCan.length;213    }214215    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);216217    return crowd;218  };219220  isDevNode = async () => {221    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);222    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);223    const findCreationDate = async (block: any) => {224      const humanBlock = block.toHuman();225      let date;226      humanBlock.block.extrinsics.forEach((ext: any) => {227        if(ext.method.section === 'timestamp') {228          date = Number(ext.method.args.now.replaceAll(',', ''));229        }230      });231      return date;232    };233    const block1date = await findCreationDate(block1);234    const block2date = await findCreationDate(block2);235    if(block2date! - block1date! < 9000) return true;236  };237  238  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {239    const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);240    let balance = await this.helper.balance.getSubstrate(address); 241    242    await promise();243    244    balance -= await this.helper.balance.getSubstrate(address);245    246    return balance;247  }248249  calculatePalletAddress(palletId: any) {250    const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));251    return encodeAddress(address);252  }253}254255class WaitGroup {256  helper: DevUniqueHelper;257258  constructor(helper: DevUniqueHelper) {259    this.helper = helper;260  }261262  /**263   * Wait for specified number of blocks264   * @param blocksCount number of blocks to wait265   * @returns 266   */267  async newBlocks(blocksCount = 1): Promise<void> {268    // eslint-disable-next-line no-async-promise-executor269    const promise = new Promise<void>(async (resolve) => {270      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {271        if (blocksCount > 0) {272          blocksCount--;273        } else {274          unsubscribe();275          resolve();276        }277      });278    });279    return promise;280  }281282  async forParachainBlockNumber(blockNumber: bigint) {283    // eslint-disable-next-line no-async-promise-executor284    return new Promise<void>(async (resolve) => {285      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {286        if (data.number.toNumber() >= blockNumber) {287          unsubscribe();288          resolve();289        }290      });291    });292  }293  294  async forRelayBlockNumber(blockNumber: bigint) {295    // eslint-disable-next-line no-async-promise-executor296    return new Promise<void>(async (resolve) => {297      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {298        if (data.value.relayParentNumber.toNumber() >= blockNumber) {299          // @ts-ignore300          unsubscribe();301          resolve();302        }303      });304    });305  }306}307308class AdminGroup {309  helper: UniqueHelper;310311  constructor(helper: UniqueHelper) {312    this.helper = helper;313  }314315  async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {316    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);317    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {318      return {319        staker: e.event.data[0].toString(),320        stake: e.event.data[1].toBigInt(),321        payout: e.event.data[2].toBigInt(),322      };323    });324  }325}