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
before · tests/src/addCollectionAdmin.test.ts
1// 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 {ApiPromise} from '@polkadot/api';18import chai from 'chai';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';2223chai.use(chaiAsPromised);24const expect = chai.expect;2526describe('Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {27  it('Add collection admin.', async () => {28    await usingApi(async (api, privateKeyWrapper) => {29      const collectionId = await createCollectionExpectSuccess();30      const alice = privateKeyWrapper('//Alice');31      const bob = privateKeyWrapper('//Bob');3233      const collection = await queryCollectionExpectSuccess(api, collectionId);34      expect(collection.owner.toString()).to.be.equal(alice.address);3536      const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));37      await submitTransactionAsync(alice, changeAdminTx);3839      const adminListAfterAddAdmin = await getAdminList(api, collectionId);40      expect(adminListAfterAddAdmin).to.be.deep.contains(normalizeAccountId(bob.address));41    });42  });43});4445describe('Negative Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {46  it("Not owner can't add collection admin.", async () => {47    await usingApi(async (api, privateKeyWrapper) => {48      const collectionId = await createCollectionExpectSuccess();49      const alice = privateKeyWrapper('//Alice');50      const bob = privateKeyWrapper('//Bob');51      const charlie = privateKeyWrapper('//CHARLIE');5253      const collection = await queryCollectionExpectSuccess(api, collectionId);54      expect(collection.owner.toString()).to.be.equal(alice.address);5556      const adminListAfterAddAdmin = await getAdminList(api, collectionId);57      expect(adminListAfterAddAdmin).to.be.not.deep.contains(normalizeAccountId(bob.address));5859      const changeAdminTxCharlie = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(charlie.address));60      await expect(submitTransactionAsync(bob, changeAdminTxCharlie)).to.be.rejected;61     62      const adminListAfterAddNewAdmin = await getAdminList(api, collectionId);63      expect(adminListAfterAddNewAdmin).to.be.not.deep.contains(normalizeAccountId(bob.address));64      expect(adminListAfterAddNewAdmin).to.be.not.deep.contains(normalizeAccountId(charlie.address));65    });66  });6768  it("Admin can't add collection admin.", async () => {69    await usingApi(async (api, privateKeyWrapper) => {70      const collectionId = await createCollectionExpectSuccess();71      const alice = privateKeyWrapper('//Alice');72      const bob = privateKeyWrapper('//Bob');73      const charlie = privateKeyWrapper('//CHARLIE');7475      const collection = await queryCollectionExpectSuccess(api, collectionId);76      expect(collection.owner.toString()).to.be.equal(alice.address);7778      const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));79      await submitTransactionAsync(alice, changeAdminTx);8081      const adminListAfterAddAdmin = await getAdminList(api, collectionId);82      expect(adminListAfterAddAdmin).to.be.deep.contains(normalizeAccountId(bob.address));8384      const changeAdminTxCharlie = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(charlie.address));85      await expect(submitTransactionAsync(bob, changeAdminTxCharlie)).to.be.rejected;86     87      const adminListAfterAddNewAdmin = await getAdminList(api, collectionId);88      expect(adminListAfterAddNewAdmin).to.be.deep.contains(normalizeAccountId(bob.address));89      expect(adminListAfterAddNewAdmin).to.be.not.deep.contains(normalizeAccountId(charlie.address));90    });91  });9293  it("Can't add collection admin of not existing collection.", async () => {94    await usingApi(async (api, privateKeyWrapper) => {95      // tslint:disable-next-line: no-bitwise96      const collectionId = (1 << 32) - 1;97      const alice = privateKeyWrapper('//Alice');98      const bob = privateKeyWrapper('//Bob');99100      const changeOwnerTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));101      await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;102103      // Verifying that nothing bad happened (network is live, new collections can be created, etc.)104      await createCollectionExpectSuccess();105    });106  });107108  it("Can't add an admin to a destroyed collection.", async () => {109    await usingApi(async (api, privateKeyWrapper) => {110      const collectionId = await createCollectionExpectSuccess();111      const alice = privateKeyWrapper('//Alice');112      const bob = privateKeyWrapper('//Bob');113      await destroyCollectionExpectSuccess(collectionId);114      const changeOwnerTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));115      await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;116117      // Verifying that nothing bad happened (network is live, new collections can be created, etc.)118      await createCollectionExpectSuccess();119    });120  });121122  it('Add an admin to a collection that has reached the maximum number of admins limit', async () => {123    await usingApi(async (api: ApiPromise, privateKeyWrapper) => {124      const alice = privateKeyWrapper('//Alice');125      const accounts = [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();135136      const chainAdminLimit = (api.consts.common.collectionAdminsLimit as any).toNumber();137      expect(chainAdminLimit).to.be.equal(5);138139      for (let i = 0; i < chainAdminLimit; i++) {140        await addCollectionAdminExpectSuccess(alice, collectionId, accounts[i]);141        const adminListAfterAddAdmin = await getAdminList(api, collectionId);142        expect(adminListAfterAddAdmin).to.be.deep.contains(normalizeAccountId(accounts[i]));143      }144145      const tx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(accounts[chainAdminLimit]));146      await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;147    });148  });149});
after · tests/src/addCollectionAdmin.test.ts
1// 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 chai from 'chai';19import chaiAsPromised from 'chai-as-promised';20import {usingPlaygrounds} from './util/playgrounds';2122chai.use(chaiAsPromised);23const expect = chai.expect;2425let donor: IKeyringPair;2627before(async () => {28  await usingPlaygrounds(async (_, privateKeyWrapper) => {29    donor = privateKeyWrapper('//Alice');30  });31});3233describe('Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {34  it('Add collection admin.', async () => {35    await usingPlaygrounds(async (helper) => {36      const [alice, bob] = await helper.arrange.creteAccounts([10n, 10n], donor);37      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});3839      const collection = await helper.collection.getData(collectionId);40      expect(collection?.normalizedOwner!).to.be.equal(alice.address);4142      await helper.nft.addAdmin(alice, collectionId, {Substrate: bob.address});4344      const adminListAfterAddAdmin = await helper.collection.getAdmins(collectionId);45      expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});46    });47  });48});4950describe('Negative Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {51  it("Not owner can't add collection admin.", async () => {52    await usingPlaygrounds(async (helper) => {53      const [alice, bob, charlie] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);54      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});5556      const collection = await helper.collection.getData(collectionId);57      expect(collection?.normalizedOwner).to.be.equal(alice.address);5859      const changeAdminTxBob = async () => helper.collection.addAdmin(bob, collectionId, {Substrate: bob.address});60      const changeAdminTxCharlie = async () => helper.collection.addAdmin(bob, collectionId, {Substrate: charlie.address});61      await expect(changeAdminTxCharlie()).to.be.rejected;62      await expect(changeAdminTxBob()).to.be.rejected;6364      const adminListAfterAddAdmin = await helper.collection.getAdmins(collectionId);65      expect(adminListAfterAddAdmin).to.be.not.deep.contains({Substrate: charlie.address});66      expect(adminListAfterAddAdmin).to.be.not.deep.contains({Substrate: bob.address});67    });68  });6970  it("Admin can't add collection admin.", async () => {71    await usingPlaygrounds(async (helper) => {72      const [alice, bob, charlie] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);73      const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});7475      await collection.addAdmin(alice, {Substrate: bob.address});7677      const adminListAfterAddAdmin = await collection.getAdmins();78      expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});7980      const changeAdminTxCharlie = async () => collection.addAdmin(bob, {Substrate: charlie.address});81      await expect(changeAdminTxCharlie()).to.be.rejected;8283      const adminListAfterAddNewAdmin = await collection.getAdmins();84      expect(adminListAfterAddNewAdmin).to.be.deep.contains({Substrate: bob.address});85      expect(adminListAfterAddNewAdmin).to.be.not.deep.contains({Substrate: charlie.address});86    });87  });8889  it("Can't add collection admin of not existing collection.", async () => {90    await usingPlaygrounds(async (helper) => {91      const [alice, bob] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);92      // tslint:disable-next-line: no-bitwise93      const collectionId = (1 << 32) - 1;9495      const addAdminTx = async () => helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});96      await expect(addAdminTx()).to.be.rejected;9798      // Verifying that nothing bad happened (network is live, new collections can be created, etc.)99      await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});100    });101  });102103  it("Can't add an admin to a destroyed collection.", async () => {104    await usingPlaygrounds(async (helper) => {105      const [alice, bob] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);106      const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});107108      await collection.burn(alice);109      const addAdminTx = async () => collection.addAdmin(alice, {Substrate: bob.address});110      await expect(addAdminTx()).to.be.rejected;111112      // Verifying that nothing bad happened (network is live, new collections can be created, etc.)113      await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});114    });115  });116117  it('Add an admin to a collection that has reached the maximum number of admins limit', async () => {118    await usingPlaygrounds(async (helper) => {119      const [alice, ...accounts] = await helper.arrange.creteAccounts([10n, 0n, 0n, 0n, 0n, 0n, 0n, 0n], donor);120      const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});121122      const chainAdminLimit = (helper.api!.consts.common.collectionAdminsLimit as any).toNumber();123      expect(chainAdminLimit).to.be.equal(5);124125      for (let i = 0; i < chainAdminLimit; i++) {126        await collection.addAdmin(alice, {Substrate: accounts[i].address});127        const adminListAfterAddAdmin = await collection.getAdmins();128        expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: accounts[i].address});129      }130131      const addExtraAdminTx = async () => collection.addAdmin(alice, {Substrate: accounts[chainAdminLimit].address});132      await expect(addExtraAdminTx()).to.be.rejected;133    });134  });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);