git.delta.rocks / unique-network / refs/commits / 09b9e64d0480

difftreelog

fix remove unused imports

Daniel Shiposha2022-10-06parent: #17a52a5.patch.diff
in: master

2 files 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 {mnemonicGenerate} from '@polkadot/util-crypto';5import {UniqueHelper} from './unique';6import {ApiPromise, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';8import {IKeyringPair} from '@polkadot/types/types';9import {ICrossAccountId} from './types';10import type {EventRecord} from '@polkadot/types/interfaces';11import {VoidFn} from '@polkadot/api/types';12import {FrameSystemEventRecord} from '@polkadot/types/lookup';131415export 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}596061export 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}114115class ArrangeGroup {116  helper: DevUniqueHelper;117118  constructor(helper: DevUniqueHelper) {119    this.helper = helper;120  }121122  /**123   * Generates accounts with the specified UNQ token balance 124   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.125   * @param donor donor account for balances126   * @returns array of newly created accounts127   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 128   */129  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {130    let nonce = await this.helper.chain.getNonce(donor.address);131    const wait = new WaitGroup(this.helper);132    const ss58Format = this.helper.chain.getChainProperties().ss58Format;133    const tokenNominal = this.helper.balance.getOneTokenNominal();134    const transactions = [];135    const accounts: IKeyringPair[] = [];136    for (const balance of balances) {137      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);138      accounts.push(recipient);139      if (balance !== 0n) {140        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);141        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));142        nonce++;143      }144    }145146    await Promise.all(transactions).catch(_e => {});147    148    //#region TODO remove this region, when nonce problem will be solved149    const checkBalances = async () => {150      let isSuccess = true;151      for (let i = 0; i < balances.length; i++) {152        const balance = await this.helper.balance.getSubstrate(accounts[i].address);153        if (balance !== balances[i] * tokenNominal) {154          isSuccess = false;155          break;156        }157      }158      return isSuccess;159    };160161    let accountsCreated = false;162    // checkBalances retry up to 5 blocks163    for (let index = 0; index < 5; index++) {164      accountsCreated = await checkBalances();165      if(accountsCreated) break;166      await wait.newBlocks(1);167    }168169    if (!accountsCreated) throw Error('Accounts generation failed');170    //#endregion171172    return accounts;173  };174175  // TODO combine this method and createAccounts into one176  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {  177    const createAsManyAsCan = async () => {178      let transactions: any = [];179      const accounts: IKeyringPair[] = [];180      let nonce = await this.helper.chain.getNonce(donor.address);181      const tokenNominal = this.helper.balance.getOneTokenNominal();182      for (let i = 0; i < accountsToCreate; i++) {183        if (i === 500) { // if there are too many accounts to create184          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 185          transactions = []; //186          nonce = await this.helper.chain.getNonce(donor.address); // update nonce 187        }188        const recepient = this.helper.util.fromSeed(mnemonicGenerate());189        accounts.push(recepient);190        if (withBalance !== 0n) {191          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);192          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));193          nonce++;194        }195      }196      197      const fullfilledAccounts = [];198      await Promise.allSettled(transactions);199      for (const account of accounts) {200        const accountBalance = await this.helper.balance.getSubstrate(account.address);201        if (accountBalance === withBalance * tokenNominal) {202          fullfilledAccounts.push(account);203        }204      }205      return fullfilledAccounts;206    };207208    209    const crowd: IKeyringPair[] = [];210    // do up to 5 retries211    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {212      const asManyAsCan = await createAsManyAsCan();213      crowd.push(...asManyAsCan);214      accountsToCreate -= asManyAsCan.length;215    }216217    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);218219    return crowd;220  };221222  isDevNode = async () => {223    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);224    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);225    const findCreationDate = async (block: any) => {226      const humanBlock = block.toHuman();227      let date;228      humanBlock.block.extrinsics.forEach((ext: any) => {229        if(ext.method.section === 'timestamp') {230          date = Number(ext.method.args.now.replaceAll(',', ''));231        }232      });233      return date;234    };235    const block1date = await findCreationDate(block1);236    const block2date = await findCreationDate(block2);237    if(block2date! - block1date! < 9000) return true;238  };239  240  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {241    const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);242    let balance = await this.helper.balance.getSubstrate(address); 243    244    await promise();245    246    balance -= await this.helper.balance.getSubstrate(address);247    248    return balance;249  }250}251252class WaitGroup {253  helper: DevUniqueHelper;254255  constructor(helper: DevUniqueHelper) {256    this.helper = helper;257  }258259  /**260   * Wait for specified number of blocks261   * @param blocksCount number of blocks to wait262   * @returns 263   */264  async newBlocks(blocksCount = 1): Promise<void> {265    // eslint-disable-next-line no-async-promise-executor266    const promise = new Promise<void>(async (resolve) => {267      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {268        if (blocksCount > 0) {269          blocksCount--;270        } else {271          unsubscribe();272          resolve();273        }274      });275    });276    return promise;277  }278279  async forParachainBlockNumber(blockNumber: bigint) {280    // eslint-disable-next-line no-async-promise-executor281    return new Promise<void>(async (resolve) => {282      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {283        if (data.number.toNumber() >= blockNumber) {284          unsubscribe();285          resolve();286        }287      });288    });289  }290  291  async forRelayBlockNumber(blockNumber: bigint) {292    // eslint-disable-next-line no-async-promise-executor293    return new Promise<void>(async (resolve) => {294      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {295        if (data.value.relayParentNumber.toNumber() >= blockNumber) {296          // @ts-ignore297          unsubscribe();298          resolve();299        }300      });301    });302  }303}304305class AdminGroup {306  helper: UniqueHelper;307308  constructor(helper: UniqueHelper) {309    this.helper = helper;310  }311312  async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {313    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);314    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {315      return {316        staker: e.event.data[0].toString(),317        stake: e.event.data[1].toBigInt(),318        payout: e.event.data[2].toBigInt(),319      };320    });321  }322}
after · tests/src/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {mnemonicGenerate} from '@polkadot/util-crypto';5import {UniqueHelper} from './unique';6import {ApiPromise, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';8import {IKeyringPair} from '@polkadot/types/types';9import {ICrossAccountId} from './types';1011export class SilentLogger {12  log(_msg: any, _level: any): void { }13  level = {14    ERROR: 'ERROR' as const,15    WARNING: 'WARNING' as const,16    INFO: 'INFO' as const,17  };18}1920export class SilentConsole {21  // TODO: Remove, this is temporary: Filter unneeded API output22  // (Jaco promised it will be removed in the next version)23  consoleErr: any;24  consoleLog: any;25  consoleWarn: any;2627  constructor() {28    this.consoleErr = console.error;29    this.consoleLog = console.log;30    this.consoleWarn = console.warn;31  }3233  enable() {  34    const outFn = (printer: any) => (...args: any[]) => {35      for (const arg of args) {36        if (typeof arg !== 'string')37          continue;38        if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')39          return;40      }41      printer(...args);42    };43  44    console.error = outFn(this.consoleErr.bind(console));45    console.log = outFn(this.consoleLog.bind(console));46    console.warn = outFn(this.consoleWarn.bind(console));47  }4849  disable() {50    console.error = this.consoleErr;51    console.log = this.consoleLog;52    console.warn = this.consoleWarn;53  }54}555657export class DevUniqueHelper extends UniqueHelper {58  /**59   * Arrange methods for tests60   */61  arrange: ArrangeGroup;62  wait: WaitGroup;63  admin: AdminGroup;6465  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {66    options.helperBase = options.helperBase ?? DevUniqueHelper;6768    super(logger, options);69    this.arrange = new ArrangeGroup(this);70    this.wait = new WaitGroup(this);71    this.admin = new AdminGroup(this);72  }7374  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {75    const wsProvider = new WsProvider(wsEndpoint);76    this.api = new ApiPromise({77      provider: wsProvider,78      signedExtensions: {79        ContractHelpers: {80          extrinsic: {},81          payload: {},82        },83        FakeTransactionFinalizer: {84          extrinsic: {},85          payload: {},86        },87      },88      rpc: {89        unique: defs.unique.rpc,90        appPromotion: defs.appPromotion.rpc,91        rmrk: defs.rmrk.rpc,92        eth: {93          feeHistory: {94            description: 'Dummy',95            params: [],96            type: 'u8',97          },98          maxPriorityFeePerGas: {99            description: 'Dummy',100            params: [],101            type: 'u8',102          },103        },104      },105    });106    await this.api.isReadyOrError;107    this.network = await UniqueHelper.detectNetwork(this.api);108  }109}110111class ArrangeGroup {112  helper: DevUniqueHelper;113114  constructor(helper: DevUniqueHelper) {115    this.helper = helper;116  }117118  /**119   * Generates accounts with the specified UNQ token balance 120   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.121   * @param donor donor account for balances122   * @returns array of newly created accounts123   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 124   */125  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {126    let nonce = await this.helper.chain.getNonce(donor.address);127    const wait = new WaitGroup(this.helper);128    const ss58Format = this.helper.chain.getChainProperties().ss58Format;129    const tokenNominal = this.helper.balance.getOneTokenNominal();130    const transactions = [];131    const accounts: IKeyringPair[] = [];132    for (const balance of balances) {133      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);134      accounts.push(recipient);135      if (balance !== 0n) {136        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);137        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));138        nonce++;139      }140    }141142    await Promise.all(transactions).catch(_e => {});143    144    //#region TODO remove this region, when nonce problem will be solved145    const checkBalances = async () => {146      let isSuccess = true;147      for (let i = 0; i < balances.length; i++) {148        const balance = await this.helper.balance.getSubstrate(accounts[i].address);149        if (balance !== balances[i] * tokenNominal) {150          isSuccess = false;151          break;152        }153      }154      return isSuccess;155    };156157    let accountsCreated = false;158    // checkBalances retry up to 5 blocks159    for (let index = 0; index < 5; index++) {160      accountsCreated = await checkBalances();161      if(accountsCreated) break;162      await wait.newBlocks(1);163    }164165    if (!accountsCreated) throw Error('Accounts generation failed');166    //#endregion167168    return accounts;169  };170171  // TODO combine this method and createAccounts into one172  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {  173    const createAsManyAsCan = async () => {174      let transactions: any = [];175      const accounts: IKeyringPair[] = [];176      let nonce = await this.helper.chain.getNonce(donor.address);177      const tokenNominal = this.helper.balance.getOneTokenNominal();178      for (let i = 0; i < accountsToCreate; i++) {179        if (i === 500) { // if there are too many accounts to create180          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 181          transactions = []; //182          nonce = await this.helper.chain.getNonce(donor.address); // update nonce 183        }184        const recepient = this.helper.util.fromSeed(mnemonicGenerate());185        accounts.push(recepient);186        if (withBalance !== 0n) {187          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);188          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));189          nonce++;190        }191      }192      193      const fullfilledAccounts = [];194      await Promise.allSettled(transactions);195      for (const account of accounts) {196        const accountBalance = await this.helper.balance.getSubstrate(account.address);197        if (accountBalance === withBalance * tokenNominal) {198          fullfilledAccounts.push(account);199        }200      }201      return fullfilledAccounts;202    };203204    205    const crowd: IKeyringPair[] = [];206    // do up to 5 retries207    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {208      const asManyAsCan = await createAsManyAsCan();209      crowd.push(...asManyAsCan);210      accountsToCreate -= asManyAsCan.length;211    }212213    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);214215    return crowd;216  };217218  isDevNode = async () => {219    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);220    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);221    const findCreationDate = async (block: any) => {222      const humanBlock = block.toHuman();223      let date;224      humanBlock.block.extrinsics.forEach((ext: any) => {225        if(ext.method.section === 'timestamp') {226          date = Number(ext.method.args.now.replaceAll(',', ''));227        }228      });229      return date;230    };231    const block1date = await findCreationDate(block1);232    const block2date = await findCreationDate(block2);233    if(block2date! - block1date! < 9000) return true;234  };235  236  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {237    const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);238    let balance = await this.helper.balance.getSubstrate(address); 239    240    await promise();241    242    balance -= await this.helper.balance.getSubstrate(address);243    244    return balance;245  }246}247248class WaitGroup {249  helper: DevUniqueHelper;250251  constructor(helper: DevUniqueHelper) {252    this.helper = helper;253  }254255  /**256   * Wait for specified number of blocks257   * @param blocksCount number of blocks to wait258   * @returns 259   */260  async newBlocks(blocksCount = 1): Promise<void> {261    // eslint-disable-next-line no-async-promise-executor262    const promise = new Promise<void>(async (resolve) => {263      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {264        if (blocksCount > 0) {265          blocksCount--;266        } else {267          unsubscribe();268          resolve();269        }270      });271    });272    return promise;273  }274275  async forParachainBlockNumber(blockNumber: bigint) {276    // eslint-disable-next-line no-async-promise-executor277    return new Promise<void>(async (resolve) => {278      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {279        if (data.number.toNumber() >= blockNumber) {280          unsubscribe();281          resolve();282        }283      });284    });285  }286  287  async forRelayBlockNumber(blockNumber: bigint) {288    // eslint-disable-next-line no-async-promise-executor289    return new Promise<void>(async (resolve) => {290      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {291        if (data.value.relayParentNumber.toNumber() >= blockNumber) {292          // @ts-ignore293          unsubscribe();294          resolve();295        }296      });297    });298  }299}300301class AdminGroup {302  helper: UniqueHelper;303304  constructor(helper: UniqueHelper) {305    this.helper = helper;306  }307308  async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {309    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);310    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {311      return {312        staker: e.event.data[0].toString(),313        stake: e.event.data[1].toBigInt(),314        payout: e.event.data[2].toBigInt(),315      };316    });317  }318}
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -10,7 +10,6 @@
 import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';
 import {IKeyringPair} from '@polkadot/types/types';
 import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
-import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';
 
 export class CrossAccountId implements ICrossAccountId {
   Substrate?: TSubstrateAccount;