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

difftreelog

Merge pull request #112 from usetech-llc/feature/NFTPAR-308_limited_owners_control

Greg Zaitsev2021-02-26parents: #6ea0c80 #4bce10c.patch.diff
in: master
Limited owners control

7 files changed

modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -382,6 +382,8 @@
         AccountTokenLimitExceeded,
         /// Collection limit bounds per collection exceeded
         CollectionLimitBoundsExceeded,
+        /// Tried to enable permissions which are only permitted to be disabled
+        OwnerPermissionsCantBeReverted,
         /// Schema data size limit bound exceeded
         SchemaDataLimitExceeded,
         /// Maximum refungibility exceeded
@@ -639,6 +641,11 @@
             let sender = ensure_signed(origin)?;
             Self::check_owner_permissions(collection_id, sender)?;
 
+            let target_collection = <Collection<T>>::get(collection_id);
+            if !target_collection.limits.owner_can_destroy {
+                fail!(Error::<T>::NoPermission);
+            }
+
             <AddressTokens<T>>::remove_prefix(collection_id);
             <Allowances<T>>::remove_prefix(collection_id);
             <Balance<T>>::remove_prefix(collection_id);
@@ -1022,9 +1029,14 @@
 
             // Transfer permissions check
             let target_collection = <Collection<T>>::get(collection_id);
-            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) ||
-                Self::is_owner_or_admin_permissions(collection_id, sender.clone()),
-                Error::<T>::NoPermission);
+            ensure!(
+                Self::is_item_owner(sender.clone(), collection_id, item_id) ||
+                (
+                    target_collection.limits.owner_can_transfer &&
+                    Self::is_owner_or_admin_permissions(collection_id, sender.clone())
+                ),
+                Error::<T>::NoPermission
+            );
 
             if target_collection.access == AccessMode::WhiteList {
                 Self::check_white_list(collection_id, &sender)?;
@@ -1098,9 +1110,14 @@
 
             // Transfer permissions check
             let target_collection = <Collection<T>>::get(collection_id);
-            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) ||
-                Self::is_owner_or_admin_permissions(collection_id, sender.clone()),
-                Error::<T>::NoPermission);
+            ensure!(
+                Self::is_item_owner(sender.clone(), collection_id, item_id) ||
+                (
+                    target_collection.limits.owner_can_transfer &&
+                    Self::is_owner_or_admin_permissions(collection_id, sender.clone())
+                ),
+                Error::<T>::NoPermission
+            );
 
             if target_collection.access == AccessMode::WhiteList {
                 Self::check_white_list(collection_id, &sender)?;
@@ -1156,8 +1173,14 @@
             Self::is_correct_transfer(collection_id, &target_collection, &recipient)?;
 
             // Transfer permissions check         
-            ensure!(appoved_transfer || Self::is_owner_or_admin_permissions(collection_id, sender.clone()),
-                Error::<T>::NoPermission);
+            ensure!(
+                appoved_transfer || 
+                (
+                    target_collection.limits.owner_can_transfer &&
+                    Self::is_owner_or_admin_permissions(collection_id, sender.clone())
+                ),
+                Error::<T>::NoPermission
+            );
 
             if target_collection.access == AccessMode::WhiteList {
                 Self::check_white_list(collection_id, &sender)?;
@@ -1524,25 +1547,32 @@
         pub fn set_collection_limits(
             origin,
             collection_id: u32,
-            limits: CollectionLimits,
+            new_limits: CollectionLimits,
         ) -> DispatchResult {
             let sender = ensure_signed(origin)?;
             Self::check_owner_permissions(collection_id, sender.clone())?;
             let mut target_collection = <Collection<T>>::get(collection_id);
+            let old_limits = target_collection.limits;
             let chain_limits = ChainLimit::get();
-            let climits = target_collection.limits;
 
             // collection bounds
-            ensure!(limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&
-                limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP,  
+            ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&
+                new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP && 
+                new_limits.sponsored_data_size <= chain_limits.custom_data_limit &&
+                new_limits.sponsored_mint_size <= chain_limits.custom_data_limit,
                 Error::<T>::CollectionLimitBoundsExceeded);
 
             // token_limit   check  prev
-            ensure!(climits.token_limit > limits.token_limit && 
-                limits.token_limit <= chain_limits.account_token_ownership_limit, 
-                Error::<T>::AccountTokenLimitExceeded);
+            ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);
+            ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);
 
-            target_collection.limits = limits;
+            ensure!(
+                (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&
+                (old_limits.owner_can_destroy || !new_limits.owner_can_destroy),
+                Error::<T>::OwnerPermissionsCantBeReverted,
+            );
+
+            target_collection.limits = new_limits;
             <Collection<T>>::insert(collection_id, target_collection);
 
             Ok(())
modifiedtests/src/approve.test.tsdiffbeforeafterboth
--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -3,6 +3,7 @@
 // file 'LICENSE', which is part of this source code package.
 //
 import { ApiPromise } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
 import BN from 'bn.js';
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
@@ -15,6 +16,7 @@
   createFungibleItemExpectSuccess,
   createItemExpectSuccess,
   destroyCollectionExpectSuccess,
+  setCollectionLimitsExpectSuccess,
   transferFromExpectSuccess,
   U128_MAX,
 } from './util/helpers';
@@ -23,10 +25,20 @@
 const expect = chai.expect;
 
 describe('Integration Test approve(spender, collection_id, item_id, amount):', () => {
+  let Alice: IKeyringPair;
+  let Bob: IKeyringPair;
+  let Charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async (api) => {
+      Alice = privateKey('//Alice');
+      Bob = privateKey('//Bob');
+      Charlie = privateKey('//Charlie');
+    });
+  });
+
   it('Execute the extrinsic and check approvedList', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
       const nftCollectionId = await createCollectionExpectSuccess();
       // nft
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
@@ -45,8 +57,6 @@
 
   it('Remove approval by using 0 amount', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
       const nftCollectionId = await createCollectionExpectSuccess();
       // nft
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
@@ -65,13 +75,30 @@
       await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob, 0);
     });
   });
+
+  it('can be called by collection owner on non-owned item when OwnerCanTransfer == true', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(Alice, collectionId, 'NFT', Bob.address);
+
+    await approveExpectSuccess(collectionId, itemId, Alice, Charlie);
+  });
 });
 
 describe('Negative Integration Test approve(spender, collection_id, item_id, amount):', () => {
+  let Alice: IKeyringPair;
+  let Bob: IKeyringPair;
+  let Charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async (api) => {
+      Alice = privateKey('//Alice');
+      Bob = privateKey('//Bob');
+      Charlie = privateKey('//Charlie');
+    });
+  });
+
   it('Approve for a collection that does not exist', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
       // nft
       const nftCollectionCount = await api.query.nft.createdCollectionCount() as unknown as number;
       await approveExpectFail(nftCollectionCount + 1, 1, Alice, Bob);
@@ -86,8 +113,6 @@
 
   it('Approve for a collection that was destroyed', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       await destroyCollectionExpectSuccess(nftCollectionId);
@@ -106,8 +131,6 @@
 
   it('Approve transfer of a token that does not exist', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       await approveExpectFail(nftCollectionId, 2, Alice, Bob);
@@ -123,8 +146,6 @@
 
   it('Approve using the address that does not own the approved token', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
       const nftCollectionId = await createCollectionExpectSuccess();
       // nft
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
@@ -140,4 +161,12 @@
       await approveExpectFail(reFungibleCollectionId, newReFungibleTokenId, Bob, Alice);
     });
   });
+
+  it('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(Alice, collectionId, 'NFT', Bob.address);
+    await setCollectionLimitsExpectSuccess(Alice, collectionId, { OwnerCanTransfer: false });
+
+    await approveExpectFail(collectionId, itemId, Alice, Charlie);
+  });
 });
modifiedtests/src/destroyCollection.test.tsdiffbeforeafterboth
--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -3,10 +3,12 @@
 // file 'LICENSE', which is part of this source code package.
 //
 
+import { IKeyringPair } from '@polkadot/types/types';
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
 import { default as usingApi } from "./substrate/substrate-api";
-import { createCollectionExpectSuccess, destroyCollectionExpectSuccess, destroyCollectionExpectFailure } from "./util/helpers";
+import { createCollectionExpectSuccess, destroyCollectionExpectSuccess, destroyCollectionExpectFailure, setCollectionLimitsExpectSuccess } from "./util/helpers";
 
 chai.use(chaiAsPromised);
 
@@ -26,6 +28,14 @@
 });
 
 describe('(!negative test!) integration test: ext. destroyCollection():', () => {
+  let alice: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async (api) => {
+      alice = privateKey('//Alice');
+    });
+  });
+
   it('(!negative test!) Destroy a collection that never existed', async () => {
     await usingApi(async (api) => {
       // Find the collection that never existed
@@ -43,4 +53,10 @@
     await destroyCollectionExpectFailure(collectionId, '//Bob');
     await destroyCollectionExpectSuccess(collectionId, '//Alice');
   });
+  it('fails when OwnerCanDestroy == false', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await setCollectionLimitsExpectSuccess(alice, collectionId, { OwnerCanDestroy: false });
+
+    await destroyCollectionExpectFailure(collectionId, '//Alice');
+  });
 });
modifiedtests/src/setCollectionLimits.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionLimits.test.ts
+++ b/tests/src/setCollectionLimits.test.ts
@@ -14,6 +14,8 @@
   createCollectionExpectSuccess, getCreatedCollectionCount,
   getCreateItemResult,
   getDetailedCollectionInfo,
+  setCollectionLimitsExpectFailure,
+  setCollectionLimitsExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -26,21 +28,8 @@
 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: {type: 'NFT'}});
-    });
-  });
-});
+const sponsorTimeout = 1;
+const tokenLimit = 1;
 
 describe('setCollectionLimits positive', () => {
   let tx;
@@ -48,6 +37,7 @@
     await usingApi(async () => {
       const keyring = new Keyring({ type: 'sr25519' });
       alice = keyring.addFromUri('//Alice');
+      collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
     });
   });
   it('execute setCollectionLimits with predefined params ', async () => {
@@ -55,25 +45,28 @@
       tx = api.tx.nft.setCollectionLimits(
         collectionIdForTesting,
         {
-          accountTokenOwnershipLimit,
-          sponsoredDataSize,
-          sponsoredMintSize,
-          tokenLimit,
+          AccountTokenOwnershipLimit: accountTokenOwnershipLimit,
+          SponsoredMintSize: sponsoredDataSize,
+          TokenLimit: tokenLimit,
+          SponsorTimeout: sponsorTimeout,
+          OwnerCanTransfer: true,
+          OwnerCanDestroy: true
         },
       );
       const events = await submitTransactionAsync(alice, tx);
       const result = getCreateItemResult(events);
+
+      // get collection limits defined previously
+      const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting) as ICollectionInterface;
+
       // 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.SponsoredMintSize.toNumber()).to.be.equal(sponsoredDataSize);
       expect(collectionInfo.Limits.TokenLimit.toNumber()).to.be.equal(tokenLimit);
-      expect(collectionInfo.Limits.SponsorTimeout.toNumber()).to.be.equal(sponsoredDataSize);
+      expect(collectionInfo.Limits.SponsorTimeout.toNumber()).to.be.equal(sponsorTimeout);
+      expect(collectionInfo.Limits.OwnerCanTransfer.valueOf()).to.be.true;
+      expect(collectionInfo.Limits.OwnerCanDestroy.valueOf()).to.be.true;
     });
   });
 });
@@ -85,6 +78,7 @@
       const keyring = new Keyring({ type: 'sr25519' });
       alice = keyring.addFromUri('//Alice');
       bob = keyring.addFromUri('//Bob');
+      collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
     });
   });
   it('execute setCollectionLimits for not exists collection', async () => {
@@ -131,4 +125,44 @@
       await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
     });
   });
+
+  it('fails when trying to enable OwnerCanTransfer after it was disabled', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await setCollectionLimitsExpectSuccess(alice, collectionId, { 
+      AccountTokenOwnershipLimit: accountTokenOwnershipLimit,
+      SponsoredMintSize: sponsoredDataSize,
+      TokenLimit: tokenLimit,
+      SponsorTimeout: sponsorTimeout,
+      OwnerCanTransfer: false,
+      OwnerCanDestroy: true
+    });
+    await setCollectionLimitsExpectFailure(alice, collectionId, { 
+      AccountTokenOwnershipLimit: accountTokenOwnershipLimit,
+      SponsoredMintSize: sponsoredDataSize,
+      TokenLimit: tokenLimit,
+      SponsorTimeout: sponsorTimeout,
+      OwnerCanTransfer: true,
+      OwnerCanDestroy: true
+    });
+  });
+
+  it('fails when trying to enable OwnerCanDestroy after it was disabled', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await setCollectionLimitsExpectSuccess(alice, collectionId, {
+      AccountTokenOwnershipLimit: accountTokenOwnershipLimit,
+      SponsoredMintSize: sponsoredDataSize,
+      TokenLimit: tokenLimit,
+      SponsorTimeout: sponsorTimeout,
+      OwnerCanTransfer: true,
+      OwnerCanDestroy: false
+    });
+    await setCollectionLimitsExpectFailure(alice, collectionId, { 
+      AccountTokenOwnershipLimit: accountTokenOwnershipLimit,
+      SponsoredMintSize: sponsoredDataSize,
+      TokenLimit: tokenLimit,
+      SponsorTimeout: sponsorTimeout,
+      OwnerCanTransfer: true,
+      OwnerCanDestroy: true
+    });
+  });
 });
modifiedtests/src/transferFrom.test.tsdiffbeforeafterboth
--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -3,6 +3,7 @@
 // file 'LICENSE', which is part of this source code package.
 //
 import { ApiPromise } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
 import privateKey from './substrate/privateKey';
@@ -18,17 +19,27 @@
   transferFromExpectFail,
   transferFromExpectSuccess,
   burnItemExpectSuccess,
+  setCollectionLimitsExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
 
 describe('Integration Test transferFrom(from, recipient, collection_id, item_id, value):', () => {
+  let Alice: IKeyringPair;
+  let Bob: IKeyringPair;
+  let Charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async (api) => {
+      Alice = privateKey('//Alice');
+      Bob = privateKey('//Bob');
+      Charlie = privateKey('//Charlie');
+    });
+  });
+
   it('Execute the extrinsic and check nftItemList - owner of token', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
@@ -66,14 +77,30 @@
       expect((await getAllowance(fungibleCollectionId, newFungibleTokenId, alice.address, bob.address)).toString()).to.equal('0');
     });
   });
+
+  it('can be called by collection owner on non-owned item when OwnerCanTransfer == true', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(Alice, collectionId, 'NFT', Bob.address);
+
+    await transferFromExpectSuccess(collectionId, itemId, Alice, Bob, Charlie);
+  });
 });
 
 describe('Negative Integration Test transferFrom(from, recipient, collection_id, item_id, value):', () => {
+  let Alice: IKeyringPair;
+  let Bob: IKeyringPair;
+  let Charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async (api) => {
+      Alice = privateKey('//Alice');
+      Bob = privateKey('//Bob');
+      Charlie = privateKey('//Charlie');
+    });
+  });
+
   it('transferFrom for a collection that does not exist', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       // nft
       const nftCollectionCount = await api.query.nft.createdCollectionCount() as unknown as number;
       await approveExpectFail(nftCollectionCount + 1, 1, Alice, Bob);
@@ -113,9 +140,6 @@
 
   it('transferFrom for not approved address', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
@@ -137,9 +161,6 @@
 
   it('transferFrom incorrect token count', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
@@ -164,9 +185,6 @@
 
   it('execute transferFrom from account that is not owner of collection', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       const Dave = privateKey('//Dave');
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
@@ -206,9 +224,6 @@
   });
   it( 'transferFrom burnt token before approve NFT', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
@@ -219,9 +234,6 @@
   });
   it( 'transferFrom burnt token before approve Fungible', async () => {
     await usingApi(async (api: ApiPromise) => {
-    const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
       await burnItemExpectSuccess(Alice, fungibleCollectionId, 1, 10);
@@ -232,9 +244,6 @@
   }); 
   it( 'transferFrom burnt token before approve ReFungible', async () => {
     await usingApi(async (api: ApiPromise) => {
-    const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
       const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
       await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);
@@ -246,9 +255,6 @@
   
   it( 'transferFrom burnt token after approve NFT', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
@@ -259,9 +265,6 @@
   });
   it( 'transferFrom burnt token after approve Fungible', async () => {
     await usingApi(async (api: ApiPromise) => {
-    const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
       await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);
@@ -272,9 +275,6 @@
   }); 
   it( 'transferFrom burnt token after approve ReFungible', async () => {
     await usingApi(async (api: ApiPromise) => {
-    const Alice = privateKey('//Alice');
-      const Bob = privateKey('//Bob');
-      const Charlie = privateKey('//Charlie');
       const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
       const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
       await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);
@@ -282,5 +282,13 @@
       await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, Bob, Alice, Charlie, 1);
           
     });
-  }); 
+  });
+
+  it('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(Alice, collectionId, 'NFT', Bob.address);
+    await setCollectionLimitsExpectSuccess(Alice, collectionId, { OwnerCanTransfer: false });
+
+    await transferFromExpectFail(collectionId, itemId, Alice, Bob, Charlie);
+  });
 });
modifiedtests/src/types.tsdiffbeforeafterboth
--- a/tests/src/types.ts
+++ b/tests/src/types.ts
@@ -17,6 +17,8 @@
     SponsoredMintSize: BN;
     TokenLimit: BN;
     SponsorTimeout: BN;
+    OwnerCanTransfer: boolean;
+    OwnerCanDestroy: boolean;
   };
   MintMode: boolean;
   Mode: {
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 { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27  success: boolean,28};2930interface CreateCollectionResult {31  success: boolean;32  collectionId: number;33}3435interface CreateItemResult {36  success: boolean;37  collectionId: number;38  itemId: number;39  recipient: string;40}4142interface TransferResult {43  success: boolean;44  collectionId: number;45  itemId: number;46  sender: string;47  recipient: string;48  value: bigint;49}5051interface IReFungibleOwner {52  Fraction: BN;53  Owner: number[];54}5556interface ITokenDataType {57  Owner: number[];58  ConstData: number[];59  VariableData: number[];60}6162interface IFungibleTokenDataType {63  Value: BN;64}6566export interface IReFungibleTokenDataType {67  Owner: IReFungibleOwner[];68  ConstData: number[];69  VariableData: number[];70}7172export function getGenericResult(events: EventRecord[]): GenericResult {73  const result: GenericResult = {74    success: false,75  };76  events.forEach(({ phase, event: { data, method, section } }) => {77    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);78    if (method === 'ExtrinsicSuccess') {79      result.success = true;80    }81  });82  return result;83}8485export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {86  let success = false;87  let collectionId: number = 0;88  events.forEach(({ phase, event: { data, method, section } }) => {89    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);90    if (method == 'ExtrinsicSuccess') {91      success = true;92    } else if ((section == 'nft') && (method == 'Created')) {93      collectionId = parseInt(data[0].toString());94    }95  });96  const result: CreateCollectionResult = {97    success,98    collectionId,99  };100  return result;101}102103export function getCreateItemResult(events: EventRecord[]): CreateItemResult {104  let success = false;105  let collectionId: number = 0;106  let itemId: number = 0;107  let recipient: string = '';108  events.forEach(({ phase, event: { data, method, section } }) => {109    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);110    if (method == 'ExtrinsicSuccess') {111      success = true;112    } else if ((section == 'nft') && (method == 'ItemCreated')) {113      collectionId = parseInt(data[0].toString());114      itemId = parseInt(data[1].toString());115      recipient = data[2].toString();116    }117  });118  const result: CreateItemResult = {119    success,120    collectionId,121    itemId,122    recipient,123  };124  return result;125}126127export function getTransferResult(events: EventRecord[]): TransferResult {128  const result: TransferResult = {129    success: false,130    collectionId: 0,131    itemId: 0,132    sender: '',133    recipient: '',134    value: 0n,135  };136137  events.forEach(({event: {data, method, section}}) => {138    if (method === 'ExtrinsicSuccess') {139      result.success = true;140    } else if (section === 'nft' && method === 'Transfer') {141      result.collectionId = +data[0].toString();142      result.itemId = +data[1].toString();143      result.sender = data[2].toString();144      result.recipient = data[3].toString();145      result.value = BigInt(data[4].toString());146    }147  });148149  return result;150}151152interface Invalid {153  type: 'Invalid';154}155156interface Nft {157  type: 'NFT';158}159160interface Fungible {161  type: 'Fungible';162  decimalPoints: number;163}164165interface ReFungible {166  type: 'ReFungible';167}168169type CollectionMode = Nft | Fungible | ReFungible | Invalid;170171export type CreateCollectionParams = {172  mode: CollectionMode,173  name: string,174  description: string,175  tokenPrefix: string,176};177178const defaultCreateCollectionParams: CreateCollectionParams = {179  description: 'description',180  mode: { type: 'NFT' },181  name: 'name',182  tokenPrefix: 'prefix',183}184185export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {186  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};187188  let collectionId: number = 0;189  await usingApi(async (api) => {190    // Get number of collections before the transaction191    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);192193    // Run the CreateCollection transaction194    const alicePrivateKey = privateKey('//Alice');195196    let modeprm = {};197    if (mode.type === 'NFT') {198      modeprm = {nft: null};199    } else if (mode.type === 'Fungible') {200      modeprm = {fungible: mode.decimalPoints};201    } else if (mode.type === 'ReFungible') {202      modeprm = {refungible: null};203    } else if (mode.type === 'Invalid') {204      modeprm = {invalid: null};205    }206207    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);208    const events = await submitTransactionAsync(alicePrivateKey, tx);209    const result = getCreateCollectionResult(events);210211    // Get number of collections after the transaction212    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);213214    // Get the collection215    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();216217    // What to expect218    // tslint:disable-next-line:no-unused-expression219    expect(result.success).to.be.true;220    expect(result.collectionId).to.be.equal(BcollectionCount);221    // tslint:disable-next-line:no-unused-expression222    expect(collection).to.be.not.null;223    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');224    expect(collection.Owner).to.be.equal(alicesPublicKey);225    expect(utf16ToStr(collection.Name)).to.be.equal(name);226    expect(utf16ToStr(collection.Description)).to.be.equal(description);227    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);228229    collectionId = result.collectionId;230  });231232  return collectionId;233}234235export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {236  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};237238  let modeprm = {};239  if (mode.type === 'NFT') {240    modeprm = {nft: null};241  } else if (mode.type === 'Fungible') {242    modeprm = {fungible: mode.decimalPoints};243  } else if (mode.type === 'ReFungible') {244    modeprm = {refungible: null};245  } else if (mode.type === 'Invalid') {246    modeprm = {invalid: null};247  }248249  await usingApi(async (api) => {250    // Get number of collections before the transaction251    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());252253    // Run the CreateCollection transaction254    const alicePrivateKey = privateKey('//Alice');255    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);256    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257    const result = getCreateCollectionResult(events);258259    // Get number of collections after the transaction260    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());261262    // What to expect263    // tslint:disable-next-line:no-unused-expression264    expect(result.success).to.be.false;265    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');266  });267}268269export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {270  let bal = new BigNumber(0);271  let unused;272  do {273    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;274    const keyring = new Keyring({ type: 'sr25519' });275    unused = keyring.addFromUri(`//${randomSeed}`);276    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());277  } while (bal.toFixed() != '0');278  return unused;279}280281export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {282  return await usingApi(async (api) => {283    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;284    return BigInt(bn.toString());285  });286}287288export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {289  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));290}291292export async function findNotExistingCollection(api: ApiPromise): Promise<number> {293  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;294  const newCollection: number = totalNumber + 1;295  return newCollection;296}297298function getDestroyResult(events: EventRecord[]): boolean {299  let success: boolean = false;300  events.forEach(({ phase, event: { data, method, section } }) => {301    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);302    if (method == 'ExtrinsicSuccess') {303      success = true;304    }305  });306  return success;307}308309export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {310  await usingApi(async (api) => {311    // Run the DestroyCollection transaction312    const alicePrivateKey = privateKey(senderSeed);313    const tx = api.tx.nft.destroyCollection(collectionId);314    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;315  });316}317318export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {319  await usingApi(async (api) => {320    // Run the DestroyCollection transaction321    const alicePrivateKey = privateKey(senderSeed);322    const tx = api.tx.nft.destroyCollection(collectionId);323    const events = await submitTransactionAsync(alicePrivateKey, tx);324    const result = getDestroyResult(events);325326    // Get the collection327    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329    // What to expect330    expect(result).to.be.true;331    expect(collection).to.be.not.null;332    expect(collection.Owner).to.be.equal(nullPublicKey);333  });334}335336export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {337  await usingApi(async (api) => {338339    // Run the transaction340    const alicePrivateKey = privateKey('//Alice');341    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);342    const events = await submitTransactionAsync(alicePrivateKey, tx);343    const result = getGenericResult(events);344345    // Get the collection346    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();347348    // What to expect349    expect(result.success).to.be.true;350    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());351    expect(collection.SponsorConfirmed).to.be.false;352  });353}354355export async function removeCollectionSponsorExpectSuccess(collectionId: number) {356  await usingApi(async (api) => {357358    // Run the transaction359    const alicePrivateKey = privateKey('//Alice');360    const tx = api.tx.nft.removeCollectionSponsor(collectionId);361    const events = await submitTransactionAsync(alicePrivateKey, tx);362    const result = getGenericResult(events);363364    // Get the collection365    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();366367    // What to expect368    expect(result.success).to.be.true;369    expect(collection.Sponsor).to.be.equal(nullPublicKey);370    expect(collection.SponsorConfirmed).to.be.false;371  });372}373374export async function removeCollectionSponsorExpectFailure(collectionId: number) {375  await usingApi(async (api) => {376377    // Run the transaction378    const alicePrivateKey = privateKey('//Alice');379    const tx = api.tx.nft.removeCollectionSponsor(collectionId);380    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;381  });382}383384export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {385  await usingApi(async (api) => {386387    // Run the transaction388    const alicePrivateKey = privateKey(senderSeed);389    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);390    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;391  });392}393394export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {395  await usingApi(async (api) => {396397    // Run the transaction398    const sender = privateKey(senderSeed);399    const tx = api.tx.nft.confirmSponsorship(collectionId);400    const events = await submitTransactionAsync(sender, tx);401    const result = getGenericResult(events);402403    // Get the collection404    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();405406    // What to expect407    expect(result.success).to.be.true;408    expect(collection.Sponsor).to.be.equal(sender.address);409    expect(collection.SponsorConfirmed).to.be.true;410  });411}412413414export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {415  await usingApi(async (api) => {416417    // Run the transaction418    const sender = privateKey(senderSeed);419    const tx = api.tx.nft.confirmSponsorship(collectionId);420    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;421  });422}423424export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {425  await usingApi(async (api) => {426    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);427    const events = await submitTransactionAsync(sender, tx);428    const result = getGenericResult(events);429430    expect(result.success).to.be.true;431  });432}433434export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {435  await usingApi(async (api) => {436    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);437    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;438    const result = getGenericResult(events);439440    expect(result.success).to.be.false;441  });442}443444export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {445  await usingApi(async (api) => {446    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);447    const events = await submitTransactionAsync(sender, tx);448    const result = getGenericResult(events);449450    expect(result.success).to.be.true;451  });452}453454export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {455  await usingApi(async (api) => {456    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);457    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;458    const result = getGenericResult(events);459460    expect(result.success).to.be.false;461  });462}463464export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {465  await usingApi(async (api) => {466    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);467    const events = await submitTransactionAsync(sender, tx);468    const result = getGenericResult(events);469470    expect(result.success).to.be.true;471  });472}473474export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {475  let whitelisted: boolean = false;476  await usingApi(async (api) => {477    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;478  });479  return whitelisted;480}481482export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {483  await usingApi(async (api) => {484    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);485    const events = await submitTransactionAsync(sender, tx);486    const result = getGenericResult(events);487488    expect(result.success).to.be.true;489  });490}491492export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {493  await usingApi(async (api) => {494    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);495    const events = await submitTransactionAsync(sender, tx);496    const result = getGenericResult(events);497498    expect(result.success).to.be.true;499  });500}501502export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {503  await usingApi(async (api) => {504    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);505    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;506    const result = getGenericResult(events);507508    expect(result.success).to.be.false;509  });510}511512export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {513  await usingApi(async (api) => {514    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));515    const events = await submitTransactionAsync(sender, tx);516    const result = getGenericResult(events);517518    expect(result.success).to.be.true;519  });520}521522export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {523  await usingApi(async (api) => {524    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));525    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;526  });527}528529export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {530  await usingApi(async (api) => {531    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));532    const events = await submitTransactionAsync(sender, tx);533    const result = getGenericResult(events);534535    expect(result.success).to.be.true;536  });537}538539export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {540  await usingApi(async (api) => {541    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));542    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;543  });544}545546export interface CreateFungibleData {547  readonly Value: bigint;548}549550export interface CreateReFungibleData { }551export interface CreateNftData { }552553export type CreateItemData = {554  NFT: CreateNftData;555} | {556  Fungible: CreateFungibleData;557} | {558  ReFungible: CreateReFungibleData;559};560561export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {562  await usingApi(async (api) => {563    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);564    const events = await submitTransactionAsync(owner, tx);565    const result = getGenericResult(events);566    // Get the item567    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();568    // What to expect569    // tslint:disable-next-line:no-unused-expression570    expect(result.success).to.be.true;571    // tslint:disable-next-line:no-unused-expression572    expect(item).to.be.not.null;573    expect(item.Owner).to.be.equal(nullPublicKey);574  });575}576577export async function578approveExpectSuccess(collectionId: number,579                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {580  await usingApi(async (api: ApiPromise) => {581    const allowanceBefore =582      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;583    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);584    const events = await submitTransactionAsync(owner, approveNftTx);585    const result = getCreateItemResult(events);586    // tslint:disable-next-line:no-unused-expression587    expect(result.success).to.be.true;588    const allowanceAfter =589      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;590    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());591  });592}593594export async function595transferFromExpectSuccess(collectionId: number,596                          tokenId: number,597                          accountApproved: IKeyringPair,598                          accountFrom: IKeyringPair,599                          accountTo: IKeyringPair,600                          value: number | bigint = 1,601                          type: string = 'NFT') {602  await usingApi(async (api: ApiPromise) => {603    let balanceBefore = new BN(0);604    if (type === 'Fungible') {605      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;606    }607    const transferFromTx = await api.tx.nft.transferFrom(608      accountFrom.address, accountTo.address, collectionId, tokenId, value);609    const events = await submitTransactionAsync(accountApproved, transferFromTx);610    const result = getCreateItemResult(events);611    // tslint:disable-next-line:no-unused-expression612    expect(result.success).to.be.true;613    if (type === 'NFT') {614      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;615      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);616    }617    if (type === 'Fungible') {618      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;619      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());620    }621    if (type === 'ReFungible') {622      const nftItemData =623        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;624      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);625      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);626    }627  });628}629630export async function631transferFromExpectFail(collectionId: number,632                       tokenId: number,633                       accountApproved: IKeyringPair,634                       accountFrom: IKeyringPair,635                       accountTo: IKeyringPair,636                       value: number | bigint = 1) {637  await usingApi(async (api: ApiPromise) => {638    const transferFromTx = await api.tx.nft.transferFrom(639      accountFrom.address, accountTo.address, collectionId, tokenId, value);640    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;641    const result = getCreateCollectionResult(events);642    // tslint:disable-next-line:no-unused-expression643    expect(result.success).to.be.false;644  });645}646647export async function648transferExpectSuccess(collectionId: number,649                      tokenId: number,650                      sender: IKeyringPair,651                      recipient: IKeyringPair,652                      value: number | bigint = 1,653                      type: string = 'NFT') {654  await usingApi(async (api: ApiPromise) => {655    let balanceBefore = new BN(0);656    if (type === 'Fungible') {657      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;658    }659    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);660    const events = await submitTransactionAsync(sender, transferTx);661    const result = getTransferResult(events);662    // tslint:disable-next-line:no-unused-expression663    expect(result.success).to.be.true;664    expect(result.collectionId).to.be.equal(collectionId);665    expect(result.itemId).to.be.equal(tokenId);666    expect(result.sender).to.be.equal(sender.address);667    expect(result.recipient).to.be.equal(recipient.address);668    expect(result.value.toString()).to.be.equal(value.toString());669    if (type === 'NFT') {670      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;671      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);672    }673    if (type === 'Fungible') {674      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;675      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());676    }677    if (type === 'ReFungible') {678      const nftItemData =679        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;680      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);681      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);682    }683  });684}685686export async function687transferExpectFail(collectionId: number,688                   tokenId: number,689                   sender: IKeyringPair,690                   recipient: IKeyringPair,691                   value: number | bigint = 1,692                   type: string = 'NFT') {693  await usingApi(async (api: ApiPromise) => {694    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);695    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;696    if (events && Array.isArray(events)) {697      const result = getCreateCollectionResult(events);698      // tslint:disable-next-line:no-unused-expression699      expect(result.success).to.be.false;700    }701  });702}703704export async function705approveExpectFail(collectionId: number,706                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {707  await usingApi(async (api: ApiPromise) => {708    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);709    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;710    const result = getCreateCollectionResult(events);711    // tslint:disable-next-line:no-unused-expression712    expect(result.success).to.be.false;713  });714}715716export async function getFungibleBalance(717  collectionId: number,718  owner: string,719) {720  return await usingApi(async (api) => {721    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};722    return BigInt(response.Value);723  });724}725726export async function createFungibleItemExpectSuccess(727  sender: IKeyringPair,728  collectionId: number,729  data: CreateFungibleData,730  owner: string = sender.address,731) {732  return await usingApi(async (api) => {733    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });734735    const events = await submitTransactionAsync(sender, tx);736    const result = getCreateItemResult(events);737738    expect(result.success).to.be.true;739    return result.itemId;740  });741}742743export async function createItemExpectSuccess(744  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {745  let newItemId: number = 0;746  await usingApi(async (api) => {747    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);748    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();749    const AItemBalance = new BigNumber(Aitem.Value);750751    if (owner === '') {752      owner = sender.address;753    }754755    let tx;756    if (createMode === 'Fungible') {757      const createData = {fungible: {value: 10}};758      tx = api.tx.nft.createItem(collectionId, owner, createData);759    } else if (createMode === 'ReFungible') {760      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};761      tx = api.tx.nft.createItem(collectionId, owner, createData);762    } else {763      tx = api.tx.nft.createItem(collectionId, owner, createMode);764    }765    const events = await submitTransactionAsync(sender, tx);766    const result = getCreateItemResult(events);767768    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);769    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();770    const BItemBalance = new BigNumber(Bitem.Value);771772    // What to expect773    // tslint:disable-next-line:no-unused-expression774    expect(result.success).to.be.true;775    if (createMode === 'Fungible') {776      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);777    } else {778      expect(BItemCount).to.be.equal(AItemCount + 1);779    }780    expect(collectionId).to.be.equal(result.collectionId);781    expect(BItemCount).to.be.equal(result.itemId);782    expect(owner).to.be.equal(result.recipient);783    newItemId = result.itemId;784  });785  return newItemId;786}787788export async function createItemExpectFailure(789  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {790  await usingApi(async (api) => {791    const tx = api.tx.nft.createItem(collectionId, owner, createMode);792    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;793    const result = getCreateItemResult(events);794795    expect(result.success).to.be.false;796  });797}798799export async function setPublicAccessModeExpectSuccess(800  sender: IKeyringPair, collectionId: number,801  accessMode: 'Normal' | 'WhiteList',802) {803  await usingApi(async (api) => {804805    // Run the transaction806    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);807    const events = await submitTransactionAsync(sender, tx);808    const result = getGenericResult(events);809810    // Get the collection811    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();812813    // What to expect814    // tslint:disable-next-line:no-unused-expression815    expect(result.success).to.be.true;816    expect(collection.Access).to.be.equal(accessMode);817  });818}819820export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {821  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');822}823824export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {825  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');826}827828export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {829  await usingApi(async (api) => {830831    // Run the transaction832    const tx = api.tx.nft.setMintPermission(collectionId, enabled);833    const events = await submitTransactionAsync(sender, tx);834    const result = getGenericResult(events);835836    // Get the collection837    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();838839    // What to expect840    // tslint:disable-next-line:no-unused-expression841    expect(result.success).to.be.true;842    expect(collection.MintMode).to.be.equal(enabled);843  });844}845846export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {847  await setMintPermissionExpectSuccess(sender, collectionId, true);848}849850export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {851  await usingApi(async (api) => {852    // Run the transaction853    const tx = api.tx.nft.setMintPermission(collectionId, enabled);854    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;855    const result = getCreateCollectionResult(events);856    // tslint:disable-next-line:no-unused-expression857    expect(result.success).to.be.false;858  });859}860861export async function isWhitelisted(collectionId: number, address: string) {862  let whitelisted: boolean = false;863  await usingApi(async (api) => {864    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;865  });866  return whitelisted;867}868869export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {870  await usingApi(async (api) => {871872    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();873874    // Run the transaction875    const tx = api.tx.nft.addToWhiteList(collectionId, address);876    const events = await submitTransactionAsync(sender, tx);877    const result = getGenericResult(events);878879    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();880881    // What to expect882    // tslint:disable-next-line:no-unused-expression883    expect(result.success).to.be.true;884    // tslint:disable-next-line: no-unused-expression885    expect(whiteListedBefore).to.be.false;886    // tslint:disable-next-line: no-unused-expression887    expect(whiteListedAfter).to.be.true;888  });889}890891export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {892  await usingApi(async (api) => {893    // Run the transaction894    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);895    const events = await submitTransactionAsync(sender, tx);896    const result = getGenericResult(events);897898    // What to expect899    // tslint:disable-next-line:no-unused-expression900    expect(result.success).to.be.true;901  });902}903904export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {905  await usingApi(async (api) => {906    // Run the transaction907    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);908    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;909    const result = getGenericResult(events);910911    // What to expect912    // tslint:disable-next-line:no-unused-expression913    expect(result.success).to.be.false;914  });915}916917export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)918  : Promise<ICollectionInterface | null> => {919  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;920};921922export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {923  // set global object - collectionsCount924  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();925};926927export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {928  return await usingApi(async (api) => {929    return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;930  });931}
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 { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27  success: boolean,28};2930interface CreateCollectionResult {31  success: boolean;32  collectionId: number;33}3435interface CreateItemResult {36  success: boolean;37  collectionId: number;38  itemId: number;39  recipient: string;40}4142interface TransferResult {43  success: boolean;44  collectionId: number;45  itemId: number;46  sender: string;47  recipient: string;48  value: bigint;49}5051interface IReFungibleOwner {52  Fraction: BN;53  Owner: number[];54}5556interface ITokenDataType {57  Owner: number[];58  ConstData: number[];59  VariableData: number[];60}6162interface IFungibleTokenDataType {63  Value: BN;64}6566export interface IReFungibleTokenDataType {67  Owner: IReFungibleOwner[];68  ConstData: number[];69  VariableData: number[];70}7172export function getGenericResult(events: EventRecord[]): GenericResult {73  const result: GenericResult = {74    success: false,75  };76  events.forEach(({ phase, event: { data, method, section } }) => {77    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);78    if (method === 'ExtrinsicSuccess') {79      result.success = true;80    }81  });82  return result;83}8485export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {86  let success = false;87  let collectionId: number = 0;88  events.forEach(({ phase, event: { data, method, section } }) => {89    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);90    if (method == 'ExtrinsicSuccess') {91      success = true;92    } else if ((section == 'nft') && (method == 'Created')) {93      collectionId = parseInt(data[0].toString());94    }95  });96  const result: CreateCollectionResult = {97    success,98    collectionId,99  };100  return result;101}102103export function getCreateItemResult(events: EventRecord[]): CreateItemResult {104  let success = false;105  let collectionId: number = 0;106  let itemId: number = 0;107  let recipient: string = '';108  events.forEach(({ phase, event: { data, method, section } }) => {109    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);110    if (method == 'ExtrinsicSuccess') {111      success = true;112    } else if ((section == 'nft') && (method == 'ItemCreated')) {113      collectionId = parseInt(data[0].toString());114      itemId = parseInt(data[1].toString());115      recipient = data[2].toString();116    }117  });118  const result: CreateItemResult = {119    success,120    collectionId,121    itemId,122    recipient,123  };124  return result;125}126127export function getTransferResult(events: EventRecord[]): TransferResult {128  const result: TransferResult = {129    success: false,130    collectionId: 0,131    itemId: 0,132    sender: '',133    recipient: '',134    value: 0n,135  };136137  events.forEach(({event: {data, method, section}}) => {138    if (method === 'ExtrinsicSuccess') {139      result.success = true;140    } else if (section === 'nft' && method === 'Transfer') {141      result.collectionId = +data[0].toString();142      result.itemId = +data[1].toString();143      result.sender = data[2].toString();144      result.recipient = data[3].toString();145      result.value = BigInt(data[4].toString());146    }147  });148149  return result;150}151152interface Invalid {153  type: 'Invalid';154}155156interface Nft {157  type: 'NFT';158}159160interface Fungible {161  type: 'Fungible';162  decimalPoints: number;163}164165interface ReFungible {166  type: 'ReFungible';167}168169type CollectionMode = Nft | Fungible | ReFungible | Invalid;170171export type CreateCollectionParams = {172  mode: CollectionMode,173  name: string,174  description: string,175  tokenPrefix: string,176};177178const defaultCreateCollectionParams: CreateCollectionParams = {179  description: 'description',180  mode: { type: 'NFT' },181  name: 'name',182  tokenPrefix: 'prefix',183}184185export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {186  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};187188  let collectionId: number = 0;189  await usingApi(async (api) => {190    // Get number of collections before the transaction191    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);192193    // Run the CreateCollection transaction194    const alicePrivateKey = privateKey('//Alice');195196    let modeprm = {};197    if (mode.type === 'NFT') {198      modeprm = {nft: null};199    } else if (mode.type === 'Fungible') {200      modeprm = {fungible: mode.decimalPoints};201    } else if (mode.type === 'ReFungible') {202      modeprm = {refungible: null};203    } else if (mode.type === 'Invalid') {204      modeprm = {invalid: null};205    }206207    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);208    const events = await submitTransactionAsync(alicePrivateKey, tx);209    const result = getCreateCollectionResult(events);210211    // Get number of collections after the transaction212    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);213214    // Get the collection215    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();216217    // What to expect218    // tslint:disable-next-line:no-unused-expression219    expect(result.success).to.be.true;220    expect(result.collectionId).to.be.equal(BcollectionCount);221    // tslint:disable-next-line:no-unused-expression222    expect(collection).to.be.not.null;223    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');224    expect(collection.Owner).to.be.equal(alicesPublicKey);225    expect(utf16ToStr(collection.Name)).to.be.equal(name);226    expect(utf16ToStr(collection.Description)).to.be.equal(description);227    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);228229    collectionId = result.collectionId;230  });231232  return collectionId;233}234235export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {236  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};237238  let modeprm = {};239  if (mode.type === 'NFT') {240    modeprm = {nft: null};241  } else if (mode.type === 'Fungible') {242    modeprm = {fungible: mode.decimalPoints};243  } else if (mode.type === 'ReFungible') {244    modeprm = {refungible: null};245  } else if (mode.type === 'Invalid') {246    modeprm = {invalid: null};247  }248249  await usingApi(async (api) => {250    // Get number of collections before the transaction251    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());252253    // Run the CreateCollection transaction254    const alicePrivateKey = privateKey('//Alice');255    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);256    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257    const result = getCreateCollectionResult(events);258259    // Get number of collections after the transaction260    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());261262    // What to expect263    // tslint:disable-next-line:no-unused-expression264    expect(result.success).to.be.false;265    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');266  });267}268269export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {270  let bal = new BigNumber(0);271  let unused;272  do {273    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;274    const keyring = new Keyring({ type: 'sr25519' });275    unused = keyring.addFromUri(`//${randomSeed}`);276    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());277  } while (bal.toFixed() != '0');278  return unused;279}280281export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {282  return await usingApi(async (api) => {283    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;284    return BigInt(bn.toString());285  });286}287288export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {289  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));290}291292export async function findNotExistingCollection(api: ApiPromise): Promise<number> {293  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;294  const newCollection: number = totalNumber + 1;295  return newCollection;296}297298function getDestroyResult(events: EventRecord[]): boolean {299  let success: boolean = false;300  events.forEach(({ phase, event: { data, method, section } }) => {301    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);302    if (method == 'ExtrinsicSuccess') {303      success = true;304    }305  });306  return success;307}308309export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {310  await usingApi(async (api) => {311    // Run the DestroyCollection transaction312    const alicePrivateKey = privateKey(senderSeed);313    const tx = api.tx.nft.destroyCollection(collectionId);314    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;315  });316}317318export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {319  await usingApi(async (api) => {320    // Run the DestroyCollection transaction321    const alicePrivateKey = privateKey(senderSeed);322    const tx = api.tx.nft.destroyCollection(collectionId);323    const events = await submitTransactionAsync(alicePrivateKey, tx);324    const result = getDestroyResult(events);325326    // Get the collection327    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329    // What to expect330    expect(result).to.be.true;331    expect(collection).to.be.not.null;332    expect(collection.Owner).to.be.equal(nullPublicKey);333  });334}335336export async function queryCollectionLimits(collectionId: number) {337  return await usingApi(async (api) => {338    return ((await api.query.nft.collection(collectionId)).toJSON() as any).Limits;339  });340}341342export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {343  await usingApi(async (api) => {344    const oldLimits = await queryCollectionLimits(collectionId);345    const newLimits = { ...oldLimits as any, ...limits };346    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);347    const events = await submitTransactionAsync(sender, tx);348    const result = getGenericResult(events);349350    expect(result.success).to.be.true;351  });352}353354export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {355  await usingApi(async (api) => {356    const oldLimits = await queryCollectionLimits(collectionId);357    const newLimits = { ...oldLimits as any, ...limits };358    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);359    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;360    const result = getGenericResult(events);361362    expect(result.success).to.be.false;363  });364}365366export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {367  await usingApi(async (api) => {368369    // Run the transaction370    const alicePrivateKey = privateKey('//Alice');371    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);372    const events = await submitTransactionAsync(alicePrivateKey, tx);373    const result = getGenericResult(events);374375    // Get the collection376    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();377378    // What to expect379    expect(result.success).to.be.true;380    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());381    expect(collection.SponsorConfirmed).to.be.false;382  });383}384385export async function removeCollectionSponsorExpectSuccess(collectionId: number) {386  await usingApi(async (api) => {387388    // Run the transaction389    const alicePrivateKey = privateKey('//Alice');390    const tx = api.tx.nft.removeCollectionSponsor(collectionId);391    const events = await submitTransactionAsync(alicePrivateKey, tx);392    const result = getGenericResult(events);393394    // Get the collection395    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();396397    // What to expect398    expect(result.success).to.be.true;399    expect(collection.Sponsor).to.be.equal(nullPublicKey);400    expect(collection.SponsorConfirmed).to.be.false;401  });402}403404export async function removeCollectionSponsorExpectFailure(collectionId: number) {405  await usingApi(async (api) => {406407    // Run the transaction408    const alicePrivateKey = privateKey('//Alice');409    const tx = api.tx.nft.removeCollectionSponsor(collectionId);410    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;411  });412}413414export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {415  await usingApi(async (api) => {416417    // Run the transaction418    const alicePrivateKey = privateKey(senderSeed);419    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);420    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;421  });422}423424export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {425  await usingApi(async (api) => {426427    // Run the transaction428    const sender = privateKey(senderSeed);429    const tx = api.tx.nft.confirmSponsorship(collectionId);430    const events = await submitTransactionAsync(sender, tx);431    const result = getGenericResult(events);432433    // Get the collection434    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();435436    // What to expect437    expect(result.success).to.be.true;438    expect(collection.Sponsor).to.be.equal(sender.address);439    expect(collection.SponsorConfirmed).to.be.true;440  });441}442443444export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {445  await usingApi(async (api) => {446447    // Run the transaction448    const sender = privateKey(senderSeed);449    const tx = api.tx.nft.confirmSponsorship(collectionId);450    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;451  });452}453454export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {455  await usingApi(async (api) => {456    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);457    const events = await submitTransactionAsync(sender, tx);458    const result = getGenericResult(events);459460    expect(result.success).to.be.true;461  });462}463464export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {465  await usingApi(async (api) => {466    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);467    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;468    const result = getGenericResult(events);469470    expect(result.success).to.be.false;471  });472}473474export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {475  await usingApi(async (api) => {476    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);477    const events = await submitTransactionAsync(sender, tx);478    const result = getGenericResult(events);479480    expect(result.success).to.be.true;481  });482}483484export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {485  await usingApi(async (api) => {486    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);487    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;488    const result = getGenericResult(events);489490    expect(result.success).to.be.false;491  });492}493494export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {495  await usingApi(async (api) => {496    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);497    const events = await submitTransactionAsync(sender, tx);498    const result = getGenericResult(events);499500    expect(result.success).to.be.true;501  });502}503504export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {505  let whitelisted: boolean = false;506  await usingApi(async (api) => {507    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;508  });509  return whitelisted;510}511512export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {513  await usingApi(async (api) => {514    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);515    const events = await submitTransactionAsync(sender, tx);516    const result = getGenericResult(events);517518    expect(result.success).to.be.true;519  });520}521522export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {523  await usingApi(async (api) => {524    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);525    const events = await submitTransactionAsync(sender, tx);526    const result = getGenericResult(events);527528    expect(result.success).to.be.true;529  });530}531532export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {533  await usingApi(async (api) => {534    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);535    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;536    const result = getGenericResult(events);537538    expect(result.success).to.be.false;539  });540}541542export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {543  await usingApi(async (api) => {544    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));545    const events = await submitTransactionAsync(sender, tx);546    const result = getGenericResult(events);547548    expect(result.success).to.be.true;549  });550}551552export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {553  await usingApi(async (api) => {554    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));555    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;556  });557}558559export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {560  await usingApi(async (api) => {561    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));562    const events = await submitTransactionAsync(sender, tx);563    const result = getGenericResult(events);564565    expect(result.success).to.be.true;566  });567}568569export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {570  await usingApi(async (api) => {571    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));572    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;573  });574}575576export interface CreateFungibleData {577  readonly Value: bigint;578}579580export interface CreateReFungibleData { }581export interface CreateNftData { }582583export type CreateItemData = {584  NFT: CreateNftData;585} | {586  Fungible: CreateFungibleData;587} | {588  ReFungible: CreateReFungibleData;589};590591export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {592  await usingApi(async (api) => {593    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);594    const events = await submitTransactionAsync(owner, tx);595    const result = getGenericResult(events);596    // Get the item597    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();598    // What to expect599    // tslint:disable-next-line:no-unused-expression600    expect(result.success).to.be.true;601    // tslint:disable-next-line:no-unused-expression602    expect(item).to.be.not.null;603    expect(item.Owner).to.be.equal(nullPublicKey);604  });605}606607export async function608approveExpectSuccess(collectionId: number,609                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {610  await usingApi(async (api: ApiPromise) => {611    const allowanceBefore =612      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;613    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);614    const events = await submitTransactionAsync(owner, approveNftTx);615    const result = getCreateItemResult(events);616    // tslint:disable-next-line:no-unused-expression617    expect(result.success).to.be.true;618    const allowanceAfter =619      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;620    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());621  });622}623624export async function625transferFromExpectSuccess(collectionId: number,626                          tokenId: number,627                          accountApproved: IKeyringPair,628                          accountFrom: IKeyringPair,629                          accountTo: IKeyringPair,630                          value: number | bigint = 1,631                          type: string = 'NFT') {632  await usingApi(async (api: ApiPromise) => {633    let balanceBefore = new BN(0);634    if (type === 'Fungible') {635      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;636    }637    const transferFromTx = await api.tx.nft.transferFrom(638      accountFrom.address, accountTo.address, collectionId, tokenId, value);639    const events = await submitTransactionAsync(accountApproved, transferFromTx);640    const result = getCreateItemResult(events);641    // tslint:disable-next-line:no-unused-expression642    expect(result.success).to.be.true;643    if (type === 'NFT') {644      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;645      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);646    }647    if (type === 'Fungible') {648      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;649      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());650    }651    if (type === 'ReFungible') {652      const nftItemData =653        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;654      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);655      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);656    }657  });658}659660export async function661transferFromExpectFail(collectionId: number,662                       tokenId: number,663                       accountApproved: IKeyringPair,664                       accountFrom: IKeyringPair,665                       accountTo: IKeyringPair,666                       value: number | bigint = 1) {667  await usingApi(async (api: ApiPromise) => {668    const transferFromTx = await api.tx.nft.transferFrom(669      accountFrom.address, accountTo.address, collectionId, tokenId, value);670    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;671    const result = getCreateCollectionResult(events);672    // tslint:disable-next-line:no-unused-expression673    expect(result.success).to.be.false;674  });675}676677export async function678transferExpectSuccess(collectionId: number,679                      tokenId: number,680                      sender: IKeyringPair,681                      recipient: IKeyringPair,682                      value: number | bigint = 1,683                      type: string = 'NFT') {684  await usingApi(async (api: ApiPromise) => {685    let balanceBefore = new BN(0);686    if (type === 'Fungible') {687      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;688    }689    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);690    const events = await submitTransactionAsync(sender, transferTx);691    const result = getTransferResult(events);692    // tslint:disable-next-line:no-unused-expression693    expect(result.success).to.be.true;694    expect(result.collectionId).to.be.equal(collectionId);695    expect(result.itemId).to.be.equal(tokenId);696    expect(result.sender).to.be.equal(sender.address);697    expect(result.recipient).to.be.equal(recipient.address);698    expect(result.value.toString()).to.be.equal(value.toString());699    if (type === 'NFT') {700      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;701      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);702    }703    if (type === 'Fungible') {704      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;705      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());706    }707    if (type === 'ReFungible') {708      const nftItemData =709        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;710      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);711      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);712    }713  });714}715716export async function717transferExpectFail(collectionId: number,718                   tokenId: number,719                   sender: IKeyringPair,720                   recipient: IKeyringPair,721                   value: number | bigint = 1,722                   type: string = 'NFT') {723  await usingApi(async (api: ApiPromise) => {724    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);725    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;726    if (events && Array.isArray(events)) {727      const result = getCreateCollectionResult(events);728      // tslint:disable-next-line:no-unused-expression729      expect(result.success).to.be.false;730    }731  });732}733734export async function735approveExpectFail(collectionId: number,736                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {737  await usingApi(async (api: ApiPromise) => {738    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);739    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;740    const result = getCreateCollectionResult(events);741    // tslint:disable-next-line:no-unused-expression742    expect(result.success).to.be.false;743  });744}745746export async function getFungibleBalance(747  collectionId: number,748  owner: string,749) {750  return await usingApi(async (api) => {751    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};752    return BigInt(response.Value);753  });754}755756export async function createFungibleItemExpectSuccess(757  sender: IKeyringPair,758  collectionId: number,759  data: CreateFungibleData,760  owner: string = sender.address,761) {762  return await usingApi(async (api) => {763    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });764765    const events = await submitTransactionAsync(sender, tx);766    const result = getCreateItemResult(events);767768    expect(result.success).to.be.true;769    return result.itemId;770  });771}772773export async function createItemExpectSuccess(774  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {775  let newItemId: number = 0;776  await usingApi(async (api) => {777    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);778    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();779    const AItemBalance = new BigNumber(Aitem.Value);780781    if (owner === '') {782      owner = sender.address;783    }784785    let tx;786    if (createMode === 'Fungible') {787      const createData = {fungible: {value: 10}};788      tx = api.tx.nft.createItem(collectionId, owner, createData);789    } else if (createMode === 'ReFungible') {790      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};791      tx = api.tx.nft.createItem(collectionId, owner, createData);792    } else {793      tx = api.tx.nft.createItem(collectionId, owner, createMode);794    }795    const events = await submitTransactionAsync(sender, tx);796    const result = getCreateItemResult(events);797798    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);799    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();800    const BItemBalance = new BigNumber(Bitem.Value);801802    // What to expect803    // tslint:disable-next-line:no-unused-expression804    expect(result.success).to.be.true;805    if (createMode === 'Fungible') {806      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);807    } else {808      expect(BItemCount).to.be.equal(AItemCount + 1);809    }810    expect(collectionId).to.be.equal(result.collectionId);811    expect(BItemCount).to.be.equal(result.itemId);812    expect(owner).to.be.equal(result.recipient);813    newItemId = result.itemId;814  });815  return newItemId;816}817818export async function createItemExpectFailure(819  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {820  await usingApi(async (api) => {821    const tx = api.tx.nft.createItem(collectionId, owner, createMode);822    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;823    const result = getCreateItemResult(events);824825    expect(result.success).to.be.false;826  });827}828829export async function setPublicAccessModeExpectSuccess(830  sender: IKeyringPair, collectionId: number,831  accessMode: 'Normal' | 'WhiteList',832) {833  await usingApi(async (api) => {834835    // Run the transaction836    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);837    const events = await submitTransactionAsync(sender, tx);838    const result = getGenericResult(events);839840    // Get the collection841    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();842843    // What to expect844    // tslint:disable-next-line:no-unused-expression845    expect(result.success).to.be.true;846    expect(collection.Access).to.be.equal(accessMode);847  });848}849850export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {851  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');852}853854export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {855  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');856}857858export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {859  await usingApi(async (api) => {860861    // Run the transaction862    const tx = api.tx.nft.setMintPermission(collectionId, enabled);863    const events = await submitTransactionAsync(sender, tx);864    const result = getGenericResult(events);865866    // Get the collection867    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();868869    // What to expect870    // tslint:disable-next-line:no-unused-expression871    expect(result.success).to.be.true;872    expect(collection.MintMode).to.be.equal(enabled);873  });874}875876export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {877  await setMintPermissionExpectSuccess(sender, collectionId, true);878}879880export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {881  await usingApi(async (api) => {882    // Run the transaction883    const tx = api.tx.nft.setMintPermission(collectionId, enabled);884    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;885    const result = getCreateCollectionResult(events);886    // tslint:disable-next-line:no-unused-expression887    expect(result.success).to.be.false;888  });889}890891export async function isWhitelisted(collectionId: number, address: string) {892  let whitelisted: boolean = false;893  await usingApi(async (api) => {894    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;895  });896  return whitelisted;897}898899export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {900  await usingApi(async (api) => {901902    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();903904    // Run the transaction905    const tx = api.tx.nft.addToWhiteList(collectionId, address);906    const events = await submitTransactionAsync(sender, tx);907    const result = getGenericResult(events);908909    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();910911    // What to expect912    // tslint:disable-next-line:no-unused-expression913    expect(result.success).to.be.true;914    // tslint:disable-next-line: no-unused-expression915    expect(whiteListedBefore).to.be.false;916    // tslint:disable-next-line: no-unused-expression917    expect(whiteListedAfter).to.be.true;918  });919}920921export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {922  await usingApi(async (api) => {923    // Run the transaction924    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);925    const events = await submitTransactionAsync(sender, tx);926    const result = getGenericResult(events);927928    // What to expect929    // tslint:disable-next-line:no-unused-expression930    expect(result.success).to.be.true;931  });932}933934export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {935  await usingApi(async (api) => {936    // Run the transaction937    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);938    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;939    const result = getGenericResult(events);940941    // What to expect942    // tslint:disable-next-line:no-unused-expression943    expect(result.success).to.be.false;944  });945}946947export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)948  : Promise<ICollectionInterface | null> => {949  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;950};951952export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {953  // set global object - collectionsCount954  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();955};956957export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {958  return await usingApi(async (api) => {959    return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;960  });961}