difftreelog
Merge pull request #148 from usetech-llc/feature/NFTPAR-373_chain_extensions
in: master
Chain extensions
10 files changed
.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 && \
@@ -11,4 +14,5 @@
nvm install v12.20.1 && \
rustup toolchain install nightly-2021-03-01 && \
rustup default nightly-2021-03-01 && \
- rustup target add wasm32-unknown-unknown
\ No newline at end of file
+ rustup target add wasm32-unknown-unknown && \
+ cargo install cargo-contract
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5395,37 +5395,37 @@
[[package]]
name = "pallet-scheduler"
version = "3.0.0"
-source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"
dependencies = [
"frame-benchmarking",
"frame-support",
"frame-system",
"log",
+ "nft-data-structs",
+ "pallet-contracts",
+ "pallet-nft",
+ "pallet-nft-transaction-payment",
"parity-scale-codec",
+ "serde",
+ "sp-core",
"sp-io",
"sp-runtime",
"sp-std",
+ "substrate-test-utils",
]
[[package]]
name = "pallet-scheduler"
version = "3.0.0"
+source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"
dependencies = [
"frame-benchmarking",
"frame-support",
"frame-system",
"log",
- "nft-data-structs",
- "pallet-contracts",
- "pallet-nft",
- "pallet-nft-transaction-payment",
"parity-scale-codec",
- "serde",
- "sp-core",
"sp-io",
"sp-runtime",
"sp-std",
- "substrate-test-utils",
]
[[package]]
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -566,10 +566,14 @@
let sender = ensure_signed(origin)?;
let collection = Self::get_collection(collection_id)?;
- Self::check_owner_or_admin_permissions(&collection, sender)?;
- <WhiteList<T>>::insert(collection_id, address, true);
-
+ Self::toggle_white_list_internal(
+ &sender,
+ &collection,
+ &address,
+ true,
+ )?;
+
Ok(())
}
@@ -591,9 +595,13 @@
let sender = ensure_signed(origin)?;
let collection = Self::get_collection(collection_id)?;
- Self::check_owner_or_admin_permissions(&collection, sender)?;
- <WhiteList<T>>::remove(collection_id, address);
+ Self::toggle_white_list_internal(
+ &sender,
+ &collection,
+ &address,
+ false,
+ )?;
Ok(())
}
@@ -983,43 +991,10 @@
pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {
let sender = ensure_signed(origin)?;
- let target_collection = Self::get_collection(collection_id)?;
-
- Self::token_exists(&target_collection, item_id)?;
-
- // Transfer permissions check
- let bypasses_limits = target_collection.limits.owner_can_transfer &&
- Self::is_owner_or_admin_permissions(
- &target_collection,
- sender.clone(),
- );
+ let collection = Self::get_collection(collection_id)?;
- let allowance_limit = if bypasses_limits {
- None
- } else if let Some(amount) = Self::owned_amount(
- sender.clone(),
- &target_collection,
- item_id,
- ) {
- Some(amount)
- } else {
- fail!(Error::<T>::NoPermission);
- };
-
- if target_collection.access == AccessMode::WhiteList {
- Self::check_white_list(&target_collection, &sender)?;
- Self::check_white_list(&target_collection, &spender)?;
- }
-
- let allowance: u128 = amount
- .checked_add(<Allowances<T>>::get(collection_id, (item_id, &sender, &spender)))
- .ok_or(Error::<T>::NumOverflow)?;
- if let Some(limit) = allowance_limit {
- ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);
- }
- <Allowances<T>>::insert(collection_id, (item_id, sender.clone(), spender.clone()), allowance);
+ Self::approve_internal(sender, spender, &collection, item_id, amount)?;
- Self::deposit_event(RawEvent::Approved(target_collection.id, item_id, sender, spender, allowance));
Ok(())
}
@@ -1047,46 +1022,10 @@
pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {
let sender = ensure_signed(origin)?;
- let target_collection = Self::get_collection(collection_id)?;
-
- // Check approval
- let approval: u128 = <Allowances<T>>::get(collection_id, (item_id, &from, &sender));
-
- // Limits check
- Self::is_correct_transfer(&target_collection, &recipient)?;
+ let collection = Self::get_collection(collection_id)?;
- // Transfer permissions check
- ensure!(
- approval >= value ||
- (
- target_collection.limits.owner_can_transfer &&
- Self::is_owner_or_admin_permissions(&target_collection, sender.clone())
- ),
- Error::<T>::NoPermission
- );
-
- if target_collection.access == AccessMode::WhiteList {
- Self::check_white_list(&target_collection, &sender)?;
- Self::check_white_list(&target_collection, &recipient)?;
- }
-
- // Reduce approval by transferred amount or remove if remaining approval drops to 0
- if approval.saturating_sub(value) > 0 {
- <Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);
- }
- else {
- <Allowances<T>>::remove(collection_id, (item_id, &from, &sender));
- }
-
- match target_collection.mode
- {
- CollectionMode::NFT => Self::transfer_nft(&target_collection, item_id, from.clone(), recipient.clone())?,
- CollectionMode::Fungible(_) => Self::transfer_fungible(&target_collection, value, &from, &recipient)?,
- CollectionMode::ReFungible => Self::transfer_refungible(&target_collection, item_id, value, from.clone(), recipient.clone())?,
- _ => ()
- };
+ Self::transfer_from_internal(sender, from, recipient, &collection, item_id, value)?;
- Self::deposit_event(RawEvent::Transfer(target_collection.id, item_id, from, recipient, value));
Ok(())
}
@@ -1127,24 +1066,10 @@
) -> DispatchResult {
let sender = ensure_signed(origin)?;
- let target_collection = Self::get_collection(collection_id)?;
- Self::token_exists(&target_collection, item_id)?;
+ let collection = Self::get_collection(collection_id)?;
- ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);
-
- // Modify permissions check
- ensure!(Self::is_item_owner(sender.clone(), &target_collection, item_id) ||
- Self::is_owner_or_admin_permissions(&target_collection, sender.clone()),
- Error::<T>::NoPermission);
+ Self::set_variable_meta_data_internal(sender, &collection, item_id, data)?;
- match target_collection.mode
- {
- CollectionMode::NFT => Self::set_nft_variable_data(&target_collection, item_id, data)?,
- CollectionMode::ReFungible => Self::set_re_fungible_variable_data(&target_collection, item_id, data)?,
- CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),
- _ => fail!(Error::<T>::UnexpectedCollectionType)
- };
-
Ok(())
}
@@ -1516,6 +1441,164 @@
Ok(())
}
+ pub fn approve_internal(
+ sender: T::AccountId,
+ spender: T::AccountId,
+ collection: &CollectionHandle<T>,
+ item_id: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ Self::token_exists(&collection, item_id)?;
+
+ // Transfer permissions check
+ let bypasses_limits = collection.limits.owner_can_transfer &&
+ Self::is_owner_or_admin_permissions(
+ &collection,
+ sender.clone(),
+ );
+
+ let allowance_limit = if bypasses_limits {
+ None
+ } else if let Some(amount) = Self::owned_amount(
+ sender.clone(),
+ &collection,
+ item_id,
+ ) {
+ Some(amount)
+ } else {
+ fail!(Error::<T>::NoPermission);
+ };
+
+ if collection.access == AccessMode::WhiteList {
+ Self::check_white_list(&collection, &sender)?;
+ Self::check_white_list(&collection, &spender)?;
+ }
+
+ let allowance: u128 = amount
+ .checked_add(<Allowances<T>>::get(collection.id, (item_id, &sender, &spender)))
+ .ok_or(Error::<T>::NumOverflow)?;
+ if let Some(limit) = allowance_limit {
+ ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);
+ }
+ <Allowances<T>>::insert(collection.id, (item_id, &sender, &spender), allowance);
+
+ Self::deposit_event(RawEvent::Approved(collection.id, item_id, sender, spender, allowance));
+ Ok(())
+ }
+
+ pub fn transfer_from_internal(
+ sender: T::AccountId,
+ from: T::AccountId,
+ recipient: T::AccountId,
+ collection: &CollectionHandle<T>,
+ item_id: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ // Check approval
+ let approval: u128 = <Allowances<T>>::get(collection.id, (item_id, &from, &sender));
+
+ // Limits check
+ Self::is_correct_transfer(&collection, &recipient)?;
+
+ // Transfer permissions check
+ ensure!(
+ approval >= amount ||
+ (
+ collection.limits.owner_can_transfer &&
+ Self::is_owner_or_admin_permissions(&collection, sender.clone())
+ ),
+ Error::<T>::NoPermission
+ );
+
+ if collection.access == AccessMode::WhiteList {
+ Self::check_white_list(&collection, &sender)?;
+ Self::check_white_list(&collection, &recipient)?;
+ }
+
+ // Reduce approval by transferred amount or remove if remaining approval drops to 0
+ let allowance = approval.saturating_sub(amount);
+ if allowance > 0 {
+ <Allowances<T>>::insert(collection.id, (item_id, &from, &sender), allowance);
+ } else {
+ <Allowances<T>>::remove(collection.id, (item_id, &from, &sender));
+ }
+
+ match collection.mode {
+ CollectionMode::NFT => {
+ Self::transfer_nft(&collection, item_id, from.clone(), recipient.clone())?
+ }
+ CollectionMode::Fungible(_) => {
+ Self::transfer_fungible(&collection, amount, &from, &recipient)?
+ }
+ CollectionMode::ReFungible => {
+ Self::transfer_refungible(&collection, item_id, amount, from.clone(), recipient.clone())?
+ }
+ _ => ()
+ };
+
+ Ok(())
+ }
+
+ pub fn set_variable_meta_data_internal(
+ sender: T::AccountId,
+ collection: &CollectionHandle<T>,
+ item_id: TokenId,
+ data: Vec<u8>,
+ ) -> DispatchResult {
+ Self::token_exists(&collection, item_id)?;
+
+ ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);
+
+ // Modify permissions check
+ ensure!(Self::is_item_owner(sender.clone(), &collection, item_id) ||
+ Self::is_owner_or_admin_permissions(&collection, sender.clone()),
+ Error::<T>::NoPermission);
+
+ match collection.mode
+ {
+ CollectionMode::NFT => Self::set_nft_variable_data(&collection, item_id, data)?,
+ CollectionMode::ReFungible => Self::set_re_fungible_variable_data(&collection, item_id, data)?,
+ CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),
+ _ => fail!(Error::<T>::UnexpectedCollectionType)
+ };
+
+ Ok(())
+ }
+
+ pub fn create_multiple_items_internal(
+ sender: T::AccountId,
+ collection: &CollectionHandle<T>,
+ owner: T::AccountId,
+ items_data: Vec<CreateItemData>,
+ ) -> DispatchResult {
+ Self::can_create_items_in_collection(&collection, &sender, &owner, items_data.len() as u32)?;
+
+ for data in &items_data {
+ Self::validate_create_item_args(&collection, data)?;
+ }
+ for data in &items_data {
+ Self::create_item_no_validation(&collection, owner.clone(), data.clone())?;
+ }
+
+ Ok(())
+ }
+
+ pub fn toggle_white_list_internal(
+ sender: &T::AccountId,
+ collection: &CollectionHandle<T>,
+ address: &T::AccountId,
+ whitelisted: bool,
+ ) -> DispatchResult {
+ Self::check_owner_or_admin_permissions(&collection, sender.clone())?;
+
+ if whitelisted {
+ <WhiteList<T>>::insert(collection.id, address, true);
+ } else {
+ <WhiteList<T>>::remove(collection.id, address);
+ }
+
+ Ok(())
+ }
fn is_correct_transfer(collection: &CollectionHandle<T>, recipient: &T::AccountId) -> DispatchResult {
let collection_id = collection.id;
runtime/src/chain_extension.rsdiffbeforeafterboth--- a/runtime/src/chain_extension.rs
+++ b/runtime/src/chain_extension.rs
@@ -19,6 +19,8 @@
pub use pallet_nft::*;
use nft_data_structs::*;
+use crate::Vec;
+
/// Create item parameters
#[derive(Debug, PartialEq, Encode, Decode)]
pub struct NFTExtCreateItem<E: Ext> {
@@ -36,13 +38,54 @@
pub amount: u128,
}
+#[derive(Debug, PartialEq, Encode, Decode)]
+pub struct NFTExtCreateMultipleItems<E: Ext> {
+ pub owner: <E::T as SysConfig>::AccountId,
+ pub collection_id: u32,
+ pub data: Vec<CreateItemData>,
+}
+
+#[derive(Debug, PartialEq, Encode, Decode)]
+pub struct NFTExtApprove<E: Ext> {
+ pub spender: <E::T as SysConfig>::AccountId,
+ pub collection_id: u32,
+ pub item_id: u32,
+ pub amount: u128,
+}
+
+#[derive(Debug, PartialEq, Encode, Decode)]
+pub struct NFTExtTransferFrom<E: Ext> {
+ pub owner: <E::T as SysConfig>::AccountId,
+ pub recipient: <E::T as SysConfig>::AccountId,
+ pub collection_id: u32,
+ pub item_id: u32,
+ pub amount: u128,
+}
+
+#[derive(Debug, PartialEq, Encode, Decode)]
+pub struct NFTExtSetVariableMetaData {
+ pub collection_id: u32,
+ pub item_id: u32,
+ pub data: Vec<u8>,
+}
+
+#[derive(Debug, PartialEq, Encode, Decode)]
+pub struct NFTExtToggleWhiteList<E: Ext> {
+ pub collection_id: u32,
+ pub address: <E::T as SysConfig>::AccountId,
+ pub whitelisted: bool,
+}
+
/// The chain Extension of NFT pallet
pub struct NFTExtension;
+pub type NftWeightInfoOf<C> = <C as pallet_nft::Config>::WeightInfo;
+
impl<C: Config + pallet_contracts::Config> ChainExtension<C> for NFTExtension {
fn call<E: Ext>(func_id: u32, env: Environment<E, InitState>) -> Result<RetVal, DispatchError>
where
E: Ext<T = C>,
+ C: pallet_nft::Config,
<E::T as SysConfig>::AccountId: UncheckedFrom<<E::T as SysConfig>::Hash> + AsRef<[u8]>,
{
// The memory of the vm stores buf in scale-codec
@@ -50,37 +93,129 @@
0 => {
let mut env = env.buf_in_buf_out();
let input: NFTExtTransfer<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::transfer())?;
let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
- match pallet_nft::Module::<C>::transfer_internal(
- env.ext().caller().clone(),
+ pallet_nft::Module::<C>::transfer_internal(
+ env.ext().address().clone(),
input.recipient,
&collection,
input.token_id,
input.amount,
- ) {
- Ok(_) => Ok(RetVal::Converging(func_id)),
- _ => Err(DispatchError::Other("Transfer error"))
- }
+ )?;
+
+ Ok(RetVal::Converging(0))
},
1 => {
// Create Item
let mut env = env.buf_in_buf_out();
let input: NFTExtCreateItem<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::create_item(input.data.len()))?;
- match pallet_nft::Module::<C>::create_item_internal(
+ pallet_nft::Module::<C>::create_item_internal(
env.ext().address().clone(),
input.collection_id,
input.owner,
input.data,
- ) {
- Ok(_) => Ok(RetVal::Converging(func_id)),
- _ => Err(DispatchError::Other("CreateItem error"))
- }
+ )?;
+
+ Ok(RetVal::Converging(0))
},
+ 2 => {
+ // Create multiple items
+ let mut env = env.buf_in_buf_out();
+ let input: NFTExtCreateMultipleItems<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::create_item(
+ input.data.iter()
+ .map(|i| i.len())
+ .sum()
+ ))?;
+
+ let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
+
+ pallet_nft::Module::<C>::create_multiple_items_internal(
+ env.ext().address().clone(),
+ &collection,
+ input.owner,
+ input.data,
+ )?;
+
+ Ok(RetVal::Converging(0))
+ },
+ 3 => {
+ // Approve
+ let mut env = env.buf_in_buf_out();
+ let input: NFTExtApprove<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::approve())?;
+
+ let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
+
+ pallet_nft::Module::<C>::approve_internal(
+ env.ext().address().clone(),
+ input.spender,
+ &collection,
+ input.item_id,
+ input.amount,
+ )?;
+
+ Ok(RetVal::Converging(0))
+ },
+ 4 => {
+ // Transfer from
+ let mut env = env.buf_in_buf_out();
+ let input: NFTExtTransferFrom<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::transfer_from())?;
+
+ let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
+
+ pallet_nft::Module::<C>::transfer_from_internal(
+ env.ext().address().clone(),
+ input.owner,
+ input.recipient,
+ &collection,
+ input.item_id,
+ input.amount
+ )?;
+
+ Ok(RetVal::Converging(0))
+ },
+ 5 => {
+ // Set variable metadata
+ let mut env = env.buf_in_buf_out();
+ let input: NFTExtSetVariableMetaData = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::set_variable_meta_data())?;
+
+ let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
+
+ pallet_nft::Module::<C>::set_variable_meta_data_internal(
+ env.ext().address().clone(),
+ &collection,
+ input.item_id,
+ input.data,
+ )?;
+
+ Ok(RetVal::Converging(0))
+ },
+ 6 => {
+ // Toggle whitelist
+ let mut env = env.buf_in_buf_out();
+ let input: NFTExtToggleWhiteList<E> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::add_to_white_list())?;
+
+ let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
+
+ pallet_nft::Module::<C>::toggle_white_list_internal(
+ &env.ext().address().clone(),
+ &collection,
+ &input.address,
+ input.whitelisted,
+ )?;
+
+ Ok(RetVal::Converging(0))
+ }
_ => {
- panic!("Passed unknown func_id to test chain extension: {}", func_id);
+ Err(DispatchError::Other("unknown chain_extension func_id"))
}
}
}
smart_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",
smart_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);
+ }
}
tests/src/contracts.test.tsdiffbeforeafterboth--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -16,9 +16,15 @@
} from "./util/contracthelpers";
import {
+ addToWhiteListExpectSuccess,
+ approveExpectSuccess,
createCollectionExpectSuccess,
createItemExpectSuccess,
- getGenericResult
+ enablePublicMintingExpectSuccess,
+ enableWhiteListExpectSuccess,
+ getGenericResult,
+ isWhitelisted,
+ transferFromExpectSuccess
} from "./util/helpers";
@@ -26,7 +32,7 @@
const expect = chai.expect;
const value = 0;
-const gasLimit = 3000n * 1000000n;
+const gasLimit = 9000n * 1000000n;
const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';
describe('Contracts', () => {
@@ -53,8 +59,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");
@@ -63,6 +71,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).unwrap();
// Transfer
@@ -77,4 +88,165 @@
expect(tokenAfter.Owner.toString()).to.be.equal(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);
+
+ 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);
+
+ 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;
+ }
+ });
+ });
});
tests/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
tests/src/transfer_contract/nft_transfer.wasmdiffbeforeafterbothbinary blob — no preview
tests/src/util/helpers.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, BlockNumber, Call, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';20import { Compact, Option, Raw, Vec } from '@polkadot/types/codec';21// import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, DispatchClass, DispatchInfo, DispatchInfoTo190, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV1, ExtrinsicPayloadV2, ExtrinsicPayloadV3, ExtrinsicPayloadV4, ExtrinsicSignatureV1, ExtrinsicSignatureV2, ExtrinsicSignatureV3, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV1, ExtrinsicV2, ExtrinsicV3, ExtrinsicV4, Hash, Header, ImmortalEra, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, Moment, MortalEra, MultiSignature, Origin, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Seal, SealV0, Signature, SignedBlock, SignerPayload, Sr25519Signature, ValidatorId, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';2223chai.use(chaiAsPromised);24const expect = chai.expect;2526export const U128_MAX = (1n << 128n) - 1n;2728type GenericResult = {29 success: boolean,30};3132interface CreateCollectionResult {33 success: boolean;34 collectionId: number;35}3637interface CreateItemResult {38 success: boolean;39 collectionId: number;40 itemId: number;41 recipient: string;42}4344interface TransferResult {45 success: boolean;46 collectionId: number;47 itemId: number;48 sender: string;49 recipient: string;50 value: bigint;51}5253interface IReFungibleOwner {54 Fraction: BN;55 Owner: number[];56}5758interface ITokenDataType {59 Owner: number[];60 ConstData: number[];61 VariableData: number[];62}6364interface IFungibleTokenDataType {65 Value: BN;66}6768interface IGetMessage {69 checkMsgNftMethod: string;70 checkMsgTrsMethod: string;71 checkMsgSysMethod: string;72}7374export interface IReFungibleTokenDataType {75 Owner: IReFungibleOwner[];76 ConstData: number[];77 VariableData: number[];78}7980export function nftEventMessage(events: EventRecord[]): IGetMessage {81 let checkMsgNftMethod: string = '';82 let checkMsgTrsMethod: string = '';83 let checkMsgSysMethod: string = '';84 events.forEach(({ event: { method, section } }) => {85 if (section === 'nft') {86 checkMsgNftMethod = method;87 } else if (section === 'treasury') {88 checkMsgTrsMethod = method;89 } else if (section === 'system') {90 checkMsgSysMethod = method;91 } else { return null; }92 });93 const result: IGetMessage = {94 checkMsgNftMethod,95 checkMsgTrsMethod,96 checkMsgSysMethod,97 };98 return result;99}100101export function getGenericResult(events: EventRecord[]): GenericResult {102 const result: GenericResult = {103 success: false,104 };105 events.forEach(({ phase, event: { data, method, section } }) => {106 // console.log(` ${phase}: ${section}.${method}:: ${data}`);107 if (method === 'ExtrinsicSuccess') {108 result.success = true;109 }110 });111 return result;112}113114115116export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {117 let success = false;118 let collectionId: number = 0;119 events.forEach(({ phase, event: { data, method, section } }) => {120 // console.log(` ${phase}: ${section}.${method}:: ${data}`);121 if (method == 'ExtrinsicSuccess') {122 success = true;123 } else if ((section == 'nft') && (method == 'CollectionCreated')) {124 collectionId = parseInt(data[0].toString());125 }126 });127 const result: CreateCollectionResult = {128 success,129 collectionId,130 };131 return result;132}133134export function getCreateItemResult(events: EventRecord[]): CreateItemResult {135 let success = false;136 let collectionId: number = 0;137 let itemId: number = 0;138 let recipient: string = '';139 events.forEach(({ phase, event: { data, method, section } }) => {140 // console.log(` ${phase}: ${section}.${method}:: ${data}`);141 if (method == 'ExtrinsicSuccess') {142 success = true;143 } else if ((section == 'nft') && (method == 'ItemCreated')) {144 collectionId = parseInt(data[0].toString());145 itemId = parseInt(data[1].toString());146 recipient = data[2].toString();147 }148 });149 const result: CreateItemResult = {150 success,151 collectionId,152 itemId,153 recipient,154 };155 return result;156}157158export function getTransferResult(events: EventRecord[]): TransferResult {159 const result: TransferResult = {160 success: false,161 collectionId: 0,162 itemId: 0,163 sender: '',164 recipient: '',165 value: 0n,166 };167168 events.forEach(({event: {data, method, section}}) => {169 if (method === 'ExtrinsicSuccess') {170 result.success = true;171 } else if (section === 'nft' && method === 'Transfer') {172 result.collectionId = +data[0].toString();173 result.itemId = +data[1].toString();174 result.sender = data[2].toString();175 result.recipient = data[3].toString();176 result.value = BigInt(data[4].toString());177 }178 });179180 return result;181}182183interface Invalid {184 type: 'Invalid';185}186187interface Nft {188 type: 'NFT';189}190191interface Fungible {192 type: 'Fungible';193 decimalPoints: number;194}195196interface ReFungible {197 type: 'ReFungible';198}199200type CollectionMode = Nft | Fungible | ReFungible | Invalid;201202export type CreateCollectionParams = {203 mode: CollectionMode,204 name: string,205 description: string,206 tokenPrefix: string,207};208209const defaultCreateCollectionParams: CreateCollectionParams = {210 description: 'description',211 mode: { type: 'NFT' },212 name: 'name',213 tokenPrefix: 'prefix',214}215216export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {217 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};218219 let collectionId: number = 0;220 await usingApi(async (api) => {221 // Get number of collections before the transaction222 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);223224 // Run the CreateCollection transaction225 const alicePrivateKey = privateKey('//Alice');226227 let modeprm = {};228 if (mode.type === 'NFT') {229 modeprm = {nft: null};230 } else if (mode.type === 'Fungible') {231 modeprm = {fungible: mode.decimalPoints};232 } else if (mode.type === 'ReFungible') {233 modeprm = {refungible: null};234 } else if (mode.type === 'Invalid') {235 modeprm = {invalid: null};236 }237238 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);239 const events = await submitTransactionAsync(alicePrivateKey, tx);240 const result = getCreateCollectionResult(events);241242 // Get number of collections after the transaction243 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244245 // Get the collection246 const collection: any = (await api.query.nft.collectionById(result.collectionId)).toJSON();247248 // What to expect249 // tslint:disable-next-line:no-unused-expression250 expect(result.success).to.be.true;251 expect(result.collectionId).to.be.equal(BcollectionCount);252 // tslint:disable-next-line:no-unused-expression253 expect(collection).to.be.not.null;254 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');255 expect(collection.Owner).to.be.equal(alicesPublicKey);256 expect(utf16ToStr(collection.Name)).to.be.equal(name);257 expect(utf16ToStr(collection.Description)).to.be.equal(description);258 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);259260 collectionId = result.collectionId;261 });262263 return collectionId;264}265266export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {267 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};268269 let modeprm = {};270 if (mode.type === 'NFT') {271 modeprm = {nft: null};272 } else if (mode.type === 'Fungible') {273 modeprm = {fungible: mode.decimalPoints};274 } else if (mode.type === 'ReFungible') {275 modeprm = {refungible: null};276 } else if (mode.type === 'Invalid') {277 modeprm = {invalid: null};278 }279280 await usingApi(async (api) => {281 // Get number of collections before the transaction282 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());283284 // Run the CreateCollection transaction285 const alicePrivateKey = privateKey('//Alice');286 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);287 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;288 const result = getCreateCollectionResult(events);289290 // Get number of collections after the transaction291 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());292293 // What to expect294 // tslint:disable-next-line:no-unused-expression295 expect(result.success).to.be.false;296 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');297 });298}299300export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {301 let bal = new BigNumber(0);302 let unused;303 do {304 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;305 const keyring = new Keyring({ type: 'sr25519' });306 unused = keyring.addFromUri(`//${randomSeed}`);307 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());308 } while (bal.toFixed() != '0');309 return unused;310}311312export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {313 return await usingApi(async (api) => {314 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;315 return BigInt(bn.toString());316 });317}318319export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {320 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));321}322323export async function findNotExistingCollection(api: ApiPromise): Promise<number> {324 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;325 const newCollection: number = totalNumber + 1;326 return newCollection;327}328329function getDestroyResult(events: EventRecord[]): boolean {330 let success: boolean = false;331 events.forEach(({ phase, event: { data, method, section } }) => {332 // console.log(` ${phase}: ${section}.${method}:: ${data}`);333 if (method == 'ExtrinsicSuccess') {334 success = true;335 }336 });337 return success;338}339340export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {341 await usingApi(async (api) => {342 // Run the DestroyCollection transaction343 const alicePrivateKey = privateKey(senderSeed);344 const tx = api.tx.nft.destroyCollection(collectionId);345 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;346 });347}348349export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {350 await usingApi(async (api) => {351 // Run the DestroyCollection transaction352 const alicePrivateKey = privateKey(senderSeed);353 const tx = api.tx.nft.destroyCollection(collectionId);354 const events = await submitTransactionAsync(alicePrivateKey, tx);355 const result = getDestroyResult(events);356357 // Get the collection358 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();359360 // What to expect361 expect(result).to.be.true;362 expect(collection).to.be.null;363 });364}365366export async function queryCollectionLimits(collectionId: number) {367 return await usingApi(async (api) => {368 return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;369 });370}371372export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {373 await usingApi(async (api) => {374 const oldLimits = await queryCollectionLimits(collectionId);375 const newLimits = { ...oldLimits as any, ...limits };376 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);377 const events = await submitTransactionAsync(sender, tx);378 const result = getGenericResult(events);379380 expect(result.success).to.be.true;381 });382}383384export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {385 await usingApi(async (api) => {386 const oldLimits = await queryCollectionLimits(collectionId);387 const newLimits = { ...oldLimits as any, ...limits };388 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);389 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;390 const result = getGenericResult(events);391392 expect(result.success).to.be.false;393 });394}395396export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {397 await usingApi(async (api) => {398399 // Run the transaction400 const alicePrivateKey = privateKey('//Alice');401 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);402 const events = await submitTransactionAsync(alicePrivateKey, tx);403 const result = getGenericResult(events);404405 // Get the collection406 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();407408 // What to expect409 expect(result.success).to.be.true;410 expect(collection.Sponsorship).to.deep.equal({411 Unconfirmed: sponsor.toString(),412 });413 });414}415416export async function removeCollectionSponsorExpectSuccess(collectionId: number) {417 await usingApi(async (api) => {418419 // Run the transaction420 const alicePrivateKey = privateKey('//Alice');421 const tx = api.tx.nft.removeCollectionSponsor(collectionId);422 const events = await submitTransactionAsync(alicePrivateKey, tx);423 const result = getGenericResult(events);424425 // Get the collection426 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();427428 // What to expect429 expect(result.success).to.be.true;430 expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });431 });432}433434export async function removeCollectionSponsorExpectFailure(collectionId: number) {435 await usingApi(async (api) => {436437 // Run the transaction438 const alicePrivateKey = privateKey('//Alice');439 const tx = api.tx.nft.removeCollectionSponsor(collectionId);440 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;441 });442}443444export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {445 await usingApi(async (api) => {446447 // Run the transaction448 const alicePrivateKey = privateKey(senderSeed);449 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);450 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;451 });452}453454export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {455 await usingApi(async (api) => {456457 // Run the transaction458 const sender = privateKey(senderSeed);459 const tx = api.tx.nft.confirmSponsorship(collectionId);460 const events = await submitTransactionAsync(sender, tx);461 const result = getGenericResult(events);462463 // Get the collection464 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();465466 // What to expect467 expect(result.success).to.be.true;468 expect(collection.Sponsorship).to.be.deep.equal({469 Confirmed: sender.address,470 });471 });472}473474475export async function confirmSponsorshipExpectFailure(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 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;482 });483}484485export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {486 await usingApi(async (api) => {487 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);488 const events = await submitTransactionAsync(sender, tx);489 const result = getGenericResult(events);490491 expect(result.success).to.be.true;492 });493}494495export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {496 await usingApi(async (api) => {497 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);498 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;499 const result = getGenericResult(events);500501 expect(result.success).to.be.false;502 });503}504505export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {506 await usingApi(async (api) => {507 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);508 const events = await submitTransactionAsync(sender, tx);509 const result = getGenericResult(events);510511 expect(result.success).to.be.true;512 });513}514515export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {516 await usingApi(async (api) => {517 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);518 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;519 const result = getGenericResult(events);520521 expect(result.success).to.be.false;522 });523}524525export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {526 await usingApi(async (api) => {527 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);528 const events = await submitTransactionAsync(sender, tx);529 const result = getGenericResult(events);530531 expect(result.success).to.be.true;532 });533}534535export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {536 let whitelisted: boolean = false;537 await usingApi(async (api) => {538 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;539 });540 return whitelisted;541}542543export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {544 await usingApi(async (api) => {545 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);546 const events = await submitTransactionAsync(sender, tx);547 const result = getGenericResult(events);548549 expect(result.success).to.be.true;550 });551}552553export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {554 await usingApi(async (api) => {555 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);556 const events = await submitTransactionAsync(sender, tx);557 const result = getGenericResult(events);558559 expect(result.success).to.be.true;560 });561}562563export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {564 await usingApi(async (api) => {565 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);566 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;567 const result = getGenericResult(events);568569 expect(result.success).to.be.false;570 });571}572573export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {574 await usingApi(async (api) => {575 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));576 const events = await submitTransactionAsync(sender, tx);577 const result = getGenericResult(events);578579 expect(result.success).to.be.true;580 });581}582583export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {584 await usingApi(async (api) => {585 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));586 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;587 });588}589590export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {591 await usingApi(async (api) => {592 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));593 const events = await submitTransactionAsync(sender, tx);594 const result = getGenericResult(events);595596 expect(result.success).to.be.true;597 });598}599600export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {601 await usingApi(async (api) => {602 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));603 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;604 });605}606607export interface CreateFungibleData {608 readonly Value: bigint;609}610611export interface CreateReFungibleData { }612export interface CreateNftData { }613614export type CreateItemData = {615 NFT: CreateNftData;616} | {617 Fungible: CreateFungibleData;618} | {619 ReFungible: CreateReFungibleData;620};621622export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {623 await usingApi(async (api) => {624 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);625 const events = await submitTransactionAsync(owner, tx);626 const result = getGenericResult(events);627 // Get the item628 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();629 // What to expect630 // tslint:disable-next-line:no-unused-expression631 expect(result.success).to.be.true;632 // tslint:disable-next-line:no-unused-expression633 expect(item).to.be.null;634 });635}636637export async function638approveExpectSuccess(collectionId: number,639 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {640 await usingApi(async (api: ApiPromise) => {641 const allowanceBefore =642 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;643 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);644 const events = await submitTransactionAsync(owner, approveNftTx);645 const result = getCreateItemResult(events);646 // tslint:disable-next-line:no-unused-expression647 expect(result.success).to.be.true;648 const allowanceAfter =649 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;650 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());651 });652}653654export async function655transferFromExpectSuccess(collectionId: number,656 tokenId: number,657 accountApproved: IKeyringPair,658 accountFrom: IKeyringPair,659 accountTo: IKeyringPair,660 value: number | bigint = 1,661 type: string = 'NFT') {662 await usingApi(async (api: ApiPromise) => {663 let balanceBefore = new BN(0);664 if (type === 'Fungible') {665 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;666 }667 const transferFromTx = await api.tx.nft.transferFrom(668 accountFrom.address, accountTo.address, collectionId, tokenId, value);669 const events = await submitTransactionAsync(accountApproved, transferFromTx);670 const result = getCreateItemResult(events);671 // tslint:disable-next-line:no-unused-expression672 expect(result.success).to.be.true;673 if (type === 'NFT') {674 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap() as ITokenDataType;675 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);676 }677 if (type === 'Fungible') {678 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, accountTo.address) as any).Value as unknown as BN;679 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());680 }681 if (type === 'ReFungible') {682 const nftItemData =683 (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).unwrap() as IReFungibleTokenDataType;684 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);685 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);686 }687 });688}689690export async function691transferFromExpectFail(collectionId: number,692 tokenId: number,693 accountApproved: IKeyringPair,694 accountFrom: IKeyringPair,695 accountTo: IKeyringPair,696 value: number | bigint = 1) {697 await usingApi(async (api: ApiPromise) => {698 const transferFromTx = await api.tx.nft.transferFrom(699 accountFrom.address, accountTo.address, collectionId, tokenId, value);700 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;701 const result = getCreateCollectionResult(events);702 // tslint:disable-next-line:no-unused-expression703 expect(result.success).to.be.false;704 });705}706707async function getBlockNumber(api: ApiPromise): Promise<number> {708 return new Promise<number>(async (resolve, reject) => {709 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {710 unsubscribe();711 resolve(head.number.toNumber());712 });713 });714}715716export async function717scheduleTransferExpectSuccess(collectionId: number,718 tokenId: number,719 sender: IKeyringPair,720 recipient: IKeyringPair,721 value: number | bigint = 1,722 type: string = 'NFT') {723 await usingApi(async (api: ApiPromise) => {724 let balanceBefore = new BN(0);725726727 let blockNumber: number | undefined = await getBlockNumber(api);728 let expectedBlockNumber = blockNumber + 2;729730 expect(blockNumber).to.be.greaterThan(0);731 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value); 732 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);733734 const events = await submitTransactionAsync(sender, scheduleTx);735736 const sponsorBalanceBefore = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());737 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());738739 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;740 expect(nftItemDataBefore.Owner.toString()).to.be.equal(sender.address);741742 // sleep for 2 blocks743 await new Promise(resolve => setTimeout(resolve, 6000 * 2));744745 const sponsorBalanceAfter = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());746 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());747748 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;749 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);750 expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());751 });752}753754755export async function756transferExpectSuccess(collectionId: number,757 tokenId: number,758 sender: IKeyringPair,759 recipient: IKeyringPair,760 value: number | bigint = 1,761 type: string = 'NFT') {762 await usingApi(async (api: ApiPromise) => {763 let balanceBefore = new BN(0);764 if (type === 'Fungible') {765 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;766 }767 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);768 const events = await submitTransactionAsync(sender, transferTx);769 const result = getTransferResult(events);770 // tslint:disable-next-line:no-unused-expression771 expect(result.success).to.be.true;772 expect(result.collectionId).to.be.equal(collectionId);773 expect(result.itemId).to.be.equal(tokenId);774 expect(result.sender).to.be.equal(sender.address);775 expect(result.recipient).to.be.equal(recipient.address);776 expect(result.value.toString()).to.be.equal(value.toString());777 if (type === 'NFT') {778 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;779 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);780 }781 if (type === 'Fungible') {782 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, recipient.address) as any).Value as unknown as BN;783 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());784 }785 if (type === 'ReFungible') {786 const nftItemData =787 (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;788 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);789 expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());790 }791 });792}793794export async function795transferExpectFail(collectionId: number,796 tokenId: number,797 sender: IKeyringPair,798 recipient: IKeyringPair,799 value: number | bigint = 1,800 type: string = 'NFT') {801 await usingApi(async (api: ApiPromise) => {802 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);803 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;804 if (events && Array.isArray(events)) {805 const result = getCreateCollectionResult(events);806 // tslint:disable-next-line:no-unused-expression807 expect(result.success).to.be.false;808 }809 });810}811812export async function813approveExpectFail(collectionId: number,814 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {815 await usingApi(async (api: ApiPromise) => {816 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);817 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;818 const result = getCreateCollectionResult(events);819 // tslint:disable-next-line:no-unused-expression820 expect(result.success).to.be.false;821 });822}823824export async function getFungibleBalance(825 collectionId: number,826 owner: string,827) {828 return await usingApi(async (api) => {829 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};830 return BigInt(response.Value);831 });832}833834export async function createFungibleItemExpectSuccess(835 sender: IKeyringPair,836 collectionId: number,837 data: CreateFungibleData,838 owner: string = sender.address,839) {840 return await usingApi(async (api) => {841 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });842843 const events = await submitTransactionAsync(sender, tx);844 const result = getCreateItemResult(events);845846 expect(result.success).to.be.true;847 return result.itemId;848 });849}850851export async function createItemExpectSuccess(852 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {853 let newItemId: number = 0;854 await usingApi(async (api) => {855 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);856 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();857 const AItemBalance = new BigNumber(Aitem.Value);858859 if (owner === '') {860 owner = sender.address;861 }862863 let tx;864 if (createMode === 'Fungible') {865 const createData = {fungible: {value: 10}};866 tx = api.tx.nft.createItem(collectionId, owner, createData);867 } else if (createMode === 'ReFungible') {868 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};869 tx = api.tx.nft.createItem(collectionId, owner, createData);870 } else {871 tx = api.tx.nft.createItem(collectionId, owner, createMode);872 }873 const events = await submitTransactionAsync(sender, tx);874 const result = getCreateItemResult(events);875876 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);877 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();878 const BItemBalance = new BigNumber(Bitem.Value);879880 // What to expect881 // tslint:disable-next-line:no-unused-expression882 expect(result.success).to.be.true;883 if (createMode === 'Fungible') {884 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);885 } else {886 expect(BItemCount).to.be.equal(AItemCount + 1);887 }888 expect(collectionId).to.be.equal(result.collectionId);889 expect(BItemCount).to.be.equal(result.itemId);890 expect(owner).to.be.equal(result.recipient);891 newItemId = result.itemId;892 });893 return newItemId;894}895896export async function createItemExpectFailure(897 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {898 await usingApi(async (api) => {899 const tx = api.tx.nft.createItem(collectionId, owner, createMode);900 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;901 const result = getCreateItemResult(events);902903 expect(result.success).to.be.false;904 });905}906907export async function setPublicAccessModeExpectSuccess(908 sender: IKeyringPair, collectionId: number,909 accessMode: 'Normal' | 'WhiteList',910) {911 await usingApi(async (api) => {912913 // Run the transaction914 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);915 const events = await submitTransactionAsync(sender, tx);916 const result = getGenericResult(events);917918 // Get the collection919 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();920921 // What to expect922 // tslint:disable-next-line:no-unused-expression923 expect(result.success).to.be.true;924 expect(collection.Access).to.be.equal(accessMode);925 });926}927928export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {929 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');930}931932export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {933 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');934}935936export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {937 await usingApi(async (api) => {938939 // Run the transaction940 const tx = api.tx.nft.setMintPermission(collectionId, enabled);941 const events = await submitTransactionAsync(sender, tx);942 const result = getGenericResult(events);943944 // Get the collection945 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();946947 // What to expect948 // tslint:disable-next-line:no-unused-expression949 expect(result.success).to.be.true;950 expect(collection.MintMode).to.be.equal(enabled);951 });952}953954export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {955 await setMintPermissionExpectSuccess(sender, collectionId, true);956}957958export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {959 await usingApi(async (api) => {960 // Run the transaction961 const tx = api.tx.nft.setMintPermission(collectionId, enabled);962 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;963 const result = getCreateCollectionResult(events);964 // tslint:disable-next-line:no-unused-expression965 expect(result.success).to.be.false;966 });967}968969export async function isWhitelisted(collectionId: number, address: string) {970 let whitelisted: boolean = false;971 await usingApi(async (api) => {972 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;973 });974 return whitelisted;975}976977export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {978 await usingApi(async (api) => {979980 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();981982 // Run the transaction983 const tx = api.tx.nft.addToWhiteList(collectionId, address);984 const events = await submitTransactionAsync(sender, tx);985 const result = getGenericResult(events);986987 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();988989 // What to expect990 // tslint:disable-next-line:no-unused-expression991 expect(result.success).to.be.true;992 // tslint:disable-next-line: no-unused-expression993 expect(whiteListedBefore).to.be.false;994 // tslint:disable-next-line: no-unused-expression995 expect(whiteListedAfter).to.be.true;996 });997}998999export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {1000 await usingApi(async (api) => {1001 // Run the transaction1002 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);1003 const events = await submitTransactionAsync(sender, tx);1004 const result = getGenericResult(events);10051006 // What to expect1007 // tslint:disable-next-line:no-unused-expression1008 expect(result.success).to.be.true;1009 });1010}10111012export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {1013 await usingApi(async (api) => {1014 // Run the transaction1015 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);1016 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1017 const result = getGenericResult(events);10181019 // What to expect1020 // tslint:disable-next-line:no-unused-expression1021 expect(result.success).to.be.false;1022 });1023}10241025export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1026 : Promise<ICollectionInterface | null> => {1027 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1028};10291030export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1031 // set global object - collectionsCount1032 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1033};10341035export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1036 return await usingApi(async (api) => {1037 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1038 });1039}1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, BlockNumber, Call, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';20import { Compact, Option, Raw, Vec } from '@polkadot/types/codec';21// import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, DispatchClass, DispatchInfo, DispatchInfoTo190, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV1, ExtrinsicPayloadV2, ExtrinsicPayloadV3, ExtrinsicPayloadV4, ExtrinsicSignatureV1, ExtrinsicSignatureV2, ExtrinsicSignatureV3, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV1, ExtrinsicV2, ExtrinsicV3, ExtrinsicV4, Hash, Header, ImmortalEra, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, Moment, MortalEra, MultiSignature, Origin, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Seal, SealV0, Signature, SignedBlock, SignerPayload, Sr25519Signature, ValidatorId, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';2223chai.use(chaiAsPromised);24const expect = chai.expect;2526export const U128_MAX = (1n << 128n) - 1n;2728type GenericResult = {29 success: boolean,30};3132interface CreateCollectionResult {33 success: boolean;34 collectionId: number;35}3637interface CreateItemResult {38 success: boolean;39 collectionId: number;40 itemId: number;41 recipient: string;42}4344interface TransferResult {45 success: boolean;46 collectionId: number;47 itemId: number;48 sender: string;49 recipient: string;50 value: bigint;51}5253interface IReFungibleOwner {54 Fraction: BN;55 Owner: number[];56}5758interface ITokenDataType {59 Owner: number[];60 ConstData: number[];61 VariableData: number[];62}6364interface IFungibleTokenDataType {65 Value: BN;66}6768interface IGetMessage {69 checkMsgNftMethod: string;70 checkMsgTrsMethod: string;71 checkMsgSysMethod: string;72}7374export interface IReFungibleTokenDataType {75 Owner: IReFungibleOwner[];76 ConstData: number[];77 VariableData: number[];78}7980export function nftEventMessage(events: EventRecord[]): IGetMessage {81 let checkMsgNftMethod: string = '';82 let checkMsgTrsMethod: string = '';83 let checkMsgSysMethod: string = '';84 events.forEach(({ event: { method, section } }) => {85 if (section === 'nft') {86 checkMsgNftMethod = method;87 } else if (section === 'treasury') {88 checkMsgTrsMethod = method;89 } else if (section === 'system') {90 checkMsgSysMethod = method;91 } else { return null; }92 });93 const result: IGetMessage = {94 checkMsgNftMethod,95 checkMsgTrsMethod,96 checkMsgSysMethod,97 };98 return result;99}100101export function getGenericResult(events: EventRecord[]): GenericResult {102 const result: GenericResult = {103 success: false,104 };105 events.forEach(({ phase, event: { data, method, section } }) => {106 // console.log(` ${phase}: ${section}.${method}:: ${data}`);107 if (method === 'ExtrinsicSuccess') {108 result.success = true;109 }110 });111 return result;112}113114115116export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {117 let success = false;118 let collectionId: number = 0;119 events.forEach(({ phase, event: { data, method, section } }) => {120 // console.log(` ${phase}: ${section}.${method}:: ${data}`);121 if (method == 'ExtrinsicSuccess') {122 success = true;123 } else if ((section == 'nft') && (method == 'CollectionCreated')) {124 collectionId = parseInt(data[0].toString());125 }126 });127 const result: CreateCollectionResult = {128 success,129 collectionId,130 };131 return result;132}133134export function getCreateItemResult(events: EventRecord[]): CreateItemResult {135 let success = false;136 let collectionId: number = 0;137 let itemId: number = 0;138 let recipient: string = '';139 events.forEach(({ phase, event: { data, method, section } }) => {140 // console.log(` ${phase}: ${section}.${method}:: ${data}`);141 if (method == 'ExtrinsicSuccess') {142 success = true;143 } else if ((section == 'nft') && (method == 'ItemCreated')) {144 collectionId = parseInt(data[0].toString());145 itemId = parseInt(data[1].toString());146 recipient = data[2].toString();147 }148 });149 const result: CreateItemResult = {150 success,151 collectionId,152 itemId,153 recipient,154 };155 return result;156}157158export function getTransferResult(events: EventRecord[]): TransferResult {159 const result: TransferResult = {160 success: false,161 collectionId: 0,162 itemId: 0,163 sender: '',164 recipient: '',165 value: 0n,166 };167168 events.forEach(({event: {data, method, section}}) => {169 if (method === 'ExtrinsicSuccess') {170 result.success = true;171 } else if (section === 'nft' && method === 'Transfer') {172 result.collectionId = +data[0].toString();173 result.itemId = +data[1].toString();174 result.sender = data[2].toString();175 result.recipient = data[3].toString();176 result.value = BigInt(data[4].toString());177 }178 });179180 return result;181}182183interface Invalid {184 type: 'Invalid';185}186187interface Nft {188 type: 'NFT';189}190191interface Fungible {192 type: 'Fungible';193 decimalPoints: number;194}195196interface ReFungible {197 type: 'ReFungible';198}199200type CollectionMode = Nft | Fungible | ReFungible | Invalid;201202export type CreateCollectionParams = {203 mode: CollectionMode,204 name: string,205 description: string,206 tokenPrefix: string,207};208209const defaultCreateCollectionParams: CreateCollectionParams = {210 description: 'description',211 mode: { type: 'NFT' },212 name: 'name',213 tokenPrefix: 'prefix',214}215216export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {217 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};218219 let collectionId: number = 0;220 await usingApi(async (api) => {221 // Get number of collections before the transaction222 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);223224 // Run the CreateCollection transaction225 const alicePrivateKey = privateKey('//Alice');226227 let modeprm = {};228 if (mode.type === 'NFT') {229 modeprm = {nft: null};230 } else if (mode.type === 'Fungible') {231 modeprm = {fungible: mode.decimalPoints};232 } else if (mode.type === 'ReFungible') {233 modeprm = {refungible: null};234 } else if (mode.type === 'Invalid') {235 modeprm = {invalid: null};236 }237238 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);239 const events = await submitTransactionAsync(alicePrivateKey, tx);240 const result = getCreateCollectionResult(events);241242 // Get number of collections after the transaction243 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244245 // Get the collection246 const collection: any = (await api.query.nft.collectionById(result.collectionId)).toJSON();247248 // What to expect249 // tslint:disable-next-line:no-unused-expression250 expect(result.success).to.be.true;251 expect(result.collectionId).to.be.equal(BcollectionCount);252 // tslint:disable-next-line:no-unused-expression253 expect(collection).to.be.not.null;254 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');255 expect(collection.Owner).to.be.equal(alicesPublicKey);256 expect(utf16ToStr(collection.Name)).to.be.equal(name);257 expect(utf16ToStr(collection.Description)).to.be.equal(description);258 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);259260 collectionId = result.collectionId;261 });262263 return collectionId;264}265266export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {267 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};268269 let modeprm = {};270 if (mode.type === 'NFT') {271 modeprm = {nft: null};272 } else if (mode.type === 'Fungible') {273 modeprm = {fungible: mode.decimalPoints};274 } else if (mode.type === 'ReFungible') {275 modeprm = {refungible: null};276 } else if (mode.type === 'Invalid') {277 modeprm = {invalid: null};278 }279280 await usingApi(async (api) => {281 // Get number of collections before the transaction282 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());283284 // Run the CreateCollection transaction285 const alicePrivateKey = privateKey('//Alice');286 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);287 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;288 const result = getCreateCollectionResult(events);289290 // Get number of collections after the transaction291 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());292293 // What to expect294 // tslint:disable-next-line:no-unused-expression295 expect(result.success).to.be.false;296 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');297 });298}299300export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {301 let bal = new BigNumber(0);302 let unused;303 do {304 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;305 const keyring = new Keyring({ type: 'sr25519' });306 unused = keyring.addFromUri(`//${randomSeed}`);307 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());308 } while (bal.toFixed() != '0');309 return unused;310}311312export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {313 return await usingApi(async (api) => {314 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;315 return BigInt(bn.toString());316 });317}318319export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {320 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));321}322323export async function findNotExistingCollection(api: ApiPromise): Promise<number> {324 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;325 const newCollection: number = totalNumber + 1;326 return newCollection;327}328329function getDestroyResult(events: EventRecord[]): boolean {330 let success: boolean = false;331 events.forEach(({ phase, event: { data, method, section } }) => {332 // console.log(` ${phase}: ${section}.${method}:: ${data}`);333 if (method == 'ExtrinsicSuccess') {334 success = true;335 }336 });337 return success;338}339340export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {341 await usingApi(async (api) => {342 // Run the DestroyCollection transaction343 const alicePrivateKey = privateKey(senderSeed);344 const tx = api.tx.nft.destroyCollection(collectionId);345 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;346 });347}348349export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {350 await usingApi(async (api) => {351 // Run the DestroyCollection transaction352 const alicePrivateKey = privateKey(senderSeed);353 const tx = api.tx.nft.destroyCollection(collectionId);354 const events = await submitTransactionAsync(alicePrivateKey, tx);355 const result = getDestroyResult(events);356357 // Get the collection358 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();359360 // What to expect361 expect(result).to.be.true;362 expect(collection).to.be.null;363 });364}365366export async function queryCollectionLimits(collectionId: number) {367 return await usingApi(async (api) => {368 return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;369 });370}371372export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {373 await usingApi(async (api) => {374 const oldLimits = await queryCollectionLimits(collectionId);375 const newLimits = { ...oldLimits as any, ...limits };376 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);377 const events = await submitTransactionAsync(sender, tx);378 const result = getGenericResult(events);379380 expect(result.success).to.be.true;381 });382}383384export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {385 await usingApi(async (api) => {386 const oldLimits = await queryCollectionLimits(collectionId);387 const newLimits = { ...oldLimits as any, ...limits };388 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);389 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;390 const result = getGenericResult(events);391392 expect(result.success).to.be.false;393 });394}395396export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {397 await usingApi(async (api) => {398399 // Run the transaction400 const alicePrivateKey = privateKey('//Alice');401 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);402 const events = await submitTransactionAsync(alicePrivateKey, tx);403 const result = getGenericResult(events);404405 // Get the collection406 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();407408 // What to expect409 expect(result.success).to.be.true;410 expect(collection.Sponsorship).to.deep.equal({411 Unconfirmed: sponsor.toString(),412 });413 });414}415416export async function removeCollectionSponsorExpectSuccess(collectionId: number) {417 await usingApi(async (api) => {418419 // Run the transaction420 const alicePrivateKey = privateKey('//Alice');421 const tx = api.tx.nft.removeCollectionSponsor(collectionId);422 const events = await submitTransactionAsync(alicePrivateKey, tx);423 const result = getGenericResult(events);424425 // Get the collection426 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();427428 // What to expect429 expect(result.success).to.be.true;430 expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });431 });432}433434export async function removeCollectionSponsorExpectFailure(collectionId: number) {435 await usingApi(async (api) => {436437 // Run the transaction438 const alicePrivateKey = privateKey('//Alice');439 const tx = api.tx.nft.removeCollectionSponsor(collectionId);440 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;441 });442}443444export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {445 await usingApi(async (api) => {446447 // Run the transaction448 const alicePrivateKey = privateKey(senderSeed);449 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);450 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;451 });452}453454export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {455 await usingApi(async (api) => {456457 // Run the transaction458 const sender = privateKey(senderSeed);459 const tx = api.tx.nft.confirmSponsorship(collectionId);460 const events = await submitTransactionAsync(sender, tx);461 const result = getGenericResult(events);462463 // Get the collection464 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();465466 // What to expect467 expect(result.success).to.be.true;468 expect(collection.Sponsorship).to.be.deep.equal({469 Confirmed: sender.address,470 });471 });472}473474475export async function confirmSponsorshipExpectFailure(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 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;482 });483}484485export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {486 await usingApi(async (api) => {487 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);488 const events = await submitTransactionAsync(sender, tx);489 const result = getGenericResult(events);490491 expect(result.success).to.be.true;492 });493}494495export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {496 await usingApi(async (api) => {497 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);498 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;499 const result = getGenericResult(events);500501 expect(result.success).to.be.false;502 });503}504505export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {506 await usingApi(async (api) => {507 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);508 const events = await submitTransactionAsync(sender, tx);509 const result = getGenericResult(events);510511 expect(result.success).to.be.true;512 });513}514515export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {516 await usingApi(async (api) => {517 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);518 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;519 const result = getGenericResult(events);520521 expect(result.success).to.be.false;522 });523}524525export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {526 await usingApi(async (api) => {527 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);528 const events = await submitTransactionAsync(sender, tx);529 const result = getGenericResult(events);530531 expect(result.success).to.be.true;532 });533}534535export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {536 let whitelisted: boolean = false;537 await usingApi(async (api) => {538 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;539 });540 return whitelisted;541}542543export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {544 await usingApi(async (api) => {545 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);546 const events = await submitTransactionAsync(sender, tx);547 const result = getGenericResult(events);548549 expect(result.success).to.be.true;550 });551}552553export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {554 await usingApi(async (api) => {555 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);556 const events = await submitTransactionAsync(sender, tx);557 const result = getGenericResult(events);558559 expect(result.success).to.be.true;560 });561}562563export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {564 await usingApi(async (api) => {565 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);566 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;567 const result = getGenericResult(events);568569 expect(result.success).to.be.false;570 });571}572573export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {574 await usingApi(async (api) => {575 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));576 const events = await submitTransactionAsync(sender, tx);577 const result = getGenericResult(events);578579 expect(result.success).to.be.true;580 });581}582583export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {584 await usingApi(async (api) => {585 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));586 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;587 });588}589590export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {591 await usingApi(async (api) => {592 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));593 const events = await submitTransactionAsync(sender, tx);594 const result = getGenericResult(events);595596 expect(result.success).to.be.true;597 });598}599600export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {601 await usingApi(async (api) => {602 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));603 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;604 });605}606607export interface CreateFungibleData {608 readonly Value: bigint;609}610611export interface CreateReFungibleData { }612export interface CreateNftData { }613614export type CreateItemData = {615 NFT: CreateNftData;616} | {617 Fungible: CreateFungibleData;618} | {619 ReFungible: CreateReFungibleData;620};621622export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {623 await usingApi(async (api) => {624 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);625 const events = await submitTransactionAsync(owner, tx);626 const result = getGenericResult(events);627 // Get the item628 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();629 // What to expect630 // tslint:disable-next-line:no-unused-expression631 expect(result.success).to.be.true;632 // tslint:disable-next-line:no-unused-expression633 expect(item).to.be.null;634 });635}636637export async function638approveExpectSuccess(collectionId: number,639 tokenId: number, owner: IKeyringPair, approved: IKeyringPair | string, amount: number | bigint = 1) {640 if (typeof approved !== 'string')641 approved = approved.address;642 await usingApi(async (api: ApiPromise) => {643 const allowanceBefore =644 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved] as any) as unknown as BN;645 const approveNftTx = await api.tx.nft.approve(approved, collectionId, tokenId, amount);646 const events = await submitTransactionAsync(owner, approveNftTx);647 const result = getCreateItemResult(events);648 // tslint:disable-next-line:no-unused-expression649 expect(result.success).to.be.true;650 const allowanceAfter =651 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved] as any) as unknown as BN;652 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());653 });654}655656export async function657transferFromExpectSuccess(collectionId: number,658 tokenId: number,659 accountApproved: IKeyringPair,660 accountFrom: IKeyringPair | string,661 accountTo: IKeyringPair,662 value: number | bigint = 1,663 type: string = 'NFT') {664 if (typeof accountFrom !== 'string')665 accountFrom = accountFrom.address;666 await usingApi(async (api: ApiPromise) => {667 let balanceBefore = new BN(0);668 if (type === 'Fungible') {669 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;670 }671 const transferFromTx = await api.tx.nft.transferFrom(672 accountFrom, accountTo.address, collectionId, tokenId, value);673 const events = await submitTransactionAsync(accountApproved, transferFromTx);674 const result = getCreateItemResult(events);675 // tslint:disable-next-line:no-unused-expression676 expect(result.success).to.be.true;677 if (type === 'NFT') {678 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap() as ITokenDataType;679 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);680 }681 if (type === 'Fungible') {682 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, accountTo.address) as any).Value as unknown as BN;683 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());684 }685 if (type === 'ReFungible') {686 const nftItemData =687 (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).unwrap() as IReFungibleTokenDataType;688 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);689 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);690 }691 });692}693694export async function695transferFromExpectFail(collectionId: number,696 tokenId: number,697 accountApproved: IKeyringPair,698 accountFrom: IKeyringPair,699 accountTo: IKeyringPair,700 value: number | bigint = 1) {701 await usingApi(async (api: ApiPromise) => {702 const transferFromTx = await api.tx.nft.transferFrom(703 accountFrom.address, accountTo.address, collectionId, tokenId, value);704 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;705 const result = getCreateCollectionResult(events);706 // tslint:disable-next-line:no-unused-expression707 expect(result.success).to.be.false;708 });709}710711async function getBlockNumber(api: ApiPromise): Promise<number> {712 return new Promise<number>(async (resolve, reject) => {713 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {714 unsubscribe();715 resolve(head.number.toNumber());716 });717 });718}719720export async function721scheduleTransferExpectSuccess(collectionId: number,722 tokenId: number,723 sender: IKeyringPair,724 recipient: IKeyringPair,725 value: number | bigint = 1,726 type: string = 'NFT') {727 await usingApi(async (api: ApiPromise) => {728 let balanceBefore = new BN(0);729730731 let blockNumber: number | undefined = await getBlockNumber(api);732 let expectedBlockNumber = blockNumber + 2;733734 expect(blockNumber).to.be.greaterThan(0);735 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value); 736 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);737738 const events = await submitTransactionAsync(sender, scheduleTx);739740 const sponsorBalanceBefore = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());741 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());742743 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;744 expect(nftItemDataBefore.Owner.toString()).to.be.equal(sender.address);745746 // sleep for 2 blocks747 await new Promise(resolve => setTimeout(resolve, 6000 * 2));748749 const sponsorBalanceAfter = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());750 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());751752 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;753 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);754 expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());755 });756}757758759export async function760transferExpectSuccess(collectionId: number,761 tokenId: number,762 sender: IKeyringPair,763 recipient: IKeyringPair,764 value: number | bigint = 1,765 type: string = 'NFT') {766 await usingApi(async (api: ApiPromise) => {767 let balanceBefore = new BN(0);768 if (type === 'Fungible') {769 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;770 }771 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);772 const events = await submitTransactionAsync(sender, transferTx);773 const result = getTransferResult(events);774 // tslint:disable-next-line:no-unused-expression775 expect(result.success).to.be.true;776 expect(result.collectionId).to.be.equal(collectionId);777 expect(result.itemId).to.be.equal(tokenId);778 expect(result.sender).to.be.equal(sender.address);779 expect(result.recipient).to.be.equal(recipient.address);780 expect(result.value.toString()).to.be.equal(value.toString());781 if (type === 'NFT') {782 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;783 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);784 }785 if (type === 'Fungible') {786 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, recipient.address) as any).Value as unknown as BN;787 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());788 }789 if (type === 'ReFungible') {790 const nftItemData =791 (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;792 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);793 expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());794 }795 });796}797798export async function799transferExpectFail(collectionId: number,800 tokenId: number,801 sender: IKeyringPair,802 recipient: IKeyringPair,803 value: number | bigint = 1,804 type: string = 'NFT') {805 await usingApi(async (api: ApiPromise) => {806 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);807 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;808 if (events && Array.isArray(events)) {809 const result = getCreateCollectionResult(events);810 // tslint:disable-next-line:no-unused-expression811 expect(result.success).to.be.false;812 }813 });814}815816export async function817approveExpectFail(collectionId: number,818 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {819 await usingApi(async (api: ApiPromise) => {820 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);821 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;822 const result = getCreateCollectionResult(events);823 // tslint:disable-next-line:no-unused-expression824 expect(result.success).to.be.false;825 });826}827828export async function getFungibleBalance(829 collectionId: number,830 owner: string,831) {832 return await usingApi(async (api) => {833 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};834 return BigInt(response.Value);835 });836}837838export async function createFungibleItemExpectSuccess(839 sender: IKeyringPair,840 collectionId: number,841 data: CreateFungibleData,842 owner: string = sender.address,843) {844 return await usingApi(async (api) => {845 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });846847 const events = await submitTransactionAsync(sender, tx);848 const result = getCreateItemResult(events);849850 expect(result.success).to.be.true;851 return result.itemId;852 });853}854855export async function createItemExpectSuccess(856 sender: IKeyringPair, collectionId: number, createMode: string, owner: string | AccountId = sender.address) {857 let newItemId: number = 0;858 await usingApi(async (api) => {859 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);860 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();861 const AItemBalance = new BigNumber(Aitem.Value);862863 let tx;864 if (createMode === 'Fungible') {865 const createData = {fungible: {value: 10}};866 tx = api.tx.nft.createItem(collectionId, owner, createData);867 } else if (createMode === 'ReFungible') {868 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};869 tx = api.tx.nft.createItem(collectionId, owner, createData);870 } else {871 tx = api.tx.nft.createItem(collectionId, owner, createMode);872 }873 const events = await submitTransactionAsync(sender, tx);874 const result = getCreateItemResult(events);875876 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);877 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();878 const BItemBalance = new BigNumber(Bitem.Value);879880 // What to expect881 // tslint:disable-next-line:no-unused-expression882 expect(result.success).to.be.true;883 if (createMode === 'Fungible') {884 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);885 } else {886 expect(BItemCount).to.be.equal(AItemCount + 1);887 }888 expect(collectionId).to.be.equal(result.collectionId);889 expect(BItemCount).to.be.equal(result.itemId);890 expect(owner.toString()).to.be.equal(result.recipient);891 newItemId = result.itemId;892 });893 return newItemId;894}895896export async function createItemExpectFailure(897 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {898 await usingApi(async (api) => {899 const tx = api.tx.nft.createItem(collectionId, owner, createMode);900 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;901 const result = getCreateItemResult(events);902903 expect(result.success).to.be.false;904 });905}906907export async function setPublicAccessModeExpectSuccess(908 sender: IKeyringPair, collectionId: number,909 accessMode: 'Normal' | 'WhiteList',910) {911 await usingApi(async (api) => {912913 // Run the transaction914 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);915 const events = await submitTransactionAsync(sender, tx);916 const result = getGenericResult(events);917918 // Get the collection919 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();920921 // What to expect922 // tslint:disable-next-line:no-unused-expression923 expect(result.success).to.be.true;924 expect(collection.Access).to.be.equal(accessMode);925 });926}927928export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {929 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');930}931932export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {933 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');934}935936export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {937 await usingApi(async (api) => {938939 // Run the transaction940 const tx = api.tx.nft.setMintPermission(collectionId, enabled);941 const events = await submitTransactionAsync(sender, tx);942 const result = getGenericResult(events);943944 // Get the collection945 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();946947 // What to expect948 // tslint:disable-next-line:no-unused-expression949 expect(result.success).to.be.true;950 expect(collection.MintMode).to.be.equal(enabled);951 });952}953954export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {955 await setMintPermissionExpectSuccess(sender, collectionId, true);956}957958export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {959 await usingApi(async (api) => {960 // Run the transaction961 const tx = api.tx.nft.setMintPermission(collectionId, enabled);962 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;963 const result = getCreateCollectionResult(events);964 // tslint:disable-next-line:no-unused-expression965 expect(result.success).to.be.false;966 });967}968969export async function isWhitelisted(collectionId: number, address: string) {970 let whitelisted: boolean = false;971 await usingApi(async (api) => {972 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;973 });974 return whitelisted;975}976977export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {978 await usingApi(async (api) => {979980 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();981982 // Run the transaction983 const tx = api.tx.nft.addToWhiteList(collectionId, address);984 const events = await submitTransactionAsync(sender, tx);985 const result = getGenericResult(events);986987 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();988989 // What to expect990 // tslint:disable-next-line:no-unused-expression991 expect(result.success).to.be.true;992 // tslint:disable-next-line: no-unused-expression993 expect(whiteListedBefore).to.be.false;994 // tslint:disable-next-line: no-unused-expression995 expect(whiteListedAfter).to.be.true;996 });997}998999export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {1000 await usingApi(async (api) => {1001 // Run the transaction1002 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);1003 const events = await submitTransactionAsync(sender, tx);1004 const result = getGenericResult(events);10051006 // What to expect1007 // tslint:disable-next-line:no-unused-expression1008 expect(result.success).to.be.true;1009 });1010}10111012export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {1013 await usingApi(async (api) => {1014 // Run the transaction1015 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);1016 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1017 const result = getGenericResult(events);10181019 // What to expect1020 // tslint:disable-next-line:no-unused-expression1021 expect(result.success).to.be.false;1022 });1023}10241025export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1026 : Promise<ICollectionInterface | null> => {1027 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1028};10291030export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1031 // set global object - collectionsCount1032 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1033};10341035export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1036 return await usingApi(async (api) => {1037 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1038 });1039}