git.delta.rocks / unique-network / refs/commits / 2f6a65e5b93a

difftreelog

Merge pull request #601 from UniqueNetwork/tests/event-logging-and-more

ut-akuznetsov2022-09-20parents: #488175c #155f75c.patch.diff
in: master

8 files changed

modifiedtests/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}) => {
modifiedtests/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}) => {
modifiedtests/src/inflation.test.tsdiffbeforeafterboth
14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License
15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
1616
17import chai from 'chai';
18import chaiAsPromised from 'chai-as-promised';17import {IKeyringPair} from '@polkadot/types/types';
19import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';18import {expect, itSub, usingPlaygrounds} from './util/playgrounds';
2019
21chai.use(chaiAsPromised);20// todo:playgrounds requires sudo, look into on the later stage
22const expect = chai.expect;
23
24describe('integration test: Inflation', () => {21describe('integration test: Inflation', () => {
22 let superuser: IKeyringPair;
23
24 before(async () => {
25 await usingPlaygrounds(async (_, privateKey) => {
26 superuser = privateKey('//Alice');
27 });
28 });
29
25 it('First year inflation is 10%', async () => {30 itSub('First year inflation is 10%', async ({helper}) => {
26 await usingApi(async (api, privateKeyWrapper) => {
27
28 // Make sure non-sudo can't start inflation31 // Make sure non-sudo can't start inflation
29 const tx = api.tx.inflation.startInflation(1);32 const [bob] = await helper.arrange.createAccounts([10n], superuser);
33
30 const bob = privateKeyWrapper('//Bob');34 await expect(helper.executeExtrinsic(bob, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
35
36 // Make sure superuser can't start inflation without explicit sudo
31 await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;37 await expect(helper.executeExtrinsic(superuser, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
3238
33 // Start inflation on relay block 1 (Alice is sudo)39 // Start inflation on relay block 1 (Alice is sudo)
34 const alice = privateKeyWrapper('//Alice');40 const tx = helper.constructApiCall('api.tx.inflation.startInflation', [1]);
35 const sudoTx = api.tx.sudo.sudo(tx as any);41 await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [tx])).to.not.be.rejected;
36 await submitTransactionAsync(alice, sudoTx);
3742
38 const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();43 const blockInterval = (helper.api!.consts.inflation.inflationBlockInterval as any).toBigInt();
39 const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();44 const totalIssuanceStart = ((await helper.api!.query.inflation.startingYearTotalIssuance()) as any).toBigInt();
40 const blockInflation = (await api.query.inflation.blockInflation()).toBigInt();45 const blockInflation = (await helper.api!.query.inflation.blockInflation() as any).toBigInt();
4146
42 const YEAR = 5259600n; // 6-second block. Blocks in one year47 const YEAR = 5259600n; // 6-second block. Blocks in one year
43 // const YEAR = 2629800n; // 12-second block. Blocks in one year48 // const YEAR = 2629800n; // 12-second block. Blocks in one year
49 const expectedInflation = totalExpectedInflation / totalActualInflation - 1n;54 const expectedInflation = totalExpectedInflation / totalActualInflation - 1n;
5055
51 expect(Math.abs(Number(expectedInflation))).to.be.lessThanOrEqual(tolerance);56 expect(Math.abs(Number(expectedInflation))).to.be.lessThanOrEqual(tolerance);
52 });
53 });57 });
54
55});58});
modifiedtests/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}) => {
modifiedtests/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;
modifiedtests/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 {
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -132,7 +132,7 @@
       accounts.push(recipient);
       if (balance !== 0n) {
         const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);
-        transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));
+        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));
         nonce++;
       }
     }
@@ -183,7 +183,7 @@
         accounts.push(recepient);
         if (withBalance !== 0n) {
           const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);
-          transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));
+          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));
           nonce++;
         }
       }
modifiedtests/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;