git.delta.rocks / unique-network / refs/commits / 9cb35ec055ed

difftreelog

Merge pull request #571 from UniqueNetwork/test/intermittent-playgrounds-update

ut-akuznetsov2022-09-08parents: #fc6e541 #eba9da9.patch.diff
in: master
Tests (utility in playgrounds): various modifications and additions

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
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -118,14 +118,15 @@
    */
   createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {
     let nonce = await this.helper.chain.getNonce(donor.address);
+    const ss58Format = this.helper.chain.getChainProperties().ss58Format;
     const tokenNominal = this.helper.balance.getOneTokenNominal();
     const transactions = [];
     const accounts: IKeyringPair[] = [];
     for (const balance of balances) {
-      const recepient = this.helper.util.fromSeed(mnemonicGenerate());
-      accounts.push(recepient);
+      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);
+      accounts.push(recipient);
       if (balance !== 0n) {
-        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, balance * tokenNominal]);
+        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);
         transactions.push(this.helper.signTransaction(donor, tx, 'account generation', {nonce}));
         nonce++;
       }
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
11import {IKeyringPair} from '@polkadot/types/types';11import {IKeyringPair} from '@polkadot/types/types';
12import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';12import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
1313
14const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {14export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {
15 const address = {} as ICrossAccountId;15 const address = {} as ICrossAccountId;
16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;
17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;
441 return signer.address;440 return signer.address;
442 }441 }
442
443 fetchAllPalletNames(): string[] {
444 if(this.api === null) throw Error('API not initialized');
445 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());
446 }
447
448 fetchMissingPalletNames(requiredPallets: string[]): string[] {
449 const palletNames = this.fetchAllPalletNames();
450 return requiredPallets.filter(p => !palletNames.includes(p));
451 }
443}452}
444453
445454
475 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();484 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();
476 }485 }
477486
478 /**487 /**
479 * 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.488 * Get information about the collection with additional data,
489 * including the number of tokens it contains, its administrators,
490 * the normalized address of the collection's owner, and decoded name and description.
480 * 491 *
481 * @param collectionId ID of collection492 * @param collectionId ID of collection
482 * @example await getData(2)493 * @example await getData(2)
483 * @returns collection information object494 * @returns collection information object
484 */495 */
485 async getData(collectionId: number): Promise<{496 async getData(collectionId: number): Promise<{
486 id: number;497 id: number;
487 name: string;498 name: string;
510 return collectionData;523 return collectionData;
511 }524 }
512525
513 /**526 /**
514 * Get the normalized addresses of the collection's administrators.527 * Get the addresses of the collection's administrators, optionally normalized.
515 * 528 *
516 * @param collectionId ID of collection529 * @param collectionId ID of collection
530 * @param normalize whether to normalize the addresses to the default ss58 format
517 * @example await getAdmins(1)531 * @example await getAdmins(1)
518 * @returns array of administrators532 * @returns array of administrators
519 */533 */
520 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {534 async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {
521 const normalized = [];535 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();
522 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {536
537 return normalize
523 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});538 ? admins.map((address: any) => {
524 else normalized.push(admin);539 return address.Substrate
525 }540 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}
541 : address;
542 })
526 return normalized;543 : admins;
527 }544 }
528545
529 /**546 /**
530 * Get the normalized addresses added to the collection allow-list.547 * Get the addresses added to the collection allow-list, optionally normalized.
531 * @param collectionId ID of collection548 * @param collectionId ID of collection
549 * @param normalize whether to normalize the addresses to the default ss58 format
532 * @example await getAllowList(1)550 * @example await getAllowList(1)
533 * @returns array of allow-listed addresses551 * @returns array of allow-listed addresses
534 */552 */
535 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {553 async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {
536 const normalized = [];
537 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();554 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();
555 return normalize
538 for (const address of allowListed) {556 ? allowListed.map((address: any) => {
539 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});557 return address.Substrate
540 else normalized.push(address);558 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}
541 }559 : address;
560 })
542 return normalized;561 : allowListed;
543 }562 }
544563
545 /**564 /**
571 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');590 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');
572 }591 }
573592
574 /**593 /**
575 * Sets the sponsor for the collection (Requires the Substrate address).594 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.
576 * 595 *
577 * @param signer keyring of signer596 * @param signer keyring of signer
578 * @param collectionId ID of collection597 * @param collectionId ID of collection
579 * @param sponsorAddress Sponsor substrate address598 * @param sponsorAddress Sponsor substrate address
580 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")599 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")
581 * @returns ```true``` if extrinsic success, otherwise ```false```600 * @returns ```true``` if extrinsic success, otherwise ```false```
582 */601 */
583 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {602 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {
584 const result = await this.helper.executeExtrinsic(603 const result = await this.helper.executeExtrinsic(
585 signer,604 signer,
608 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');627 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');
609 }628 }
629
630 /**
631 * Removes the sponsor of a collection, regardless if it consented or not.
632 *
633 * @param signer keyring of signer
634 * @param collectionId ID of collection
635 * @example removeSponsor(aliceKeyring, 10)
636 * @returns ```true``` if extrinsic success, otherwise ```false```
637 */
638 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {
639 const result = await this.helper.executeExtrinsic(
640 signer,
641 'api.tx.unique.removeCollectionSponsor', [collectionId],
642 true,
643 );
644
645 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');
646 }
610647
611 /**648 /**
612 * Sets the limits of the collection. At least one limit must be specified for a correct call.649 * Sets the limits of the collection. At least one limit must be specified for a correct call.
2004 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2041 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);
2005 }2042 }
2043
2044 async removeSponsor(signer: TSigner) {
2045 return await this.helper.collection.removeSponsor(signer, this.collectionId);
2046 }
20062047
2007 async setLimits(signer: TSigner, limits: ICollectionLimits) {2048 async setLimits(signer: TSigner, limits: ICollectionLimits) {
2008 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2049 return await this.helper.collection.setLimits(signer, this.collectionId, limits);
2016 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2057 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);
2017 }2058 }
20182059
2019 async enableAllowList(signer: TSigner, value = true/*: 'Normal' | 'AllowList' = 'AllowList'*/) {2060 async enableCertainPermissions(signer: TSigner, accessMode: 'AllowList' | 'Normal' | undefined = 'AllowList', mintMode: boolean | undefined = true) {
2020 return await this.setPermissions(signer, value ? {access: 'AllowList', mintMode: true} : {access: 'Normal'});2061 return await this.setPermissions(signer, {access: accessMode, mintMode: mintMode});
2021 }2062 }
20222063
2023 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2064 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {