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

difftreelog

Merge remote-tracking branch 'origin/feature/NFTPAR-373_chain_extensions' into feature/NFTPAR-366_upstream_updates

Yaroslav Bolyukin2021-06-04parents: #e2828aa #6df0cda.patch.diff
in: master

8 files changed

modified.devcontainer/Dockerfilediffbeforeafterboth
--- a/.devcontainer/Dockerfile
+++ b/.devcontainer/Dockerfile
@@ -3,6 +3,9 @@
 RUN apt-get update && export DEBIAN_FRONTEND=noninteractive && \
     apt-get -y install --no-install-recommends libssl-dev pkg-config libclang-dev clang
 
+RUN curl -L -o- https://github.com/WebAssembly/binaryen/releases/download/version_101/binaryen-version_101-x86_64-linux.tar.gz | \
+    tar xz --strip-components=1 -C /usr
+
 USER vscode
 
 RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash && \
@@ -14,4 +17,4 @@
     rustup default nightly-2021-05-30 && \
     rustup target add wasm32-unknown-unknown && \
     rustup component add rustfmt clippy && \
-    cargo install cargo-expand cargo-edit
+    cargo install cargo-expand cargo-edit cargo-contract
modifiedruntime/src/chain_extension.rsdiffbeforeafterboth
--- a/runtime/src/chain_extension.rs
+++ b/runtime/src/chain_extension.rs
@@ -97,7 +97,7 @@
                 let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
 
                 pallet_nft::Module::<C>::transfer_internal(
-                    &C::CrossAccountId::from_sub(env.ext().caller().clone()),
+                    &C::CrossAccountId::from_sub(env.ext().address().clone()),
                     &C::CrossAccountId::from_sub(input.recipient),
                     &collection,
                     input.token_id,
modifiedsmart_contracs/transfer/Cargo.tomldiffbeforeafterboth
--- a/smart_contracs/transfer/Cargo.toml
+++ b/smart_contracs/transfer/Cargo.toml
@@ -4,15 +4,17 @@
 authors = ["[Greg Zaitsev] <[your_email]>"]
 edition = "2018"
 
+[workspace]
+
 [dependencies]
-ink_primitives = { git = "https://github.com/usetech-llc/ink", branch = "unique", default-features = false }
-ink_metadata = { git = "https://github.com/usetech-llc/ink", branch = "unique", default-features = false, features = ["derive"], optional = true }
-ink_env = { git = "https://github.com/usetech-llc/ink", branch = "unique", default-features = false }
-ink_storage = { git = "https://github.com/usetech-llc/ink", branch = "unique", default-features = false }
-ink_lang = { git = "https://github.com/usetech-llc/ink", branch = "unique", default-features = false }
+ink_primitives = { default-features = false }
+ink_metadata = { default-features = false, features = ["derive"], optional = true }
+ink_env = { default-features = false }
+ink_storage = { default-features = false }
+ink_lang = { default-features = false }
 
-scale = { package = "parity-scale-codec", version = "1.3", default-features = false, features = ["derive"] }
-scale-info = { version = "0.4.1", default-features = false, features = ["derive"], optional = true }
+scale = { package = "parity-scale-codec", version = "2.1.1", default-features = false, features = ["derive"] }
+scale-info = { version = "0.6.0", default-features = false, features = ["derive"] }
 
 [lib]
 name = "nft_transfer"
@@ -28,6 +30,7 @@
     "ink_metadata/std",
     "ink_env/std",
     "ink_storage/std",
+    "ink_lang/std",
     "ink_primitives/std",
     "scale/std",
     "scale-info/std",
modifiedsmart_contracs/transfer/lib.rsdiffbeforeafterboth
--- a/smart_contracs/transfer/lib.rs
+++ b/smart_contracs/transfer/lib.rs
@@ -1,4 +1,6 @@
 #![cfg_attr(not(feature = "std"), no_std)]
+extern crate alloc;
+use alloc::vec::Vec;
 
 use ink_lang as ink;
 use ink_env::{Environment, DefaultEnvironment};
@@ -36,6 +38,24 @@
     }
 }
 
+#[derive(scale::Encode, scale::Decode, scale_info::TypeInfo)]
+pub enum CreateItemData {
+    Nft {
+        const_data: Vec<u8>,
+        variable_data: Vec<u8>,
+    },
+    Fungible {
+        value: u128,
+    },
+    ReFungible {
+        const_data: Vec<u8>,
+        variable_data: Vec<u8>,
+        pieces: u128,
+    },
+}
+
+type DefaultAccountId = <DefaultEnvironment as Environment>::AccountId;
+
 #[ink::chain_extension]
 pub trait NftChainExtension {
     type ErrorCode = NftErrorCode;
@@ -43,11 +63,26 @@
     /// Transfer one NFT token from sender
     ///
     #[ink(extension = 0, returns_result = false)]
-    fn transfer(recipient: <DefaultEnvironment as Environment>::AccountId, collection_id: u32, token_id: u32, amount: u128);
+    fn transfer(recipient: DefaultAccountId, collection_id: u32, token_id: u32, amount: u128);
+    #[ink(extension = 1, returns_result = false)]
+    fn create_item(owner: DefaultAccountId, collection_id: u32, data: CreateItemData);
+    #[ink(extension = 2, returns_result = false)]
+    fn create_multiple_items(owner: DefaultAccountId, collection_id: u32, data: Vec<CreateItemData>);
+    #[ink(extension = 3, returns_result = false)]
+    fn approve(spender: DefaultAccountId, collection_id: u32, item_id: u32, amount: u128);
+    #[ink(extension = 4, returns_result = false)]
+    fn transfer_from(owner: DefaultAccountId, recipient: DefaultAccountId, collection_id: u32, item_id: u32, amount: u128);
+    #[ink(extension = 5, returns_result = false)]
+    fn set_variable_meta_data(collection_id: u32, item_id: u32, data: Vec<u8>);
+    #[ink(extension = 6, returns_result = false)]
+    fn toggle_white_list(collection_id: u32, address: DefaultAccountId, whitelisted: bool);
 }
 
-#[ink::contract(env = crate::NftEnvironment)]
+#[ink::contract(env = crate::NftEnvironment, dynamic_storage_allocator = true)]
 mod nft_transfer {
+    use alloc::vec::Vec;
+    // use ink_storage::Vec;
+    use crate::CreateItemData;
 
     #[ink(storage)]
     pub struct NftTransfer {
@@ -69,6 +104,42 @@
                 .extension()
                 .transfer(recipient, collection_id, token_id, amount);
         }
+        #[ink(message)]
+        pub fn create_item(&mut self, recipient: AccountId, collection_id: u32, data: CreateItemData) {
+            let _ = self.env()
+                .extension()
+                .create_item(recipient, collection_id, data);
+        }
+        #[ink(message)]
+        pub fn create_multiple_items(&mut self, owner: AccountId, collection_id: u32, data: Vec<CreateItemData>) {
+            let _ = self.env()
+                .extension()
+                .create_multiple_items(owner, collection_id, data);
+        }
+        #[ink(message)]
+        pub fn approve(&mut self, spender: AccountId, collection_id: u32, item_id: u32, amount: u128) {
+            let _ = self.env()
+                .extension()
+                .approve(spender, collection_id, item_id, amount);
+        }
+        #[ink(message)]
+        pub fn transfer_from(&mut self, owner: AccountId, recipient: AccountId, collection_id: u32, item_id: u32, amount: u128) {
+            let _ = self.env()
+                .extension()
+                .transfer_from(owner, recipient, collection_id, item_id, amount);
+        }
+        #[ink(message)]
+        pub fn set_variable_meta_data(&mut self, collection_id: u32, item_id: u32, data: Vec<u8>) {
+            let _ = self.env()
+                .extension()
+                .set_variable_meta_data(collection_id, item_id, data);
+        }
+        #[ink(message)]
+        pub fn toggle_white_list(&mut self, collection_id: u32, address: AccountId, whitelisted: bool) {
+            let _ = self.env()
+                .extension()
+                .toggle_white_list(collection_id, address, whitelisted);
+        }
 
     }
 
modifiedtests/src/contracts.test.tsdiffbeforeafterboth
--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -16,10 +16,16 @@
 } from "./util/contracthelpers";
 
 import {
+  addToWhiteListExpectSuccess,
+  approveExpectSuccess,
   createCollectionExpectSuccess,
   createItemExpectSuccess,
+  enablePublicMintingExpectSuccess,
+  enableWhiteListExpectSuccess,
   getGenericResult,
-  normalizeAccountId
+  normalizeAccountId,
+  isWhitelisted,
+  transferFromExpectSuccess
 } from "./util/helpers";
 
 
@@ -27,7 +33,7 @@
 const expect = chai.expect;
 
 const value = 0;
-const gasLimit = 3000n * 1000000n;
+const gasLimit = 9000n * 1000000n;
 const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';
 
 describe('Contracts', () => {
@@ -54,8 +60,10 @@
       expect(newContractInstance.address.toString()).to.equal(marketContractAddress);
     });
   });
+});
 
-  it('Can transfer NFT using smart contract.', async () => {
+describe.only('Chain extensions', () => {
+  it('Transfer CE', async () => {
     await usingApi(async api => {
       const alice = privateKey("//Alice");
       const bob = privateKey("//Bob");
@@ -64,6 +72,9 @@
       const collectionId = await createCollectionExpectSuccess();
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
       const [contract, deployer] = await deployTransferContract(api);
+      const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);
+      await submitTransactionAsync(alice, changeAdminTx);
+
       const tokenBefore: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON();
       
       // Transfer
@@ -78,4 +89,165 @@
       expect(tokenAfter.Owner).to.be.deep.equal(normalizeAccountId(bob.address));
     });
   });
+
+  it('Mint CE', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//Bob');
+
+      const collectionId = await createCollectionExpectSuccess();
+      const [contract, deployer] = await deployTransferContract(api);
+      await enablePublicMintingExpectSuccess(alice, collectionId);
+      await enableWhiteListExpectSuccess(alice, collectionId);
+      await addToWhiteListExpectSuccess(alice, collectionId, contract.address);
+      await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+
+      const transferTx = contract.tx.createItem(value, gasLimit, bob.address, collectionId, { Nft: {const_data: '0x010203', variable_data: '0x020304' }});
+      const events = await submitTransactionAsync(alice, transferTx);
+      const result = getGenericResult(events);
+      expect(result.success).to.be.true;
+
+      const tokensAfter: any = (await api.query.nft.nftItemList.entries(collectionId) as any).map((kv: any) => kv[1].toJSON());
+      expect(tokensAfter).to.be.deep.equal([
+        {
+          Owner: bob.address,
+          ConstData: '0x010203',
+          VariableData: '0x020304',
+        },
+      ]);
+    });
+  });
+
+  it('Bulk mint CE', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//Bob');
+
+      const collectionId = await createCollectionExpectSuccess();
+      const [contract, deployer] = await deployTransferContract(api);
+      await enablePublicMintingExpectSuccess(alice, collectionId);
+      await enableWhiteListExpectSuccess(alice, collectionId);
+      await addToWhiteListExpectSuccess(alice, collectionId, contract.address);
+      await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+
+      const transferTx = contract.tx.createMultipleItems(value, gasLimit, bob.address, collectionId, [
+        { Nft: { const_data: '0x010203', variable_data: '0x020304' } },
+        { Nft: { const_data: '0x010204', variable_data: '0x020305' } },
+        { Nft: { const_data: '0x010205', variable_data: '0x020306' } }
+      ]);
+      const events = await submitTransactionAsync(alice, transferTx);
+      const result = getGenericResult(events);
+      expect(result.success).to.be.true;
+
+      const tokensAfter: any = (await api.query.nft.nftItemList.entries(collectionId) as any)
+        .map((kv: any) => kv[1].toJSON())
+        .sort((a: any, b: any) => a.ConstData.localeCompare(b.ConstData));
+      expect(tokensAfter).to.be.deep.equal([
+        {
+          Owner: bob.address,
+          ConstData: '0x010203',
+          VariableData: '0x020304',
+        },
+        {
+          Owner: bob.address,
+          ConstData: '0x010204',
+          VariableData: '0x020305',
+        },
+        {
+          Owner: bob.address,
+          ConstData: '0x010205',
+          VariableData: '0x020306',
+        },
+      ]);
+    });
+  });
+
+  it('Approve CE', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//Bob');
+      const charlie = privateKey('//Charlie');
+
+      const collectionId = await createCollectionExpectSuccess();
+      const [contract, deployer] = await deployTransferContract(api);
+      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());
+
+      const transferTx = contract.tx.approve(value, gasLimit, bob.address, collectionId, tokenId, 1);
+      const events = await submitTransactionAsync(alice, transferTx);
+      const result = getGenericResult(events);
+      expect(result.success).to.be.true;
+
+      await transferFromExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), charlie, 1, 'NFT');
+    });
+  });
+
+  it('TransferFrom CE', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//Bob');
+      const charlie = privateKey('//Charlie');
+
+      const collectionId = await createCollectionExpectSuccess();
+      const [contract, deployer] = await deployTransferContract(api);
+      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+      await approveExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), 1);
+
+      const transferTx = contract.tx.transferFrom(value, gasLimit, bob.address, charlie.address, collectionId, tokenId, 1);
+      const events = await submitTransactionAsync(alice, transferTx);
+      const result = getGenericResult(events);
+      expect(result.success).to.be.true;
+
+      const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap()
+      expect(token.Owner.toString()).to.be.equal(charlie.address);
+    });
+  });
+
+  it('SetVariableMetaData CE', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+
+      const collectionId = await createCollectionExpectSuccess();
+      const [contract, deployer] = await deployTransferContract(api);
+      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());
+
+      const transferTx = contract.tx.setVariableMetaData(value, gasLimit, collectionId, tokenId, '0x121314');
+      const events = await submitTransactionAsync(alice, transferTx);
+      const result = getGenericResult(events);
+      expect(result.success).to.be.true;
+
+      const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap()
+      expect(token.VariableData.toString()).to.be.equal('0x121314');
+    });
+  });
+
+  it('ToggleWhiteList CE', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//Bob');
+
+      const collectionId = await createCollectionExpectSuccess();
+      const [contract, deployer] = await deployTransferContract(api);
+      const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);
+      await submitTransactionAsync(alice, changeAdminTx);      
+
+      expect(await isWhitelisted(collectionId, bob.address)).to.be.false;
+
+      {
+        const transferTx = contract.tx.toggleWhiteList(value, gasLimit, collectionId, bob.address, true);
+        const events = await submitTransactionAsync(alice, transferTx);
+        const result = getGenericResult(events);
+        expect(result.success).to.be.true;
+
+        expect(await isWhitelisted(collectionId, bob.address)).to.be.true;
+      }
+      {
+        const transferTx = contract.tx.toggleWhiteList(value, gasLimit, collectionId, bob.address, false);
+        const events = await submitTransactionAsync(alice, transferTx);
+        const result = getGenericResult(events);
+        expect(result.success).to.be.true;
+
+        expect(await isWhitelisted(collectionId, bob.address)).to.be.false;
+      }
+    });
+  });
 });
modifiedtests/src/transfer_contract/metadata.jsondiffbeforeafterboth
--- a/tests/src/transfer_contract/metadata.json
+++ b/tests/src/transfer_contract/metadata.json
@@ -1,9 +1,9 @@
 {
   "metadataVersion": "0.1.0",
   "source": {
-    "hash": "0xfbbc0729acefed9d99f93f6cbb751d12e317958fd0fe183f5781329b37f1bf6e",
-    "language": "ink! 3.0.0-rc2",
-    "compiler": "rustc 1.51.0-nightly"
+    "hash": "0xc6c3f47adeafe86d1674ed72c7179605787842f2f05a2d7da0dbabf3c4fa1aa8",
+    "language": "ink! 3.0.0-rc3",
+    "compiler": "rustc 1.52.0-nightly"
   },
   "contract": {
     "name": "nft_transfer",
@@ -24,7 +24,7 @@
         "name": [
           "default"
         ],
-        "selector": "0x6a3712e2"
+        "selector": "0xed4b9d1b"
       }
     ],
     "docs": [],
@@ -78,7 +78,268 @@
         ],
         "payable": false,
         "returnType": null,
-        "selector": "0xfae3a09d"
+        "selector": "0x84a15da1"
+      },
+      {
+        "args": [
+          {
+            "name": "recipient",
+            "type": {
+              "displayName": [
+                "AccountId"
+              ],
+              "type": 1
+            }
+          },
+          {
+            "name": "collection_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "data",
+            "type": {
+              "displayName": [
+                "CreateItemData"
+              ],
+              "type": 6
+            }
+          }
+        ],
+        "docs": [],
+        "mutates": true,
+        "name": [
+          "create_item"
+        ],
+        "payable": false,
+        "returnType": null,
+        "selector": "0xd7c3f083"
+      },
+      {
+        "args": [
+          {
+            "name": "owner",
+            "type": {
+              "displayName": [
+                "AccountId"
+              ],
+              "type": 1
+            }
+          },
+          {
+            "name": "collection_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "data",
+            "type": {
+              "displayName": [
+                "Vec"
+              ],
+              "type": 8
+            }
+          }
+        ],
+        "docs": [],
+        "mutates": true,
+        "name": [
+          "create_multiple_items"
+        ],
+        "payable": false,
+        "returnType": null,
+        "selector": "0x15f9a1eb"
+      },
+      {
+        "args": [
+          {
+            "name": "spender",
+            "type": {
+              "displayName": [
+                "AccountId"
+              ],
+              "type": 1
+            }
+          },
+          {
+            "name": "collection_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "item_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "amount",
+            "type": {
+              "displayName": [
+                "u128"
+              ],
+              "type": 5
+            }
+          }
+        ],
+        "docs": [],
+        "mutates": true,
+        "name": [
+          "approve"
+        ],
+        "payable": false,
+        "returnType": null,
+        "selector": "0x681266a0"
+      },
+      {
+        "args": [
+          {
+            "name": "owner",
+            "type": {
+              "displayName": [
+                "AccountId"
+              ],
+              "type": 1
+            }
+          },
+          {
+            "name": "recipient",
+            "type": {
+              "displayName": [
+                "AccountId"
+              ],
+              "type": 1
+            }
+          },
+          {
+            "name": "collection_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "item_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "amount",
+            "type": {
+              "displayName": [
+                "u128"
+              ],
+              "type": 5
+            }
+          }
+        ],
+        "docs": [],
+        "mutates": true,
+        "name": [
+          "transfer_from"
+        ],
+        "payable": false,
+        "returnType": null,
+        "selector": "0x0b396f18"
+      },
+      {
+        "args": [
+          {
+            "name": "collection_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "item_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "data",
+            "type": {
+              "displayName": [
+                "Vec"
+              ],
+              "type": 7
+            }
+          }
+        ],
+        "docs": [],
+        "mutates": true,
+        "name": [
+          "set_variable_meta_data"
+        ],
+        "payable": false,
+        "returnType": null,
+        "selector": "0xb0b26da2"
+      },
+      {
+        "args": [
+          {
+            "name": "collection_id",
+            "type": {
+              "displayName": [
+                "u32"
+              ],
+              "type": 4
+            }
+          },
+          {
+            "name": "address",
+            "type": {
+              "displayName": [
+                "AccountId"
+              ],
+              "type": 1
+            }
+          },
+          {
+            "name": "whitelisted",
+            "type": {
+              "displayName": [
+                "bool"
+              ],
+              "type": 9
+            }
+          }
+        ],
+        "docs": [],
+        "mutates": true,
+        "name": [
+          "toggle_white_list"
+        ],
+        "payable": false,
+        "returnType": null,
+        "selector": "0x98574dac"
       }
     ]
   },
@@ -93,7 +354,8 @@
         "composite": {
           "fields": [
             {
-              "type": 2
+              "type": 2,
+              "typeName": "[u8; 32]"
             }
           ]
         }
@@ -126,6 +388,82 @@
       "def": {
         "primitive": "u128"
       }
+    },
+    {
+      "def": {
+        "variant": {
+          "variants": [
+            {
+              "fields": [
+                {
+                  "name": "const_data",
+                  "type": 7,
+                  "typeName": "Vec<u8>"
+                },
+                {
+                  "name": "variable_data",
+                  "type": 7,
+                  "typeName": "Vec<u8>"
+                }
+              ],
+              "name": "Nft"
+            },
+            {
+              "fields": [
+                {
+                  "name": "value",
+                  "type": 5,
+                  "typeName": "u128"
+                }
+              ],
+              "name": "Fungible"
+            },
+            {
+              "fields": [
+                {
+                  "name": "const_data",
+                  "type": 7,
+                  "typeName": "Vec<u8>"
+                },
+                {
+                  "name": "variable_data",
+                  "type": 7,
+                  "typeName": "Vec<u8>"
+                },
+                {
+                  "name": "pieces",
+                  "type": 5,
+                  "typeName": "u128"
+                }
+              ],
+              "name": "ReFungible"
+            }
+          ]
+        }
+      },
+      "path": [
+        "nft_transfer",
+        "CreateItemData"
+      ]
+    },
+    {
+      "def": {
+        "sequence": {
+          "type": 3
+        }
+      }
+    },
+    {
+      "def": {
+        "sequence": {
+          "type": 6
+        }
+      }
+    },
+    {
+      "def": {
+        "primitive": "bool"
+      }
     }
   ]
 }
\ No newline at end of file
modifiedtests/src/transfer_contract/nft_transfer.wasmdiffbeforeafterboth

binary blob — no preview

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 type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { u128 } from '@polkadot/types/primitive';9import { IKeyringPair } from '@polkadot/types/types';10import { evmToAddress } from '@polkadot/util-crypto';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 type CrossAccountId = {25  substrate: string,26} | {27  ethereum: string,28};29export function normalizeAccountId(input: string | CrossAccountId | IKeyringPair): CrossAccountId {30  if (typeof input === 'string')31    return { substrate: input };32  if ('address' in input) {33    return { substrate: input.address };34  }35  if ('ethereum' in input) {36    input.ethereum = input.ethereum.toLowerCase();37  }38  return input;39}40export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {41  input = normalizeAccountId(input);42  if ('substrate' in input) {43    return input.substrate;44  } else {45    return evmToAddress(input.ethereum);46  }47}4849export const U128_MAX = (1n << 128n) - 1n;5051type GenericResult = {52  success: boolean,53};5455interface CreateCollectionResult {56  success: boolean;57  collectionId: number;58}5960interface CreateItemResult {61  success: boolean;62  collectionId: number;63  itemId: number;64  recipient?: CrossAccountId;65}6667interface TransferResult {68  success: boolean;69  collectionId: number;70  itemId: number;71  sender?: CrossAccountId;72  recipient?: CrossAccountId;73  value: bigint;74}7576interface IReFungibleOwner {77  Fraction: BN;78  Owner: number[];79}8081interface ITokenDataType {82  Owner: number[];83  ConstData: number[];84  VariableData: number[];85}8687interface IFungibleTokenDataType {88  Value: BN;89}9091interface IGetMessage {92  checkMsgNftMethod: string;93  checkMsgTrsMethod: string;94  checkMsgSysMethod: string;95}9697export interface IReFungibleTokenDataType {98  Owner: IReFungibleOwner[];99  ConstData: number[];100  VariableData: number[];101}102103export function nftEventMessage(events: EventRecord[]): IGetMessage {104  let checkMsgNftMethod: string = '';105  let checkMsgTrsMethod: string = '';106  let checkMsgSysMethod: string = '';107  events.forEach(({ event: { method, section } }) => {108    if (section === 'nft') {109      checkMsgNftMethod = method;110    } else if (section === 'treasury') {111      checkMsgTrsMethod = method;112    } else if (section === 'system') {113      checkMsgSysMethod = method;114    } else { return null; }115  });116  const result: IGetMessage = {117    checkMsgNftMethod,118    checkMsgTrsMethod,119    checkMsgSysMethod,120  };121  return result;122}123124export function getGenericResult(events: EventRecord[]): GenericResult {125  const result: GenericResult = {126    success: false,127  };128  events.forEach(({ phase, event: { data, method, section } }) => {129    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);130    if (method === 'ExtrinsicSuccess') {131      result.success = true;132    }133  });134  return result;135}136137138139export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {140  let success = false;141  let collectionId: number = 0;142  events.forEach(({ phase, event: { data, method, section } }) => {143    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);144    if (method == 'ExtrinsicSuccess') {145      success = true;146    } else if ((section == 'nft') && (method == 'CollectionCreated')) {147      collectionId = parseInt(data[0].toString());148    }149  });150  const result: CreateCollectionResult = {151    success,152    collectionId,153  };154  return result;155}156157export function getCreateItemResult(events: EventRecord[]): CreateItemResult {158  let success = false;159  let collectionId: number = 0;160  let itemId: number = 0;161  let recipient;162  events.forEach(({ phase, event: { data, method, section } }) => {163    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);164    if (method == 'ExtrinsicSuccess') {165      success = true;166    } else if ((section == 'nft') && (method == 'ItemCreated')) {167      collectionId = parseInt(data[0].toString());168      itemId = parseInt(data[1].toString());169      recipient = data[2].toJSON();170    }171  });172  const result: CreateItemResult = {173    success,174    collectionId,175    itemId,176    recipient,177  };178  return result;179}180181export function getTransferResult(events: EventRecord[]): TransferResult {182  const result: TransferResult = {183    success: false,184    collectionId: 0,185    itemId: 0,186    value: 0n,187  };188189  events.forEach(({ event: { data, method, section } }) => {190    if (method === 'ExtrinsicSuccess') {191      result.success = true;192    } else if (section === 'nft' && method === 'Transfer') {193      result.collectionId = +data[0].toString();194      result.itemId = +data[1].toString();195      result.sender = data[2].toJSON() as CrossAccountId;196      result.recipient = data[3].toJSON() as CrossAccountId;197      result.value = BigInt(data[4].toString());198    }199  });200201  return result;202}203204interface Invalid {205  type: 'Invalid';206}207208interface Nft {209  type: 'NFT';210}211212interface Fungible {213  type: 'Fungible';214  decimalPoints: number;215}216217interface ReFungible {218  type: 'ReFungible';219}220221type CollectionMode = Nft | Fungible | ReFungible | Invalid;222223export type CreateCollectionParams = {224  mode: CollectionMode,225  name: string,226  description: string,227  tokenPrefix: string,228};229230const defaultCreateCollectionParams: CreateCollectionParams = {231  description: 'description',232  mode: { type: 'NFT' },233  name: 'name',234  tokenPrefix: 'prefix',235}236237export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {238  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };239240  let collectionId: number = 0;241  await usingApi(async (api) => {242    // Get number of collections before the transaction243    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244245    // Run the CreateCollection transaction246    const alicePrivateKey = privateKey('//Alice');247248    let modeprm = {};249    if (mode.type === 'NFT') {250      modeprm = { nft: null };251    } else if (mode.type === 'Fungible') {252      modeprm = { fungible: mode.decimalPoints };253    } else if (mode.type === 'ReFungible') {254      modeprm = { refungible: null };255    } else if (mode.type === 'Invalid') {256      modeprm = { invalid: null };257    }258259    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);260    const events = await submitTransactionAsync(alicePrivateKey, tx);261    const result = getCreateCollectionResult(events);262263    // Get number of collections after the transaction264    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);265266    // Get the collection267    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();268269    // What to expect270    // tslint:disable-next-line:no-unused-expression271    expect(result.success).to.be.true;272    expect(result.collectionId).to.be.equal(BcollectionCount);273    // tslint:disable-next-line:no-unused-expression274    expect(collection).to.be.not.null;275    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');276    expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));277    expect(utf16ToStr(collection.Name)).to.be.equal(name);278    expect(utf16ToStr(collection.Description)).to.be.equal(description);279    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);280281    collectionId = result.collectionId;282  });283284  return collectionId;285}286287export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {288  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };289290  let modeprm = {};291  if (mode.type === 'NFT') {292    modeprm = { nft: null };293  } else if (mode.type === 'Fungible') {294    modeprm = { fungible: mode.decimalPoints };295  } else if (mode.type === 'ReFungible') {296    modeprm = { refungible: null };297  } else if (mode.type === 'Invalid') {298    modeprm = { invalid: null };299  }300301  await usingApi(async (api) => {302    // Get number of collections before the transaction303    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());304305    // Run the CreateCollection transaction306    const alicePrivateKey = privateKey('//Alice');307    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);308    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;309    const result = getCreateCollectionResult(events);310311    // Get number of collections after the transaction312    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());313314    // What to expect315    // tslint:disable-next-line:no-unused-expression316    expect(result.success).to.be.false;317    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');318  });319}320321export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {322  let bal = new BigNumber(0);323  let unused;324  do {325    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;326    const keyring = new Keyring({ type: 'sr25519' });327    unused = keyring.addFromUri(`//${randomSeed}`);328    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());329  } while (bal.toFixed() != '0');330  return unused;331}332333export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {334  return await usingApi(async (api) => {335    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;336    return BigInt(bn.toString());337  });338}339340export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {341  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));342}343344export async function findNotExistingCollection(api: ApiPromise): Promise<number> {345  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;346  const newCollection: number = totalNumber + 1;347  return newCollection;348}349350function getDestroyResult(events: EventRecord[]): boolean {351  let success: boolean = false;352  events.forEach(({ phase, event: { data, method, section } }) => {353    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);354    if (method == 'ExtrinsicSuccess') {355      success = true;356    }357  });358  return success;359}360361export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {362  await usingApi(async (api) => {363    // Run the DestroyCollection transaction364    const alicePrivateKey = privateKey(senderSeed);365    const tx = api.tx.nft.destroyCollection(collectionId);366    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;367  });368}369370export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {371  await usingApi(async (api) => {372    // Run the DestroyCollection transaction373    const alicePrivateKey = privateKey(senderSeed);374    const tx = api.tx.nft.destroyCollection(collectionId);375    const events = await submitTransactionAsync(alicePrivateKey, tx);376    const result = getDestroyResult(events);377378    // Get the collection379    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();380381    // What to expect382    expect(result).to.be.true;383    expect(collection).to.be.null;384  });385}386387export async function queryCollectionLimits(collectionId: number) {388  return await usingApi(async (api) => {389    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;390  });391}392393export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {394  await usingApi(async (api) => {395    const oldLimits = await queryCollectionLimits(collectionId);396    const newLimits = { ...oldLimits as any, ...limits };397    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);398    const events = await submitTransactionAsync(sender, tx);399    const result = getGenericResult(events);400401    expect(result.success).to.be.true;402  });403}404405export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const oldLimits = await queryCollectionLimits(collectionId);408    const newLimits = { ...oldLimits as any, ...limits };409    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);410    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;411    const result = getGenericResult(events);412413    expect(result.success).to.be.false;414  });415}416417export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {418  await usingApi(async (api) => {419420    // Run the transaction421    const alicePrivateKey = privateKey('//Alice');422    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);423    const events = await submitTransactionAsync(alicePrivateKey, tx);424    const result = getGenericResult(events);425426    // Get the collection427    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();428429    // What to expect430    expect(result.success).to.be.true;431    expect(collection.Sponsorship).to.deep.equal({432      unconfirmed: sponsor,433    });434  });435}436437export async function removeCollectionSponsorExpectSuccess(collectionId: number) {438  await usingApi(async (api) => {439440    // Run the transaction441    const alicePrivateKey = privateKey('//Alice');442    const tx = api.tx.nft.removeCollectionSponsor(collectionId);443    const events = await submitTransactionAsync(alicePrivateKey, tx);444    const result = getGenericResult(events);445446    // Get the collection447    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();448449    // What to expect450    expect(result.success).to.be.true;451    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });452  });453}454455export async function removeCollectionSponsorExpectFailure(collectionId: number) {456  await usingApi(async (api) => {457458    // Run the transaction459    const alicePrivateKey = privateKey('//Alice');460    const tx = api.tx.nft.removeCollectionSponsor(collectionId);461    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;462  });463}464465export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {466  await usingApi(async (api) => {467468    // Run the transaction469    const alicePrivateKey = privateKey(senderSeed);470    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);471    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;472  });473}474475export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {476  await usingApi(async (api) => {477478    // Run the transaction479    const sender = privateKey(senderSeed);480    const tx = api.tx.nft.confirmSponsorship(collectionId);481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    // Get the collection485    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();486487    // What to expect488    expect(result.success).to.be.true;489    expect(collection.Sponsorship).to.be.deep.equal({490      confirmed: sender.address,491    });492  });493}494495496export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {497  await usingApi(async (api) => {498499    // Run the transaction500    const sender = privateKey(senderSeed);501    const tx = api.tx.nft.confirmSponsorship(collectionId);502    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;503  });504}505506export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {507  await usingApi(async (api) => {508    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);509    const events = await submitTransactionAsync(sender, tx);510    const result = getGenericResult(events);511512    expect(result.success).to.be.true;513  });514}515516export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {517  await usingApi(async (api) => {518    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);519    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;520    const result = getGenericResult(events);521522    expect(result.success).to.be.false;523  });524}525526export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {527  await usingApi(async (api) => {528    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);529    const events = await submitTransactionAsync(sender, tx);530    const result = getGenericResult(events);531532    expect(result.success).to.be.true;533  });534}535536export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {537  await usingApi(async (api) => {538    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);539    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;540    const result = getGenericResult(events);541542    expect(result.success).to.be.false;543  });544}545546export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {547  await usingApi(async (api) => {548    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);549    const events = await submitTransactionAsync(sender, tx);550    const result = getGenericResult(events);551552    expect(result.success).to.be.true;553  });554}555556export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {557  let whitelisted: boolean = false;558  await usingApi(async (api) => {559    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;560  });561  return whitelisted;562}563564export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {565  await usingApi(async (api) => {566    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());567    const events = await submitTransactionAsync(sender, tx);568    const result = getGenericResult(events);569570    expect(result.success).to.be.true;571  });572}573574export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {575  await usingApi(async (api) => {576    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());577    const events = await submitTransactionAsync(sender, tx);578    const result = getGenericResult(events);579580    expect(result.success).to.be.true;581  });582}583584export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {585  await usingApi(async (api) => {586    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());587    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;588    const result = getGenericResult(events);589590    expect(result.success).to.be.false;591  });592}593594export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {595  await usingApi(async (api) => {596    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));597    const events = await submitTransactionAsync(sender, tx);598    const result = getGenericResult(events);599600    expect(result.success).to.be.true;601  });602}603604export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {605  await usingApi(async (api) => {606    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));607    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;608  });609}610611export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {612  await usingApi(async (api) => {613    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));614    const events = await submitTransactionAsync(sender, tx);615    const result = getGenericResult(events);616617    expect(result.success).to.be.true;618  });619}620621export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {622  await usingApi(async (api) => {623    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));624    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;625  });626}627628export interface CreateFungibleData {629  readonly Value: bigint;630}631632export interface CreateReFungibleData { }633export interface CreateNftData { }634635export type CreateItemData = {636  NFT: CreateNftData;637} | {638  Fungible: CreateFungibleData;639} | {640  ReFungible: CreateReFungibleData;641};642643export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {644  await usingApi(async (api) => {645    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);646    const events = await submitTransactionAsync(owner, tx);647    const result = getGenericResult(events);648    // Get the item649    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();650    // What to expect651    // tslint:disable-next-line:no-unused-expression652    expect(result.success).to.be.true;653    // tslint:disable-next-line:no-unused-expression654    expect(item).to.be.null;655  });656}657658export async function659  approveExpectSuccess(collectionId: number,660    tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1) {661  await usingApi(async (api: ApiPromise) => {662    approved = normalizeAccountId(approved);663    const allowanceBefore =664      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;665    const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);666    const events = await submitTransactionAsync(owner, approveNftTx);667    const result = getCreateItemResult(events);668    // tslint:disable-next-line:no-unused-expression669    expect(result.success).to.be.true;670    const allowanceAfter =671      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;672    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());673  });674}675676export async function677  transferFromExpectSuccess(collectionId: number,678    tokenId: number,679    accountApproved: IKeyringPair,680    accountFrom: IKeyringPair,681    accountTo: IKeyringPair | CrossAccountId,682    value: number | bigint = 1,683    type: string = 'NFT') {684  await usingApi(async (api: ApiPromise) => {685    const to = normalizeAccountId(accountTo);686    let balanceBefore = new BN(0);687    if (type === 'Fungible') {688      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;689    }690    const transferFromTx = api.tx.nft.transferFrom(691      normalizeAccountId(accountFrom.address), to, collectionId, tokenId, value);692    const events = await submitTransactionAsync(accountApproved, transferFromTx);693    const result = getCreateItemResult(events);694    // tslint:disable-next-line:no-unused-expression695    expect(result.success).to.be.true;696    if (type === 'NFT') {697      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;698      expect(nftItemData.Owner).to.be.deep.equal(to);699    }700    if (type === 'Fungible') {701      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;702      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());703    }704    if (type === 'ReFungible') {705      const nftItemData =706        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;707      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));708      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);709    }710  });711}712713export async function714  transferFromExpectFail(collectionId: number,715    tokenId: number,716    accountApproved: IKeyringPair,717    accountFrom: IKeyringPair,718    accountTo: IKeyringPair,719    value: number | bigint = 1) {720  await usingApi(async (api: ApiPromise) => {721    const transferFromTx = api.tx.nft.transferFrom(722      normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);723    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;724    const result = getCreateCollectionResult(events);725    // tslint:disable-next-line:no-unused-expression726    expect(result.success).to.be.false;727  });728}729730export async function731  transferExpectSuccess(collectionId: number,732    tokenId: number,733    sender: IKeyringPair,734    recipient: IKeyringPair | CrossAccountId,735    value: number | bigint = 1,736    type: string = 'NFT') {737  await usingApi(async (api: ApiPromise) => {738    const to = normalizeAccountId(recipient);739740    let balanceBefore = new BN(0);741    if (type === 'Fungible') {742      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;743    }744    const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);745    const events = await submitTransactionAsync(sender, transferTx);746    const result = getTransferResult(events);747    // tslint:disable-next-line:no-unused-expression748    expect(result.success).to.be.true;749    expect(result.collectionId).to.be.equal(collectionId);750    expect(result.itemId).to.be.equal(tokenId);751    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));752    expect(result.recipient).to.be.deep.equal(to);753    expect(result.value.toString()).to.be.equal(value.toString());754    if (type === 'NFT') {755      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;756      expect(nftItemData.Owner).to.be.deep.equal(to);757    }758    if (type === 'Fungible') {759      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;760      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());761    }762    if (type === 'ReFungible') {763      const nftItemData =764        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;765      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);766      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());767    }768  });769}770771export async function772  transferExpectFail(collectionId: number,773    tokenId: number,774    sender: IKeyringPair,775    recipient: IKeyringPair,776    value: number | bigint = 1,777    type: string = 'NFT') {778  await usingApi(async (api: ApiPromise) => {779    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);780    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;781    if (events && Array.isArray(events)) {782      const result = getCreateCollectionResult(events);783      // tslint:disable-next-line:no-unused-expression784      expect(result.success).to.be.false;785    }786  });787}788789export async function790  approveExpectFail(collectionId: number,791    tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {792  await usingApi(async (api: ApiPromise) => {793    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);794    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;795    const result = getCreateCollectionResult(events);796    // tslint:disable-next-line:no-unused-expression797    expect(result.success).to.be.false;798  });799}800801export async function getFungibleBalance(802  collectionId: number,803  owner: string,804) {805  return await usingApi(async (api) => {806    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };807    return BigInt(response.Value);808  });809}810811export async function createFungibleItemExpectSuccess(812  sender: IKeyringPair,813  collectionId: number,814  data: CreateFungibleData,815  owner: CrossAccountId | string = sender.address,816) {817  return await usingApi(async (api) => {818    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });819820    const events = await submitTransactionAsync(sender, tx);821    const result = getCreateItemResult(events);822823    expect(result.success).to.be.true;824    return result.itemId;825  });826}827828export async function createItemExpectSuccess(829  sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {830  let newItemId: number = 0;831  await usingApi(async (api) => {832    const to = normalizeAccountId(owner);833    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);834    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();835    const AItemBalance = new BigNumber(Aitem.Value);836837    let tx;838    if (createMode === 'Fungible') {839      const createData = { fungible: { value: 10 } };840      tx = api.tx.nft.createItem(collectionId, to, createData);841    } else if (createMode === 'ReFungible') {842      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };843      tx = api.tx.nft.createItem(collectionId, to, createData);844    } else {845      tx = api.tx.nft.createItem(collectionId, to, createMode);846    }847848    const events = await submitTransactionAsync(sender, tx);849    const result = getCreateItemResult(events);850851    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);852    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();853    const BItemBalance = new BigNumber(Bitem.Value);854855    // What to expect856    // tslint:disable-next-line:no-unused-expression857    expect(result.success).to.be.true;858    if (createMode === 'Fungible') {859      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);860    } else {861      expect(BItemCount).to.be.equal(AItemCount + 1);862    }863    expect(collectionId).to.be.equal(result.collectionId);864    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());865    expect(to).to.be.deep.equal(result.recipient);866    newItemId = result.itemId;867  });868  return newItemId;869}870871export async function createItemExpectFailure(872  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {873  await usingApi(async (api) => {874    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);875    876    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;877    const result = getCreateItemResult(events);878879    expect(result.success).to.be.false;880  });881}882883export async function setPublicAccessModeExpectSuccess(884  sender: IKeyringPair, collectionId: number,885  accessMode: 'Normal' | 'WhiteList',886) {887  await usingApi(async (api) => {888889    // Run the transaction890    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);891    const events = await submitTransactionAsync(sender, tx);892    const result = getGenericResult(events);893894    // Get the collection895    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();896897    // What to expect898    // tslint:disable-next-line:no-unused-expression899    expect(result.success).to.be.true;900    expect(collection.Access).to.be.equal(accessMode);901  });902}903904export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {905  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');906}907908export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {909  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');910}911912export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {913  await usingApi(async (api) => {914915    // Run the transaction916    const tx = api.tx.nft.setMintPermission(collectionId, enabled);917    const events = await submitTransactionAsync(sender, tx);918    const result = getGenericResult(events);919920    // Get the collection921    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();922923    // What to expect924    // tslint:disable-next-line:no-unused-expression925    expect(result.success).to.be.true;926    expect(collection.MintMode).to.be.equal(enabled);927  });928}929930export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {931  await setMintPermissionExpectSuccess(sender, collectionId, true);932}933934export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {935  await usingApi(async (api) => {936    // Run the transaction937    const tx = api.tx.nft.setMintPermission(collectionId, enabled);938    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;939    const result = getCreateCollectionResult(events);940    // tslint:disable-next-line:no-unused-expression941    expect(result.success).to.be.false;942  });943}944945export async function isWhitelisted(collectionId: number, address: string) {946  let whitelisted: boolean = false;947  await usingApi(async (api) => {948    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;949  });950  return whitelisted;951}952953export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {954  await usingApi(async (api) => {955956    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();957958    // Run the transaction959    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));960    const events = await submitTransactionAsync(sender, tx);961    const result = getGenericResult(events);962963    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();964965    // What to expect966    // tslint:disable-next-line:no-unused-expression967    expect(result.success).to.be.true;968    // tslint:disable-next-line: no-unused-expression969    expect(whiteListedBefore).to.be.false;970    // tslint:disable-next-line: no-unused-expression971    expect(whiteListedAfter).to.be.true;972  });973}974975export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {976  await usingApi(async (api) => {977    // Run the transaction978    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));979    const events = await submitTransactionAsync(sender, tx);980    const result = getGenericResult(events);981982    // What to expect983    // tslint:disable-next-line:no-unused-expression984    expect(result.success).to.be.true;985  });986}987988export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {989  await usingApi(async (api) => {990    // Run the transaction991    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));992    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;993    const result = getGenericResult(events);994995    // What to expect996    // tslint:disable-next-line:no-unused-expression997    expect(result.success).to.be.false;998  });999}10001001export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1002  : Promise<ICollectionInterface | null> => {1003  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1004};10051006export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1007  // set global object - collectionsCount1008  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1009};10101011export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1012  return await usingApi(async (api) => {1013    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1014  });1015}
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 type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { u128 } from '@polkadot/types/primitive';9import { IKeyringPair } from '@polkadot/types/types';10import { evmToAddress } from '@polkadot/util-crypto';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 type CrossAccountId = {25  substrate: string,26} | {27  ethereum: string,28};29export function normalizeAccountId(input: string | CrossAccountId | IKeyringPair): CrossAccountId {30  if (typeof input === 'string')31    return { substrate: input };32  if ('address' in input) {33    return { substrate: input.address };34  }35  if ('ethereum' in input) {36    input.ethereum = input.ethereum.toLowerCase();37  }38  return input;39}40export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {41  input = normalizeAccountId(input);42  if ('substrate' in input) {43    return input.substrate;44  } else {45    return evmToAddress(input.ethereum);46  }47}4849export const U128_MAX = (1n << 128n) - 1n;5051type GenericResult = {52  success: boolean,53};5455interface CreateCollectionResult {56  success: boolean;57  collectionId: number;58}5960interface CreateItemResult {61  success: boolean;62  collectionId: number;63  itemId: number;64  recipient?: CrossAccountId;65}6667interface TransferResult {68  success: boolean;69  collectionId: number;70  itemId: number;71  sender?: CrossAccountId;72  recipient?: CrossAccountId;73  value: bigint;74}7576interface IReFungibleOwner {77  Fraction: BN;78  Owner: number[];79}8081interface ITokenDataType {82  Owner: number[];83  ConstData: number[];84  VariableData: number[];85}8687interface IFungibleTokenDataType {88  Value: BN;89}9091interface IGetMessage {92  checkMsgNftMethod: string;93  checkMsgTrsMethod: string;94  checkMsgSysMethod: string;95}9697export interface IReFungibleTokenDataType {98  Owner: IReFungibleOwner[];99  ConstData: number[];100  VariableData: number[];101}102103export function nftEventMessage(events: EventRecord[]): IGetMessage {104  let checkMsgNftMethod: string = '';105  let checkMsgTrsMethod: string = '';106  let checkMsgSysMethod: string = '';107  events.forEach(({ event: { method, section } }) => {108    if (section === 'nft') {109      checkMsgNftMethod = method;110    } else if (section === 'treasury') {111      checkMsgTrsMethod = method;112    } else if (section === 'system') {113      checkMsgSysMethod = method;114    } else { return null; }115  });116  const result: IGetMessage = {117    checkMsgNftMethod,118    checkMsgTrsMethod,119    checkMsgSysMethod,120  };121  return result;122}123124export function getGenericResult(events: EventRecord[]): GenericResult {125  const result: GenericResult = {126    success: false,127  };128  events.forEach(({ phase, event: { data, method, section } }) => {129    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);130    if (method === 'ExtrinsicSuccess') {131      result.success = true;132    }133  });134  return result;135}136137138139export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {140  let success = false;141  let collectionId: number = 0;142  events.forEach(({ phase, event: { data, method, section } }) => {143    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);144    if (method == 'ExtrinsicSuccess') {145      success = true;146    } else if ((section == 'nft') && (method == 'CollectionCreated')) {147      collectionId = parseInt(data[0].toString());148    }149  });150  const result: CreateCollectionResult = {151    success,152    collectionId,153  };154  return result;155}156157export function getCreateItemResult(events: EventRecord[]): CreateItemResult {158  let success = false;159  let collectionId: number = 0;160  let itemId: number = 0;161  let recipient;162  events.forEach(({ phase, event: { data, method, section } }) => {163    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);164    if (method == 'ExtrinsicSuccess') {165      success = true;166    } else if ((section == 'nft') && (method == 'ItemCreated')) {167      collectionId = parseInt(data[0].toString());168      itemId = parseInt(data[1].toString());169      recipient = data[2].toJSON();170    }171  });172  const result: CreateItemResult = {173    success,174    collectionId,175    itemId,176    recipient,177  };178  return result;179}180181export function getTransferResult(events: EventRecord[]): TransferResult {182  const result: TransferResult = {183    success: false,184    collectionId: 0,185    itemId: 0,186    value: 0n,187  };188189  events.forEach(({ event: { data, method, section } }) => {190    if (method === 'ExtrinsicSuccess') {191      result.success = true;192    } else if (section === 'nft' && method === 'Transfer') {193      result.collectionId = +data[0].toString();194      result.itemId = +data[1].toString();195      result.sender = data[2].toJSON() as CrossAccountId;196      result.recipient = data[3].toJSON() as CrossAccountId;197      result.value = BigInt(data[4].toString());198    }199  });200201  return result;202}203204interface Invalid {205  type: 'Invalid';206}207208interface Nft {209  type: 'NFT';210}211212interface Fungible {213  type: 'Fungible';214  decimalPoints: number;215}216217interface ReFungible {218  type: 'ReFungible';219}220221type CollectionMode = Nft | Fungible | ReFungible | Invalid;222223export type CreateCollectionParams = {224  mode: CollectionMode,225  name: string,226  description: string,227  tokenPrefix: string,228};229230const defaultCreateCollectionParams: CreateCollectionParams = {231  description: 'description',232  mode: { type: 'NFT' },233  name: 'name',234  tokenPrefix: 'prefix',235}236237export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {238  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };239240  let collectionId: number = 0;241  await usingApi(async (api) => {242    // Get number of collections before the transaction243    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244245    // Run the CreateCollection transaction246    const alicePrivateKey = privateKey('//Alice');247248    let modeprm = {};249    if (mode.type === 'NFT') {250      modeprm = { nft: null };251    } else if (mode.type === 'Fungible') {252      modeprm = { fungible: mode.decimalPoints };253    } else if (mode.type === 'ReFungible') {254      modeprm = { refungible: null };255    } else if (mode.type === 'Invalid') {256      modeprm = { invalid: null };257    }258259    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);260    const events = await submitTransactionAsync(alicePrivateKey, tx);261    const result = getCreateCollectionResult(events);262263    // Get number of collections after the transaction264    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);265266    // Get the collection267    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();268269    // What to expect270    // tslint:disable-next-line:no-unused-expression271    expect(result.success).to.be.true;272    expect(result.collectionId).to.be.equal(BcollectionCount);273    // tslint:disable-next-line:no-unused-expression274    expect(collection).to.be.not.null;275    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');276    expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));277    expect(utf16ToStr(collection.Name)).to.be.equal(name);278    expect(utf16ToStr(collection.Description)).to.be.equal(description);279    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);280281    collectionId = result.collectionId;282  });283284  return collectionId;285}286287export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {288  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };289290  let modeprm = {};291  if (mode.type === 'NFT') {292    modeprm = { nft: null };293  } else if (mode.type === 'Fungible') {294    modeprm = { fungible: mode.decimalPoints };295  } else if (mode.type === 'ReFungible') {296    modeprm = { refungible: null };297  } else if (mode.type === 'Invalid') {298    modeprm = { invalid: null };299  }300301  await usingApi(async (api) => {302    // Get number of collections before the transaction303    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());304305    // Run the CreateCollection transaction306    const alicePrivateKey = privateKey('//Alice');307    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);308    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;309    const result = getCreateCollectionResult(events);310311    // Get number of collections after the transaction312    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());313314    // What to expect315    // tslint:disable-next-line:no-unused-expression316    expect(result.success).to.be.false;317    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');318  });319}320321export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {322  let bal = new BigNumber(0);323  let unused;324  do {325    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;326    const keyring = new Keyring({ type: 'sr25519' });327    unused = keyring.addFromUri(`//${randomSeed}`);328    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());329  } while (bal.toFixed() != '0');330  return unused;331}332333export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {334  return await usingApi(async (api) => {335    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;336    return BigInt(bn.toString());337  });338}339340export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {341  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));342}343344export async function findNotExistingCollection(api: ApiPromise): Promise<number> {345  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;346  const newCollection: number = totalNumber + 1;347  return newCollection;348}349350function getDestroyResult(events: EventRecord[]): boolean {351  let success: boolean = false;352  events.forEach(({ phase, event: { data, method, section } }) => {353    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);354    if (method == 'ExtrinsicSuccess') {355      success = true;356    }357  });358  return success;359}360361export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {362  await usingApi(async (api) => {363    // Run the DestroyCollection transaction364    const alicePrivateKey = privateKey(senderSeed);365    const tx = api.tx.nft.destroyCollection(collectionId);366    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;367  });368}369370export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {371  await usingApi(async (api) => {372    // Run the DestroyCollection transaction373    const alicePrivateKey = privateKey(senderSeed);374    const tx = api.tx.nft.destroyCollection(collectionId);375    const events = await submitTransactionAsync(alicePrivateKey, tx);376    const result = getDestroyResult(events);377378    // Get the collection379    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();380381    // What to expect382    expect(result).to.be.true;383    expect(collection).to.be.null;384  });385}386387export async function queryCollectionLimits(collectionId: number) {388  return await usingApi(async (api) => {389    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;390  });391}392393export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {394  await usingApi(async (api) => {395    const oldLimits = await queryCollectionLimits(collectionId);396    const newLimits = { ...oldLimits as any, ...limits };397    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);398    const events = await submitTransactionAsync(sender, tx);399    const result = getGenericResult(events);400401    expect(result.success).to.be.true;402  });403}404405export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const oldLimits = await queryCollectionLimits(collectionId);408    const newLimits = { ...oldLimits as any, ...limits };409    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);410    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;411    const result = getGenericResult(events);412413    expect(result.success).to.be.false;414  });415}416417export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {418  await usingApi(async (api) => {419420    // Run the transaction421    const alicePrivateKey = privateKey('//Alice');422    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);423    const events = await submitTransactionAsync(alicePrivateKey, tx);424    const result = getGenericResult(events);425426    // Get the collection427    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();428429    // What to expect430    expect(result.success).to.be.true;431    expect(collection.Sponsorship).to.deep.equal({432      unconfirmed: sponsor,433    });434  });435}436437export async function removeCollectionSponsorExpectSuccess(collectionId: number) {438  await usingApi(async (api) => {439440    // Run the transaction441    const alicePrivateKey = privateKey('//Alice');442    const tx = api.tx.nft.removeCollectionSponsor(collectionId);443    const events = await submitTransactionAsync(alicePrivateKey, tx);444    const result = getGenericResult(events);445446    // Get the collection447    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();448449    // What to expect450    expect(result.success).to.be.true;451    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });452  });453}454455export async function removeCollectionSponsorExpectFailure(collectionId: number) {456  await usingApi(async (api) => {457458    // Run the transaction459    const alicePrivateKey = privateKey('//Alice');460    const tx = api.tx.nft.removeCollectionSponsor(collectionId);461    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;462  });463}464465export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {466  await usingApi(async (api) => {467468    // Run the transaction469    const alicePrivateKey = privateKey(senderSeed);470    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);471    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;472  });473}474475export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {476  await usingApi(async (api) => {477478    // Run the transaction479    const sender = privateKey(senderSeed);480    const tx = api.tx.nft.confirmSponsorship(collectionId);481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    // Get the collection485    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();486487    // What to expect488    expect(result.success).to.be.true;489    expect(collection.Sponsorship).to.be.deep.equal({490      confirmed: sender.address,491    });492  });493}494495496export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {497  await usingApi(async (api) => {498499    // Run the transaction500    const sender = privateKey(senderSeed);501    const tx = api.tx.nft.confirmSponsorship(collectionId);502    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;503  });504}505506export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {507  await usingApi(async (api) => {508    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);509    const events = await submitTransactionAsync(sender, tx);510    const result = getGenericResult(events);511512    expect(result.success).to.be.true;513  });514}515516export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {517  await usingApi(async (api) => {518    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);519    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;520    const result = getGenericResult(events);521522    expect(result.success).to.be.false;523  });524}525526export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {527  await usingApi(async (api) => {528    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);529    const events = await submitTransactionAsync(sender, tx);530    const result = getGenericResult(events);531532    expect(result.success).to.be.true;533  });534}535536export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {537  await usingApi(async (api) => {538    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);539    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;540    const result = getGenericResult(events);541542    expect(result.success).to.be.false;543  });544}545546export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {547  await usingApi(async (api) => {548    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);549    const events = await submitTransactionAsync(sender, tx);550    const result = getGenericResult(events);551552    expect(result.success).to.be.true;553  });554}555556export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {557  let whitelisted: boolean = false;558  await usingApi(async (api) => {559    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;560  });561  return whitelisted;562}563564export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {565  await usingApi(async (api) => {566    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());567    const events = await submitTransactionAsync(sender, tx);568    const result = getGenericResult(events);569570    expect(result.success).to.be.true;571  });572}573574export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {575  await usingApi(async (api) => {576    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());577    const events = await submitTransactionAsync(sender, tx);578    const result = getGenericResult(events);579580    expect(result.success).to.be.true;581  });582}583584export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {585  await usingApi(async (api) => {586    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());587    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;588    const result = getGenericResult(events);589590    expect(result.success).to.be.false;591  });592}593594export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {595  await usingApi(async (api) => {596    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));597    const events = await submitTransactionAsync(sender, tx);598    const result = getGenericResult(events);599600    expect(result.success).to.be.true;601  });602}603604export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {605  await usingApi(async (api) => {606    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));607    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;608  });609}610611export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {612  await usingApi(async (api) => {613    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));614    const events = await submitTransactionAsync(sender, tx);615    const result = getGenericResult(events);616617    expect(result.success).to.be.true;618  });619}620621export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {622  await usingApi(async (api) => {623    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));624    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;625  });626}627628export interface CreateFungibleData {629  readonly Value: bigint;630}631632export interface CreateReFungibleData { }633export interface CreateNftData { }634635export type CreateItemData = {636  NFT: CreateNftData;637} | {638  Fungible: CreateFungibleData;639} | {640  ReFungible: CreateReFungibleData;641};642643export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {644  await usingApi(async (api) => {645    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);646    const events = await submitTransactionAsync(owner, tx);647    const result = getGenericResult(events);648    // Get the item649    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();650    // What to expect651    // tslint:disable-next-line:no-unused-expression652    expect(result.success).to.be.true;653    // tslint:disable-next-line:no-unused-expression654    expect(item).to.be.null;655  });656}657658export async function659  approveExpectSuccess(collectionId: number,660    tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1) {661  await usingApi(async (api: ApiPromise) => {662    approved = normalizeAccountId(approved);663    const allowanceBefore =664      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;665    const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);666    const events = await submitTransactionAsync(owner, approveNftTx);667    const result = getCreateItemResult(events);668    // tslint:disable-next-line:no-unused-expression669    expect(result.success).to.be.true;670    const allowanceAfter =671      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;672    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());673  });674}675676export async function677  transferFromExpectSuccess(collectionId: number,678    tokenId: number,679    accountApproved: IKeyringPair,680    accountFrom: IKeyringPair | CrossAccountId,681    accountTo: IKeyringPair | CrossAccountId,682    value: number | bigint = 1,683    type: string = 'NFT') {684  await usingApi(async (api: ApiPromise) => {685    const to = normalizeAccountId(accountTo);686    let balanceBefore = new BN(0);687    if (type === 'Fungible') {688      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;689    }690    const transferFromTx = api.tx.nft.transferFrom(691      normalizeAccountId(accountFrom), to, collectionId, tokenId, value);692    const events = await submitTransactionAsync(accountApproved, transferFromTx);693    const result = getCreateItemResult(events);694    // tslint:disable-next-line:no-unused-expression695    expect(result.success).to.be.true;696    if (type === 'NFT') {697      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;698      expect(nftItemData.Owner).to.be.deep.equal(to);699    }700    if (type === 'Fungible') {701      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;702      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());703    }704    if (type === 'ReFungible') {705      const nftItemData =706        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;707      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));708      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);709    }710  });711}712713export async function714  transferFromExpectFail(collectionId: number,715    tokenId: number,716    accountApproved: IKeyringPair,717    accountFrom: IKeyringPair,718    accountTo: IKeyringPair,719    value: number | bigint = 1) {720  await usingApi(async (api: ApiPromise) => {721    const transferFromTx = api.tx.nft.transferFrom(722      normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);723    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;724    const result = getCreateCollectionResult(events);725    // tslint:disable-next-line:no-unused-expression726    expect(result.success).to.be.false;727  });728}729730export async function731  transferExpectSuccess(collectionId: number,732    tokenId: number,733    sender: IKeyringPair,734    recipient: IKeyringPair | CrossAccountId,735    value: number | bigint = 1,736    type: string = 'NFT') {737  await usingApi(async (api: ApiPromise) => {738    const to = normalizeAccountId(recipient);739740    let balanceBefore = new BN(0);741    if (type === 'Fungible') {742      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;743    }744    const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);745    const events = await submitTransactionAsync(sender, transferTx);746    const result = getTransferResult(events);747    // tslint:disable-next-line:no-unused-expression748    expect(result.success).to.be.true;749    expect(result.collectionId).to.be.equal(collectionId);750    expect(result.itemId).to.be.equal(tokenId);751    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));752    expect(result.recipient).to.be.deep.equal(to);753    expect(result.value.toString()).to.be.equal(value.toString());754    if (type === 'NFT') {755      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;756      expect(nftItemData.Owner).to.be.deep.equal(to);757    }758    if (type === 'Fungible') {759      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;760      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());761    }762    if (type === 'ReFungible') {763      const nftItemData =764        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;765      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);766      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());767    }768  });769}770771export async function772  transferExpectFail(collectionId: number,773    tokenId: number,774    sender: IKeyringPair,775    recipient: IKeyringPair,776    value: number | bigint = 1,777    type: string = 'NFT') {778  await usingApi(async (api: ApiPromise) => {779    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);780    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;781    if (events && Array.isArray(events)) {782      const result = getCreateCollectionResult(events);783      // tslint:disable-next-line:no-unused-expression784      expect(result.success).to.be.false;785    }786  });787}788789export async function790  approveExpectFail(collectionId: number,791    tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {792  await usingApi(async (api: ApiPromise) => {793    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);794    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;795    const result = getCreateCollectionResult(events);796    // tslint:disable-next-line:no-unused-expression797    expect(result.success).to.be.false;798  });799}800801export async function getFungibleBalance(802  collectionId: number,803  owner: string,804) {805  return await usingApi(async (api) => {806    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };807    return BigInt(response.Value);808  });809}810811export async function createFungibleItemExpectSuccess(812  sender: IKeyringPair,813  collectionId: number,814  data: CreateFungibleData,815  owner: CrossAccountId | string = sender.address,816) {817  return await usingApi(async (api) => {818    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });819820    const events = await submitTransactionAsync(sender, tx);821    const result = getCreateItemResult(events);822823    expect(result.success).to.be.true;824    return result.itemId;825  });826}827828export async function createItemExpectSuccess(829  sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {830  let newItemId: number = 0;831  await usingApi(async (api) => {832    const to = normalizeAccountId(owner);833    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);834    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();835    const AItemBalance = new BigNumber(Aitem.Value);836837    let tx;838    if (createMode === 'Fungible') {839      const createData = { fungible: { value: 10 } };840      tx = api.tx.nft.createItem(collectionId, to, createData);841    } else if (createMode === 'ReFungible') {842      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };843      tx = api.tx.nft.createItem(collectionId, to, createData);844    } else {845      tx = api.tx.nft.createItem(collectionId, to, createMode);846    }847848    const events = await submitTransactionAsync(sender, tx);849    const result = getCreateItemResult(events);850851    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);852    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();853    const BItemBalance = new BigNumber(Bitem.Value);854855    // What to expect856    // tslint:disable-next-line:no-unused-expression857    expect(result.success).to.be.true;858    if (createMode === 'Fungible') {859      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);860    } else {861      expect(BItemCount).to.be.equal(AItemCount + 1);862    }863    expect(collectionId).to.be.equal(result.collectionId);864    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());865    expect(to).to.be.deep.equal(result.recipient);866    newItemId = result.itemId;867  });868  return newItemId;869}870871export async function createItemExpectFailure(872  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {873  await usingApi(async (api) => {874    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);875    876    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;877    const result = getCreateItemResult(events);878879    expect(result.success).to.be.false;880  });881}882883export async function setPublicAccessModeExpectSuccess(884  sender: IKeyringPair, collectionId: number,885  accessMode: 'Normal' | 'WhiteList',886) {887  await usingApi(async (api) => {888889    // Run the transaction890    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);891    const events = await submitTransactionAsync(sender, tx);892    const result = getGenericResult(events);893894    // Get the collection895    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();896897    // What to expect898    // tslint:disable-next-line:no-unused-expression899    expect(result.success).to.be.true;900    expect(collection.Access).to.be.equal(accessMode);901  });902}903904export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {905  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');906}907908export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {909  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');910}911912export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {913  await usingApi(async (api) => {914915    // Run the transaction916    const tx = api.tx.nft.setMintPermission(collectionId, enabled);917    const events = await submitTransactionAsync(sender, tx);918    const result = getGenericResult(events);919920    // Get the collection921    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();922923    // What to expect924    // tslint:disable-next-line:no-unused-expression925    expect(result.success).to.be.true;926    expect(collection.MintMode).to.be.equal(enabled);927  });928}929930export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {931  await setMintPermissionExpectSuccess(sender, collectionId, true);932}933934export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {935  await usingApi(async (api) => {936    // Run the transaction937    const tx = api.tx.nft.setMintPermission(collectionId, enabled);938    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;939    const result = getCreateCollectionResult(events);940    // tslint:disable-next-line:no-unused-expression941    expect(result.success).to.be.false;942  });943}944945export async function isWhitelisted(collectionId: number, address: string) {946  let whitelisted: boolean = false;947  await usingApi(async (api) => {948    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;949  });950  return whitelisted;951}952953export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {954  await usingApi(async (api) => {955956    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();957958    // Run the transaction959    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));960    const events = await submitTransactionAsync(sender, tx);961    const result = getGenericResult(events);962963    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();964965    // What to expect966    // tslint:disable-next-line:no-unused-expression967    expect(result.success).to.be.true;968    // tslint:disable-next-line: no-unused-expression969    expect(whiteListedBefore).to.be.false;970    // tslint:disable-next-line: no-unused-expression971    expect(whiteListedAfter).to.be.true;972  });973}974975export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {976  await usingApi(async (api) => {977    // Run the transaction978    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));979    const events = await submitTransactionAsync(sender, tx);980    const result = getGenericResult(events);981982    // What to expect983    // tslint:disable-next-line:no-unused-expression984    expect(result.success).to.be.true;985  });986}987988export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {989  await usingApi(async (api) => {990    // Run the transaction991    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));992    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;993    const result = getGenericResult(events);994995    // What to expect996    // tslint:disable-next-line:no-unused-expression997    expect(result.success).to.be.false;998  });999}10001001export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1002  : Promise<ICollectionInterface | null> => {1003  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1004};10051006export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1007  // set global object - collectionsCount1008  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1009};10101011export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1012  return await usingApi(async (api) => {1013    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1014  });1015}