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
--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -14,136 +14,122 @@
 // 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 {ApiPromise} from '@polkadot/api';
+import {IKeyringPair} from '@polkadot/types/types';
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';
+import {usingPlaygrounds} from './util/playgrounds';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
 
+let donor: IKeyringPair;
+
+before(async () => {
+  await usingPlaygrounds(async (_, privateKeyWrapper) => {
+    donor = privateKeyWrapper('//Alice');
+  });
+});
+
 describe('Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
   it('Add collection admin.', async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const alice = privateKeyWrapper('//Alice');
-      const bob = privateKeyWrapper('//Bob');
+    await usingPlaygrounds(async (helper) => {
+      const [alice, bob] = await helper.arrange.creteAccounts([10n, 10n], donor);
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
 
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.owner.toString()).to.be.equal(alice.address);
+      const collection = await helper.collection.getData(collectionId);
+      expect(collection?.normalizedOwner!).to.be.equal(alice.address);
 
-      const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
-      await submitTransactionAsync(alice, changeAdminTx);
+      await helper.nft.addAdmin(alice, collectionId, {Substrate: bob.address});
 
-      const adminListAfterAddAdmin = await getAdminList(api, collectionId);
-      expect(adminListAfterAddAdmin).to.be.deep.contains(normalizeAccountId(bob.address));
+      const adminListAfterAddAdmin = await helper.collection.getAdmins(collectionId);
+      expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});
     });
   });
 });
 
 describe('Negative Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
   it("Not owner can't add collection admin.", async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const alice = privateKeyWrapper('//Alice');
-      const bob = privateKeyWrapper('//Bob');
-      const charlie = privateKeyWrapper('//CHARLIE');
+    await usingPlaygrounds(async (helper) => {
+      const [alice, bob, charlie] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
 
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.owner.toString()).to.be.equal(alice.address);
+      const collection = await helper.collection.getData(collectionId);
+      expect(collection?.normalizedOwner).to.be.equal(alice.address);
 
-      const adminListAfterAddAdmin = await getAdminList(api, collectionId);
-      expect(adminListAfterAddAdmin).to.be.not.deep.contains(normalizeAccountId(bob.address));
+      const changeAdminTxBob = async () => helper.collection.addAdmin(bob, collectionId, {Substrate: bob.address});
+      const changeAdminTxCharlie = async () => helper.collection.addAdmin(bob, collectionId, {Substrate: charlie.address});
+      await expect(changeAdminTxCharlie()).to.be.rejected;
+      await expect(changeAdminTxBob()).to.be.rejected;
 
-      const changeAdminTxCharlie = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(charlie.address));
-      await expect(submitTransactionAsync(bob, changeAdminTxCharlie)).to.be.rejected;
-     
-      const adminListAfterAddNewAdmin = await getAdminList(api, collectionId);
-      expect(adminListAfterAddNewAdmin).to.be.not.deep.contains(normalizeAccountId(bob.address));
-      expect(adminListAfterAddNewAdmin).to.be.not.deep.contains(normalizeAccountId(charlie.address));
+      const adminListAfterAddAdmin = await helper.collection.getAdmins(collectionId);
+      expect(adminListAfterAddAdmin).to.be.not.deep.contains({Substrate: charlie.address});
+      expect(adminListAfterAddAdmin).to.be.not.deep.contains({Substrate: bob.address});
     });
   });
 
   it("Admin can't add collection admin.", async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const alice = privateKeyWrapper('//Alice');
-      const bob = privateKeyWrapper('//Bob');
-      const charlie = privateKeyWrapper('//CHARLIE');
+    await usingPlaygrounds(async (helper) => {
+      const [alice, bob, charlie] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);
+      const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
 
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.owner.toString()).to.be.equal(alice.address);
+      await collection.addAdmin(alice, {Substrate: bob.address});
 
-      const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
-      await submitTransactionAsync(alice, changeAdminTx);
+      const adminListAfterAddAdmin = await collection.getAdmins();
+      expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: bob.address});
 
-      const adminListAfterAddAdmin = await getAdminList(api, collectionId);
-      expect(adminListAfterAddAdmin).to.be.deep.contains(normalizeAccountId(bob.address));
+      const changeAdminTxCharlie = async () => collection.addAdmin(bob, {Substrate: charlie.address});
+      await expect(changeAdminTxCharlie()).to.be.rejected;
 
-      const changeAdminTxCharlie = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(charlie.address));
-      await expect(submitTransactionAsync(bob, changeAdminTxCharlie)).to.be.rejected;
-     
-      const adminListAfterAddNewAdmin = await getAdminList(api, collectionId);
-      expect(adminListAfterAddNewAdmin).to.be.deep.contains(normalizeAccountId(bob.address));
-      expect(adminListAfterAddNewAdmin).to.be.not.deep.contains(normalizeAccountId(charlie.address));
+      const adminListAfterAddNewAdmin = await collection.getAdmins();
+      expect(adminListAfterAddNewAdmin).to.be.deep.contains({Substrate: bob.address});
+      expect(adminListAfterAddNewAdmin).to.be.not.deep.contains({Substrate: charlie.address});
     });
   });
 
   it("Can't add collection admin of not existing collection.", async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
+    await usingPlaygrounds(async (helper) => {
+      const [alice, bob] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);
       // tslint:disable-next-line: no-bitwise
       const collectionId = (1 << 32) - 1;
-      const alice = privateKeyWrapper('//Alice');
-      const bob = privateKeyWrapper('//Bob');
 
-      const changeOwnerTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
-      await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;
+      const addAdminTx = async () => helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});
+      await expect(addAdminTx()).to.be.rejected;
 
       // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
-      await createCollectionExpectSuccess();
+      await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
     });
   });
 
   it("Can't add an admin to a destroyed collection.", async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const alice = privateKeyWrapper('//Alice');
-      const bob = privateKeyWrapper('//Bob');
-      await destroyCollectionExpectSuccess(collectionId);
-      const changeOwnerTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
-      await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;
+    await usingPlaygrounds(async (helper) => {
+      const [alice, bob] = await helper.arrange.creteAccounts([10n, 10n, 10n], donor);
+      const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
+
+      await collection.burn(alice);
+      const addAdminTx = async () => collection.addAdmin(alice, {Substrate: bob.address});
+      await expect(addAdminTx()).to.be.rejected;
 
       // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
-      await createCollectionExpectSuccess();
+      await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
     });
   });
 
   it('Add an admin to a collection that has reached the maximum number of admins limit', async () => {
-    await usingApi(async (api: ApiPromise, privateKeyWrapper) => {
-      const alice = privateKeyWrapper('//Alice');
-      const accounts = [
-        privateKeyWrapper('//AdminTest/1').address,
-        privateKeyWrapper('//AdminTest/2').address,
-        privateKeyWrapper('//AdminTest/3').address,
-        privateKeyWrapper('//AdminTest/4').address,
-        privateKeyWrapper('//AdminTest/5').address,
-        privateKeyWrapper('//AdminTest/6').address,
-        privateKeyWrapper('//AdminTest/7').address,
-      ];
-      const collectionId = await createCollectionExpectSuccess();
+    await usingPlaygrounds(async (helper) => {
+      const [alice, ...accounts] = await helper.arrange.creteAccounts([10n, 0n, 0n, 0n, 0n, 0n, 0n, 0n], donor);
+      const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
 
-      const chainAdminLimit = (api.consts.common.collectionAdminsLimit as any).toNumber();
+      const chainAdminLimit = (helper.api!.consts.common.collectionAdminsLimit as any).toNumber();
       expect(chainAdminLimit).to.be.equal(5);
 
       for (let i = 0; i < chainAdminLimit; i++) {
-        await addCollectionAdminExpectSuccess(alice, collectionId, accounts[i]);
-        const adminListAfterAddAdmin = await getAdminList(api, collectionId);
-        expect(adminListAfterAddAdmin).to.be.deep.contains(normalizeAccountId(accounts[i]));
+        await collection.addAdmin(alice, {Substrate: accounts[i].address});
+        const adminListAfterAddAdmin = await collection.getAdmins();
+        expect(adminListAfterAddAdmin).to.be.deep.contains({Substrate: accounts[i].address});
       }
 
-      const tx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(accounts[chainAdminLimit]));
-      await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
+      const addExtraAdminTx = async () => collection.addAdmin(alice, {Substrate: accounts[chainAdminLimit].address});
+      await expect(addExtraAdminTx()).to.be.rejected;
     });
   });
 });
modifiedtests/src/util/playgrounds/index.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/index.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {IKeyringPair} from '@polkadot/types/types';5import {UniqueHelper} from './unique';6import config from '../../config';7import '../../interfaces/augment-api-events';8import * as defs from '../../interfaces/definitions';9import {ApiPromise, WsProvider} from '@polkadot/api';101112class SilentLogger {13  log(msg: any, level: any): void {}14  level = {15    ERROR: 'ERROR' as const,16    WARNING: 'WARNING' as const,17    INFO: 'INFO' as const,18  };19}202122class DevUniqueHelper extends UniqueHelper {23  async connect(wsEndpoint: string, listeners?: any): Promise<void> {24    const wsProvider = new WsProvider(wsEndpoint);25    this.api = new ApiPromise({26      provider: wsProvider, 27      signedExtensions: {28        ContractHelpers: {29          extrinsic: {},30          payload: {},31        },32        FakeTransactionFinalizer: {33          extrinsic: {},34          payload: {},35        },36      },37      rpc: {38        unique: defs.unique.rpc,39        rmrk: defs.rmrk.rpc,40        eth: {41          feeHistory: {42            description: 'Dummy',43            params: [],44            type: 'u8',45          },46          maxPriorityFeePerGas: {47            description: 'Dummy',48            params: [],49            type: 'u8',50          },51        },52      },53    });54    await this.api.isReadyOrError;55    this.network = await UniqueHelper.detectNetwork(this.api);56  }57}5859export const usingPlaygrounds = async (code: (helper: UniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {60  // TODO: Remove, this is temporary: Filter unneeded API output61  // (Jaco promised it will be removed in the next version)62  const consoleErr = console.error;63  const consoleLog = console.log;64  const consoleWarn = console.warn;6566  const outFn = (printer: any) => (...args: any[]) => {67    for (const arg of args) {68      if (typeof arg !== 'string')69        continue;70      if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))71        return;72    }73    printer(...args);74  };7576  console.error = outFn(consoleErr.bind(console));77  console.log = outFn(consoleLog.bind(console));78  console.warn = outFn(consoleWarn.bind(console));79  const helper = new DevUniqueHelper(new SilentLogger());8081  try {82    await helper.connect(config.substrateUrl);83    const ss58Format = helper.chain.getChainProperties().ss58Format;84    const privateKey = (seed: string) => helper.util.fromSeed(seed, ss58Format);85    await code(helper, privateKey);86  } 87  finally {88    await helper.disconnect();89    console.error = consoleErr;90    console.log = consoleLog;91    console.warn = consoleWarn;92  }93};
after · tests/src/util/playgrounds/index.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {IKeyringPair} from '@polkadot/types/types';5import config from '../../config';6import '../../interfaces/augment-api-events';7import {DevUniqueHelper} from './unique.dev';89class SilentLogger {10  log(msg: any, level: any): void { }11  level = {12    ERROR: 'ERROR' as const,13    WARNING: 'WARNING' as const,14    INFO: 'INFO' as const,15  };16}1718export const usingPlaygrounds = async (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {19  // TODO: Remove, this is temporary: Filter unneeded API output20  // (Jaco promised it will be removed in the next version)21  const consoleErr = console.error;22  const consoleLog = console.log;23  const consoleWarn = console.warn;2425  const outFn = (printer: any) => (...args: any[]) => {26    for (const arg of args) {27      if (typeof arg !== 'string')28        continue;29      if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))30        return;31    }32    printer(...args);33  };3435  console.error = outFn(consoleErr.bind(console));36  console.log = outFn(consoleLog.bind(console));37  console.warn = outFn(consoleWarn.bind(console));38  const helper = new DevUniqueHelper(new SilentLogger());3940  try {41    await helper.connect(config.substrateUrl);42    const ss58Format = helper.chain.getChainProperties().ss58Format;43    const privateKey = (seed: string) => helper.util.fromSeed(seed, ss58Format);44    await code(helper, privateKey);45  }46  finally {47    await helper.disconnect();48    console.error = consoleErr;49    console.log = consoleLog;50    console.warn = consoleWarn;51  }52};
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);