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

difftreelog

set limits test scenarios

kpozdnikin2020-12-31parent: #49640f3.patch.diff
in: master

5 files changed

modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -19,6 +19,7 @@
     "test": "mocha --timeout 9999999 -r ts-node/register ./**/*.test.ts",
     "load": "mocha --timeout 9999999 -r ts-node/register ./**/*.load.ts",
     "testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",
+    "testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
     "testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
     "testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts"
   },
addedtests/src/setCollectionLimits.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/setCollectionLimits.test.ts
@@ -0,0 +1,145 @@
+// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
+import { ApiPromise, Keyring } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import usingApi, { submitTransactionAsync } from './substrate/substrate-api';
+import { ICollectionInterface } from './types';
+import {
+  createCollectionExpectSuccess, getCreatedCollectionCount,
+  getCreateItemResult,
+  getDetailedCollectionInfo,
+} from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+let alice: IKeyringPair;
+let bob: IKeyringPair;
+let collectionIdForTesting: number;
+
+const accountTokenOwnershipLimit = 0;
+const sponsoredDataSize = 0;
+const sponsoredMintSize = 0;
+const tokenLimit = 0;
+
+describe('hooks', () => {
+  before(async () => {
+    await usingApi(async () => {
+      const keyring = new Keyring({ type: 'sr25519' });
+      alice = keyring.addFromUri('//Alice');
+    });
+  });
+  it('choose or create collection for testing', async () => {
+    await usingApi(async () => {
+      collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});
+      console.log('collectionIdForTesting', collectionIdForTesting);
+    });
+  });
+});
+
+describe('setCollectionLimits positive', () => {
+  let tx;
+  before(async () => {
+    await usingApi(async () => {
+      const keyring = new Keyring({ type: 'sr25519' });
+      alice = keyring.addFromUri('//Alice');
+    });
+  });
+  it('execute setCollectionLimits with predefined params ', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      tx = api.tx.nft.setCollectionLimits(
+        collectionIdForTesting,
+        {
+          accountTokenOwnershipLimit,
+          sponsoredDataSize,
+          sponsoredMintSize,
+          tokenLimit,
+        },
+      );
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getCreateItemResult(events);
+      // tslint:disable-next-line:no-unused-expression
+      expect(result.success).to.be.true;
+    });
+  });
+  it('get collection limits defined in previous test', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting) as ICollectionInterface;
+      expect(collectionInfo.Limits.AccountTokenOwnershipLimit.toNumber()).to.be.equal(accountTokenOwnershipLimit);
+      expect(collectionInfo.Limits.SponsoredMintSize.toNumber()).to.be.equal(sponsoredMintSize);
+      expect(collectionInfo.Limits.TokenLimit.toNumber()).to.be.equal(tokenLimit);
+      expect(collectionInfo.Limits.SponsorTimeout.toNumber()).to.be.equal(sponsoredDataSize);
+    });
+  });
+});
+
+describe('setCollectionLimits negative', () => {
+  let tx;
+  before(async () => {
+    await usingApi(async () => {
+      const keyring = new Keyring({ type: 'sr25519' });
+      alice = keyring.addFromUri('//Alice');
+      bob = keyring.addFromUri('//Bob');
+    });
+  });
+  it('execute setCollectionLimits for not exists collection', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      const collectionCount = await getCreatedCollectionCount(api);
+      const nonExistedCollectionId = collectionCount + 1;
+      tx = api.tx.nft.setCollectionLimits(
+        nonExistedCollectionId,
+        {
+          accountTokenOwnershipLimit,
+          sponsoredDataSize,
+          sponsoredMintSize,
+          tokenLimit,
+        },
+      );
+      try {
+        await submitTransactionAsync(alice, tx);
+      } catch (e) {
+        // tslint:disable-next-line:no-unused-expression
+        expect(e).to.be.exist;
+      }
+    });
+  });
+  it('execute setCollectionLimits from user who is not owner of this collection', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      tx = api.tx.nft.setCollectionLimits(
+        collectionIdForTesting,
+        {
+          accountTokenOwnershipLimit,
+          sponsoredDataSize,
+          sponsoredMintSize,
+          tokenLimit,
+        },
+      );
+      try {
+        await submitTransactionAsync(bob, tx);
+      } catch (e) {
+        // tslint:disable-next-line:no-unused-expression
+        expect(e).to.be.exist;
+      }
+    });
+  });
+  it('execute setCollectionLimits with incorrect limits', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      tx = api.tx.nft.setCollectionLimits(
+        collectionIdForTesting,
+        {
+          accountTokenOwnershipLimit: 'awdawd',
+          sponsorTransferTimeout: 'awd',
+          sponsoredDataSize: '12312312312312312',
+          tokenLimit: '-100',
+        },
+      );
+      try {
+        await submitTransactionAsync(alice, tx);
+      } catch (e) {
+        // tslint:disable-next-line:no-unused-expression
+        expect(e).to.be.exist;
+      }
+    });
+  });
+});
modifiedtests/src/setSchemaVersion.test.tsdiffbeforeafterboth
--- a/tests/src/setSchemaVersion.test.ts
+++ b/tests/src/setSchemaVersion.test.ts
@@ -1,4 +1,4 @@
-// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
+// https://unique-network.readthedocs.io/en/latest/jsapi.html#setschemaversion
 import { ApiPromise, Keyring } from '@polkadot/api';
 import { IKeyringPair } from '@polkadot/types/types';
 import BN from 'bn.js';
@@ -6,7 +6,13 @@
 import chaiAsPromised from 'chai-as-promised';
 import usingApi, { submitTransactionAsync } from './substrate/substrate-api';
 import { ICollectionInterface } from './types';
-import { createCollectionExpectSuccess, destroyCollectionExpectSuccess, getCreateItemResult } from './util/helpers';
+import {
+  createCollectionExpectSuccess,
+  destroyCollectionExpectSuccess,
+  getCreatedCollectionCount,
+  getCreateItemResult,
+  getDetailedCollectionInfo,
+} from './util/helpers';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -19,16 +25,6 @@
 2. Save just created collection id.
 3. Use this id for setSchemaVersion.
 */
-
-const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)
-  : Promise<ICollectionInterface | null> => {
-  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;
-};
-
-const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {
-  // set global object - collectionsCount
-  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();
-};
 
 describe('hooks', () => {
   before(async () => {
@@ -57,7 +53,7 @@
       tx = api.tx.nft.setSchemaVersion(collectionIdForTesting, 'Unique');
       const events = await submitTransactionAsync(alice, tx);
       const result = getCreateItemResult(events);
-      const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting);
+      const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting) as ICollectionInterface;
       // tslint:disable-next-line:no-unused-expression
       expect(result.success).to.be.true;
       // tslint:disable-next-line:no-unused-expression
@@ -72,7 +68,7 @@
       tx = api.tx.nft.setSchemaVersion(collectionIdForTesting, 'ImageURL');
       const events = await submitTransactionAsync(alice, tx);
       const result = getCreateItemResult(events);
-      const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting);
+      const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting) as ICollectionInterface;
       // tslint:disable-next-line:no-unused-expression
       expect(result.success).to.be.true;
       // tslint:disable-next-line:no-unused-expression
modifiedtests/src/types.tsdiffbeforeafterboth
--- a/tests/src/types.ts
+++ b/tests/src/types.ts
@@ -7,14 +7,20 @@
   // constOnChainSchema
   Description: [BN, BN]; // utf16
   isReFungible: boolean;
+  Limits: {
+    AccountTokenOwnershipLimit: BN;
+    SponsoredMintSize: BN;
+    TokenLimit: BN;
+    SponsorTimeout: BN;
+  };
   MintMode: boolean;
   Mode: {
     Nft: null;
   };
   Name: [BN, BN]; // utf16
   OffchainSchema: [Uint8Array];
+  Owner: [Uint8Array];
   SchemaVersion: string;
-  Owner: [Uint8Array];
   // prefix
   // sponsor
   // tokenPrefix
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { ApiPromise, Keyring } from "@polkadot/api";10import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "../substrate/substrate-api";11import privateKey from '../substrate/privateKey';12import { alicesPublicKey, nullPublicKey } from "../accounts";13import { strToUTF16, utf16ToStr, hexToStr } from '../util/util';14import { IKeyringPair } from "@polkadot/types/types";15import { BigNumber } from 'bignumber.js';16import { Struct, Enum } from '@polkadot/types/codec';17import { u128 } from '@polkadot/types/primitive';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122type GenericResult = {23  success: boolean,24};2526type CreateCollectionResult = {27  success: boolean,28  collectionId: number29};3031type CreateItemResult = {32  success: boolean,33  collectionId: number,34  itemId: number35};3637export function getGenericResult(events: EventRecord[]): GenericResult {38  let result: GenericResult = {39    success: false40  }41  events.forEach(({ phase, event: { data, method, section } }) => {42    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);43    if (method == 'ExtrinsicSuccess') {44      result.success = true;45    }46  });47  return result;48}4950export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {51  let success = false;52  let collectionId: number = 0;53  events.forEach(({ phase, event: { data, method, section } }) => {54    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);55    if (method == 'ExtrinsicSuccess') {56      success = true;57    } else if ((section == 'nft') && (method == 'Created')) {58      collectionId = parseInt(data[0].toString());59    }60  });61  let result: CreateCollectionResult = {62    success,63    collectionId64  }65  return result;66}6768export function getCreateItemResult(events: EventRecord[]): CreateItemResult {69  let success = false;70  let collectionId: number = 0;71  let itemId: number = 0;72  events.forEach(({ phase, event: { data, method, section } }) => {73    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);74    if (method == 'ExtrinsicSuccess') {75      success = true;76    } else if ((section == 'nft') && (method == 'ItemCreated')) {77      collectionId = parseInt(data[0].toString());78      itemId = parseInt(data[1].toString());79    }80  });81  let result: CreateItemResult = {82    success,83    collectionId,84    itemId85  }86  return result;87}8889export type CollectionMode = 'NFT' | 'Fungible' | 'ReFungible';90export type CreateCollectionParams = {91  mode: CollectionMode,92  name: string,93  description: string,94  tokenPrefix: string95};9697const defaultCreateCollectionParams: CreateCollectionParams = {98  name: 'name',99  description: 'description',100  mode: 'NFT',101  tokenPrefix: 'prefix'102}103104export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {105  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};106107  let collectionId: number = 0;108  await usingApi(async (api) => {109    // Get number of collections before the transaction110    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());111112    // Run the CreateCollection transaction113    const alicePrivateKey = privateKey('//Alice');114    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);115    const events = await submitTransactionAsync(alicePrivateKey, tx);116    const result = getCreateCollectionResult(events);117118    // Get number of collections after the transaction119    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());120121    // Get the collection 122    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();123124    // What to expect125    expect(result.success).to.be.true;126    expect(result.collectionId).to.be.equal(BcollectionCount);127    expect(collection).to.be.not.null;128    expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');129    expect(collection.Owner).to.be.equal(alicesPublicKey);130    expect(utf16ToStr(collection.Name)).to.be.equal(name);131    expect(utf16ToStr(collection.Description)).to.be.equal(description);132    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);133134    collectionId = result.collectionId;135  });136137  return collectionId;138}139  140export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {141  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};142143  await usingApi(async (api) => {144    // Get number of collections before the transaction145    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());146147    // Run the CreateCollection transaction148    const alicePrivateKey = privateKey('//Alice');149    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);150    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;151    const result = getCreateCollectionResult(events);152153    // Get number of collections after the transaction154    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());155156    // What to expect157    expect(result.success).to.be.false;158    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');159  });160}161  162export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {163  let bal = new BigNumber(0);164  let unused;165  do {166    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));167    const keyring = new Keyring({ type: 'sr25519' });168    unused = keyring.addFromUri(`//${randomSeed}`);169    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());170  } while (bal.toFixed() != '0');171  return unused; 172}173174function getDestroyResult(events: EventRecord[]): boolean {175  let success: boolean = false;176  events.forEach(({ phase, event: { data, method, section } }) => {177    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);178    if (method == 'ExtrinsicSuccess') {179      success = true;180    }181  });182  return success;183}184185export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {186  await usingApi(async (api) => {187    // Run the DestroyCollection transaction188    const alicePrivateKey = privateKey(senderSeed);189    const tx = api.tx.nft.destroyCollection(collectionId);190    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;191  });192}193194export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {195  await usingApi(async (api) => {196    // Run the DestroyCollection transaction197    const alicePrivateKey = privateKey(senderSeed);198    const tx = api.tx.nft.destroyCollection(collectionId);199    const events = await submitTransactionAsync(alicePrivateKey, tx);200    const result = getDestroyResult(events);201202    // Get the collection 203    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();204205    // What to expect206    expect(result).to.be.true;207    expect(collection).to.be.not.null;208    expect(collection.Owner).to.be.equal(nullPublicKey);209  });210}211212export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {213  await usingApi(async (api) => {214215    // Run the transaction216    const alicePrivateKey = privateKey('//Alice');217    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);218    const events = await submitTransactionAsync(alicePrivateKey, tx);219    const result = getGenericResult(events);220221    // Get the collection 222    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();223224    // What to expect225    expect(result.success).to.be.true;226    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());227    expect(collection.SponsorConfirmed).to.be.false;228  });229}230231export async function removeCollectionSponsorExpectSuccess(collectionId: number) {232  await usingApi(async (api) => {233234    // Run the transaction235    const alicePrivateKey = privateKey('//Alice');236    const tx = api.tx.nft.removeCollectionSponsor(collectionId);237    const events = await submitTransactionAsync(alicePrivateKey, tx);238    const result = getGenericResult(events);239240    // Get the collection 241    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();242243    // What to expect244    expect(result.success).to.be.true;245    expect(collection.Sponsor).to.be.equal(nullPublicKey);246    expect(collection.SponsorConfirmed).to.be.false;247  });248}249250export async function removeCollectionSponsorExpectFailure(collectionId: number) {251  await usingApi(async (api) => {252253    // Run the transaction254    const alicePrivateKey = privateKey('//Alice');255    const tx = api.tx.nft.removeCollectionSponsor(collectionId);256    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257  });258}259260export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {261  await usingApi(async (api) => {262263    // Run the transaction264    const alicePrivateKey = privateKey(senderSeed);265    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);266    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;267  });268}269270export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {271  await usingApi(async (api) => {272273    // Run the transaction274    const sender = privateKey(senderSeed);275    const tx = api.tx.nft.confirmSponsorship(collectionId);276    const events = await submitTransactionAsync(sender, tx);277    const result = getGenericResult(events);278279    // Get the collection 280    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();281282    // What to expect283    expect(result.success).to.be.true;284    expect(collection.Sponsor).to.be.equal(sender.address);285    expect(collection.SponsorConfirmed).to.be.true;286  });287}288289export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {290  await usingApi(async (api) => {291292    // Run the transaction293    const sender = privateKey(senderSeed);294    const tx = api.tx.nft.confirmSponsorship(collectionId);295    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;296  });297}298299export interface CreateFungibleData extends Struct {300  readonly value: u128;301};302303export interface CreateReFungibleData extends Struct {};304export interface CreateNftData extends Struct {};305306export interface CreateItemData extends Enum {307  NFT: CreateNftData,308  Fungible: CreateFungibleData,309  ReFungible: CreateReFungibleData310};311312export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {313  let newItemId: number = 0;314  await usingApi(async (api) => {315    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());316    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    317    const AItemBalance = new BigNumber(Aitem.Value);318319    if (owner === '') owner = sender.address;320321    let tx;322    if (createMode == 'Fungible') {323      let createData = {fungible: {value: 10}};324      tx = api.tx.nft.createItem(collectionId, owner, createData);325    }326    else {327      tx = api.tx.nft.createItem(collectionId, owner, createMode);328    }329    const events = await submitTransactionAsync(sender, tx);330    const result = getCreateItemResult(events);331332    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());333    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    334    const BItemBalance = new BigNumber(Bitem.Value);335336    // What to expect337    expect(result.success).to.be.true;338    if (createMode == 'Fungible') {339      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);340    }341    else {342      expect(BItemCount).to.be.equal(AItemCount+1);343    }344    expect(collectionId).to.be.equal(result.collectionId);345    expect(BItemCount).to.be.equal(result.itemId);346    newItemId = result.itemId;347  });348  return newItemId;349}350351export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {352  await usingApi(async (api) => {353354    // Run the transaction355    const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');356    const events = await submitTransactionAsync(sender, tx);357    const result = getGenericResult(events);358359    // Get the collection 360    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();361362    // What to expect363    expect(result.success).to.be.true;364    expect(collection.Access).to.be.equal('WhiteList');365  });366}367368export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {369  await usingApi(async (api) => {370371    // Run the transaction372    const tx = api.tx.nft.setMintPermission(collectionId, true);373    const events = await submitTransactionAsync(sender, tx);374    const result = getGenericResult(events);375376    // Get the collection 377    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();378379    // What to expect380    expect(result.success).to.be.true;381    expect(collection.MintMode).to.be.equal(true);382  });383}384385export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {386  await usingApi(async (api) => {387388    // Run the transaction389    const tx = api.tx.nft.addToWhiteList(collectionId, address);390    const events = await submitTransactionAsync(sender, tx);391    const result = getGenericResult(events);392393    // Get the collection 394    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();395396    // What to expect397    expect(result.success).to.be.true;398    expect(collection.MintMode).to.be.equal(true);399  });400}401
after · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { ApiPromise, Keyring } from "@polkadot/api";10import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "../substrate/substrate-api";11import privateKey from '../substrate/privateKey';12import { alicesPublicKey, nullPublicKey } from "../accounts";13import { strToUTF16, utf16ToStr, hexToStr } from './util';14import { IKeyringPair } from '@polkadot/types/types';15import { BigNumber } from 'bignumber.js';16import { Struct, Enum } from '@polkadot/types/codec';17import { u128 } from '@polkadot/types/primitive';18import { ICollectionInterface } from '../types';19import BN from "bn.js";2021chai.use(chaiAsPromised);22const expect = chai.expect;2324type GenericResult = {25  success: boolean,26};2728type CreateCollectionResult = {29  success: boolean,30  collectionId: number31};3233type CreateItemResult = {34  success: boolean,35  collectionId: number,36  itemId: number37};3839export function getGenericResult(events: EventRecord[]): GenericResult {40  let result: GenericResult = {41    success: false42  }43  events.forEach(({ phase, event: { data, method, section } }) => {44    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);45    if (method == 'ExtrinsicSuccess') {46      result.success = true;47    }48  });49  return result;50}5152export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {53  let success = false;54  let collectionId: number = 0;55  events.forEach(({ phase, event: { data, method, section } }) => {56    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);57    if (method == 'ExtrinsicSuccess') {58      success = true;59    } else if ((section == 'nft') && (method == 'Created')) {60      collectionId = parseInt(data[0].toString());61    }62  });63  let result: CreateCollectionResult = {64    success,65    collectionId66  }67  return result;68}6970export function getCreateItemResult(events: EventRecord[]): CreateItemResult {71  let success = false;72  let collectionId: number = 0;73  let itemId: number = 0;74  events.forEach(({ phase, event: { data, method, section } }) => {75    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);76    if (method == 'ExtrinsicSuccess') {77      success = true;78    } else if ((section == 'nft') && (method == 'ItemCreated')) {79      collectionId = parseInt(data[0].toString());80      itemId = parseInt(data[1].toString());81    }82  });83  let result: CreateItemResult = {84    success,85    collectionId,86    itemId87  }88  return result;89}9091export type CollectionMode = 'NFT' | 'Fungible' | 'ReFungible';92export type CreateCollectionParams = {93  mode: CollectionMode,94  name: string,95  description: string,96  tokenPrefix: string97};9899const defaultCreateCollectionParams: CreateCollectionParams = {100  name: 'name',101  description: 'description',102  mode: 'NFT',103  tokenPrefix: 'prefix'104}105106export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {107  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};108109  let collectionId: number = 0;110  await usingApi(async (api) => {111    // Get number of collections before the transaction112    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());113114    // Run the CreateCollection transaction115    const alicePrivateKey = privateKey('//Alice');116    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);117    const events = await submitTransactionAsync(alicePrivateKey, tx);118    const result = getCreateCollectionResult(events);119120    // Get number of collections after the transaction121    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());122123    // Get the collection 124    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();125126    // What to expect127    expect(result.success).to.be.true;128    expect(result.collectionId).to.be.equal(BcollectionCount);129    expect(collection).to.be.not.null;130    expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');131    expect(collection.Owner).to.be.equal(alicesPublicKey);132    expect(utf16ToStr(collection.Name)).to.be.equal(name);133    expect(utf16ToStr(collection.Description)).to.be.equal(description);134    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);135136    collectionId = result.collectionId;137  });138139  return collectionId;140}141  142export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {143  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};144145  await usingApi(async (api) => {146    // Get number of collections before the transaction147    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());148149    // Run the CreateCollection transaction150    const alicePrivateKey = privateKey('//Alice');151    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);152    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;153    const result = getCreateCollectionResult(events);154155    // Get number of collections after the transaction156    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());157158    // What to expect159    expect(result.success).to.be.false;160    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');161  });162}163  164export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {165  let bal = new BigNumber(0);166  let unused;167  do {168    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));169    const keyring = new Keyring({ type: 'sr25519' });170    unused = keyring.addFromUri(`//${randomSeed}`);171    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());172  } while (bal.toFixed() != '0');173  return unused; 174}175176function getDestroyResult(events: EventRecord[]): boolean {177  let success: boolean = false;178  events.forEach(({ phase, event: { data, method, section } }) => {179    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);180    if (method == 'ExtrinsicSuccess') {181      success = true;182    }183  });184  return success;185}186187export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {188  await usingApi(async (api) => {189    // Run the DestroyCollection transaction190    const alicePrivateKey = privateKey(senderSeed);191    const tx = api.tx.nft.destroyCollection(collectionId);192    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;193  });194}195196export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {197  await usingApi(async (api) => {198    // Run the DestroyCollection transaction199    const alicePrivateKey = privateKey(senderSeed);200    const tx = api.tx.nft.destroyCollection(collectionId);201    const events = await submitTransactionAsync(alicePrivateKey, tx);202    const result = getDestroyResult(events);203204    // Get the collection 205    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();206207    // What to expect208    expect(result).to.be.true;209    expect(collection).to.be.not.null;210    expect(collection.Owner).to.be.equal(nullPublicKey);211  });212}213214export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {215  await usingApi(async (api) => {216217    // Run the transaction218    const alicePrivateKey = privateKey('//Alice');219    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);220    const events = await submitTransactionAsync(alicePrivateKey, tx);221    const result = getGenericResult(events);222223    // Get the collection 224    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();225226    // What to expect227    expect(result.success).to.be.true;228    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());229    expect(collection.SponsorConfirmed).to.be.false;230  });231}232233export async function removeCollectionSponsorExpectSuccess(collectionId: number) {234  await usingApi(async (api) => {235236    // Run the transaction237    const alicePrivateKey = privateKey('//Alice');238    const tx = api.tx.nft.removeCollectionSponsor(collectionId);239    const events = await submitTransactionAsync(alicePrivateKey, tx);240    const result = getGenericResult(events);241242    // Get the collection 243    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();244245    // What to expect246    expect(result.success).to.be.true;247    expect(collection.Sponsor).to.be.equal(nullPublicKey);248    expect(collection.SponsorConfirmed).to.be.false;249  });250}251252export async function removeCollectionSponsorExpectFailure(collectionId: number) {253  await usingApi(async (api) => {254255    // Run the transaction256    const alicePrivateKey = privateKey('//Alice');257    const tx = api.tx.nft.removeCollectionSponsor(collectionId);258    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;259  });260}261262export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {263  await usingApi(async (api) => {264265    // Run the transaction266    const alicePrivateKey = privateKey(senderSeed);267    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);268    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;269  });270}271272export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {273  await usingApi(async (api) => {274275    // Run the transaction276    const sender = privateKey(senderSeed);277    const tx = api.tx.nft.confirmSponsorship(collectionId);278    const events = await submitTransactionAsync(sender, tx);279    const result = getGenericResult(events);280281    // Get the collection 282    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();283284    // What to expect285    expect(result.success).to.be.true;286    expect(collection.Sponsor).to.be.equal(sender.address);287    expect(collection.SponsorConfirmed).to.be.true;288  });289}290291export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {292  await usingApi(async (api) => {293294    // Run the transaction295    const sender = privateKey(senderSeed);296    const tx = api.tx.nft.confirmSponsorship(collectionId);297    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;298  });299}300301export interface CreateFungibleData extends Struct {302  readonly value: u128;303};304305export interface CreateReFungibleData extends Struct {};306export interface CreateNftData extends Struct {};307308export interface CreateItemData extends Enum {309  NFT: CreateNftData,310  Fungible: CreateFungibleData,311  ReFungible: CreateReFungibleData312};313314export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {315  let newItemId: number = 0;316  await usingApi(async (api) => {317    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());318    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    319    const AItemBalance = new BigNumber(Aitem.Value);320321    if (owner === '') owner = sender.address;322323    let tx;324    if (createMode == 'Fungible') {325      let createData = {fungible: {value: 10}};326      tx = api.tx.nft.createItem(collectionId, owner, createData);327    }328    else {329      tx = api.tx.nft.createItem(collectionId, owner, createMode);330    }331    const events = await submitTransactionAsync(sender, tx);332    const result = getCreateItemResult(events);333334    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());335    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    336    const BItemBalance = new BigNumber(Bitem.Value);337338    // What to expect339    expect(result.success).to.be.true;340    if (createMode == 'Fungible') {341      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);342    }343    else {344      expect(BItemCount).to.be.equal(AItemCount+1);345    }346    expect(collectionId).to.be.equal(result.collectionId);347    expect(BItemCount).to.be.equal(result.itemId);348    newItemId = result.itemId;349  });350  return newItemId;351}352353export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {354  await usingApi(async (api) => {355356    // Run the transaction357    const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');358    const events = await submitTransactionAsync(sender, tx);359    const result = getGenericResult(events);360361    // Get the collection 362    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();363364    // What to expect365    expect(result.success).to.be.true;366    expect(collection.Access).to.be.equal('WhiteList');367  });368}369370export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {371  await usingApi(async (api) => {372373    // Run the transaction374    const tx = api.tx.nft.setMintPermission(collectionId, true);375    const events = await submitTransactionAsync(sender, tx);376    const result = getGenericResult(events);377378    // Get the collection 379    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();380381    // What to expect382    expect(result.success).to.be.true;383    expect(collection.MintMode).to.be.equal(true);384  });385}386387export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {388  await usingApi(async (api) => {389390    // Run the transaction391    const tx = api.tx.nft.addToWhiteList(collectionId, address);392    const events = await submitTransactionAsync(sender, tx);393    const result = getGenericResult(events);394395    // Get the collection 396    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();397398    // What to expect399    expect(result.success).to.be.true;400    expect(collection.MintMode).to.be.equal(true);401  });402}403404export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)405  : Promise<ICollectionInterface | null> => {406  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;407};408409export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {410  // set global object - collectionsCount411  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();412};