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

difftreelog

add extension class to playgrounds

Max Andreev2022-08-23parent: #83d3baa.patch.diff
in: master
+ add creteAccounts method
+ move addCollectionAdmin tests to playgrounds

4 files changed

modifiedtests/src/addCollectionAdmin.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 {ApiPromise} from '@polkadot/api';17import {IKeyringPair} from '@polkadot/types/types';
18import chai from 'chai';18import chai from 'chai';
19import chaiAsPromised from 'chai-as-promised';19import chaiAsPromised from 'chai-as-promised';
20import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
21import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';20import {usingPlaygrounds} from './util/playgrounds';
2221
23chai.use(chaiAsPromised);22chai.use(chaiAsPromised);
24const expect = chai.expect;23const expect = chai.expect;
24
25let donor: IKeyringPair;
26
27before(async () => {
28 await usingPlaygrounds(async (_, privateKeyWrapper) => {
29 donor = privateKeyWrapper('//Alice');
30 });
31});
2532
26describe('Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {33describe('Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
27 it('Add collection admin.', async () => {34 it('Add collection admin.', async () => {
28 await usingApi(async (api, privateKeyWrapper) => {35 await usingPlaygrounds(async (helper) => {
29 const collectionId = await createCollectionExpectSuccess();36 const [alice, bob] = await helper.arrange.creteAccounts([10n, 10n], donor);
30 const alice = privateKeyWrapper('//Alice');37 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
31 const bob = privateKeyWrapper('//Bob');
3238
33 const collection = await queryCollectionExpectSuccess(api, collectionId);39 const collection = await helper.collection.getData(collectionId);
34 expect(collection.owner.toString()).to.be.equal(alice.address);40 expect(collection?.normalizedOwner!).to.be.equal(alice.address);
3541
36 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));42 await helper.nft.addAdmin(alice, collectionId, {Substrate: bob.address});
37 await submitTransactionAsync(alice, changeAdminTx);
3843
39 const adminListAfterAddAdmin = await getAdminList(api, collectionId);44 const adminListAfterAddAdmin = await helper.collection.getAdmins(collectionId);
40 expect(adminListAfterAddAdmin).to.be.deep.contains(normalizeAccountId(bob.address));45 expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});
41 });46 });
42 });47 });
43});48});
4449
45describe('Negative Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {50describe('Negative Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
46 it("Not owner can't add collection admin.", async () => {51 it("Not owner can't add collection admin.", async () => {
47 await usingApi(async (api, privateKeyWrapper) => {52 await usingPlaygrounds(async (helper) => {
48 const collectionId = await createCollectionExpectSuccess();53 const [alice, bob, charlie] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);
49 const alice = privateKeyWrapper('//Alice');
50 const bob = privateKeyWrapper('//Bob');
51 const charlie = privateKeyWrapper('//CHARLIE');54 const {collectionId} = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
5255
53 const collection = await queryCollectionExpectSuccess(api, collectionId);56 const collection = await helper.collection.getData(collectionId);
54 expect(collection.owner.toString()).to.be.equal(alice.address);57 expect(collection?.normalizedOwner).to.be.equal(alice.address);
5558
56 const adminListAfterAddAdmin = await getAdminList(api, collectionId);59 const changeAdminTxBob = async () => helper.collection.addAdmin(bob, collectionId, {Substrate: bob.address});
57 expect(adminListAfterAddAdmin).to.be.not.deep.contains(normalizeAccountId(bob.address));
58
59 const changeAdminTxCharlie = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(charlie.address));60 const changeAdminTxCharlie = async () => helper.collection.addAdmin(bob, collectionId, {Substrate: charlie.address});
60 await expect(submitTransactionAsync(bob, changeAdminTxCharlie)).to.be.rejected;61 await expect(changeAdminTxCharlie()).to.be.rejected;
61 62 await expect(changeAdminTxBob()).to.be.rejected;
63
62 const adminListAfterAddNewAdmin = await getAdminList(api, collectionId);64 const adminListAfterAddAdmin = await helper.collection.getAdmins(collectionId);
63 expect(adminListAfterAddNewAdmin).to.be.not.deep.contains(normalizeAccountId(bob.address));65 expect(adminListAfterAddAdmin).to.be.not.deep.contains({Substrate: charlie.address});
64 expect(adminListAfterAddNewAdmin).to.be.not.deep.contains(normalizeAccountId(charlie.address));66 expect(adminListAfterAddAdmin).to.be.not.deep.contains({Substrate: bob.address});
65 });67 });
66 });68 });
6769
68 it("Admin can't add collection admin.", async () => {70 it("Admin can't add collection admin.", async () => {
69 await usingApi(async (api, privateKeyWrapper) => {71 await usingPlaygrounds(async (helper) => {
70 const collectionId = await createCollectionExpectSuccess();72 const [alice, bob, charlie] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);
71 const alice = privateKeyWrapper('//Alice');
72 const bob = privateKeyWrapper('//Bob');
73 const charlie = privateKeyWrapper('//CHARLIE');
74
75 const collection = await queryCollectionExpectSuccess(api, collectionId);73 const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
76 expect(collection.owner.toString()).to.be.equal(alice.address);
7774
78 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));75 await collection.addAdmin(alice, {Substrate: bob.address});
79 await submitTransactionAsync(alice, changeAdminTx);
8076
81 const adminListAfterAddAdmin = await getAdminList(api, collectionId);77 const adminListAfterAddAdmin = await collection.getAdmins();
82 expect(adminListAfterAddAdmin).to.be.deep.contains(normalizeAccountId(bob.address));78 expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});
8379
84 const changeAdminTxCharlie = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(charlie.address));80 const changeAdminTxCharlie = async () => collection.addAdmin(bob, {Substrate: charlie.address});
85 await expect(submitTransactionAsync(bob, changeAdminTxCharlie)).to.be.rejected;81 await expect(changeAdminTxCharlie()).to.be.rejected;
86 82
87 const adminListAfterAddNewAdmin = await getAdminList(api, collectionId);83 const adminListAfterAddNewAdmin = await collection.getAdmins();
88 expect(adminListAfterAddNewAdmin).to.be.deep.contains(normalizeAccountId(bob.address));84 expect(adminListAfterAddNewAdmin).to.be.deep.contains({Substrate: bob.address});
89 expect(adminListAfterAddNewAdmin).to.be.not.deep.contains(normalizeAccountId(charlie.address));85 expect(adminListAfterAddNewAdmin).to.be.not.deep.contains({Substrate: charlie.address});
90 });86 });
91 });87 });
9288
93 it("Can't add collection admin of not existing collection.", async () => {89 it("Can't add collection admin of not existing collection.", async () => {
94 await usingApi(async (api, privateKeyWrapper) => {90 await usingPlaygrounds(async (helper) => {
91 const [alice, bob] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);
95 // tslint:disable-next-line: no-bitwise92 // tslint:disable-next-line: no-bitwise
96 const collectionId = (1 << 32) - 1;93 const collectionId = (1 << 32) - 1;
97 const alice = privateKeyWrapper('//Alice');
98 const bob = privateKeyWrapper('//Bob');
9994
100 const changeOwnerTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));95 const addAdminTx = async () => helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});
101 await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;96 await expect(addAdminTx()).to.be.rejected;
10297
103 // Verifying that nothing bad happened (network is live, new collections can be created, etc.)98 // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
104 await createCollectionExpectSuccess();99 await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
105 });100 });
106 });101 });
107102
108 it("Can't add an admin to a destroyed collection.", async () => {103 it("Can't add an admin to a destroyed collection.", async () => {
109 await usingApi(async (api, privateKeyWrapper) => {104 await usingPlaygrounds(async (helper) => {
110 const collectionId = await createCollectionExpectSuccess();105 const [alice, bob] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);
111 const alice = privateKeyWrapper('//Alice');106 const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
112 const bob = privateKeyWrapper('//Bob');107
113 await destroyCollectionExpectSuccess(collectionId);108 await collection.burn(alice);
114 const changeOwnerTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));109 const addAdminTx = async () => collection.addAdmin(alice, {Substrate: bob.address});
115 await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;110 await expect(addAdminTx()).to.be.rejected;
116111
117 // Verifying that nothing bad happened (network is live, new collections can be created, etc.)112 // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
118 await createCollectionExpectSuccess();113 await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
119 });114 });
120 });115 });
121116
122 it('Add an admin to a collection that has reached the maximum number of admins limit', async () => {117 it('Add an admin to a collection that has reached the maximum number of admins limit', async () => {
123 await usingApi(async (api: ApiPromise, privateKeyWrapper) => {118 await usingPlaygrounds(async (helper) => {
124 const alice = privateKeyWrapper('//Alice');
125 const accounts = [119 const [alice, ...accounts] = await helper.arrange.creteAccounts([10n, 0n, 0n, 0n, 0n, 0n, 0n, 0n], donor);
126 privateKeyWrapper('//AdminTest/1').address,
127 privateKeyWrapper('//AdminTest/2').address,
128 privateKeyWrapper('//AdminTest/3').address,
129 privateKeyWrapper('//AdminTest/4').address,
130 privateKeyWrapper('//AdminTest/5').address,
131 privateKeyWrapper('//AdminTest/6').address,
132 privateKeyWrapper('//AdminTest/7').address,
133 ];
134 const collectionId = await createCollectionExpectSuccess();120 const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
135121
136 const chainAdminLimit = (api.consts.common.collectionAdminsLimit as any).toNumber();122 const chainAdminLimit = (helper.api!.consts.common.collectionAdminsLimit as any).toNumber();
137 expect(chainAdminLimit).to.be.equal(5);123 expect(chainAdminLimit).to.be.equal(5);
138124
139 for (let i = 0; i < chainAdminLimit; i++) {125 for (let i = 0; i < chainAdminLimit; i++) {
140 await addCollectionAdminExpectSuccess(alice, collectionId, accounts[i]);126 await collection.addAdmin(alice, {Substrate: accounts[i].address});
141 const adminListAfterAddAdmin = await getAdminList(api, collectionId);127 const adminListAfterAddAdmin = await collection.getAdmins();
142 expect(adminListAfterAddAdmin).to.be.deep.contains(normalizeAccountId(accounts[i]));128 expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: accounts[i].address});
143 }129 }
144130
145 const tx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(accounts[chainAdminLimit]));131 const addExtraAdminTx = async () => collection.addAdmin(alice, {Substrate: accounts[chainAdminLimit].address});
146 await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;132 await expect(addExtraAdminTx()).to.be.rejected;
147 });133 });
148 });134 });
149});135});
modifiedtests/src/util/playgrounds/index.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -2,15 +2,12 @@
 // SPDX-License-Identifier: Apache-2.0
 
 import {IKeyringPair} from '@polkadot/types/types';
-import {UniqueHelper} from './unique';
 import config from '../../config';
 import '../../interfaces/augment-api-events';
-import * as defs from '../../interfaces/definitions';
-import {ApiPromise, WsProvider} from '@polkadot/api';
-
+import {DevUniqueHelper} from './unique.dev';
 
 class SilentLogger {
-  log(msg: any, level: any): void {}
+  log(msg: any, level: any): void { }
   level = {
     ERROR: 'ERROR' as const,
     WARNING: 'WARNING' as const,
@@ -18,45 +15,7 @@
   };
 }
 
-
-class DevUniqueHelper extends UniqueHelper {
-  async connect(wsEndpoint: string, listeners?: any): Promise<void> {
-    const wsProvider = new WsProvider(wsEndpoint);
-    this.api = new ApiPromise({
-      provider: wsProvider, 
-      signedExtensions: {
-        ContractHelpers: {
-          extrinsic: {},
-          payload: {},
-        },
-        FakeTransactionFinalizer: {
-          extrinsic: {},
-          payload: {},
-        },
-      },
-      rpc: {
-        unique: defs.unique.rpc,
-        rmrk: defs.rmrk.rpc,
-        eth: {
-          feeHistory: {
-            description: 'Dummy',
-            params: [],
-            type: 'u8',
-          },
-          maxPriorityFeePerGas: {
-            description: 'Dummy',
-            params: [],
-            type: 'u8',
-          },
-        },
-      },
-    });
-    await this.api.isReadyOrError;
-    this.network = await UniqueHelper.detectNetwork(this.api);
-  }
-}
-
-export const usingPlaygrounds = async (code: (helper: UniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
+export const usingPlaygrounds = async (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
   // TODO: Remove, this is temporary: Filter unneeded API output
   // (Jaco promised it will be removed in the next version)
   const consoleErr = console.error;
@@ -83,7 +42,7 @@
     const ss58Format = helper.chain.getChainProperties().ss58Format;
     const privateKey = (seed: string) => helper.util.fromSeed(seed, ss58Format);
     await code(helper, privateKey);
-  } 
+  }
   finally {
     await helper.disconnect();
     console.error = consoleErr;
addedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -0,0 +1,90 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// SPDX-License-Identifier: Apache-2.0
+
+import {mnemonicGenerate} from '@polkadot/util-crypto';
+import {UniqueHelper} from './unique';
+import {IKeyringPair} from '@polkadot/types/types';
+import {ApiPromise, WsProvider} from '@polkadot/api';
+import * as defs from '../../interfaces/definitions';
+
+
+export class DevUniqueHelper extends UniqueHelper {
+  /**
+   * Arrange methods for tests
+   */
+  arrange: UniqueArrange;
+
+  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
+    super(logger);
+    this.arrange = new UniqueArrange(this);
+  }
+
+  async connect(wsEndpoint: string, listeners?: any): Promise<void> {
+    const wsProvider = new WsProvider(wsEndpoint);
+    this.api = new ApiPromise({
+      provider: wsProvider,
+      signedExtensions: {
+        ContractHelpers: {
+          extrinsic: {},
+          payload: {},
+        },
+        FakeTransactionFinalizer: {
+          extrinsic: {},
+          payload: {},
+        },
+      },
+      rpc: {
+        unique: defs.unique.rpc,
+        rmrk: defs.rmrk.rpc,
+        eth: {
+          feeHistory: {
+            description: 'Dummy',
+            params: [],
+            type: 'u8',
+          },
+          maxPriorityFeePerGas: {
+            description: 'Dummy',
+            params: [],
+            type: 'u8',
+          },
+        },
+      },
+    });
+    await this.api.isReadyOrError;
+    this.network = await UniqueHelper.detectNetwork(this.api);
+  }
+}
+
+class UniqueArrange {
+  helper: UniqueHelper;
+
+  constructor(helper: UniqueHelper) {
+    this.helper = helper;
+  }
+
+  /**
+   * Generates accounts with the specified UNQ token balance 
+   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.
+   * @param donor donor account for balances
+   * @returns array of newly created accounts
+   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 
+   */
+  creteAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {
+    let nonce = await this.helper.chain.getNonce(donor.address);
+    const tokenNominal = this.helper.balance.getOneTokenNominal();
+    const transactions = [];
+    const accounts = [];
+    for (const balance of balances) {
+      const recepient = this.helper.util.fromSeed(mnemonicGenerate());
+      accounts.push(recepient);
+      if (balance !== 0n) {
+        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, balance * tokenNominal]);
+        transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));
+        nonce++;
+      }
+    }
+
+    await Promise.all(transactions);
+    return accounts;
+  };
+}
\ No newline at end of file
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -439,7 +439,7 @@
     return this.transactionStatus.FAIL;
   }
 
-  signTransaction(sender: TSigner, transaction: any, label = 'transaction', options = null) {
+  signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {
     const sign = (callback: any) => {
       if(options !== null) return transaction.signAndSend(sender, options, callback);
       return transaction.signAndSend(sender, callback);