difftreelog
tests: thorough event logging + a few more tests refactored
in: master
7 files changed
tests/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",
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.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from './util/playgrounds';1920let alice: IKeyringPair;21let bob: IKeyringPair;22const MAX_REFUNGIBLE_PIECES = 1_000_000_000_000_000_000_000n;2324describe('integration test: Refungible functionality:', async () => {25 before(async function() {26 await usingPlaygrounds(async (helper, privateKey) => {27 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);2829 alice = privateKey('//Alice');30 bob = privateKey('//Bob');31 });32 });33 34 itSub('Create refungible collection and token', async ({helper}) => {35 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});3637 const itemCountBefore = await collection.getLastTokenId();38 const token = await collection.mintToken(alice, 100n);39 40 const itemCountAfter = await collection.getLastTokenId();41 42 // What to expect43 expect(token?.tokenId).to.be.gte(itemCountBefore);44 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);45 expect(itemCountAfter.toString()).to.be.equal(token?.tokenId.toString());46 });47 48 itSub('Checking RPC methods when interacting with maximum allowed values (MAX_REFUNGIBLE_PIECES)', async ({helper}) => {49 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});50 51 const token = await collection.mintToken(alice, MAX_REFUNGIBLE_PIECES);52 53 expect(await collection.getTokenBalance(token.tokenId, {Substrate: alice.address})).to.be.equal(MAX_REFUNGIBLE_PIECES);54 55 await collection.transferToken(alice, token.tokenId, {Substrate: bob.address}, MAX_REFUNGIBLE_PIECES);56 expect(await collection.getTokenBalance(token.tokenId, {Substrate: bob.address})).to.be.equal(MAX_REFUNGIBLE_PIECES);57 expect(await token.getTotalPieces()).to.be.equal(MAX_REFUNGIBLE_PIECES);58 59 await expect(collection.mintToken(alice, MAX_REFUNGIBLE_PIECES + 1n))60 .to.eventually.be.rejectedWith(/refungible\.WrongRefungiblePieces/);61 });62 63 itSub('RPC method tokenOnewrs for refungible collection and token', async ({helper, privateKey}) => {64 const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};65 const facelessCrowd = Array(7).fill(0).map((_, i) => ({Substrate: privateKey(`//Alice+${i}`).address}));6667 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});6869 const token = await collection.mintToken(alice, 10_000n);7071 await token.transfer(alice, {Substrate: bob.address}, 1000n);72 await token.transfer(alice, ethAcc, 900n);73 74 for (let i = 0; i < 7; i++) {75 await token.transfer(alice, facelessCrowd[i], 50n * BigInt(i + 1));76 } 7778 const owners = await token.getTop10Owners();7980 // What to expect81 expect(owners).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);82 expect(owners.length).to.be.equal(10);83 84 const eleven = privateKey('//ALice+11');85 expect(await token.transfer(alice, {Substrate: eleven.address}, 10n)).to.be.true;86 expect((await token.getTop10Owners()).length).to.be.equal(10);87 });88 89 itSub('Transfer token pieces', async ({helper}) => {90 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});91 const token = await collection.mintToken(alice, 100n);9293 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);94 expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;95 96 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);97 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);98 99 await expect(token.transfer(alice, {Substrate: bob.address}, 41n))100 .to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);101 });102103 itSub('Create multiple tokens', async ({helper}) => {104 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});105 // TODO: fix mintMultipleTokens106 // await collection.mintMultipleTokens(alice, [107 // {owner: {Substrate: alice.address}, pieces: 1n},108 // {owner: {Substrate: alice.address}, pieces: 2n},109 // {owner: {Substrate: alice.address}, pieces: 100n},110 // ]);111 await helper.rft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, [112 {pieces: 1n}, 113 {pieces: 2n}, 114 {pieces: 100n},115 ]);116 const lastTokenId = await collection.getLastTokenId();117 expect(lastTokenId).to.be.equal(3);118 expect(await collection.getTokenBalance(lastTokenId, {Substrate: alice.address})).to.be.equal(100n);119 });120121 itSub('Burn some pieces', async ({helper}) => {122 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});123 const token = await collection.mintToken(alice, 100n);124 expect(await collection.isTokenExists(token.tokenId)).to.be.true;125 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);126 expect((await token.burn(alice, 99n)).success).to.be.true;127 expect(await collection.isTokenExists(token.tokenId)).to.be.true;128 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(1n);129 });130131 itSub('Burn all pieces', async ({helper}) => {132 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});133 const token = await collection.mintToken(alice, 100n);134 135 expect(await collection.isTokenExists(token.tokenId)).to.be.true;136 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);137138 expect((await token.burn(alice, 100n)).success).to.be.true;139 expect(await collection.isTokenExists(token.tokenId)).to.be.false;140 });141142 itSub('Burn some pieces for multiple users', async ({helper}) => {143 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});144 const token = await collection.mintToken(alice, 100n);145146 expect(await collection.isTokenExists(token.tokenId)).to.be.true;147 148 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);149 expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;150151 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);152 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);153154 expect((await token.burn(alice, 40n)).success).to.be.true;155156 expect(await collection.isTokenExists(token.tokenId)).to.be.true;157 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);158159 expect((await token.burn(bob, 59n)).success).to.be.true;160161 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(1n);162 expect(await collection.isTokenExists(token.tokenId)).to.be.true;163164 expect((await token.burn(bob, 1n)).success).to.be.true;165166 expect(await collection.isTokenExists(token.tokenId)).to.be.false;167 });168169 itSub('Set allowance for token', async ({helper}) => {170 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});171 const token = await collection.mintToken(alice, 100n);172 173 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);174175 expect(await token.approve(alice, {Substrate: bob.address}, 60n)).to.be.true;176 expect(await token.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(60n);177178 expect(await token.transferFrom(bob, {Substrate: alice.address}, {Substrate: bob.address}, 20n)).to.be.true;179 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(80n);180 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(20n);181 expect(await token.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(40n);182 });183184 itSub('Repartition', async ({helper}) => {185 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});186 const token = await collection.mintToken(alice, 100n);187188 expect(await token.repartition(alice, 200n)).to.be.true;189 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(200n);190 expect(await token.getTotalPieces()).to.be.equal(200n);191 192 expect(await token.transfer(alice, {Substrate: bob.address}, 110n)).to.be.true;193 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(90n);194 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(110n);195 196 await expect(token.repartition(alice, 80n))197 .to.eventually.be.rejectedWith(/refungible\.RepartitionWhileNotOwningAllPieces/);198 199 expect(await token.transfer(alice, {Substrate: bob.address}, 90n)).to.be.true;200 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);201 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(200n);202203 expect(await token.repartition(bob, 150n)).to.be.true;204 await expect(token.transfer(bob, {Substrate: alice.address}, 160n))205 .to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);206 });207208 itSub('Repartition with increased amount', async ({helper}) => {209 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});210 const token = await collection.mintToken(alice, 100n);211 await token.repartition(alice, 200n);212 const chainEvents = helper.chainLog.slice(-1)[0].events.map((x: any) => x.event);213 expect(chainEvents).to.include.deep.members([{214 method: 'ItemCreated',215 section: 'common',216 index: '0x4202',217 data: [ 218 helper.api!.createType('u32', collection.collectionId).toHuman(), 219 helper.api!.createType('u32', token.tokenId).toHuman(),220 {Substrate: alice.address}, 221 '100',222 ],223 }]);224 });225226 itSub('Repartition with decreased amount', async ({helper}) => {227 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});228 const token = await collection.mintToken(alice, 100n);229 await token.repartition(alice, 50n);230 const chainEvents = helper.chainLog.slice(-1)[0].events.map((x: any) => x.event);231 expect(chainEvents).to.include.deep.members([{232 method: 'ItemDestroyed',233 section: 'common',234 index: '0x4203',235 data: [ 236 helper.api!.createType('u32', collection.collectionId).toHuman(), 237 helper.api!.createType('u32', token.tokenId).toHuman(),238 {Substrate: alice.address}, 239 '50',240 ],241 }]);242 });243 244 itSub('Create new collection with properties', async ({helper}) => {245 const properties = [{key: 'key1', value: 'val1'}];246 const tokenPropertyPermissions = [{key: 'key1', permission: {tokenOwner: true, mutable: false, collectionAdmin: true}}];247 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test', properties, tokenPropertyPermissions});248 const info = await collection.getData();249 expect(info?.raw.properties).to.be.deep.equal(properties);250 expect(info?.raw.tokenPropertyPermissions).to.be.deep.equal(tokenPropertyPermissions);251 });252});2531// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from './util/playgrounds';1920const MAX_REFUNGIBLE_PIECES = 1_000_000_000_000_000_000_000n;2122describe('integration test: Refungible functionality:', async () => {23 let alice: IKeyringPair;24 let bob: IKeyringPair;2526 before(async function() {27 await usingPlaygrounds(async (helper, privateKey) => {28 requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);2930 const donor = privateKey('//Alice');31 [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);32 });33 });34 35 itSub('Create refungible collection and token', async ({helper}) => {36 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});3738 const itemCountBefore = await collection.getLastTokenId();39 const token = await collection.mintToken(alice, 100n);40 41 const itemCountAfter = await collection.getLastTokenId();42 43 // What to expect44 expect(token?.tokenId).to.be.gte(itemCountBefore);45 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);46 expect(itemCountAfter.toString()).to.be.equal(token?.tokenId.toString());47 });48 49 itSub('Checking RPC methods when interacting with maximum allowed values (MAX_REFUNGIBLE_PIECES)', async ({helper}) => {50 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});51 52 const token = await collection.mintToken(alice, MAX_REFUNGIBLE_PIECES);53 54 expect(await collection.getTokenBalance(token.tokenId, {Substrate: alice.address})).to.be.equal(MAX_REFUNGIBLE_PIECES);55 56 await collection.transferToken(alice, token.tokenId, {Substrate: bob.address}, MAX_REFUNGIBLE_PIECES);57 expect(await collection.getTokenBalance(token.tokenId, {Substrate: bob.address})).to.be.equal(MAX_REFUNGIBLE_PIECES);58 expect(await token.getTotalPieces()).to.be.equal(MAX_REFUNGIBLE_PIECES);59 60 await expect(collection.mintToken(alice, MAX_REFUNGIBLE_PIECES + 1n))61 .to.eventually.be.rejectedWith(/refungible\.WrongRefungiblePieces/);62 });63 64 itSub('RPC method tokenOnewrs for refungible collection and token', async ({helper, privateKey}) => {65 const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};66 const facelessCrowd = Array(7).fill(0).map((_, i) => ({Substrate: privateKey(`//Alice+${i}`).address}));6768 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});6970 const token = await collection.mintToken(alice, 10_000n);7172 await token.transfer(alice, {Substrate: bob.address}, 1000n);73 await token.transfer(alice, ethAcc, 900n);74 75 for (let i = 0; i < 7; i++) {76 await token.transfer(alice, facelessCrowd[i], 50n * BigInt(i + 1));77 } 7879 const owners = await token.getTop10Owners();8081 // What to expect82 expect(owners).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);83 expect(owners.length).to.be.equal(10);84 85 const eleven = privateKey('//ALice+11');86 expect(await token.transfer(alice, {Substrate: eleven.address}, 10n)).to.be.true;87 expect((await token.getTop10Owners()).length).to.be.equal(10);88 });89 90 itSub('Transfer token pieces', async ({helper}) => {91 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});92 const token = await collection.mintToken(alice, 100n);9394 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);95 expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;96 97 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);98 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);99 100 await expect(token.transfer(alice, {Substrate: bob.address}, 41n))101 .to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);102 });103104 itSub('Create multiple tokens', async ({helper}) => {105 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});106 // TODO: fix mintMultipleTokens107 // await collection.mintMultipleTokens(alice, [108 // {owner: {Substrate: alice.address}, pieces: 1n},109 // {owner: {Substrate: alice.address}, pieces: 2n},110 // {owner: {Substrate: alice.address}, pieces: 100n},111 // ]);112 await helper.rft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, [113 {pieces: 1n}, 114 {pieces: 2n}, 115 {pieces: 100n},116 ]);117 const lastTokenId = await collection.getLastTokenId();118 expect(lastTokenId).to.be.equal(3);119 expect(await collection.getTokenBalance(lastTokenId, {Substrate: alice.address})).to.be.equal(100n);120 });121122 itSub('Burn some pieces', async ({helper}) => {123 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});124 const token = await collection.mintToken(alice, 100n);125 expect(await collection.isTokenExists(token.tokenId)).to.be.true;126 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);127 expect((await token.burn(alice, 99n)).success).to.be.true;128 expect(await collection.isTokenExists(token.tokenId)).to.be.true;129 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(1n);130 });131132 itSub('Burn all pieces', async ({helper}) => {133 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});134 const token = await collection.mintToken(alice, 100n);135 136 expect(await collection.isTokenExists(token.tokenId)).to.be.true;137 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);138139 expect((await token.burn(alice, 100n)).success).to.be.true;140 expect(await collection.isTokenExists(token.tokenId)).to.be.false;141 });142143 itSub('Burn some pieces for multiple users', async ({helper}) => {144 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});145 const token = await collection.mintToken(alice, 100n);146147 expect(await collection.isTokenExists(token.tokenId)).to.be.true;148 149 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);150 expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;151152 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);153 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);154155 expect((await token.burn(alice, 40n)).success).to.be.true;156157 expect(await collection.isTokenExists(token.tokenId)).to.be.true;158 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);159160 expect((await token.burn(bob, 59n)).success).to.be.true;161162 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(1n);163 expect(await collection.isTokenExists(token.tokenId)).to.be.true;164165 expect((await token.burn(bob, 1n)).success).to.be.true;166167 expect(await collection.isTokenExists(token.tokenId)).to.be.false;168 });169170 itSub('Set allowance for token', async ({helper}) => {171 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});172 const token = await collection.mintToken(alice, 100n);173 174 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);175176 expect(await token.approve(alice, {Substrate: bob.address}, 60n)).to.be.true;177 expect(await token.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(60n);178179 expect(await token.transferFrom(bob, {Substrate: alice.address}, {Substrate: bob.address}, 20n)).to.be.true;180 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(80n);181 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(20n);182 expect(await token.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(40n);183 });184185 itSub('Repartition', async ({helper}) => {186 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});187 const token = await collection.mintToken(alice, 100n);188189 expect(await token.repartition(alice, 200n)).to.be.true;190 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(200n);191 expect(await token.getTotalPieces()).to.be.equal(200n);192 193 expect(await token.transfer(alice, {Substrate: bob.address}, 110n)).to.be.true;194 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(90n);195 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(110n);196 197 await expect(token.repartition(alice, 80n))198 .to.eventually.be.rejectedWith(/refungible\.RepartitionWhileNotOwningAllPieces/);199 200 expect(await token.transfer(alice, {Substrate: bob.address}, 90n)).to.be.true;201 expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);202 expect(await token.getBalance({Substrate: bob.address})).to.be.equal(200n);203204 expect(await token.repartition(bob, 150n)).to.be.true;205 await expect(token.transfer(bob, {Substrate: alice.address}, 160n))206 .to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);207 });208209 itSub('Repartition with increased amount', async ({helper}) => {210 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});211 const token = await collection.mintToken(alice, 100n);212 await token.repartition(alice, 200n);213 const chainEvents = helper.chainLog.slice(-1)[0].events;214 expect(chainEvents).to.deep.include({215 section: 'common',216 method: 'ItemCreated',217 index: [66, 2],218 data: [219 collection.collectionId,220 token.tokenId,221 {substrate: alice.address}, 222 100n,223 ],224 phase: {applyExtrinsic: 2},225 });226 });227228 itSub('Repartition with decreased amount', async ({helper}) => {229 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});230 const token = await collection.mintToken(alice, 100n);231 await token.repartition(alice, 50n);232 const chainEvents = helper.chainLog.slice(-1)[0].events;233 expect(chainEvents).to.deep.include({234 method: 'ItemDestroyed',235 section: 'common',236 index: [66, 3],237 data: [238 collection.collectionId,239 token.tokenId,240 {substrate: alice.address}, 241 50n,242 ],243 phase: {applyExtrinsic: 2},244 });245 });246 247 itSub('Create new collection with properties', async ({helper}) => {248 const properties = [{key: 'key1', value: 'val1'}];249 const tokenPropertyPermissions = [{key: 'key1', permission: {tokenOwner: true, mutable: false, collectionAdmin: true}}];250 const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test', properties, tokenPropertyPermissions});251 const info = await collection.getData();252 expect(info?.raw.properties).to.be.deep.equal(properties);253 expect(info?.raw.tokenPropertyPermissions).to.be.deep.equal(tokenPropertyPermissions);254 });255});256tests/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,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 {
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -9,7 +9,7 @@
import {ApiInterfaceEvents} 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;
}
}
@@ -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/*, 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());
+ events = this.eventHelper.extractEvents(result);
}
catch(e) {
if(!(e as object).hasOwnProperty('status')) throw e;