git.delta.rocks / unique-network / refs/commits / 4e55e3985dac

difftreelog

tests: thorough event logging + a few more tests refactored

Fahrrader2022-09-19parent: #065efcf.patch.diff
in: master

7 files changed

modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -64,6 +64,7 @@
     "testTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/transfer.test.ts",
     "testBurnItem": "mocha --timeout 9999999 -r ts-node/register ./**/burnItem.test.ts",
     "testAdminTransferAndBurn": "mocha --timeout 9999999 -r ts-node/register ./**/adminTransferAndBurn.test.ts",
+    "testMintModes": "mocha --timeout 9999999 -r ts-node/register ./**/mintModes.test.ts",
     "testSetMintPermission": "mocha --timeout 9999999 -r ts-node/register ./**/setMintPermission.test.ts",
     "testSetPublicAccessMode": "mocha --timeout 9999999 -r ts-node/register ./**/setPublicAccessMode.test.ts",
     "testCreditFeesToTreasury": "mocha --timeout 9999999 -r ts-node/register ./**/creditFeesToTreasury.test.ts",
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
--- 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);
   });
-
 });
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,31 @@
 
 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;
+        // topics: any[];
+      }[];
+  },
+  moduleError?: string;
+}
+
+export interface ISubscribeBlockEventsData {
+  number: number;
+  hash: string;
+  timestamp: number; 
+  events: IEvent[];
 }
 
 export interface ILogger {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
9import {ApiInterfaceEvents} from '@polkadot/api/types';9import {ApiInterfaceEvents} from '@polkadot/api/types';
10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';
11import {IKeyringPair} from '@polkadot/types/types';11import {IKeyringPair} from '@polkadot/types/types';
12import {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';12import {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';
1313
14export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {14export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {
15 const address = {} as ICrossAccountId;15 const address = {} as ICrossAccountId;
149 return {success, tokens};149 return {success, tokens};
150 }150 }
151151
152 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {152 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {
153 let eventId = null;153 let eventId = null;
154 events.forEach(({event: {data, method, section}}) => {154 events.forEach(({event: {data, method, section}}) => {
155 if ((section === expectedSection) && (method === expectedMethod)) {155 if ((section === expectedSection) && (method === expectedMethod)) {
163 return eventId === collectionId;163 return eventId === collectionId;
164 }164 }
165165
166 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {166 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {
167 const normalizeAddress = (address: string | ICrossAccountId) => {167 const normalizeAddress = (address: string | ICrossAccountId) => {
168 if(typeof address === 'string') return address;168 if(typeof address === 'string') return address;
169 const obj = {} as any;169 const obj = {} as any;
195 }195 }
196}196}
197197
198class UniqueEventHelper {
199 private static extractIndex(index: any): [number, number] | string {
200 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];
201 return index.toJSON();
202 }
203
204 private static extractSub(data: any, subTypes: any): {[key: string]: any} {
205 let obj: any = {};
206 let index = 0;
207
208 if (data.entries)
209 for(const [key, value] of data.entries()) {
210 obj[key] = this.extractData(value, subTypes[index]);
211 index++;
212 }
213 else obj = data.toJSON();
214
215 return obj;
216 }
217
218 private static extractData(data: any, type: any): any {
219 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();
220 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();
221 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);
222 return data.toHuman();
223 }
224
225 public static extractEvents(records: ITransactionResult): IEvent[] {
226 const parsedEvents: IEvent[] = [];
227
228 records.result.events.forEach((record) => {
229 const {event, phase} = record;
230 const types = (event as any).typeDef;
231
232 const eventData: IEvent = {
233 section: event.section.toString(),
234 method: event.method.toString(),
235 index: this.extractIndex(event.index),
236 data: [],
237 phase: phase.toJSON(),
238 };
239
240 event.data.forEach((val: any, index: number) => {
241 eventData.data.push(this.extractData(val, types[index]));
242 });
243
244 parsedEvents.push(eventData);
245 });
246
247 return parsedEvents;
248 }
249}
198250
199class ChainHelperBase {251class ChainHelperBase {
200 transactionStatus = UniqueUtil.transactionStatus;252 transactionStatus = UniqueUtil.transactionStatus;
201 chainLogType = UniqueUtil.chainLogType;253 chainLogType = UniqueUtil.chainLogType;
202 util: typeof UniqueUtil;254 util: typeof UniqueUtil;
255 eventHelper: typeof UniqueEventHelper;
203 logger: ILogger;256 logger: ILogger;
204 api: ApiPromise | null;257 api: ApiPromise | null;
205 forcedNetwork: TUniqueNetworks | null;258 forcedNetwork: TUniqueNetworks | null;
208261
209 constructor(logger?: ILogger) {262 constructor(logger?: ILogger) {
210 this.util = UniqueUtil;263 this.util = UniqueUtil;
264 this.eventHelper = UniqueEventHelper;
211 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();265 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();
212 this.logger = logger;266 this.logger = logger;
213 this.api = null;267 this.api = null;
290 return {api, network};344 return {api, network};
291 }345 }
292346
293 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {347 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {
294 const {events, status} = data;348 const {events, status} = data;
295 if (status.isReady) {349 if (status.isReady) {
296 return this.transactionStatus.NOT_READY;350 return this.transactionStatus.NOT_READY;
299 return this.transactionStatus.NOT_READY;353 return this.transactionStatus.NOT_READY;
300 }354 }
301 if (status.isInBlock || status.isFinalized) {355 if (status.isInBlock || status.isFinalized) {
302 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');356 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');
303 if (errors.length > 0) {357 if (errors.length > 0) {
304 return this.transactionStatus.FAIL;358 return this.transactionStatus.FAIL;
305 }359 }
306 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {360 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {
307 return this.transactionStatus.SUCCESS;361 return this.transactionStatus.SUCCESS;
308 }362 }
309 }363 }
332 if (result.hasOwnProperty('dispatchError')) {386 if (result.hasOwnProperty('dispatchError')) {
333 const dispatchError = result['dispatchError'];387 const dispatchError = result['dispatchError'];
334388
335 if (dispatchError && dispatchError.isModule) {389 if (dispatchError) {
390 if (dispatchError.isModule) {
336 const modErr = dispatchError.asModule;391 const modErr = dispatchError.asModule;
337 const errorMeta = dispatchError.registry.findMetaError(modErr);392 const errorMeta = dispatchError.registry.findMetaError(modErr);
338393
339 moduleError = `${errorMeta.section}.${errorMeta.name}`;394 moduleError = `${errorMeta.section}.${errorMeta.name}`;
340 }395 } else {
396 moduleError = dispatchError.toHuman();
397 }
341 else {398 } else {
342 this.logger.log(result, this.logger.level.ERROR);399 this.logger.log(result, this.logger.level.ERROR);
343 }400 }
344 }401 }
364 return call(...params);421 return call(...params);
365 }422 }
366423
367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false/*, failureMessage='expected success'*/) {424 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true/*, failureMessage='expected success'*/) {
368 if(this.api === null) throw Error('API not initialized');425 if(this.api === null) throw Error('API not initialized');
369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);426 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);
370427
371 const startTime = (new Date()).getTime();428 const startTime = (new Date()).getTime();
372 let result: ITransactionResult;429 let result: ITransactionResult;
373 let events = [];430 let events: IEvent[] = [];
374 try {431 try {
375 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;432 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;
376 events = result.result.events.map((x: any) => x.toHuman());433 events = this.eventHelper.extractEvents(result);
377 }434 }
378 catch(e) {435 catch(e) {
379 if(!(e as object).hasOwnProperty('status')) throw e;436 if(!(e as object).hasOwnProperty('status')) throw e;