git.delta.rocks / unique-network / refs/commits / eba9da942ea3

difftreelog

test(util-playgrounds) modifications and additions of all stripes

Fahrrader2022-09-08parent: #fc6e541.patch.diff
in: master

5 files changed

modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -64,6 +64,7 @@
     "testBurnItem": "mocha --timeout 9999999 -r ts-node/register ./**/burnItem.test.ts",
     "testAdminTransferAndBurn": "mocha --timeout 9999999 -r ts-node/register ./**/adminTransferAndBurn.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",
     "testContractSponsoring": "mocha --timeout 9999999 -r ts-node/register ./**/contractSponsoring.test.ts",
     "testEnableContractSponsoring": "mocha --timeout 9999999 -r ts-node/register ./**/enableContractSponsoring.test.ts",
@@ -71,7 +72,6 @@
     "testSetContractSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setContractSponsoringRateLimit.test.ts",
     "testSetOffchainSchema": "mocha --timeout 9999999 -r ts-node/register ./**/setOffchainSchema.test.ts",
     "testOverflow": "mocha --timeout 9999999 -r ts-node/register ./**/overflow.test.ts",
-    "testSetVariableMetadataSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetadataSponsoringRateLimit.test.ts",
     "testInflation": "mocha --timeout 9999999 -r ts-node/register ./**/inflation.test.ts",
     "testScheduler": "mocha --timeout 9999999 -r ts-node/register ./**/scheduler.test.ts",
     "testSchedulingEVM": "mocha --timeout 9999999 -r ts-node/register ./**/eth/scheduling.test.ts",
modifiedtests/src/util/playgrounds/index.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -2,6 +2,7 @@
 // SPDX-License-Identifier: Apache-2.0
 
 import {IKeyringPair} from '@polkadot/types/types';
+import {Context} from 'mocha';
 import config from '../../config';
 import '../../interfaces/augment-api-events';
 import {DevUniqueHelper, SilentLogger, SilentConsole} from './unique.dev';
@@ -24,3 +25,39 @@
     silentConsole.disable();
   }
 };
+
+export enum Pallets {
+  Inflation = 'inflation',
+  RmrkCore = 'rmrkcore',
+  RmrkEquip = 'rmrkequip',
+  ReFungible = 'refungible',
+  Fungible = 'fungible',
+  NFT = 'nonfungible',
+  Scheduler = 'scheduler',
+}
+
+export function requirePalletsOrSkip(test: Context, helper: DevUniqueHelper, requiredPallets: string[]) {
+  const missingPallets = helper.fetchMissingPalletNames(requiredPallets);
+    
+  if (missingPallets.length > 0) {
+    const skipMsg = `\tSkipping test '${test.test?.title}'.\n\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;
+    console.warn('\x1b[38:5:208m%s\x1b[0m', skipMsg);
+    test.skip();
+  }
+}
+
+export async function itSub(name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
+  (opts.only ? it.only : 
+    opts.skip ? it.skip : it)(name, async function () {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      if (opts.requiredPallets) {
+        requirePalletsOrSkip(this, helper, opts.requiredPallets);
+      }
+      
+      await cb({helper, privateKey});
+    });
+  });
+}
+itSub.only = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {only: true});
+itSub.skip = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {skip: true});
+itSub.ifWithPallets = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {requiredPallets: required});
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -102,9 +102,9 @@
 }
 
 export interface ICollectionCreationOptions {
-  name: string | number[];
-  description: string | number[];
-  tokenPrefix: string | number[];
+  name?: string | number[];
+  description?: string | number[];
+  tokenPrefix?: string | number[];
   mode?: {
     nft?: null;
     refungible?: null;
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {mnemonicGenerate} from '@polkadot/util-crypto';5import {UniqueHelper} from './unique';6import {ApiPromise, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';8import {IKeyringPair} from '@polkadot/types/types';91011export class SilentLogger {12  log(_msg: any, _level: any): void { }13  level = {14    ERROR: 'ERROR' as const,15    WARNING: 'WARNING' as const,16    INFO: 'INFO' as const,17  };18}192021export class SilentConsole {22  // TODO: Remove, this is temporary: Filter unneeded API output23  // (Jaco promised it will be removed in the next version)24  consoleErr: any;25  consoleLog: any;26  consoleWarn: any;2728  constructor() {29    this.consoleErr = console.error;30    this.consoleLog = console.log;31    this.consoleWarn = console.warn;32  }3334  enable() {  35    const outFn = (printer: any) => (...args: any[]) => {36      for (const arg of args) {37        if (typeof arg !== 'string')38          continue;39        if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis: UniqueApi/2, RmrkApi/1') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')40          return;41      }42      printer(...args);43    };44  45    console.error = outFn(this.consoleErr.bind(console));46    console.log = outFn(this.consoleLog.bind(console));47    console.warn = outFn(this.consoleWarn.bind(console));48  }4950  disable() {51    console.error = this.consoleErr;52    console.log = this.consoleLog;53    console.warn = this.consoleWarn;54  }55}565758export class DevUniqueHelper extends UniqueHelper {59  /**60   * Arrange methods for tests61   */62  arrange: ArrangeGroup;6364  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {65    super(logger);66    this.arrange = new ArrangeGroup(this);67  }6869  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {70    const wsProvider = new WsProvider(wsEndpoint);71    this.api = new ApiPromise({72      provider: wsProvider,73      signedExtensions: {74        ContractHelpers: {75          extrinsic: {},76          payload: {},77        },78        FakeTransactionFinalizer: {79          extrinsic: {},80          payload: {},81        },82      },83      rpc: {84        unique: defs.unique.rpc,85        rmrk: defs.rmrk.rpc,86        eth: {87          feeHistory: {88            description: 'Dummy',89            params: [],90            type: 'u8',91          },92          maxPriorityFeePerGas: {93            description: 'Dummy',94            params: [],95            type: 'u8',96          },97        },98      },99    });100    await this.api.isReadyOrError;101    this.network = await UniqueHelper.detectNetwork(this.api);102  }103}104105class ArrangeGroup {106  helper: UniqueHelper;107108  constructor(helper: UniqueHelper) {109    this.helper = helper;110  }111112  /**113   * Generates accounts with the specified UNQ token balance 114   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.115   * @param donor donor account for balances116   * @returns array of newly created accounts117   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 118   */119  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {120    let nonce = await this.helper.chain.getNonce(donor.address);121    const tokenNominal = this.helper.balance.getOneTokenNominal();122    const transactions = [];123    const accounts: IKeyringPair[] = [];124    for (const balance of balances) {125      const recepient = this.helper.util.fromSeed(mnemonicGenerate());126      accounts.push(recepient);127      if (balance !== 0n) {128        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, balance * tokenNominal]);129        transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));130        nonce++;131      }132    }133134    await Promise.all(transactions).catch(_e => {});135    136    //#region TODO remove this region, when nonce problem will be solved137    const checkBalances = async () => {138      let isSuccess = true;139      for (let i = 0; i < balances.length; i++) {140        const balance = await this.helper.balance.getSubstrate(accounts[i].address);141        if (balance !== balances[i] * tokenNominal) {142          isSuccess = false;143          break;144        }145      }146      return isSuccess;147    };148149    let accountsCreated = false;150    // checkBalances retry up to 5 blocks151    for (let index = 0; index < 5; index++) {152      accountsCreated = await checkBalances();153      if(accountsCreated) break;154      await this.waitNewBlocks(1);155    }156157    if (!accountsCreated) throw Error('Accounts generation failed');158    //#endregion159160    return accounts;161  };162 163  /**164   * Wait for specified bnumber of blocks165   * @param blocksCount number of blocks to wait166   * @returns 167   */168  async waitNewBlocks(blocksCount = 1): Promise<void> {169    // eslint-disable-next-line no-async-promise-executor170    const promise = new Promise<void>(async (resolve) => {171      const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {172        if (blocksCount > 0) {173          blocksCount--;174        } else {175          unsubscribe();176          resolve();177        }178      });179    });180    return promise;181  }182}
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -11,13 +11,12 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
 
-const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {
+export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {
   const address = {} as ICrossAccountId;
   if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;
   if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;
   return address;
 };
-
 
 const nesting = {
   toChecksumAddress(address: string): string {
@@ -440,6 +439,16 @@
     if(typeof signer === 'string') return signer;
     return signer.address;
   }
+
+  fetchAllPalletNames(): string[] {
+    if(this.api === null) throw Error('API not initialized');
+    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());
+  }
+  
+  fetchMissingPalletNames(requiredPallets: string[]): string[] {
+    const palletNames = this.fetchAllPalletNames();
+    return requiredPallets.filter(p => !palletNames.includes(p));
+  }
 }
 
 
@@ -476,7 +485,9 @@
   }
 
   /**
-   * Get information about the collection with additional data, including the number of tokens it contains, its administrators, the normalized address of the collection's owner, and decoded name and description.
+   * Get information about the collection with additional data, 
+   * including the number of tokens it contains, its administrators, 
+   * the normalized address of the collection's owner, and decoded name and description.
    * 
    * @param collectionId ID of collection
    * @example await getData(2)
@@ -504,42 +515,50 @@
       collectionData[key] = this.helper.util.vec2str(humanCollection[key]);
     }
 
-    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;
+    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) 
+      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) 
+      : 0;
     collectionData.admins = await this.getAdmins(collectionId);
 
     return collectionData;
   }
 
   /**
-   * Get the normalized addresses of the collection's administrators.
+   * Get the addresses of the collection's administrators, optionally normalized.
    * 
    * @param collectionId ID of collection
+   * @param normalize whether to normalize the addresses to the default ss58 format
    * @example await getAdmins(1)
    * @returns array of administrators
    */
-  async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {
-    const normalized = [];
-    for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {
-      if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});
-      else normalized.push(admin);
-    }
-    return normalized;
+  async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {
+    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();
+
+    return normalize
+      ? admins.map((address: any) => {
+        return address.Substrate
+          ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}
+          : address;
+      }) 
+      : admins;
   }
 
   /**
-   * Get the normalized addresses added to the collection allow-list.
+   * Get the addresses added to the collection allow-list, optionally normalized.
    * @param collectionId ID of collection
+   * @param normalize whether to normalize the addresses to the default ss58 format
    * @example await getAllowList(1)
    * @returns array of allow-listed addresses
    */
-  async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {
-    const normalized = [];
+  async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {
     const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();
-    for (const address of allowListed) {
-      if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});
-      else normalized.push(address);
-    }
-    return normalized;
+    return normalize
+      ? allowListed.map((address: any) => {
+        return address.Substrate
+          ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}
+          : address;
+      }) 
+      : allowListed;
   }
 
   /**
@@ -572,7 +591,7 @@
   }
 
   /**
-   * Sets the sponsor for the collection (Requires the Substrate address).
+   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.
    * 
    * @param signer keyring of signer
    * @param collectionId ID of collection
@@ -609,6 +628,24 @@
   }
 
   /**
+   * Removes the sponsor of a collection, regardless if it consented or not.
+   * 
+   * @param signer keyring of signer
+   * @param collectionId ID of collection
+   * @example removeSponsor(aliceKeyring, 10)
+   * @returns ```true``` if extrinsic success, otherwise ```false```
+   */
+  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {
+    const result = await this.helper.executeExtrinsic(
+      signer,
+      'api.tx.unique.removeCollectionSponsor', [collectionId],
+      true,
+    );
+
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');
+  }
+
+  /**
    * Sets the limits of the collection. At least one limit must be specified for a correct call.
    * 
    * @param signer keyring of signer
@@ -2004,6 +2041,10 @@
     return await this.helper.collection.confirmSponsorship(signer, this.collectionId);
   }
 
+  async removeSponsor(signer: TSigner) {
+    return await this.helper.collection.removeSponsor(signer, this.collectionId);
+  }
+
   async setLimits(signer: TSigner, limits: ICollectionLimits) {
     return await this.helper.collection.setLimits(signer, this.collectionId, limits);
   }
@@ -2016,8 +2057,8 @@
     return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);
   }
 
-  async enableAllowList(signer: TSigner, value = true/*: 'Normal' | 'AllowList' = 'AllowList'*/) {
-    return await this.setPermissions(signer, value ? {access: 'AllowList', mintMode: true} : {access: 'Normal'});
+  async enableCertainPermissions(signer: TSigner, accessMode: 'AllowList' | 'Normal' | undefined = 'AllowList', mintMode: boolean | undefined = true) {
+    return await this.setPermissions(signer, {access: accessMode, mintMode: mintMode});
   }
 
   async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {