difftreelog
Split promotion tests to sequential and parallel
in: master
- add globalSetup script to set app promotion admin - move calculatePalleteAddress helper to DevUniqueHelper
5 files changed
tests/globalSetup.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/globalSetup.ts
@@ -0,0 +1,18 @@
+import {Pallets, usingPlaygrounds} from './src/util/playgrounds/index';
+
+export async function mochaGlobalSetup() {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ // Set up App Promotion admin
+ const missingPallets = helper.fetchMissingPalletNames([Pallets.AppPromotion]);
+ if (missingPallets.length === 0) {
+ const superuser = await privateKey('//Alice');
+ const palletAddress = helper.arrange.calculatePalleteAddress('appstake');
+ const palletAdmin = await privateKey('//PromotionAdmin');
+ const api = helper.getApi();
+ await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+ const nominal = helper.balance.getOneTokenNominal();
+ await helper.balance.transferToSubstrate(superuser, palletAdmin.address, 1000n * nominal);
+ await helper.balance.transferToSubstrate(superuser, palletAddress, 1000n * nominal);
+ }
+ });
+}
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -21,7 +21,7 @@
},
"mocha": {
"timeout": 9999999,
- "require": "ts-node/register"
+ "require": ["ts-node/register", "./globalSetup.ts"]
},
"scripts": {
"lint": "eslint --ext .ts,.js src/",
tests/src/app-promotion.seqtest.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/app-promotion.seqtest.ts
@@ -0,0 +1,83 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip} from './util/playgrounds';
+import {expect} from './eth/util/playgrounds';
+
+let superuser: IKeyringPair;
+let donor: IKeyringPair;
+let palletAdmin: IKeyringPair;
+let nominal: bigint;
+let palletAddress;
+let accounts: IKeyringPair[];
+
+
+describe('App promotion', () => {
+ before(async function () {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);
+ superuser = await privateKey('//Alice');
+ donor = await privateKey({filename: __filename});
+ palletAddress = helper.arrange.calculatePalleteAddress('appstake');
+ palletAdmin = await privateKey('//PromotionAdmin');
+ const api = helper.getApi();
+ await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+ nominal = helper.balance.getOneTokenNominal();
+ await helper.balance.transferToSubstrate(donor, palletAdmin.address, 1000n * nominal);
+ await helper.balance.transferToSubstrate(donor, palletAddress, 1000n * nominal);
+ accounts = await helper.arrange.createCrowd(100, 1000n, donor); // create accounts-pool to speed up tests
+ });
+ });
+
+ describe('admin adress', () => {
+ itSub('can be set by sudo only', async ({helper}) => {
+ const api = helper.getApi();
+ const nonAdmin = accounts.pop()!;
+ // nonAdmin can not set admin not from himself nor as a sudo
+ await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
+ });
+
+ itSub('can be any valid CrossAccountId', async ({helper}) => {
+ // We are not going to set an eth address as a sponsor,
+ // but we do want to check, it doesn't break anything;
+ const api = helper.getApi();
+ const account = accounts.pop()!;
+ const ethAccount = helper.address.substrateToEth(account.address);
+ // Alice sets Ethereum address as a sudo. Then Substrate address back...
+ await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
+ await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
+
+ // ...It doesn't break anything;
+ const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+ await expect(helper.signTransaction(account, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ });
+
+ itSub('can be reassigned', async ({helper}) => {
+ const api = helper.getApi();
+ const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
+
+ await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: oldAdmin.address})))).to.be.fulfilled;
+ await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: newAdmin.address})))).to.be.fulfilled;
+ await expect(helper.signTransaction(oldAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+
+ await expect(helper.signTransaction(newAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
+ });
+ });
+});
+
tests/src/app-promotion.test.tsdiffbeforeafterboth--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -16,17 +16,14 @@
import {IKeyringPair} from '@polkadot/types/types';
import {itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip} from './util/playgrounds';
-import {encodeAddress} from '@polkadot/util-crypto';
-import {stringToU8a} from '@polkadot/util';
import {DevUniqueHelper} from './util/playgrounds/unique.dev';
import {itEth, expect, SponsoringMode} from './eth/util/playgrounds';
-let superuser: IKeyringPair;
let donor: IKeyringPair;
let palletAdmin: IKeyringPair;
let nominal: bigint;
-const palletAddress = calculatePalleteAddress('appstake');
-let accounts: IKeyringPair[] = [];
+let palletAddress: string;
+let accounts: IKeyringPair[];
const LOCKING_PERIOD = 20n; // 20 blocks of relay
const UNLOCKING_PERIOD = 10n; // 10 blocks of parachain
const rewardAvailableInBlock = (stakedInBlock: bigint) => {
@@ -38,11 +35,9 @@
before(async function () {
await usingPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);
- superuser = await privateKey('//Alice');
donor = await privateKey({filename: __filename});
- [palletAdmin] = await helper.arrange.createAccounts([100n], donor);
- const api = helper.getApi();
- await helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+ palletAddress = helper.arrange.calculatePalleteAddress('appstake');
+ palletAdmin = await privateKey('//PromotionAdmin');
nominal = helper.balance.getOneTokenNominal();
await helper.balance.transferToSubstrate(donor, palletAdmin.address, 1000n * nominal);
await helper.balance.transferToSubstrate(donor, palletAddress, 1000n * nominal);
@@ -223,58 +218,10 @@
expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
}));
- });
- });
-
- describe('admin adress', () => {
- itSub('can be set by sudo only', async ({helper}) => {
- const api = helper.getApi();
- const nonAdmin = accounts.pop()!;
- // nonAdmin can not set admin not from himself nor as a sudo
- await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
- await expect(helper.signTransaction(nonAdmin, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
-
- // Alice can
- await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
- });
-
- itSub('can be any valid CrossAccountId', async ({helper}) => {
- // We are not going to set an eth address as a sponsor,
- // but we do want to check, it doesn't break anything;
- const api = helper.getApi();
- const account = accounts.pop()!;
- const ethAccount = helper.address.substrateToEth(account.address);
- // Alice sets Ethereum address as a sudo. Then Substrate address back...
- await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
- await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
-
- // ...It doesn't break anything;
- const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(account, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
});
-
- itSub('can be reassigned', async ({helper}) => {
- const api = helper.getApi();
- const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-
- await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: oldAdmin.address})))).to.be.fulfilled;
- await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: newAdmin.address})))).to.be.fulfilled;
- await expect(helper.signTransaction(oldAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
-
- await expect(helper.signTransaction(newAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
- });
});
describe('collection sponsoring', () => {
- before(async function () {
- await usingPlaygrounds(async (helper) => {
- const api = helper.getApi();
- const tx = api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
- await helper.signTransaction(superuser, tx);
- });
- });
-
itSub('should actually sponsor transactions', async ({helper}) => {
const api = helper.getApi();
const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
@@ -708,11 +655,6 @@
});
});
});
-
-function calculatePalleteAddress(palletId: any) {
- const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));
- return encodeAddress(address);
-}
function calculateIncome(base: bigint, calcPeriod: bigint, iter = 0): bigint {
const DAY = 7200n;
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth1// 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}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 calculatePalleteAddress(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}