difftreelog
Merge pull request #601 from UniqueNetwork/tests/event-logging-and-more
in: master
8 files changed
tests/src/app-promotion.test.tsdiffbeforeafterboth--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -555,9 +555,8 @@
const flipper = await helper.eth.deployFlipper(contractOwner);
await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
- const stopSponsoringResult = await helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]);
- expect(stopSponsoringResult.status).to.equal('Fail');
- expect(stopSponsoringResult.moduleError).to.equal('appPromotion.NoPermission');
+ await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]))
+ .to.be.rejectedWith(/appPromotion\.NoPermission/);
});
itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {
tests/src/fungible.test.tsdiffbeforeafterboth--- a/tests/src/fungible.test.ts
+++ b/tests/src/fungible.test.ts
@@ -15,18 +15,18 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {U128_MAX} from './util/helpers';
import {itSub, usingPlaygrounds, expect} from './util/playgrounds';
-// todo:playgrounds get rid of globals
-let alice: IKeyringPair;
-let bob: IKeyringPair;
+const U128_MAX = (1n << 128n) - 1n;
describe('integration test: Fungible functionality:', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
});
});
@@ -82,7 +82,7 @@
expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(60n);
expect(await collection.getBalance(ethAcc)).to.be.equal(140n);
- await expect(collection.transfer(alice, {Substrate: bob.address}, 350n)).to.eventually.be.rejected;
+ await expect(collection.transfer(alice, {Substrate: bob.address}, 350n)).to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);
});
itSub('Tokens multiple creation', async ({helper}) => {
tests/src/inflation.test.tsdiffbeforeafterboth--- a/tests/src/inflation.test.ts
+++ b/tests/src/inflation.test.ts
@@ -14,42 +14,45 @@
// 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 chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect, itSub, usingPlaygrounds} from './util/playgrounds';
+// todo:playgrounds requires sudo, look into on the later stage
describe('integration test: Inflation', () => {
- it('First year inflation is 10%', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
+ let superuser: IKeyringPair;
- // Make sure non-sudo can't start inflation
- const tx = api.tx.inflation.startInflation(1);
- const bob = privateKeyWrapper('//Bob');
- await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
+ before(async () => {
+ await usingPlaygrounds(async (_, privateKey) => {
+ superuser = privateKey('//Alice');
+ });
+ });
+
+ itSub('First year inflation is 10%', async ({helper}) => {
+ // Make sure non-sudo can't start inflation
+ const [bob] = await helper.arrange.createAccounts([10n], superuser);
- // Start inflation on relay block 1 (Alice is sudo)
- const alice = privateKeyWrapper('//Alice');
- const sudoTx = api.tx.sudo.sudo(tx as any);
- await submitTransactionAsync(alice, sudoTx);
+ await expect(helper.executeExtrinsic(bob, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
- const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();
- const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();
- const blockInflation = (await api.query.inflation.blockInflation()).toBigInt();
+ // Make sure superuser can't start inflation without explicit sudo
+ await expect(helper.executeExtrinsic(superuser, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
- const YEAR = 5259600n; // 6-second block. Blocks in one year
- // const YEAR = 2629800n; // 12-second block. Blocks in one year
+ // Start inflation on relay block 1 (Alice is sudo)
+ const tx = helper.constructApiCall('api.tx.inflation.startInflation', [1]);
+ await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [tx])).to.not.be.rejected;
- const totalExpectedInflation = totalIssuanceStart / 10n;
- const totalActualInflation = blockInflation * YEAR / blockInterval;
+ const blockInterval = (helper.api!.consts.inflation.inflationBlockInterval as any).toBigInt();
+ const totalIssuanceStart = ((await helper.api!.query.inflation.startingYearTotalIssuance()) as any).toBigInt();
+ const blockInflation = (await helper.api!.query.inflation.blockInflation() as any).toBigInt();
- const tolerance = 0.00001; // Relative difference per year between theoretical and actual inflation
- const expectedInflation = totalExpectedInflation / totalActualInflation - 1n;
+ const YEAR = 5259600n; // 6-second block. Blocks in one year
+ // const YEAR = 2629800n; // 12-second block. Blocks in one year
+
+ const totalExpectedInflation = totalIssuanceStart / 10n;
+ const totalActualInflation = blockInflation * YEAR / blockInterval;
+
+ const tolerance = 0.00001; // Relative difference per year between theoretical and actual inflation
+ const expectedInflation = totalExpectedInflation / totalActualInflation - 1n;
- expect(Math.abs(Number(expectedInflation))).to.be.lessThanOrEqual(tolerance);
- });
+ expect(Math.abs(Number(expectedInflation))).to.be.lessThanOrEqual(tolerance);
});
-
});
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -17,17 +17,18 @@
import {IKeyringPair} from '@polkadot/types/types';
import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from './util/playgrounds';
-let alice: IKeyringPair;
-let bob: IKeyringPair;
const MAX_REFUNGIBLE_PIECES = 1_000_000_000_000_000_000_000n;
describe('integration test: Refungible functionality:', async () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async function() {
await usingPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
});
});
@@ -209,36 +210,38 @@
const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
const token = await collection.mintToken(alice, 100n);
await token.repartition(alice, 200n);
- const chainEvents = helper.chainLog.slice(-1)[0].events.map((x: any) => x.event);
- expect(chainEvents).to.include.deep.members([{
- method: 'ItemCreated',
+ const chainEvents = helper.chainLog.slice(-1)[0].events;
+ expect(chainEvents).to.deep.include({
section: 'common',
- index: '0x4202',
- data: [
- helper.api!.createType('u32', collection.collectionId).toHuman(),
- helper.api!.createType('u32', token.tokenId).toHuman(),
- {Substrate: alice.address},
- '100',
+ method: 'ItemCreated',
+ index: [66, 2],
+ data: [
+ collection.collectionId,
+ token.tokenId,
+ {substrate: alice.address},
+ 100n,
],
- }]);
+ phase: {applyExtrinsic: 2},
+ });
});
itSub('Repartition with decreased amount', async ({helper}) => {
const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
const token = await collection.mintToken(alice, 100n);
await token.repartition(alice, 50n);
- const chainEvents = helper.chainLog.slice(-1)[0].events.map((x: any) => x.event);
- expect(chainEvents).to.include.deep.members([{
+ const chainEvents = helper.chainLog.slice(-1)[0].events;
+ expect(chainEvents).to.deep.include({
method: 'ItemDestroyed',
section: 'common',
- index: '0x4203',
- data: [
- helper.api!.createType('u32', collection.collectionId).toHuman(),
- helper.api!.createType('u32', token.tokenId).toHuman(),
- {Substrate: alice.address},
- '50',
+ index: [66, 3],
+ data: [
+ collection.collectionId,
+ token.tokenId,
+ {substrate: alice.address},
+ 50n,
],
- }]);
+ phase: {applyExtrinsic: 2},
+ });
});
itSub('Create new collection with properties', async ({helper}) => {
tests/src/tx-version-presence.test.tsdiffbeforeafterboth--- a/tests/src/tx-version-presence.test.ts
+++ b/tests/src/tx-version-presence.test.ts
@@ -14,7 +14,7 @@
// 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 { Metadata } from '@polkadot/types';
+import {Metadata} from '@polkadot/types';
import {itSub, usingPlaygrounds, expect} from './util/playgrounds';
let metadata: Metadata;
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -3,20 +3,30 @@
import {IKeyringPair} from '@polkadot/types/types';
-export interface IChainEvent {
- data: any;
+export interface IEvent {
+ section: string;
method: string;
- section: string;
+ index: [number, number] | string;
+ data: any[];
+ phase: {applyExtrinsic: number} | 'Initialization',
}
export interface ITransactionResult {
- status: 'Fail' | 'Success';
- result: {
- events: {
- event: IChainEvent
- }[];
- },
- moduleError?: string;
+ status: 'Fail' | 'Success';
+ result: {
+ events: {
+ phase: any, // {ApplyExtrinsic: number} | 'Initialization',
+ event: IEvent;
+ }[];
+ },
+ moduleError?: string;
+}
+
+export interface ISubscribeBlockEventsData {
+ number: number;
+ hash: string;
+ timestamp: number;
+ events: IEvent[];
}
export interface ILogger {
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';91011export 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 }) {66 super(logger);67 this.arrange = new ArrangeGroup(this);68 this.wait = new WaitGroup(this);69 this.admin = new AdminGroup(this);70 }7172 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {73 const wsProvider = new WsProvider(wsEndpoint);74 this.api = new ApiPromise({75 provider: wsProvider,76 signedExtensions: {77 ContractHelpers: {78 extrinsic: {},79 payload: {},80 },81 FakeTransactionFinalizer: {82 extrinsic: {},83 payload: {},84 },85 },86 rpc: {87 unique: defs.unique.rpc,88 appPromotion: defs.appPromotion.rpc,89 rmrk: defs.rmrk.rpc,90 eth: {91 feeHistory: {92 description: 'Dummy',93 params: [],94 type: 'u8',95 },96 maxPriorityFeePerGas: {97 description: 'Dummy',98 params: [],99 type: 'u8',100 },101 },102 },103 });104 await this.api.isReadyOrError;105 this.network = await UniqueHelper.detectNetwork(this.api);106 }107}108109class ArrangeGroup {110 helper: UniqueHelper;111112 constructor(helper: UniqueHelper) {113 this.helper = helper;114 }115116 /**117 * Generates accounts with the specified UNQ token balance 118 * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.119 * @param donor donor account for balances120 * @returns array of newly created accounts121 * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 122 */123 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {124 let nonce = await this.helper.chain.getNonce(donor.address);125 const wait = new WaitGroup(this.helper);126 const ss58Format = this.helper.chain.getChainProperties().ss58Format;127 const tokenNominal = this.helper.balance.getOneTokenNominal();128 const transactions = [];129 const accounts: IKeyringPair[] = [];130 for (const balance of balances) {131 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);132 accounts.push(recipient);133 if (balance !== 0n) {134 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);135 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));136 nonce++;137 }138 }139140 await Promise.all(transactions).catch(_e => {});141 142 //#region TODO remove this region, when nonce problem will be solved143 const checkBalances = async () => {144 let isSuccess = true;145 for (let i = 0; i < balances.length; i++) {146 const balance = await this.helper.balance.getSubstrate(accounts[i].address);147 if (balance !== balances[i] * tokenNominal) {148 isSuccess = false;149 break;150 }151 }152 return isSuccess;153 };154155 let accountsCreated = false;156 // checkBalances retry up to 5 blocks157 for (let index = 0; index < 5; index++) {158 accountsCreated = await checkBalances();159 if(accountsCreated) break;160 await wait.newBlocks(1);161 }162163 if (!accountsCreated) throw Error('Accounts generation failed');164 //#endregion165166 return accounts;167 };168169 // TODO combine this method and createAccounts into one170 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 171 const createAsManyAsCan = async () => {172 let transactions: any = [];173 const accounts: IKeyringPair[] = [];174 let nonce = await this.helper.chain.getNonce(donor.address);175 const tokenNominal = this.helper.balance.getOneTokenNominal();176 for (let i = 0; i < accountsToCreate; i++) {177 if (i === 500) { // if there are too many accounts to create178 await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 179 transactions = []; //180 nonce = await this.helper.chain.getNonce(donor.address); // update nonce 181 }182 const recepient = this.helper.util.fromSeed(mnemonicGenerate());183 accounts.push(recepient);184 if (withBalance !== 0n) {185 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);186 transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));187 nonce++;188 }189 }190 191 const fullfilledAccounts = [];192 await Promise.allSettled(transactions);193 for (const account of accounts) {194 const accountBalance = await this.helper.balance.getSubstrate(account.address);195 if (accountBalance === withBalance * tokenNominal) {196 fullfilledAccounts.push(account);197 }198 }199 return fullfilledAccounts;200 };201202 203 const crowd: IKeyringPair[] = [];204 // do up to 5 retries205 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {206 const asManyAsCan = await createAsManyAsCan();207 crowd.push(...asManyAsCan);208 accountsToCreate -= asManyAsCan.length;209 }210211 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);212213 return crowd;214 };215216 isDevNode = async () => {217 const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));218 const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));219 const findCreationDate = async (block: any) => {220 const humanBlock = block.toHuman();221 let date;222 humanBlock.block.extrinsics.forEach((ext: any) => {223 if(ext.method.section === 'timestamp') {224 date = Number(ext.method.args.now.replaceAll(',', ''));225 }226 });227 return date;228 };229 const block1date = await findCreationDate(block1);230 const block2date = await findCreationDate(block2);231 if(block2date! - block1date! < 9000) return true;232 };233}234235class WaitGroup {236 helper: UniqueHelper;237238 constructor(helper: UniqueHelper) {239 this.helper = helper;240 }241242 /**243 * Wait for specified bnumber of blocks244 * @param blocksCount number of blocks to wait245 * @returns 246 */247 async newBlocks(blocksCount = 1): Promise<void> {248 // eslint-disable-next-line no-async-promise-executor249 const promise = new Promise<void>(async (resolve) => {250 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {251 if (blocksCount > 0) {252 blocksCount--;253 } else {254 unsubscribe();255 resolve();256 }257 });258 });259 return promise;260 }261262 async forParachainBlockNumber(blockNumber: bigint) {263 // eslint-disable-next-line no-async-promise-executor264 return new Promise<void>(async (resolve) => {265 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {266 if (data.number.toNumber() >= blockNumber) {267 unsubscribe();268 resolve();269 }270 });271 });272 }273 274 async forRelayBlockNumber(blockNumber: bigint) {275 // eslint-disable-next-line no-async-promise-executor276 return new Promise<void>(async (resolve) => {277 const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {278 if (data.value.relayParentNumber.toNumber() >= blockNumber) {279 // @ts-ignore280 unsubscribe();281 resolve();282 }283 });284 });285 }286}287288class AdminGroup {289 helper: UniqueHelper;290291 constructor(helper: UniqueHelper) {292 this.helper = helper;293 }294295 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {296 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);297 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {298 return {299 staker: e.event.data[0].toString(),300 stake: e.event.data[1].toBigInt(),301 payout: e.event.data[2].toBigInt(),302 };303 });304 }305}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';91011export 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 }) {66 super(logger);67 this.arrange = new ArrangeGroup(this);68 this.wait = new WaitGroup(this);69 this.admin = new AdminGroup(this);70 }7172 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {73 const wsProvider = new WsProvider(wsEndpoint);74 this.api = new ApiPromise({75 provider: wsProvider,76 signedExtensions: {77 ContractHelpers: {78 extrinsic: {},79 payload: {},80 },81 FakeTransactionFinalizer: {82 extrinsic: {},83 payload: {},84 },85 },86 rpc: {87 unique: defs.unique.rpc,88 appPromotion: defs.appPromotion.rpc,89 rmrk: defs.rmrk.rpc,90 eth: {91 feeHistory: {92 description: 'Dummy',93 params: [],94 type: 'u8',95 },96 maxPriorityFeePerGas: {97 description: 'Dummy',98 params: [],99 type: 'u8',100 },101 },102 },103 });104 await this.api.isReadyOrError;105 this.network = await UniqueHelper.detectNetwork(this.api);106 }107}108109class ArrangeGroup {110 helper: UniqueHelper;111112 constructor(helper: UniqueHelper) {113 this.helper = helper;114 }115116 /**117 * Generates accounts with the specified UNQ token balance 118 * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.119 * @param donor donor account for balances120 * @returns array of newly created accounts121 * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 122 */123 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {124 let nonce = await this.helper.chain.getNonce(donor.address);125 const wait = new WaitGroup(this.helper);126 const ss58Format = this.helper.chain.getChainProperties().ss58Format;127 const tokenNominal = this.helper.balance.getOneTokenNominal();128 const transactions = [];129 const accounts: IKeyringPair[] = [];130 for (const balance of balances) {131 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);132 accounts.push(recipient);133 if (balance !== 0n) {134 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);135 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));136 nonce++;137 }138 }139140 await Promise.all(transactions).catch(_e => {});141 142 //#region TODO remove this region, when nonce problem will be solved143 const checkBalances = async () => {144 let isSuccess = true;145 for (let i = 0; i < balances.length; i++) {146 const balance = await this.helper.balance.getSubstrate(accounts[i].address);147 if (balance !== balances[i] * tokenNominal) {148 isSuccess = false;149 break;150 }151 }152 return isSuccess;153 };154155 let accountsCreated = false;156 // checkBalances retry up to 5 blocks157 for (let index = 0; index < 5; index++) {158 accountsCreated = await checkBalances();159 if(accountsCreated) break;160 await wait.newBlocks(1);161 }162163 if (!accountsCreated) throw Error('Accounts generation failed');164 //#endregion165166 return accounts;167 };168169 // TODO combine this method and createAccounts into one170 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 171 const createAsManyAsCan = async () => {172 let transactions: any = [];173 const accounts: IKeyringPair[] = [];174 let nonce = await this.helper.chain.getNonce(donor.address);175 const tokenNominal = this.helper.balance.getOneTokenNominal();176 for (let i = 0; i < accountsToCreate; i++) {177 if (i === 500) { // if there are too many accounts to create178 await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 179 transactions = []; //180 nonce = await this.helper.chain.getNonce(donor.address); // update nonce 181 }182 const recepient = this.helper.util.fromSeed(mnemonicGenerate());183 accounts.push(recepient);184 if (withBalance !== 0n) {185 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);186 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));187 nonce++;188 }189 }190 191 const fullfilledAccounts = [];192 await Promise.allSettled(transactions);193 for (const account of accounts) {194 const accountBalance = await this.helper.balance.getSubstrate(account.address);195 if (accountBalance === withBalance * tokenNominal) {196 fullfilledAccounts.push(account);197 }198 }199 return fullfilledAccounts;200 };201202 203 const crowd: IKeyringPair[] = [];204 // do up to 5 retries205 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {206 const asManyAsCan = await createAsManyAsCan();207 crowd.push(...asManyAsCan);208 accountsToCreate -= asManyAsCan.length;209 }210211 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);212213 return crowd;214 };215216 isDevNode = async () => {217 const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));218 const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));219 const findCreationDate = async (block: any) => {220 const humanBlock = block.toHuman();221 let date;222 humanBlock.block.extrinsics.forEach((ext: any) => {223 if(ext.method.section === 'timestamp') {224 date = Number(ext.method.args.now.replaceAll(',', ''));225 }226 });227 return date;228 };229 const block1date = await findCreationDate(block1);230 const block2date = await findCreationDate(block2);231 if(block2date! - block1date! < 9000) return true;232 };233}234235class WaitGroup {236 helper: UniqueHelper;237238 constructor(helper: UniqueHelper) {239 this.helper = helper;240 }241242 /**243 * Wait for specified bnumber of blocks244 * @param blocksCount number of blocks to wait245 * @returns 246 */247 async newBlocks(blocksCount = 1): Promise<void> {248 // eslint-disable-next-line no-async-promise-executor249 const promise = new Promise<void>(async (resolve) => {250 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {251 if (blocksCount > 0) {252 blocksCount--;253 } else {254 unsubscribe();255 resolve();256 }257 });258 });259 return promise;260 }261262 async forParachainBlockNumber(blockNumber: bigint) {263 // eslint-disable-next-line no-async-promise-executor264 return new Promise<void>(async (resolve) => {265 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {266 if (data.number.toNumber() >= blockNumber) {267 unsubscribe();268 resolve();269 }270 });271 });272 }273 274 async forRelayBlockNumber(blockNumber: bigint) {275 // eslint-disable-next-line no-async-promise-executor276 return new Promise<void>(async (resolve) => {277 const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {278 if (data.value.relayParentNumber.toNumber() >= blockNumber) {279 // @ts-ignore280 unsubscribe();281 resolve();282 }283 });284 });285 }286}287288class AdminGroup {289 helper: UniqueHelper;290291 constructor(helper: UniqueHelper) {292 this.helper = helper;293 }294295 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {296 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);297 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {298 return {299 staker: e.event.data[0].toString(),300 stake: e.event.data[1].toBigInt(),301 payout: e.event.data[2].toBigInt(),302 };303 });304 }305}tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -6,10 +6,10 @@
/* eslint-disable no-prototype-builtins */
import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';
-import {ApiInterfaceEvents} from '@polkadot/api/types';
+import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';
import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
-import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
+import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {
const address = {} as ICrossAccountId;
@@ -149,7 +149,7 @@
return {success, tokens};
}
- static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {
+ static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {
let eventId = null;
events.forEach(({event: {data, method, section}}) => {
if ((section === expectedSection) && (method === expectedMethod)) {
@@ -163,7 +163,7 @@
return eventId === collectionId;
}
- static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {
+ static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {
const normalizeAddress = (address: string | ICrossAccountId) => {
if(typeof address === 'string') return address;
const obj = {} as any;
@@ -195,11 +195,64 @@
}
}
+class UniqueEventHelper {
+ private static extractIndex(index: any): [number, number] | string {
+ if(index.toRawType() === '[u8;2]') return [index[0], index[1]];
+ return index.toJSON();
+ }
+
+ private static extractSub(data: any, subTypes: any): {[key: string]: any} {
+ let obj: any = {};
+ let index = 0;
+
+ if (data.entries) {
+ for(const [key, value] of data.entries()) {
+ obj[key] = this.extractData(value, subTypes[index]);
+ index++;
+ }
+ } else obj = data.toJSON();
+ return obj;
+ }
+
+ private static extractData(data: any, type: any): any {
+ if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();
+ if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();
+ if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);
+ return data.toHuman();
+ }
+
+ public static extractEvents(records: ITransactionResult): IEvent[] {
+ const parsedEvents: IEvent[] = [];
+
+ records.result.events.forEach((record) => {
+ const {event, phase} = record;
+ const types = (event as any).typeDef;
+
+ const eventData: IEvent = {
+ section: event.section.toString(),
+ method: event.method.toString(),
+ index: this.extractIndex(event.index),
+ data: [],
+ phase: phase.toJSON(),
+ };
+
+ event.data.forEach((val: any, index: number) => {
+ eventData.data.push(this.extractData(val, types[index]));
+ });
+
+ parsedEvents.push(eventData);
+ });
+
+ return parsedEvents;
+ }
+}
+
class ChainHelperBase {
transactionStatus = UniqueUtil.transactionStatus;
chainLogType = UniqueUtil.chainLogType;
util: typeof UniqueUtil;
+ eventHelper: typeof UniqueEventHelper;
logger: ILogger;
api: ApiPromise | null;
forcedNetwork: TUniqueNetworks | null;
@@ -208,6 +261,7 @@
constructor(logger?: ILogger) {
this.util = UniqueUtil;
+ this.eventHelper = UniqueEventHelper;
if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();
this.logger = logger;
this.api = null;
@@ -290,7 +344,7 @@
return {api, network};
}
- getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {
+ getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {
const {events, status} = data;
if (status.isReady) {
return this.transactionStatus.NOT_READY;
@@ -299,11 +353,11 @@
return this.transactionStatus.NOT_READY;
}
if (status.isInBlock || status.isFinalized) {
- const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');
+ const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');
if (errors.length > 0) {
return this.transactionStatus.FAIL;
}
- if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {
+ if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {
return this.transactionStatus.SUCCESS;
}
}
@@ -311,7 +365,7 @@
return this.transactionStatus.FAIL;
}
- signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {
+ signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {
const sign = (callback: any) => {
if(options !== null) return transaction.signAndSend(sender, options, callback);
return transaction.signAndSend(sender, callback);
@@ -332,13 +386,16 @@
if (result.hasOwnProperty('dispatchError')) {
const dispatchError = result['dispatchError'];
- if (dispatchError && dispatchError.isModule) {
- const modErr = dispatchError.asModule;
- const errorMeta = dispatchError.registry.findMetaError(modErr);
+ if (dispatchError) {
+ if (dispatchError.isModule) {
+ const modErr = dispatchError.asModule;
+ const errorMeta = dispatchError.registry.findMetaError(modErr);
- moduleError = `${errorMeta.section}.${errorMeta.name}`;
- }
- else {
+ moduleError = `${errorMeta.section}.${errorMeta.name}`;
+ } else {
+ moduleError = dispatchError.toHuman();
+ }
+ } else {
this.logger.log(result, this.logger.level.ERROR);
}
}
@@ -364,16 +421,16 @@
return call(...params);
}
- async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false/*, failureMessage='expected success'*/) {
+ async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {
if(this.api === null) throw Error('API not initialized');
if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);
const startTime = (new Date()).getTime();
let result: ITransactionResult;
- let events = [];
+ let events: IEvent[] = [];
try {
- result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;
- events = result.result.events.map((x: any) => x.toHuman());
+ result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;
+ events = this.eventHelper.extractEvents(result);
}
catch(e) {
if(!(e as object).hasOwnProperty('status')) throw e;