git.delta.rocks / unique-network / refs/commits / 8eb82cd98ff6

difftreelog

Merge branch 'develop' into feature/NFTPAR-93

sotmorskiy2020-10-05parents: #4fc8a38 #ab1a681.patch.diff
in: master
# Conflicts:
#	tests/package-lock.json
#	tests/package.json

11 files changed

modifiedREADME.mddiffbeforeafterboth
--- a/README.md
+++ b/README.md
@@ -142,6 +142,12 @@
     "enable_println": "bool",
     "max_subject_len": "u32"
   },
+  "AccessMode": {
+    "_enum": [
+      "Normal",
+      "WhiteList"
+    ]
+  },
   "CollectionMode": {
     "_enum": {
       "Invalid": null,
@@ -181,19 +187,25 @@
   "CollectionType": {
     "Owner": "AccountId",
     "Mode": "CollectionMode",
-    "Access": "u8",
+    "Access": "AccessMode",
     "DecimalPoints": "u32",
     "Name": "Vec<u16>",
     "Description": "Vec<u16>",
     "TokenPrefix": "Vec<u8>",
     "CustomDataSize": "u32",
+    "MintMode": "bool",
     "OffchainSchema": "Vec<u8>",
     "Sponsor": "AccountId",
     "UnconfirmedSponsor": "AccountId"
   },
+  "ApprovePermissions": {
+    "Approved": "AccountId",
+    "Amount": "u64"
+  },
   "RawData": "Vec<u8>",
   "Address": "AccountId",
   "LookupSource": "AccountId",
   "Weight": "u64"
 }
+
 ```
\ No newline at end of file
modifiednode/src/chain_spec.rsdiffbeforeafterboth
--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -1,8 +1,9 @@
-use nft_runtime::{
-    AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig,
-    SystemConfig, WASM_BINARY,
-};
-use nft_runtime::{ContractsConfig, ContractsSchedule};
+// use nft_runtime::{
+//     AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig,
+//     SystemConfig, WASM_BINARY,
+// };
+// use nft_runtime::{ContractsConfig, ContractsSchedule, NftConfig, CollectionType};
+use nft_runtime::*;
 use sc_service::ChainType;
 use sp_consensus_aura::sr25519::AuthorityId as AuraId;
 use sp_core::{sr25519, Pair, Public};
@@ -128,6 +129,25 @@
                 .collect(),
         }),
         sudo: Some(SudoConfig { key: root_key }),
+        nft: Some(NftConfig {
+            collection: vec![(1, CollectionType { 
+                owner: get_account_id_from_seed::<sr25519::Public>("Alice"),
+                mode: CollectionMode::NFT(50),
+                access: AccessMode::Normal,
+                decimal_points: 0,
+                name: vec!(),
+                description: vec!(),
+                token_prefix: vec!(),
+                custom_data_size: 50,
+                mint_mode: false,
+                offchain_schema: vec!(),
+                sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
+                unconfirmed_sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
+            })],
+            nft_item_id: vec!(),
+            fungible_item_id: vec!(),
+            refungible_item_id: vec!(),
+        }),
         contracts: Some(ContractsConfig {
             current_schedule: ContractsSchedule {
                 enable_println,
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
before · pallets/nft/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23/// For more guidance on Substrate FRAME, see the example pallet4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs5use codec::{Decode, Encode};6pub use frame_support::{7    construct_runtime, decl_event, decl_module, decl_storage,8    dispatch::DispatchResult,9    ensure, parameter_types,10    traits::{11        Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,12        Randomness, WithdrawReason,13    },14    weights::{15        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},16        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,17        WeightToFeePolynomial,18    },19    IsSubType, StorageValue,20};2122use frame_system::{self as system, ensure_signed};23use sp_runtime::sp_std::prelude::Vec;24use sp_runtime::{25    traits::{26        DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,27        SignedExtension, Zero,28    },29    transaction_validity::{30        InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,31        ValidTransaction,32    },33    FixedPointOperand, FixedU128,34};35use sp_std::prelude::*;3637#[cfg(test)]38mod mock;3940#[cfg(test)]41mod tests;4243#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]44pub enum CollectionMode {45    Invalid,46    // custom data size47    NFT(u32),48    // decimal points49    Fungible(u32),50    // custom data size and decimal points51    ReFungible(u32, u32),52}5354impl Into<u8> for CollectionMode {55    fn into(self) -> u8 {56        match self {57            CollectionMode::Invalid => 0,58            CollectionMode::NFT(_) => 1,59            CollectionMode::Fungible(_) => 2,60            CollectionMode::ReFungible(_, _) => 3,61        }62    }63}6465#[derive(Encode, Decode, Debug, Clone, PartialEq)]66pub enum AccessMode {67    Normal,68    WhiteList,69}70impl Default for AccessMode {71    fn default() -> Self {72        Self::Normal73    }74}7576impl Default for CollectionMode {77    fn default() -> Self {78        Self::Invalid79    }80}8182#[derive(Encode, Decode, Default, Clone, PartialEq)]83#[cfg_attr(feature = "std", derive(Debug))]84pub struct Ownership<AccountId> {85    pub owner: AccountId,86    pub fraction: u128,87}8889#[derive(Encode, Decode, Default, Clone, PartialEq)]90#[cfg_attr(feature = "std", derive(Debug))]91pub struct CollectionType<AccountId> {92    pub owner: AccountId,93    pub mode: CollectionMode,94    pub access: AccessMode,95    pub decimal_points: u32,96    pub name: Vec<u16>,        // 64 include null escape char97    pub description: Vec<u16>, // 256 include null escape char98    pub token_prefix: Vec<u8>, // 16 include null escape char99    pub custom_data_size: u32,100    pub offchain_schema: Vec<u8>,101    pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender102    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship103}104105#[derive(Encode, Decode, Default, Clone, PartialEq)]106#[cfg_attr(feature = "std", derive(Debug))]107pub struct CollectionAdminsType<AccountId> {108    pub admin: AccountId,109    pub collection_id: u64,110}111112#[derive(Encode, Decode, Default, Clone, PartialEq)]113#[cfg_attr(feature = "std", derive(Debug))]114pub struct NftItemType<AccountId> {115    pub collection: u64,116    pub owner: AccountId,117    pub data: Vec<u8>,118}119120#[derive(Encode, Decode, Default, Clone, PartialEq)]121#[cfg_attr(feature = "std", derive(Debug))]122pub struct FungibleItemType<AccountId> {123    pub collection: u64,124    pub owner: AccountId,125    pub value: u128,126}127128#[derive(Encode, Decode, Default, Clone, PartialEq)]129#[cfg_attr(feature = "std", derive(Debug))]130pub struct ReFungibleItemType<AccountId> {131    pub collection: u64,132    pub owner: Vec<Ownership<AccountId>>,133    pub data: Vec<u8>,134}135136#[derive(Encode, Decode, Default, Clone, PartialEq)]137#[cfg_attr(feature = "std", derive(Debug))]138pub struct ApprovePermissions<AccountId> {139    pub approved: AccountId,140    pub amount: u64,141}142143#[derive(Encode, Decode, Default, Clone, PartialEq)]144#[cfg_attr(feature = "std", derive(Debug))]145pub struct VestingItem<AccountId, Moment> {146    pub sender: AccountId,147    pub recipient: AccountId,148    pub collection_id: u64,149    pub item_id: u64,150    pub amount: u64,151    pub vesting_date: Moment,152}153154pub trait Trait: system::Trait {155    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;156}157158decl_storage! {159    trait Store for Module<T: Trait> as Nft {160161        // Private members162        NextCollectionID: u64;163        CreatedCollectionCount: u64;164        ChainVersion: u64;165        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;166167        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;168        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;169        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;170171        /// Balance owner per collection map172        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;173174        /// second parameter: item id + owner account id175        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;176177        /// Item collections178        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;179        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;180        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;181182        // Active vesting list183        // pub VestingList get(fn vesting): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => VestingItem<T::AccountId, T::Moment>;184185        /// Index list186        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;187188        // Sponsorship189        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;190        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;191    }192}193194decl_event!(195    pub enum Event<T>196    where197        AccountId = <T as system::Trait>::AccountId,198    {199        Created(u64, u8, AccountId),200        ItemCreated(u64, u64),201        ItemDestroyed(u64, u64),202    }203);204205decl_module! {206    pub struct Module<T: Trait> for enum Call where origin: T::Origin {207208        fn deposit_event() = default;209210        fn on_initialize(now: T::BlockNumber) -> Weight {211212            if ChainVersion::get() == 0213            {214                let value = NextCollectionID::get();215                CreatedCollectionCount::put(value);216                ChainVersion::put(2);217            }218219            0220        }221222        // Create collection of NFT with given parameters223        //224        // @param customDataSz size of custom data in each collection item225        // returns collection ID226        #[weight = 0]227        pub fn create_collection(   origin,228                                    collection_name: Vec<u16>,229                                    collection_description: Vec<u16>,230                                    token_prefix: Vec<u8>,231                                    mode: CollectionMode) -> DispatchResult {232233            // Anyone can create a collection234            let who = ensure_signed(origin)?;235            let custom_data_size = match mode {236                CollectionMode::NFT(size) => size,237                CollectionMode::ReFungible(size, _) => size,238                _ => 0239            };240241            let decimal_points = match mode {242                CollectionMode::Fungible(points) => points,243                CollectionMode::ReFungible(_, points) => points,244                _ => 0245            };246247            // check params248            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");249250            let mut name = collection_name.to_vec();251            name.push(0);252            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");253254            let mut description = collection_description.to_vec();255            description.push(0);256            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");257258            let mut prefix = token_prefix.to_vec();259            prefix.push(0);260            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");261262            // Generate next collection ID263            let next_id = CreatedCollectionCount::get()264                .checked_add(1)265                .expect("collection id error");266267            CreatedCollectionCount::put(next_id);268269            // Create new collection270            let new_collection = CollectionType {271                owner: who.clone(),272                name: name,273                mode: mode.clone(),274                access: AccessMode::Normal,275                description: description,276                decimal_points: decimal_points,277                token_prefix: prefix,278                offchain_schema: Vec::new(),279                custom_data_size: custom_data_size,280                sponsor: T::AccountId::default(),281                unconfirmed_sponsor: T::AccountId::default(),282            };283284            // Add new collection to map285            <Collection<T>>::insert(next_id, new_collection);286287            // call event288            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));289290            Ok(())291        }292293        #[weight = 0]294        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {295296            let sender = ensure_signed(origin)?;297            Self::check_owner_permissions(collection_id, sender)?;298299            // TODO Items remove300            <AddressTokens<T>>::remove_prefix(collection_id);301            <ApprovedList<T>>::remove_prefix(collection_id);302            <Balance<T>>::remove_prefix(collection_id);303            <ItemListIndex>::remove(collection_id);304            <AdminList<T>>::remove(collection_id);305            <Collection<T>>::remove(collection_id);306            <WhiteList<T>>::remove(collection_id);307308            Ok(())309        }310311        #[weight = 0]312        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {313314            let sender = ensure_signed(origin)?;315            Self::check_owner_permissions(collection_id, sender)?;316            let mut target_collection = <Collection<T>>::get(collection_id);317            target_collection.owner = new_owner;318            <Collection<T>>::insert(collection_id, target_collection);319320            Ok(())321        }322323        #[weight = 0]324        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {325326            let sender = ensure_signed(origin)?;327            Self::check_owner_or_admin_permissions(collection_id, sender)?;328            let mut admin_arr: Vec<T::AccountId> = Vec::new();329330            if <AdminList<T>>::contains_key(collection_id)331            {332                admin_arr = <AdminList<T>>::get(collection_id);333                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");334            }335336            admin_arr.push(new_admin_id);337            <AdminList<T>>::insert(collection_id, admin_arr);338339            Ok(())340        }341342        #[weight = 0]343        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {344345            let sender = ensure_signed(origin)?;346            Self::check_owner_or_admin_permissions(collection_id, sender)?;347348            if <AdminList<T>>::contains_key(collection_id)349            {350                let mut admin_arr = <AdminList<T>>::get(collection_id);351                admin_arr.retain(|i| *i != account_id);352                <AdminList<T>>::insert(collection_id, admin_arr);353            }354355            Ok(())356        }357358        #[weight = 0]359        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {360361            let sender = ensure_signed(origin)?;362            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");363364            let mut target_collection = <Collection<T>>::get(collection_id);365            ensure!(sender == target_collection.owner, "You do not own this collection");366367            target_collection.unconfirmed_sponsor = new_sponsor;368            <Collection<T>>::insert(collection_id, target_collection);369370            Ok(())371        }372373        #[weight = 0]374        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {375376            let sender = ensure_signed(origin)?;377            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");378379            let mut target_collection = <Collection<T>>::get(collection_id);380            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");381382            target_collection.sponsor = target_collection.unconfirmed_sponsor;383            target_collection.unconfirmed_sponsor = T::AccountId::default();384            <Collection<T>>::insert(collection_id, target_collection);385386            Ok(())387        }388389        #[weight = 0]390        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {391392            let sender = ensure_signed(origin)?;393            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");394395            let mut target_collection = <Collection<T>>::get(collection_id);396            ensure!(sender == target_collection.owner, "You do not own this collection");397398            target_collection.sponsor = T::AccountId::default();399            <Collection<T>>::insert(collection_id, target_collection);400401            Ok(())402        }403404        #[weight = 0]405        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {406407            let sender = ensure_signed(origin)?;408            let target_collection = <Collection<T>>::get(collection_id);409            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;410411            match target_collection.mode412            {413                CollectionMode::NFT(_) => {414415                    // check size416                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");417418                    // Create nft item419                    let item = NftItemType {420                        collection: collection_id,421                        owner: owner,422                        data: properties.clone(),423                    };424425                    Self::add_nft_item(item)?;426427                },428                CollectionMode::Fungible(_) => {429430                    // check size431                    ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");432433                    let item = FungibleItemType {434                        collection: collection_id,435                        owner: owner,436                        value: (10 as u128).pow(target_collection.decimal_points)437                    };438439                    Self::add_fungible_item(item)?;440                },441                CollectionMode::ReFungible(_, _) => {442443                    // check size444                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");445446                    let mut owner_list = Vec::new();447                    let value = (10 as u128).pow(target_collection.decimal_points);448                    owner_list.push(Ownership {owner: owner.clone(), fraction: value});449450                    let item = ReFungibleItemType {451                        collection: collection_id,452                        owner: owner_list,453                        data: properties.clone()454                    };455456                    Self::add_refungible_item(item)?;457                },458                _ => { ensure!(1 == 0,"just error"); }459460            };461462            // call event463            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));464465            Ok(())466        }467468        #[weight = 0]469        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {470471            let sender = ensure_signed(origin)?;472            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);473            if !item_owner474            {475                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;476            }477            let target_collection = <Collection<T>>::get(collection_id);478479            match target_collection.mode480            {481                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,482                CollectionMode::Fungible(_)  => Self::burn_fungible_item(collection_id, item_id)?,483                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,484                _ => ()485            };486487            // call event488            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));489490            Ok(())491        }492493        #[weight = 0]494        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {495496            let sender = ensure_signed(origin)?;497            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");498499            let target_collection = <Collection<T>>::get(collection_id);500501            // TODO: implement other modes502            match target_collection.mode503            {504                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,505                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,506                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,507                _ => ()508            };509510            Ok(())511        }512513        #[weight = 0]514        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {515516            let sender = ensure_signed(origin)?;517518            // amount param stub519            let amount = 100000000;520521            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");522523            let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));524            if list_exists {525526                let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));527                let item_contains = list.iter().any(|i| i.approved == approved);528529                if !item_contains {530                    list.push(ApprovePermissions { approved: approved.clone(), amount: amount });531                    <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);532                }533            } else {534535                let mut list = Vec::new();536                list.push(ApprovePermissions { approved: approved.clone(), amount: amount });537                <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);538            }539540            Ok(())541        }542543        #[weight = 0]544        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {545546            let sender = ensure_signed(origin)?;547            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));548            if approved_list_exists549            {550                let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));551                let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());552                ensure!(opt_item.is_some(), "No approve found");553                ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");554555                // remove approve556                let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))557                    .into_iter().filter(|i| i.approved != sender.clone()).collect();558                <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);559            }560            else561            {562                Self::check_owner_or_admin_permissions(collection_id, sender)?;563            }564565            let target_collection = <Collection<T>>::get(collection_id);566567            match target_collection.mode568            {569                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,570                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,571                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,572                _ => ()573            };574575            Ok(())576        }577578        #[weight = 0]579        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {580581            // let no_perm_mes = "You do not have permissions to modify this collection";582            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);583            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));584            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);585586            // // on_nft_received  call587588            // Self::transfer(origin, collection_id, item_id, new_owner)?;589590            Ok(())591        }592593        #[weight = 0]594        pub fn set_offchain_schema(595            origin,596            collection_id: u64,597            schema: Vec<u8>598        ) -> DispatchResult {599            let sender = ensure_signed(origin)?;600            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;601602            let mut target_collection = <Collection<T>>::get(collection_id);603            target_collection.offchain_schema = schema;604            <Collection<T>>::insert(collection_id, target_collection);605606            Ok(())607        }608    }609}610611impl<T: Trait> Module<T> {612    fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {613        let current_index = <ItemListIndex>::get(item.collection)614            .checked_add(1)615            .expect("Item list index id error");616        let itemcopy = item.clone();617        let owner = item.owner.clone();618        let value = item.value as u64;619620        Self::add_token_index(item.collection, current_index, owner.clone())?;621622        <ItemListIndex>::insert(item.collection, current_index);623        <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);624625        // Update balance626        let new_balance = <Balance<T>>::get(item.collection, owner.clone())627            .checked_add(value)628            .unwrap();629        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);630631        Ok(())632    }633634    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {635        let current_index = <ItemListIndex>::get(item.collection)636            .checked_add(1)637            .expect("Item list index id error");638        let itemcopy = item.clone();639640        let value = item.owner.first().unwrap().fraction as u64;641        let owner = item.owner.first().unwrap().owner.clone();642643        Self::add_token_index(item.collection, current_index, owner.clone())?;644645        <ItemListIndex>::insert(item.collection, current_index);646        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);647648        // Update balance649        let new_balance = <Balance<T>>::get(item.collection, owner.clone())650            .checked_add(value)651            .unwrap();652        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);653654        Ok(())655    }656657    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {658        let current_index = <ItemListIndex>::get(item.collection)659            .checked_add(1)660            .expect("Item list index id error");661662        let item_owner = item.owner.clone();663        let collection_id = item.collection.clone();664        Self::add_token_index(collection_id, current_index, item.owner.clone())?;665666        <ItemListIndex>::insert(collection_id, current_index);667        <NftItemList<T>>::insert(collection_id, current_index, item);668669        // Update balance670        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())671            .checked_add(1)672            .unwrap();673        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);674675        Ok(())676    }677678    fn burn_refungible_item(679        collection_id: u64,680        item_id: u64,681        owner: T::AccountId,682    ) -> DispatchResult {683        ensure!(684            <ReFungibleItemList<T>>::contains_key(collection_id, item_id),685            "Item does not exists"686        );687        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);688        let item = collection689            .owner690            .iter()691            .filter(|&i| i.owner == owner)692            .next()693            .unwrap();694        Self::remove_token_index(collection_id, item_id, owner.clone())?;695696        // remove approve list697        <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));698699        // update balance700        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())701            .checked_sub(item.fraction as u64)702            .unwrap();703        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);704705        <ReFungibleItemList<T>>::remove(collection_id, item_id);706707        Ok(())708    }709710    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {711        ensure!(712            <NftItemList<T>>::contains_key(collection_id, item_id),713            "Item does not exists"714        );715        let item = <NftItemList<T>>::get(collection_id, item_id);716        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;717718        // remove approve list719        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));720721        // update balance722        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())723            .checked_sub(1)724            .unwrap();725        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);726        <NftItemList<T>>::remove(collection_id, item_id);727728        Ok(())729    }730731    fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {732        ensure!(733            <FungibleItemList<T>>::contains_key(collection_id, item_id),734            "Item does not exists"735        );736        let item = <FungibleItemList<T>>::get(collection_id, item_id);737        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;738739        // remove approve list740        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));741742        // update balance743        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())744            .checked_sub(item.value as u64)745            .unwrap();746        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);747748        <FungibleItemList<T>>::remove(collection_id, item_id);749750        Ok(())751    }752753    fn collection_exists(collection_id: u64) -> DispatchResult {754        ensure!(755            <Collection<T>>::contains_key(collection_id),756            "This collection does not exist"757        );758        Ok(())759    }760761    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {762        Self::collection_exists(collection_id)?;763764        let target_collection = <Collection<T>>::get(collection_id);765        ensure!(766            subject == target_collection.owner,767            "You do not own this collection"768        );769770        Ok(())771    }772773    fn check_owner_or_admin_permissions(774        collection_id: u64,775        subject: T::AccountId,776    ) -> DispatchResult {777        Self::collection_exists(collection_id)?;778779        let target_collection = <Collection<T>>::get(collection_id);780        let is_owner = subject == target_collection.owner;781782        let no_perm_mes = "You do not have permissions to modify this collection";783        let exists = <AdminList<T>>::contains_key(collection_id);784785        if !is_owner {786            ensure!(exists, no_perm_mes);787            ensure!(788                <AdminList<T>>::get(collection_id).contains(&subject),789                no_perm_mes790            );791        }792        Ok(())793    }794795    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {796        let target_collection = <Collection<T>>::get(collection_id);797798        match target_collection.mode {799            CollectionMode::NFT(_) => {800                <NftItemList<T>>::get(collection_id, item_id).owner == subject801            }802            CollectionMode::Fungible(_) => {803                <FungibleItemList<T>>::get(collection_id, item_id).owner == subject804            }805            CollectionMode::ReFungible(_, _) => {806                <ReFungibleItemList<T>>::get(collection_id, item_id)807                    .owner808                    .iter()809                    .any(|i| i.owner == subject)810            }811            CollectionMode::Invalid => false,812        }813    }814815    fn transfer_fungible(816        collection_id: u64,817        item_id: u64,818        value: u64,819        owner: T::AccountId,820        new_owner: T::AccountId,821    ) -> DispatchResult {822        let full_item = <FungibleItemList<T>>::get(collection_id, item_id);823        let amount = full_item.value;824825        ensure!(amount >= value.into(), "Item balance not enouth");826827        // update balance828        let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())829            .checked_sub(value)830            .unwrap();831        <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);832833        let mut new_owner_account_id = 0;834        let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());835        if new_owner_items.len() > 0 {836            new_owner_account_id = new_owner_items[0];837        }838839        let val64 = value.into();840841        // transfer842        if amount == val64 && new_owner_account_id == 0 {843            // change owner844            // new owner do not have account845            let mut new_full_item = full_item.clone();846            new_full_item.owner = new_owner.clone();847            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);848849            // update balance850            let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())851                .checked_add(value)852                .unwrap();853            <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);854855            // update index collection856            Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;857        } else {858            let mut new_full_item = full_item.clone();859            new_full_item.value -= val64;860861            // separate amount862            if new_owner_account_id > 0 {863                // new owner has account864                let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);865                item.value += val64;866867                // update balance868                let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())869                    .checked_add(value)870                    .unwrap();871                <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);872873                <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);874            } else {875                // new owner do not have account876                let item = FungibleItemType {877                    collection: collection_id,878                    owner: new_owner.clone(),879                    value: val64,880                };881882                Self::add_fungible_item(item)?;883            }884885            if amount == val64 {886                Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;887888                // remove approve list889                <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));890                <FungibleItemList<T>>::remove(collection_id, item_id);891            }892893            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);894        }895896        Ok(())897    }898899    fn transfer_refungible(900        collection_id: u64,901        item_id: u64,902        value: u64,903        owner: T::AccountId,904        new_owner: T::AccountId,905    ) -> DispatchResult {906        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);907        let item = full_item908            .owner909            .iter()910            .filter(|i| i.owner == owner)911            .next()912            .unwrap();913        let amount = item.fraction;914915        ensure!(amount >= value.into(), "Item balance not enouth");916917        // update balance918        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())919            .checked_sub(value)920            .unwrap();921        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);922923        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())924            .checked_add(value)925            .unwrap();926        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);927928        let old_owner = item.owner.clone();929        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);930        let val64 = value.into();931932        // transfer933        if amount == val64 && !new_owner_has_account {934            // change owner935            // new owner do not have account936            let mut new_full_item = full_item.clone();937            new_full_item938                .owner939                .iter_mut()940                .find(|i| i.owner == owner)941                .unwrap()942                .owner = new_owner.clone();943            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);944945            // update index collection946            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;947        } else {948            let mut new_full_item = full_item.clone();949            new_full_item950                .owner951                .iter_mut()952                .find(|i| i.owner == owner)953                .unwrap()954                .fraction -= val64;955956            // separate amount957            if new_owner_has_account {958                // new owner has account959                new_full_item960                    .owner961                    .iter_mut()962                    .find(|i| i.owner == new_owner)963                    .unwrap()964                    .fraction += val64;965            } else {966                // new owner do not have account967                new_full_item.owner.push(Ownership {968                    owner: new_owner.clone(),969                    fraction: val64,970                });971                Self::add_token_index(collection_id, item_id, new_owner.clone())?;972            }973974            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);975        }976977        Ok(())978    }979980    fn transfer_nft(981        collection_id: u64,982        item_id: u64,983        sender: T::AccountId,984        new_owner: T::AccountId,985    ) -> DispatchResult {986        let mut item = <NftItemList<T>>::get(collection_id, item_id);987988        ensure!(989            sender == item.owner,990            "sender parameter and item owner must be equal"991        );992993        // update balance994        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())995            .checked_sub(1)996            .unwrap();997        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);998999        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1000            .checked_add(1)1001            .unwrap();1002        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10031004        // change owner1005        let old_owner = item.owner.clone();1006        item.owner = new_owner.clone();1007        <NftItemList<T>>::insert(collection_id, item_id, item);10081009        // update index collection1010        Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;10111012        // reset approved list1013        <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1014        Ok(())1015    }10161017    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1018        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1019        if list_exists {1020            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1021            let item_contains = list.contains(&item_index.clone());10221023            if !item_contains {1024                list.push(item_index.clone());1025            }10261027            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1028        } else {1029            let mut itm = Vec::new();1030            itm.push(item_index.clone());1031            <AddressTokens<T>>::insert(collection_id, owner, itm);1032        }10331034        Ok(())1035    }10361037    fn remove_token_index(1038        collection_id: u64,1039        item_index: u64,1040        owner: T::AccountId,1041    ) -> DispatchResult {1042        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1043        if list_exists {1044            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1045            let item_contains = list.contains(&item_index.clone());10461047            if item_contains {1048                list.retain(|&item| item != item_index);1049                <AddressTokens<T>>::insert(collection_id, owner, list);1050            }1051        }10521053        Ok(())1054    }10551056    fn move_token_index(1057        collection_id: u64,1058        item_index: u64,1059        old_owner: T::AccountId,1060        new_owner: T::AccountId,1061    ) -> DispatchResult {1062        Self::remove_token_index(collection_id, item_index, old_owner)?;1063        Self::add_token_index(collection_id, item_index, new_owner)?;10641065        Ok(())1066    }1067}10681069////////////////////////////////////////////////////////////////////////////////////////////////////1070// Economic models10711072/// Fee multiplier.1073pub type Multiplier = FixedU128;10741075type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1076    <T as system::Trait>::AccountId,1077>>::Balance;1078type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1079    <T as system::Trait>::AccountId,1080>>::NegativeImbalance;10811082/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1083/// in the queue.1084#[derive(Encode, Decode, Clone, Eq, PartialEq)]1085pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1086    #[codec(compact)] BalanceOf<T>,1087);10881089impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1090    for ChargeTransactionPayment<T>1091{1092    #[cfg(feature = "std")]1093    fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1094        write!(f, "ChargeTransactionPayment<{:?}>", self.0)1095    }1096    #[cfg(not(feature = "std"))]1097    fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1098        Ok(())1099    }1100}11011102impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1103where1104    T::Call:1105        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1106    BalanceOf<T>: Send + Sync + FixedPointOperand,1107{1108    /// utility constructor. Used only in client/factory code.1109    pub fn from(fee: BalanceOf<T>) -> Self {1110        Self(fee)1111    }11121113    pub fn traditional_fee(1114        len: usize,1115        info: &DispatchInfoOf<T::Call>,1116        tip: BalanceOf<T>,1117    ) -> BalanceOf<T>1118    where1119        T::Call: Dispatchable<Info = DispatchInfo>,1120    {1121        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1122    }11231124    fn withdraw_fee(1125        &self,1126        who: &T::AccountId,1127        call: &T::Call,1128        info: &DispatchInfoOf<T::Call>,1129        len: usize,1130    ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1131        let tip = self.0;11321133        // Set fee based on call type. Creating collection costs 1 Unique.1134        // All other transactions have traditional fees so far1135        let fee = match call.is_sub_type() {1136            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1137            _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1138                                                        // _ => <BalanceOf<T>>::from(100)1139        };11401141        // Determine who is paying transaction fee based on ecnomic model1142        // Parse call to extract collection ID and access collection sponsor1143        let sponsor: T::AccountId = match call.is_sub_type() {1144            Some(Call::create_item(collection_id, _properties, _owner)) => {1145                <Collection<T>>::get(collection_id).sponsor1146            }1147            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1148                <Collection<T>>::get(collection_id).sponsor1149            }11501151            _ => T::AccountId::default(),1152        };11531154        let mut who_pays_fee: T::AccountId = sponsor.clone();1155        if sponsor == T::AccountId::default() {1156            who_pays_fee = who.clone();1157        }11581159        // Only mess with balances if fee is not zero.1160        if fee.is_zero() {1161            return Ok((fee, None));1162        }11631164        match <T as transaction_payment::Trait>::Currency::withdraw(1165            &who_pays_fee,1166            fee,1167            if tip.is_zero() {1168                WithdrawReason::TransactionPayment.into()1169            } else {1170                WithdrawReason::TransactionPayment | WithdrawReason::Tip1171            },1172            ExistenceRequirement::KeepAlive,1173        ) {1174            Ok(imbalance) => Ok((fee, Some(imbalance))),1175            Err(_) => Err(InvalidTransaction::Payment.into()),1176        }1177    }1178}11791180impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1181    for ChargeTransactionPayment<T>1182where1183    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1184    T::Call:1185        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1186{1187    const IDENTIFIER: &'static str = "ChargeTransactionPayment";1188    type AccountId = T::AccountId;1189    type Call = T::Call;1190    type AdditionalSigned = ();1191    type Pre = (1192        BalanceOf<T>,1193        Self::AccountId,1194        Option<NegativeImbalanceOf<T>>,1195        BalanceOf<T>,1196    );1197    fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1198        Ok(())1199    }12001201    fn validate(1202        &self,1203        who: &Self::AccountId,1204        call: &Self::Call,1205        info: &DispatchInfoOf<Self::Call>,1206        len: usize,1207    ) -> TransactionValidity {1208        let (fee, _) = self.withdraw_fee(who, call, info, len)?;12091210        let mut r = ValidTransaction::default();1211        // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1212        // will be a bit more than setting the priority to tip. For now, this is enough.1213        r.priority = fee.saturated_into::<TransactionPriority>();1214        Ok(r)1215    }12161217    fn pre_dispatch(1218        self,1219        who: &Self::AccountId,1220        call: &Self::Call,1221        info: &DispatchInfoOf<Self::Call>,1222        len: usize,1223    ) -> Result<Self::Pre, TransactionValidityError> {1224        let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1225        Ok((self.0, who.clone(), imbalance, fee))1226    }12271228    fn post_dispatch(1229        pre: Self::Pre,1230        info: &DispatchInfoOf<Self::Call>,1231        post_info: &PostDispatchInfoOf<Self::Call>,1232        len: usize,1233        _result: &DispatchResult,1234    ) -> Result<(), TransactionValidityError> {1235        let (tip, who, imbalance, fee) = pre;1236        if let Some(payed) = imbalance {1237            let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1238                len as u32, info, post_info, tip,1239            );1240            let refund = fee.saturating_sub(actual_fee);1241            let actual_payment =1242                match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1243                    &who, refund,1244                ) {1245                    Ok(refund_imbalance) => {1246                        // The refund cannot be larger than the up front payed max weight.1247                        // `PostDispatchInfo::calc_unspent` guards against such a case.1248                        match payed.offset(refund_imbalance) {1249                            Ok(actual_payment) => actual_payment,1250                            Err(_) => return Err(InvalidTransaction::Payment.into()),1251                        }1252                    }1253                    // We do not recreate the account using the refund. The up front payment1254                    // is gone in that case.1255                    Err(_) => payed,1256                };1257            let imbalances = actual_payment.split(tip);1258            <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1259                Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1260            );1261        }1262        Ok(())1263    }1264}
after · pallets/nft/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23#[cfg(feature = "std")]4pub use serde::*;56use codec::{Decode, Encode};7pub use frame_support::{8    construct_runtime, decl_event, decl_module, decl_storage,9    dispatch::DispatchResult,10    ensure, parameter_types,11    traits::{12        Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,13        Randomness, WithdrawReason,14    },15    weights::{16        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},17        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,18        WeightToFeePolynomial,19    },20    IsSubType, StorageValue,21};2223use frame_system::{self as system, ensure_signed};24use sp_runtime::sp_std::prelude::Vec;25use sp_runtime::{26    traits::{27        DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,28        SignedExtension, Zero,29    },30    transaction_validity::{31        InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,32        ValidTransaction,33    },34    FixedPointOperand, FixedU128,35};3637#[cfg(test)]38mod mock;3940#[cfg(test)]41mod tests;4243// Structs44// #region4546#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]47#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]48pub enum CollectionMode {49    Invalid,50    // custom data size51    NFT(u32),52    // decimal points53    Fungible(u32),54    // custom data size and decimal points55    ReFungible(u32, u32),56}5758impl Into<u8> for CollectionMode {59    fn into(self) -> u8 {60        match self {61            CollectionMode::Invalid => 0,62            CollectionMode::NFT(_) => 1,63            CollectionMode::Fungible(_) => 2,64            CollectionMode::ReFungible(_, _) => 3,65        }66    }67}6869#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]70#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]71pub enum AccessMode {72    Normal,73    WhiteList,74}75impl Default for AccessMode {76    fn default() -> Self {77        Self::Normal78    }79}8081impl Default for CollectionMode {82    fn default() -> Self {83        Self::Invalid84    }85}8687#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]88#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]89pub struct Ownership<AccountId> {90    pub owner: AccountId,91    pub fraction: u128,92}9394#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]95#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]96pub struct CollectionType<AccountId> {97    pub owner: AccountId,98    pub mode: CollectionMode,99    pub access: AccessMode,100    pub decimal_points: u32,101    pub name: Vec<u16>,        // 64 include null escape char102    pub description: Vec<u16>, // 256 include null escape char103    pub token_prefix: Vec<u8>, // 16 include null escape char104    pub custom_data_size: u32,105    pub mint_mode: bool,106    pub offchain_schema: Vec<u8>,107    pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender108    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship109}110111#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]112#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]113pub struct CollectionAdminsType<AccountId> {114    pub admin: AccountId,115    pub collection_id: u64,116}117118#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]119#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]120pub struct NftItemType<AccountId> {121    pub collection: u64,122    pub owner: AccountId,123    pub data: Vec<u8>,124}125126#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]127#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]128pub struct FungibleItemType<AccountId> {129    pub collection: u64,130    pub owner: AccountId,131    pub value: u128,132}133134#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]135#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]136pub struct ReFungibleItemType<AccountId> {137    pub collection: u64,138    pub owner: Vec<Ownership<AccountId>>,139    pub data: Vec<u8>,140}141142#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]143#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]144pub struct ApprovePermissions<AccountId> {145    pub approved: AccountId,146    pub amount: u64,147}148149#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]150#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]151pub struct VestingItem<AccountId, Moment> {152    pub sender: AccountId,153    pub recipient: AccountId,154    pub collection_id: u64,155    pub item_id: u64,156    pub amount: u64,157    pub vesting_date: Moment,158}159160pub trait Trait: system::Trait {161    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;162}163164// #endregion165166decl_storage! {167    trait Store for Module<T: Trait> as Nft {168169        // Private members170        NextCollectionID: u64;171        CreatedCollectionCount: u64;172        ChainVersion: u64;173        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;174175        pub Collection get(fn collection) config(): map hasher(identity) u64 => CollectionType<T::AccountId>;176        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;177        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;178179        /// Balance owner per collection map180        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;181182        /// second parameter: item id + owner account id183        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;184185        /// Item collections186        pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;187        pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;188        pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;189190        /// Index list191        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;192193        // Sponsorship194        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;195        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;196    }197    add_extra_genesis {198        build(|config: &GenesisConfig<T>| {199			// Modification of storage200            for (_num, _c) in &config.collection {201                <Module<T>>::init_collection(_c);202            }203204            for (_num, _q, _i) in &config.nft_item_id {205                <Module<T>>::init_nft_token(_i);206            }207208            for (_num, _q, _i) in &config.fungible_item_id {209                <Module<T>>::init_fungible_token(_i);210            }211212            for (_num, _q, _i) in &config.refungible_item_id {213                <Module<T>>::init_refungible_token(_i);214            }215		})216    }217}218219decl_event!(220    pub enum Event<T>221    where222        AccountId = <T as system::Trait>::AccountId,223    {224        Created(u64, u8, AccountId),225        ItemCreated(u64, u64),226        ItemDestroyed(u64, u64),227    }228);229230decl_module! {231    pub struct Module<T: Trait> for enum Call where origin: T::Origin {232233        fn deposit_event() = default;234235        fn on_initialize(now: T::BlockNumber) -> Weight {236237            if ChainVersion::get() < 2238            {239                let value = NextCollectionID::get();240                CreatedCollectionCount::put(value);241                ChainVersion::put(2);242            }243244            0245        }246247        // Create collection of NFT with given parameters248        //249        // @param customDataSz size of custom data in each collection item250        // returns collection ID251        #[weight = 0]252        pub fn create_collection(origin,253                                 collection_name: Vec<u16>,254                                 collection_description: Vec<u16>,255                                 token_prefix: Vec<u8>,256                                 mode: CollectionMode) -> DispatchResult {257258            // Anyone can create a collection259            let who = ensure_signed(origin)?;260            let custom_data_size = match mode {261                CollectionMode::NFT(size) => size,262                CollectionMode::ReFungible(size, _) => size,263                _ => 0264            };265266            let decimal_points = match mode {267                CollectionMode::Fungible(points) => points,268                CollectionMode::ReFungible(_, points) => points,269                _ => 0270            };271272            // check params273            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");274275            let mut name = collection_name.to_vec();276            name.push(0);277            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");278279            let mut description = collection_description.to_vec();280            description.push(0);281            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");282283            let mut prefix = token_prefix.to_vec();284            prefix.push(0);285            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");286287            // Generate next collection ID288            let next_id = CreatedCollectionCount::get()289                .checked_add(1)290                .expect("collection id error");291292            CreatedCollectionCount::put(next_id);293294            // Create new collection295            let new_collection = CollectionType {296                owner: who.clone(),297                name: name,298                mode: mode.clone(),299                mint_mode: false,300                access: AccessMode::Normal,301                description: description,302                decimal_points: decimal_points,303                token_prefix: prefix,304                offchain_schema: Vec::new(),305                custom_data_size: custom_data_size,306                sponsor: T::AccountId::default(),307                unconfirmed_sponsor: T::AccountId::default(),308            };309310            // Add new collection to map311            <Collection<T>>::insert(next_id, new_collection);312313            // call event314            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));315316            Ok(())317        }318319        #[weight = 0]320        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {321322            let sender = ensure_signed(origin)?;323            Self::check_owner_permissions(collection_id, sender)?;324325            // TODO Items remove326            <AddressTokens<T>>::remove_prefix(collection_id);327            <ApprovedList<T>>::remove_prefix(collection_id);328            <Balance<T>>::remove_prefix(collection_id);329            <ItemListIndex>::remove(collection_id);330            <AdminList<T>>::remove(collection_id);331            <Collection<T>>::remove(collection_id);332            <WhiteList<T>>::remove(collection_id);333334            Ok(())335        }336337        #[weight = 0]338        pub fn add_to_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{339340            let sender = ensure_signed(origin)?;341            Self::check_owner_or_admin_permissions(collection_id, sender)?;342343            let mut white_list_collection: Vec<T::AccountId>;344            if <WhiteList<T>>::contains_key(collection_id) {345                white_list_collection = <WhiteList<T>>::get(collection_id);346                if !white_list_collection.contains(&address.clone())347                {348                    white_list_collection.push(address.clone());349                }350            }351            else {352                white_list_collection = Vec::new();353                white_list_collection.push(address.clone());354            }355356            <WhiteList<T>>::insert(collection_id, white_list_collection);357            Ok(())358        }359360        #[weight = 0]361        pub fn remove_from_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{362363            let sender = ensure_signed(origin)?;364            Self::check_owner_or_admin_permissions(collection_id, sender)?;365366            if <WhiteList<T>>::contains_key(collection_id) {367                let mut white_list_collection = <WhiteList<T>>::get(collection_id);368                if white_list_collection.contains(&address.clone())369                {370                    white_list_collection.retain(|i| *i != address.clone());371                    <WhiteList<T>>::insert(collection_id, white_list_collection);372                }373            }374375            Ok(())376        }377378        #[weight = 0]379        pub fn set_public_access_mode(origin, collection_id: u64, mode: AccessMode) -> DispatchResult380        {381            let sender = ensure_signed(origin)?;382383            Self::check_owner_permissions(collection_id, sender)?;384            let mut target_collection = <Collection<T>>::get(collection_id);385            target_collection.access = mode;386            <Collection<T>>::insert(collection_id, target_collection);387388            Ok(())389        }390391        #[weight = 0]392        pub fn set_mint_permission(origin, collection_id: u64, mint_permission: bool) -> DispatchResult393        {394            let sender = ensure_signed(origin)?;395396            Self::check_owner_permissions(collection_id, sender)?;397            let mut target_collection = <Collection<T>>::get(collection_id);398            target_collection.mint_mode = mint_permission;399            <Collection<T>>::insert(collection_id, target_collection);400401            Ok(())402        }403404        #[weight = 0]405        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {406407            let sender = ensure_signed(origin)?;408            Self::check_owner_permissions(collection_id, sender)?;409            let mut target_collection = <Collection<T>>::get(collection_id);410            target_collection.owner = new_owner;411            <Collection<T>>::insert(collection_id, target_collection);412413            Ok(())414        }415416        #[weight = 0]417        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {418419            let sender = ensure_signed(origin)?;420            Self::check_owner_or_admin_permissions(collection_id, sender)?;421            let mut admin_arr: Vec<T::AccountId> = Vec::new();422423            if <AdminList<T>>::contains_key(collection_id)424            {425                admin_arr = <AdminList<T>>::get(collection_id);426                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");427            }428429            admin_arr.push(new_admin_id);430            <AdminList<T>>::insert(collection_id, admin_arr);431432            Ok(())433        }434435        #[weight = 0]436        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {437438            let sender = ensure_signed(origin)?;439            Self::check_owner_or_admin_permissions(collection_id, sender)?;440441            if <AdminList<T>>::contains_key(collection_id)442            {443                let mut admin_arr = <AdminList<T>>::get(collection_id);444                admin_arr.retain(|i| *i != account_id);445                <AdminList<T>>::insert(collection_id, admin_arr);446            }447448            Ok(())449        }450451        #[weight = 0]452        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {453454            let sender = ensure_signed(origin)?;455            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");456457            let mut target_collection = <Collection<T>>::get(collection_id);458            ensure!(sender == target_collection.owner, "You do not own this collection");459460            target_collection.unconfirmed_sponsor = new_sponsor;461            <Collection<T>>::insert(collection_id, target_collection);462463            Ok(())464        }465466        #[weight = 0]467        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {468469            let sender = ensure_signed(origin)?;470            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");471472            let mut target_collection = <Collection<T>>::get(collection_id);473            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");474475            target_collection.sponsor = target_collection.unconfirmed_sponsor;476            target_collection.unconfirmed_sponsor = T::AccountId::default();477            <Collection<T>>::insert(collection_id, target_collection);478479            Ok(())480        }481482        #[weight = 0]483        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {484485            let sender = ensure_signed(origin)?;486            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");487488            let mut target_collection = <Collection<T>>::get(collection_id);489            ensure!(sender == target_collection.owner, "You do not own this collection");490491            target_collection.sponsor = T::AccountId::default();492            <Collection<T>>::insert(collection_id, target_collection);493494            Ok(())495        }496497        #[weight = 0]498        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {499500            let sender = ensure_signed(origin)?;501            Self::collection_exists(collection_id)?;502            let target_collection = <Collection<T>>::get(collection_id);503504            if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {505                ensure!(target_collection.mint_mode == true, "Public minting is not allowed for this collection");506                Self::check_white_list(collection_id, &owner)?;507                Self::check_white_list(collection_id, &sender)?;508            }509510            match target_collection.mode511            {512                CollectionMode::NFT(_) => {513514                    // check size515                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");516517                    // Create nft item518                    let item = NftItemType {519                        collection: collection_id,520                        owner: owner,521                        data: properties.clone(),522                    };523524                    Self::add_nft_item(item)?;525526                },527                CollectionMode::Fungible(_) => {528529                    // check size530                    ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");531532                    let item = FungibleItemType {533                        collection: collection_id,534                        owner: owner,535                        value: (10 as u128).pow(target_collection.decimal_points)536                    };537538                    Self::add_fungible_item(item)?;539                },540                CollectionMode::ReFungible(_, _) => {541542                    // check size543                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");544545                    let mut owner_list = Vec::new();546                    let value = (10 as u128).pow(target_collection.decimal_points);547                    owner_list.push(Ownership {owner: owner.clone(), fraction: value});548549                    let item = ReFungibleItemType {550                        collection: collection_id,551                        owner: owner_list,552                        data: properties.clone()553                    };554555                    Self::add_refungible_item(item)?;556                },557                _ => { ensure!(1 == 0,"just error"); }558559            };560561            // call event562            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));563564            Ok(())565        }566567        #[weight = 0]568        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {569570            let sender = ensure_signed(origin)?;571            Self::collection_exists(collection_id)?;572573            // Transfer permissions check574            let target_collection = <Collection<T>>::get(collection_id);575            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 576                Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 577                "Only item owner, collection owner and admins can modify item");578579            if target_collection.access == AccessMode::WhiteList {580                Self::check_white_list(collection_id, &sender)?;581            }582583            match target_collection.mode584            {585                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,586                CollectionMode::Fungible(_)  => Self::burn_fungible_item(collection_id, item_id)?,587                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,588                _ => ()589            };590591            // call event592            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));593594            Ok(())595        }596597        #[weight = 0]598        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {599600            let sender = ensure_signed(origin)?;601602            // Transfer permissions check603            let target_collection = <Collection<T>>::get(collection_id);604            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 605                Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 606                "Only item owner, collection owner and admins can modify item");607608            if target_collection.access == AccessMode::WhiteList {609                Self::check_white_list(collection_id, &sender)?;610                Self::check_white_list(collection_id, &recipient)?;611            }612613            match target_collection.mode614            {615                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,616                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,617                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,618                _ => ()619            };620621            Ok(())622        }623624        #[weight = 0]625        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {626627            let sender = ensure_signed(origin)?;628629            // Transfer permissions check630            let target_collection = <Collection<T>>::get(collection_id);631            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 632                Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 633                "Only item owner, collection owner and admins can approve");634635            if target_collection.access == AccessMode::WhiteList {636                Self::check_white_list(collection_id, &sender)?;637                Self::check_white_list(collection_id, &approved)?;638            }639640            // amount param stub641            let amount = 100000000;642643            let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));644            if list_exists {645646                let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));647                let item_contains = list.iter().any(|i| i.approved == approved);648649                if !item_contains {650                    list.push(ApprovePermissions { approved: approved.clone(), amount: amount });651                    <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);652                }653            } else {654655                let mut list = Vec::new();656                list.push(ApprovePermissions { approved: approved.clone(), amount: amount });657                <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);658            }659660            Ok(())661        }662663        #[weight = 0]664        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {665666            let sender = ensure_signed(origin)?;667            let mut appoved_transfer = false;668669            // Check approve670            if <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone())) {671                let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));672                let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());673                appoved_transfer = opt_item.is_some();674                ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");675            }676677            // Transfer permissions check678            let target_collection = <Collection<T>>::get(collection_id);679            ensure!(appoved_transfer || Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 680                "Only item owner, collection owner and admins can modify items");681682            if target_collection.access == AccessMode::WhiteList {683                Self::check_white_list(collection_id, &sender)?;684                Self::check_white_list(collection_id, &recipient)?;685            }686687            // remove approve688            let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))689                .into_iter().filter(|i| i.approved != sender.clone()).collect();690            <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);691692693            match target_collection.mode694            {695                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,696                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,697                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,698                _ => ()699            };700701            Ok(())702        }703704        #[weight = 0]705        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {706707            // let no_perm_mes = "You do not have permissions to modify this collection";708            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);709            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));710            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);711712            // // on_nft_received  call713714            // Self::transfer(origin, collection_id, item_id, new_owner)?;715716            Ok(())717        }718719        #[weight = 0]720        pub fn set_offchain_schema(721            origin,722            collection_id: u64,723            schema: Vec<u8>724        ) -> DispatchResult {725            let sender = ensure_signed(origin)?;726            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;727728            let mut target_collection = <Collection<T>>::get(collection_id);729            target_collection.offchain_schema = schema;730            <Collection<T>>::insert(collection_id, target_collection);731732            Ok(())733        }734    }735}736737impl<T: Trait> Module<T> {738    fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {739        let current_index = <ItemListIndex>::get(item.collection)740            .checked_add(1)741            .expect("Item list index id error");742        let itemcopy = item.clone();743        let owner = item.owner.clone();744        let value = item.value as u64;745746        Self::add_token_index(item.collection, current_index, owner.clone())?;747748        <ItemListIndex>::insert(item.collection, current_index);749        <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);750751        // Update balance752        let new_balance = <Balance<T>>::get(item.collection, owner.clone())753            .checked_add(value)754            .unwrap();755        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);756757        Ok(())758    }759760    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {761        let current_index = <ItemListIndex>::get(item.collection)762            .checked_add(1)763            .expect("Item list index id error");764        let itemcopy = item.clone();765766        let value = item.owner.first().unwrap().fraction as u64;767        let owner = item.owner.first().unwrap().owner.clone();768769        Self::add_token_index(item.collection, current_index, owner.clone())?;770771        <ItemListIndex>::insert(item.collection, current_index);772        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);773774        // Update balance775        let new_balance = <Balance<T>>::get(item.collection, owner.clone())776            .checked_add(value)777            .unwrap();778        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);779780        Ok(())781    }782783    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {784        let current_index = <ItemListIndex>::get(item.collection)785            .checked_add(1)786            .expect("Item list index id error");787788        let item_owner = item.owner.clone();789        let collection_id = item.collection.clone();790        Self::add_token_index(collection_id, current_index, item.owner.clone())?;791792        <ItemListIndex>::insert(collection_id, current_index);793        <NftItemList<T>>::insert(collection_id, current_index, item);794795        // Update balance796        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())797            .checked_add(1)798            .unwrap();799        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);800801        Ok(())802    }803804    fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {805        ensure!(806            <ReFungibleItemList<T>>::contains_key(collection_id, item_id),807            "Item does not exists"808        );809        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);810        let item = collection811            .owner812            .iter()813            .filter(|&i| i.owner == owner)814            .next()815            .unwrap();816        Self::remove_token_index(collection_id, item_id, owner.clone())?;817818        // remove approve list819        <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));820821        // update balance822        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())823            .checked_sub(item.fraction as u64)824            .unwrap();825        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);826827        <ReFungibleItemList<T>>::remove(collection_id, item_id);828829        Ok(())830    }831832    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {833        ensure!(834            <NftItemList<T>>::contains_key(collection_id, item_id),835            "Item does not exists"836        );837        let item = <NftItemList<T>>::get(collection_id, item_id);838        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;839840        // remove approve list841        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));842843        // update balance844        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())845            .checked_sub(1)846            .unwrap();847        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);848        <NftItemList<T>>::remove(collection_id, item_id);849850        Ok(())851    }852853    fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {854        ensure!(855            <FungibleItemList<T>>::contains_key(collection_id, item_id),856            "Item does not exists"857        );858        let item = <FungibleItemList<T>>::get(collection_id, item_id);859        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;860861        // remove approve list862        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));863864        // update balance865        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())866            .checked_sub(item.value as u64)867            .unwrap();868        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);869870        <FungibleItemList<T>>::remove(collection_id, item_id);871872        Ok(())873    }874875    fn collection_exists(collection_id: u64) -> DispatchResult {876        ensure!(877            <Collection<T>>::contains_key(collection_id),878            "This collection does not exist"879        );880        Ok(())881    }882883    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {884        Self::collection_exists(collection_id)?;885886        let target_collection = <Collection<T>>::get(collection_id);887        ensure!(888            subject == target_collection.owner,889            "You do not own this collection"890        );891892        Ok(())893    }894895    fn is_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> bool {896897        let target_collection = <Collection<T>>::get(collection_id);898        let mut result: bool = subject == target_collection.owner;899        let exists = <AdminList<T>>::contains_key(collection_id);900901        if !result & exists {902            if <AdminList<T>>::get(collection_id).contains(&subject) {903                result = true904            }905        }906907        result908    }909910    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {911        912        Self::collection_exists(collection_id)?;913        let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());914915        ensure!(result, "You do not have permissions to modify this collection");916        Ok(())917    }918919    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {920        let target_collection = <Collection<T>>::get(collection_id);921922        match target_collection.mode {923            CollectionMode::NFT(_) => {924                <NftItemList<T>>::get(collection_id, item_id).owner == subject925            }926            CollectionMode::Fungible(_) => {927                <FungibleItemList<T>>::get(collection_id, item_id).owner == subject928            }929            CollectionMode::ReFungible(_, _) => {930                <ReFungibleItemList<T>>::get(collection_id, item_id)931                    .owner932                    .iter()933                    .any(|i| i.owner == subject)934            }935            CollectionMode::Invalid => false,936        }937    }938939    fn check_white_list(collection_id: u64, address: &T::AccountId) -> DispatchResult {940941        let mes = "Address is not in white list";942        ensure!(<WhiteList<T>>::contains_key(collection_id), mes);943        let wl = <WhiteList<T>>::get(collection_id);944        ensure!(wl.contains(address), mes);945946        Ok(())947    }948949    fn transfer_fungible(950        collection_id: u64,951        item_id: u64,952        value: u64,953        owner: T::AccountId,954        new_owner: T::AccountId,955    ) -> DispatchResult {956957        ensure!(958            <FungibleItemList<T>>::contains_key(collection_id, item_id),959            "Item not exists"960        );961962        let full_item = <FungibleItemList<T>>::get(collection_id, item_id);963        let amount = full_item.value;964965        ensure!(amount >= value.into(), "Item balance not enouth");966967        // update balance968        let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())969            .checked_sub(value)970            .unwrap();971        <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);972973        let mut new_owner_account_id = 0;974        let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());975        if new_owner_items.len() > 0 {976            new_owner_account_id = new_owner_items[0];977        }978979        let val64 = value.into();980981        // transfer982        if amount == val64 && new_owner_account_id == 0 {983            // change owner984            // new owner do not have account985            let mut new_full_item = full_item.clone();986            new_full_item.owner = new_owner.clone();987            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);988989            // update balance990            let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())991                .checked_add(value)992                .unwrap();993            <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);994995            // update index collection996            Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;997        } else {998            let mut new_full_item = full_item.clone();999            new_full_item.value -= val64;10001001            // separate amount1002            if new_owner_account_id > 0 {1003                // new owner has account1004                let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);1005                item.value += val64;10061007                // update balance1008                let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1009                    .checked_add(value)1010                    .unwrap();1011                <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10121013                <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);1014            } else {1015                // new owner do not have account1016                let item = FungibleItemType {1017                    collection: collection_id,1018                    owner: new_owner.clone(),1019                    value: val64,1020                };10211022                Self::add_fungible_item(item)?;1023            }10241025            if amount == val64 {1026                Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;10271028                // remove approve list1029                <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));1030                <FungibleItemList<T>>::remove(collection_id, item_id);1031            }10321033            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1034        }10351036        Ok(())1037    }10381039    fn transfer_refungible(1040        collection_id: u64,1041        item_id: u64,1042        value: u64,1043        owner: T::AccountId,1044        new_owner: T::AccountId,1045    ) -> DispatchResult {10461047        ensure!(1048            <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1049            "Item not exists"1050        );10511052        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);1053        let item = full_item1054            .owner1055            .iter()1056            .filter(|i| i.owner == owner)1057            .next()1058            .unwrap();1059        let amount = item.fraction;10601061        ensure!(amount >= value.into(), "Item balance not enouth");10621063        // update balance1064        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1065            .checked_sub(value)1066            .unwrap();1067        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);10681069        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1070            .checked_add(value)1071            .unwrap();1072        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10731074        let old_owner = item.owner.clone();1075        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);1076        let val64 = value.into();10771078        // transfer1079        if amount == val64 && !new_owner_has_account {1080            // change owner1081            // new owner do not have account1082            let mut new_full_item = full_item.clone();1083            new_full_item1084                .owner1085                .iter_mut()1086                .find(|i| i.owner == owner)1087                .unwrap()1088                .owner = new_owner.clone();1089            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);10901091            // update index collection1092            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;1093        } else {1094            let mut new_full_item = full_item.clone();1095            new_full_item1096                .owner1097                .iter_mut()1098                .find(|i| i.owner == owner)1099                .unwrap()1100                .fraction -= val64;11011102            // separate amount1103            if new_owner_has_account {1104                // new owner has account1105                new_full_item1106                    .owner1107                    .iter_mut()1108                    .find(|i| i.owner == new_owner)1109                    .unwrap()1110                    .fraction += val64;1111            } else {1112                // new owner do not have account1113                new_full_item.owner.push(Ownership {1114                    owner: new_owner.clone(),1115                    fraction: val64,1116                });1117                Self::add_token_index(collection_id, item_id, new_owner.clone())?;1118            }11191120            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1121        }11221123        Ok(())1124    }11251126    fn transfer_nft(1127        collection_id: u64,1128        item_id: u64,1129        sender: T::AccountId,1130        new_owner: T::AccountId,1131    ) -> DispatchResult {1132    1133        ensure!(1134            <NftItemList<T>>::contains_key(collection_id, item_id),1135            "Item not exists"1136        );11371138        let mut item = <NftItemList<T>>::get(collection_id, item_id);11391140        ensure!(1141            sender == item.owner,1142            "sender parameter and item owner must be equal"1143        );11441145        // update balance1146        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1147            .checked_sub(1)1148            .unwrap();1149        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);11501151        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1152            .checked_add(1)1153            .unwrap();1154        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);11551156        // change owner1157        let old_owner = item.owner.clone();1158        item.owner = new_owner.clone();1159        <NftItemList<T>>::insert(collection_id, item_id, item);11601161        // update index collection1162        Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;11631164        // reset approved list1165        <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1166        Ok(())1167    }11681169    fn init_collection(item: &CollectionType<T::AccountId>){11701171                // check params1172                assert!(item.decimal_points <= 4, "decimal_points parameter must be lower than 4");1173                assert!(item.name.len() <= 64, "Collection name can not be longer than 63 char");1174                assert!(item.name.len() <= 256, "Collection description can not be longer than 255 char");1175                assert!(item.token_prefix.len() <= 16, "Token prefix can not be longer than 15 char");1176    1177                // Generate next collection ID1178                let next_id = CreatedCollectionCount::get()1179                    .checked_add(1)1180                    .expect("collection id error");1181    1182                CreatedCollectionCount::put(next_id);  1183    }11841185    fn init_nft_token(item: &NftItemType<T::AccountId>){11861187        let current_index = <ItemListIndex>::get(item.collection)1188            .checked_add(1)1189            .expect("Item list index id error");11901191        let item_owner = item.owner.clone();1192        let collection_id = item.collection.clone();1193        Self::add_token_index(collection_id, current_index, item.owner.clone()).unwrap();11941195        <ItemListIndex>::insert(collection_id, current_index);11961197        // Update balance1198        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())1199            .checked_add(1)1200            .unwrap();1201        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);1202    }12031204    fn init_fungible_token(item: &FungibleItemType<T::AccountId>){12051206        let current_index = <ItemListIndex>::get(item.collection)1207            .checked_add(1)1208            .expect("Item list index id error");1209        let owner = item.owner.clone();1210        let value = item.value as u64;12111212        Self::add_token_index(item.collection, current_index, owner.clone()).unwrap();12131214        <ItemListIndex>::insert(item.collection, current_index);12151216        // Update balance1217        let new_balance = <Balance<T>>::get(item.collection, owner.clone())1218            .checked_add(value)1219            .unwrap();1220        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);1221    }12221223    fn init_refungible_token(item: &ReFungibleItemType<T::AccountId>){12241225        let current_index = <ItemListIndex>::get(item.collection)1226            .checked_add(1)1227            .expect("Item list index id error");12281229        let value = item.owner.first().unwrap().fraction as u64;1230        let owner = item.owner.first().unwrap().owner.clone();12311232        Self::add_token_index(item.collection, current_index, owner.clone()).unwrap();12331234        <ItemListIndex>::insert(item.collection, current_index);12351236        // Update balance1237        let new_balance = <Balance<T>>::get(item.collection, owner.clone())1238            .checked_add(value)1239            .unwrap();1240        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);1241    }12421243    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1244        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1245        if list_exists {1246            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1247            let item_contains = list.contains(&item_index.clone());12481249            if !item_contains {1250                list.push(item_index.clone());1251            }12521253            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1254        } else {1255            let mut itm = Vec::new();1256            itm.push(item_index.clone());1257            <AddressTokens<T>>::insert(collection_id, owner, itm);1258        }12591260        Ok(())1261    }12621263    fn remove_token_index(1264        collection_id: u64,1265        item_index: u64,1266        owner: T::AccountId,1267    ) -> DispatchResult {1268        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1269        if list_exists {1270            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1271            let item_contains = list.contains(&item_index.clone());12721273            if item_contains {1274                list.retain(|&item| item != item_index);1275                <AddressTokens<T>>::insert(collection_id, owner, list);1276            }1277        }12781279        Ok(())1280    }12811282    fn move_token_index(1283        collection_id: u64,1284        item_index: u64,1285        old_owner: T::AccountId,1286        new_owner: T::AccountId,1287    ) -> DispatchResult {1288        Self::remove_token_index(collection_id, item_index, old_owner)?;1289        Self::add_token_index(collection_id, item_index, new_owner)?;12901291        Ok(())1292    }1293}12941295////////////////////////////////////////////////////////////////////////////////////////////////////1296// Economic models1297// #region12981299/// Fee multiplier.1300pub type Multiplier = FixedU128;13011302type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1303    <T as system::Trait>::AccountId,1304>>::Balance;1305type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1306    <T as system::Trait>::AccountId,1307>>::NegativeImbalance;13081309/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1310/// in the queue.1311#[derive(Encode, Decode, Clone, Eq, PartialEq)]1312pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1313    #[codec(compact)] BalanceOf<T>,1314);13151316impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1317    for ChargeTransactionPayment<T>1318{1319    #[cfg(feature = "std")]1320    fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1321        write!(f, "ChargeTransactionPayment<{:?}>", self.0)1322    }1323    #[cfg(not(feature = "std"))]1324    fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1325        Ok(())1326    }1327}13281329impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1330where1331    T::Call:1332        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1333    BalanceOf<T>: Send + Sync + FixedPointOperand,1334{1335    /// utility constructor. Used only in client/factory code.1336    pub fn from(fee: BalanceOf<T>) -> Self {1337        Self(fee)1338    }13391340    pub fn traditional_fee(1341        len: usize,1342        info: &DispatchInfoOf<T::Call>,1343        tip: BalanceOf<T>,1344    ) -> BalanceOf<T>1345    where1346        T::Call: Dispatchable<Info = DispatchInfo>,1347    {1348        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1349    }13501351    fn withdraw_fee(1352        &self,1353        who: &T::AccountId,1354        call: &T::Call,1355        info: &DispatchInfoOf<T::Call>,1356        len: usize,1357    ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1358        let tip = self.0;13591360        // Set fee based on call type. Creating collection costs 1 Unique.1361        // All other transactions have traditional fees so far1362        let fee = match call.is_sub_type() {1363            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1364            _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1365                                                        // _ => <BalanceOf<T>>::from(100)1366        };13671368        // Determine who is paying transaction fee based on ecnomic model1369        // Parse call to extract collection ID and access collection sponsor1370        let sponsor: T::AccountId = match call.is_sub_type() {1371            Some(Call::create_item(collection_id, _properties, _owner)) => {1372                <Collection<T>>::get(collection_id).sponsor1373            }1374            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1375                <Collection<T>>::get(collection_id).sponsor1376            }13771378            _ => T::AccountId::default(),1379        };13801381        let mut who_pays_fee: T::AccountId = sponsor.clone();1382        if sponsor == T::AccountId::default() {1383            who_pays_fee = who.clone();1384        }13851386        // Only mess with balances if fee is not zero.1387        if fee.is_zero() {1388            return Ok((fee, None));1389        }13901391        match <T as transaction_payment::Trait>::Currency::withdraw(1392            &who_pays_fee,1393            fee,1394            if tip.is_zero() {1395                WithdrawReason::TransactionPayment.into()1396            } else {1397                WithdrawReason::TransactionPayment | WithdrawReason::Tip1398            },1399            ExistenceRequirement::KeepAlive,1400        ) {1401            Ok(imbalance) => Ok((fee, Some(imbalance))),1402            Err(_) => Err(InvalidTransaction::Payment.into()),1403        }1404    }1405}14061407impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1408    for ChargeTransactionPayment<T>1409where1410    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1411    T::Call:1412        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1413{1414    const IDENTIFIER: &'static str = "ChargeTransactionPayment";1415    type AccountId = T::AccountId;1416    type Call = T::Call;1417    type AdditionalSigned = ();1418    type Pre = (1419        BalanceOf<T>,1420        Self::AccountId,1421        Option<NegativeImbalanceOf<T>>,1422        BalanceOf<T>,1423    );1424    fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1425        Ok(())1426    }14271428    fn validate(1429        &self,1430        who: &Self::AccountId,1431        call: &Self::Call,1432        info: &DispatchInfoOf<Self::Call>,1433        len: usize,1434    ) -> TransactionValidity {1435        let (fee, _) = self.withdraw_fee(who, call, info, len)?;14361437        let mut r = ValidTransaction::default();1438        // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1439        // will be a bit more than setting the priority to tip. For now, this is enough.1440        r.priority = fee.saturated_into::<TransactionPriority>();1441        Ok(r)1442    }14431444    fn pre_dispatch(1445        self,1446        who: &Self::AccountId,1447        call: &Self::Call,1448        info: &DispatchInfoOf<Self::Call>,1449        len: usize,1450    ) -> Result<Self::Pre, TransactionValidityError> {1451        let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1452        Ok((self.0, who.clone(), imbalance, fee))1453    }14541455    fn post_dispatch(1456        pre: Self::Pre,1457        info: &DispatchInfoOf<Self::Call>,1458        post_info: &PostDispatchInfoOf<Self::Call>,1459        len: usize,1460        _result: &DispatchResult,1461    ) -> Result<(), TransactionValidityError> {1462        let (tip, who, imbalance, fee) = pre;1463        if let Some(payed) = imbalance {1464            let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1465                len as u32, info, post_info, tip,1466            );1467            let refund = fee.saturating_sub(actual_fee);1468            let actual_payment =1469                match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1470                    &who, refund,1471                ) {1472                    Ok(refund_imbalance) => {1473                        // The refund cannot be larger than the up front payed max weight.1474                        // `PostDispatchInfo::calc_unspent` guards against such a case.1475                        match payed.offset(refund_imbalance) {1476                            Ok(actual_payment) => actual_payment,1477                            Err(_) => return Err(InvalidTransaction::Payment.into()),1478                        }1479                    }1480                    // We do not recreate the account using the refund. The up front payment1481                    // is gone in that case.1482                    Err(_) => payed,1483                };1484            let imbalances = actual_payment.split(tip);1485            <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1486                Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1487            );1488        }1489        Ok(())1490    }1491}1492// #endregion
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -1,8 +1,10 @@
 // Tests to be written here
 use crate::mock::*;
-use crate::{ApprovePermissions, CollectionMode, Ownership};
+use crate::{ApprovePermissions, CollectionMode, AccessMode, Ownership};
 use frame_support::{assert_noop, assert_ok};
 
+// Use cases tests region
+// #region
 #[test]
 fn create_nft_item() {
     new_test_ext().execute_with(|| {
@@ -321,15 +323,16 @@
         assert_eq!(TemplateModule::balance_count(1, 1), 1);
         assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
-        assert_noop!(
-            TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
-            "You do not have permissions to modify this collection"
-        );
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
 
         // do approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
         assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
-        assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));
+        assert_ok!(TemplateModule::approve(origin1.clone(), 3, 1, 1));
         assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
         assert_eq!(
             TemplateModule::approved(1, (1, 1))[0],
@@ -390,15 +393,16 @@
         assert_eq!(TemplateModule::balance_count(1, 1), 1000);
         assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
-        assert_noop!(
-            TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
-            "You do not have permissions to modify this collection"
-        );
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
 
         // do approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
         assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
-        assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));
+        assert_ok!(TemplateModule::approve(origin1.clone(), 3, 1, 1));
         assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
         assert_eq!(
             TemplateModule::approved(1, (1, 1))[0],
@@ -425,7 +429,7 @@
         assert_eq!(
             TemplateModule::approved(1, (1, 1))[0],
             ApprovePermissions {
-                approved: 10,
+                approved: 3,
                 amount: 100000000
             }
         );
@@ -461,15 +465,16 @@
         assert_eq!(TemplateModule::balance_count(1, 1), 1000);
         assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
-        assert_noop!(
-            TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
-            "You do not have permissions to modify this collection"
-        );
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
 
         // do approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
         assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
-        assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));
+        assert_ok!(TemplateModule::approve(origin1.clone(), 3, 1, 1));
         assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
         assert_eq!(
             TemplateModule::approved(1, (1, 1))[0],
@@ -496,7 +501,7 @@
         assert_eq!(
             TemplateModule::approved(1, (1, 1))[0],
             ApprovePermissions {
-                approved: 10,
+                approved: 3,
                 amount: 100000000
             }
         );
@@ -573,7 +578,6 @@
         let mode: CollectionMode = CollectionMode::NFT(2000);
 
         let origin1 = Origin::signed(1);
-        let origin2 = Origin::signed(2);
         assert_ok!(TemplateModule::create_collection(
             origin1.clone(),
             col_name1.clone(),
@@ -583,7 +587,7 @@
         ));
         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
         assert_ok!(TemplateModule::create_item(
-            origin2.clone(),
+            origin1.clone(),
             1,
             [1, 2, 3].to_vec(),
             1
@@ -614,7 +618,6 @@
         let mode: CollectionMode = CollectionMode::Fungible(3);
 
         let origin1 = Origin::signed(1);
-        let origin2 = Origin::signed(2);
         assert_ok!(TemplateModule::create_collection(
             origin1.clone(),
             col_name1.clone(),
@@ -624,7 +627,7 @@
         ));
         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
         assert_ok!(TemplateModule::create_item(
-            origin2.clone(),
+            origin1.clone(),
             1,
             [].to_vec(),
             1
@@ -661,6 +664,11 @@
             token_prefix1.clone(),
             mode
         ));
+        
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+
         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
         assert_ok!(TemplateModule::create_item(
             origin2.clone(),
@@ -928,6 +936,13 @@
         // approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
         assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);
+
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
+
         assert_ok!(TemplateModule::transfer_from(
             origin2.clone(),
             1,
@@ -942,3 +957,833 @@
         assert_eq!(TemplateModule::balance_count(1, 2), 1);
     });
 }
+
+// #endregion
+
+// Coverage tests region
+// #region
+
+#[test]
+fn owner_can_add_address_to_white_list() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
+
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_eq!(TemplateModule::white_list(1)[0], 2);
+    });
+}
+
+#[test]
+fn admin_can_add_address_to_white_list() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_to_white_list(origin2.clone(), 1, 3));
+        assert_eq!(TemplateModule::white_list(1)[0], 3);
+    });
+}
+
+#[test]
+fn nonprivileged_user_cannot_add_address_to_white_list() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_noop!(TemplateModule::add_to_white_list(origin2.clone(), 1, 3), "You do not have permissions to modify this collection");
+    });
+}
+
+#[test]
+fn nobody_can_add_address_to_white_list_of_nonexisting_collection() {
+    new_test_ext().execute_with(|| {
+
+        let origin1 = Origin::signed(1);
+        assert_noop!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2), "This collection does not exist");
+    });
+}
+
+#[test]
+fn nobody_can_add_address_to_white_list_of_deleted_collection() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
+
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::destroy_collection(origin1.clone(), 1));
+        assert_noop!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2), "This collection does not exist");
+    });
+}
+
+// If address is already added to white list, nothing happens
+#[test]
+fn address_is_already_added_to_white_list() {
+    new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
+
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_eq!(TemplateModule::white_list(1)[0], 2);
+        assert_eq!(TemplateModule::white_list(1).len(), 1);
+    });
+}
+
+#[test]
+fn owner_can_remove_address_from_white_list() {
+    new_test_ext().execute_with(|| {
+        
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
+
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 2));
+        assert_eq!(TemplateModule::white_list(1).len(), 0);
+    });
+}
+
+#[test]
+fn admin_can_remove_address_from_white_list() {
+    new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
+
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
+        assert_ok!(TemplateModule::remove_from_white_list(origin2.clone(), 1, 3));
+        assert_eq!(TemplateModule::white_list(1).len(), 0);
+    });
+}
+
+#[test]
+fn nonprivileged_user_cannot_remove_address_from_white_list() {
+    new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_noop!(TemplateModule::remove_from_white_list(origin2.clone(), 1, 2), "You do not have permissions to modify this collection");
+        assert_eq!(TemplateModule::white_list(1)[0], 2);
+    });
+}
+
+#[test]
+fn nobody_can_remove_address_from_white_list_of_nonexisting_collection() {
+    new_test_ext().execute_with(|| {
+
+        let origin1 = Origin::signed(1);
+        assert_noop!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 2), "This collection does not exist");
+    });
+}
+
+#[test]
+fn nobody_can_remove_address_from_white_list_of_deleted_collection() {
+    new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::destroy_collection(origin1.clone(), 1));
+        assert_noop!(TemplateModule::remove_from_white_list(origin2.clone(), 1, 2), "This collection does not exist");
+        assert_eq!(TemplateModule::white_list(1).len(), 0);
+    });
+}
+
+// If address is already removed from white list, nothing happens
+#[test]
+fn address_is_already_removed_from_white_list() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
+
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 2));
+        assert_eq!(TemplateModule::white_list(1).len(), 0);
+    });
+}
+
+// If Public Access mode is set to WhiteList, tokens can’t be transferred from a non-whitelisted address with transfer or transferFrom (2 tests)
+#[test]
+fn white_list_test_1() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+
+        assert_noop!(TemplateModule::transfer(
+            origin1.clone(),
+            3,
+            1,
+            1,
+            1
+        ), "Address is not in white list");
+    });
+}
+
+#[test]
+fn white_list_test_2() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+
+        // do approve
+        assert_ok!(TemplateModule::approve(origin1.clone(), 1, 1, 1));
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
+
+        assert_ok!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 1));
+
+        assert_noop!(TemplateModule::transfer_from(
+            origin1.clone(),
+            1,
+            3,
+            1,
+            1,
+            1
+        ), "Address is not in white list");
+    });
+}
+
+// If Public Access mode is set to WhiteList, tokens can’t be transferred to a non-whitelisted address with transfer or transferFrom (2 tests)
+#[test]
+fn white_list_test_3() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+
+        assert_noop!(TemplateModule::transfer(
+            origin1.clone(),
+            3,
+            1,
+            1,
+            1
+        ), "Address is not in white list");
+    });
+}
+
+#[test]
+fn white_list_test_4() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+
+        // do approve
+        assert_ok!(TemplateModule::approve(origin1.clone(), 1, 1, 1));
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
+
+        assert_ok!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 2));
+
+        assert_noop!(TemplateModule::transfer_from(
+            origin1.clone(),
+            1,
+            3,
+            1,
+            1,
+            1
+        ), "Address is not in white list");
+    });
+}
+
+// If Public Access mode is set to WhiteList, tokens can’t be destroyed by a non-whitelisted address (even if it owned them before enabling WhiteList mode)
+#[test]
+fn white_list_test_5() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_noop!(TemplateModule::burn_item(origin1.clone(), 1, 1), "Address is not in white list");
+    });
+}
+
+// If Public Access mode is set to WhiteList, oken transfers can’t be Approved by a non-whitelisted address (see Approve method).
+#[test]
+fn white_list_test_6() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+
+        // do approve
+        assert_noop!(TemplateModule::approve(origin1.clone(), 1, 1, 1), "Address is not in white list");
+    });
+}
+
+// If Public Access mode is set to WhiteList, tokens can be transferred from a whitelisted address with transfer or transferFrom (2 tests) and
+//          tokens can be transferred from a whitelisted address with transfer or transferFrom (2 tests)
+#[test]
+fn white_list_test_7() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+
+        assert_ok!(TemplateModule::transfer(
+            origin1.clone(),
+            2,
+            1,
+            1,
+            1
+        ));
+    });
+}
+
+#[test]
+fn white_list_test_8() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+
+        // do approve
+        assert_ok!(TemplateModule::approve(origin1.clone(), 1, 1, 1));
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
+
+        assert_ok!(TemplateModule::transfer_from(
+            origin1.clone(),
+            1,
+            2,
+            1,
+            1,
+            1
+        ));
+    });
+}
+
+// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by owner.
+#[test]
+fn white_list_test_9() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, false));
+
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+    });
+}
+
+// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by admin.
+#[test]
+fn white_list_test_10() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, false));
+
+        assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
+
+        assert_ok!(TemplateModule::create_item(
+            origin2.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            2
+        ));
+    });
+}
+
+// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and white listed address.
+#[test]
+fn white_list_test_11() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, false));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+
+        assert_noop!(TemplateModule::create_item(
+            origin2.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            2
+        ), "Collection is not in mint mode");
+    });
+}
+
+// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and non-white listed address.
+#[test]
+fn white_list_test_12() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, false));
+
+        assert_noop!(TemplateModule::create_item(
+            origin2.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            2
+        ), "Collection is not in mint mode");
+    });
+}
+
+// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by owner.
+#[test]
+fn white_list_test_13() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+    });
+}
+
+// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by admin.
+#[test]
+fn white_list_test_14() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+
+        assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
+
+        assert_ok!(TemplateModule::create_item(
+            origin2.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            2
+        ));
+    });
+}
+
+// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens cannot be created by non-privileged and non-white listed address.
+#[test]
+fn white_list_test_15() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+
+        assert_noop!(TemplateModule::create_item(
+            origin2.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            2
+        ), "Address is not in white list");
+    });
+}
+
+// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by non-privileged and white listed address.
+#[test]
+fn white_list_test_16() {
+    new_test_ext().execute_with(|| {
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+        let mode: CollectionMode = CollectionMode::NFT(2000);
+
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
+
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+
+        assert_ok!(TemplateModule::create_item(
+            origin2.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            2
+        ));
+    });
+}
+
+// #endregion
\ No newline at end of file
modifiedrun-testnet.shdiffbeforeafterboth
--- a/run-testnet.sh
+++ b/run-testnet.sh
@@ -49,6 +49,7 @@
   --rpc-port $RPCPORT \
   --name $NODE \
   --ws-external \
+  --ws-max-connections 10000 \
   --rpc-cors all \
   -lruntime \
   $BOOTNODES;
modifiedruntime/src/lib.rsdiffbeforeafterboth
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -53,8 +53,10 @@
 
 pub use timestamp::Call as TimestampCall;
 
-/// Importing a nft pallet
-pub use nft;
+/// Re-export a nft pallet
+/// TODO: Check this re-export. Is this safe and good style?
+extern crate nft;
+pub use nft::*;
 
 /// An index to a block.
 pub type BlockNumber = u32;
@@ -111,7 +113,7 @@
     spec_name: create_runtime_str!("nft"),
     impl_name: create_runtime_str!("nft"),
     authoring_version: 1,
-    spec_version: 1,
+    spec_version: 2,
     impl_version: 1,
     apis: RUNTIME_API_VERSIONS,
     transaction_version: 1,
@@ -318,7 +320,7 @@
         Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},
         TransactionPayment: transaction_payment::{Module, Storage},
         Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},
-        Nft: nft::{Module, Call, Storage, Event<T>},
+        Nft: nft::{Module, Call, Config<T>, Storage, Event<T>},
     }
 );
 
addedtests/src/blocks-production.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/blocks-production.test.ts
@@ -0,0 +1,48 @@
+import usingApi from "./substrate/substrate-api";
+import promisifySubstrate from "./substrate/promisify-substrate";
+import { expect } from "chai";
+
+describe('Blocks Production', () => {
+  it('Node produces new blocks', async () => {
+    await usingApi(async api => {
+      const blocksPromise = promisifySubstrate(api, () => {
+        return new Promise<number[]>((resolve, reject) => {
+          const blockNumbers: number[] = [];
+          const unsubscribe = api.rpc.chain.subscribeNewHeads(async head => {
+            blockNumbers.push(head.number.toNumber());
+            if(blockNumbers.length >= 2) {
+              (await unsubscribe)();
+              resolve(blockNumbers);
+            }
+          });
+        })
+      })();
+
+      let blocks: number[] | undefined = undefined;
+
+      const timeoutPromise = new Promise<void>((resolve, reject) => {
+        let secondsPassed = 0;
+        let incrementSeconds = () => {
+          secondsPassed++;
+          if(secondsPassed > 5 * 60) {
+            reject('Block production test failed due to timeout.');
+            return;
+          }
+
+          if(blocks) {
+            resolve();
+            return;
+          }
+
+          setTimeout(incrementSeconds, 1000);
+        }
+
+        incrementSeconds();
+      });
+
+      blocks = await Promise.race([blocksPromise, timeoutPromise]) as number[];
+
+      expect(blocks[0]).to.be.lessThan(blocks[1]);
+    });
+  });
+});
modifiedtests/src/config.tsdiffbeforeafterboth
--- a/tests/src/config.ts
+++ b/tests/src/config.ts
@@ -34,6 +34,20 @@
         "ReFungible": "(u32, u32)"
       }
     },
+    "Ownership": {
+      "Owner": "AccountId",
+      "Fraction": "u128"
+    },
+    "FungibleItemType": {
+      "Collection": "u64",
+      "Owner": "AccountId",
+      "Value": "u128"
+    },
+    "ReFungibleItemType": {
+      "Collection": "u64",
+      "Owner": "Vec<Ownership>",
+      "Data": "Vec<u8>"
+    },
     "NftItemType": {
       "Collection": "u64",
       "Owner": "AccountId",
@@ -57,10 +71,15 @@
       "Description": "Vec<u16>",
       "TokenPrefix": "Vec<u8>",
       "CustomDataSize": "u32",
+      "MintMode": "bool",
       "OffchainSchema": "Vec<u8>",
       "Sponsor": "AccountId",
       "UnconfirmedSponsor": "AccountId"
     },
+    "ApprovePermissions": {
+      "Approved": "AccountId",
+      "Amount": "u64"
+    },
     "RawData": "Vec<u8>",
     "Address": "AccountId",
     "LookupSource": "AccountId",
modifiedtests/src/connection.test.tsdiffbeforeafterboth
--- a/tests/src/connection.test.ts
+++ b/tests/src/connection.test.ts
@@ -15,9 +15,9 @@
     });
   });
 
-  it('Cannot connect to 0.0.0.0', () => {
-    const neverConnectProvider = new WsProvider('ws://0.0.0.0:9944');
-    expect((async () => {
+  it('Cannot connect to 255.255.255.255', async () => {
+    const neverConnectProvider = new WsProvider('ws://255.255.255.255:9944');
+    await expect((async () => {
       await usingApi(async api => {
         const health = await api.rpc.system.health();
       }, { provider: neverConnectProvider });
modifiedtests/src/substrate/promisify-substrate.tsdiffbeforeafterboth
--- a/tests/src/substrate/promisify-substrate.ts
+++ b/tests/src/substrate/promisify-substrate.ts
@@ -4,19 +4,21 @@
 
 export default function promisifySubstrate<T extends (...args: any[]) => any>(api: ApiPromise, action: T): (...args: Parameters<T>) => Promise<PromiseType<ReturnType<T>>> {
   return (...args: Parameters<T>) => {
-    const promise = new Promise<PromiseType<ReturnType<T>>>((resolve, reject) => {
+    const promise = new Promise<PromiseType<ReturnType<T>>>((resolve: ((result: PromiseType<ReturnType<T>>) => void) | undefined, reject: ((error: any) => void) | undefined) => {
       const cleanup = () => {
         api.off('disconnected', fail);
         api.off('error', fail);
+        resolve = undefined;
+        reject = undefined;
       };
 
       const success = (r: any) => {
+        resolve && resolve(r);
         cleanup();
-        resolve(r);
       };
       const fail = (error: any) => {
+        reject && reject(error);
         cleanup();
-        reject(error);
       };
       
       api.on('disconnected', fail);
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -10,13 +10,16 @@
 
 export default async function usingApi(action: (api: ApiPromise) => Promise<void>, settings: ApiOptions | undefined = undefined): Promise<void> {
   settings = settings || defaultApiOptions();
-  let api: ApiPromise | undefined = undefined;
+  let api: ApiPromise = new ApiPromise(settings);
 
   try {
-    api = new ApiPromise(settings);
-    await promisifySubstrate(api, () => api && api.isReady)();
-    await action(api);
+    await promisifySubstrate(api, async () => {
+      if(api) {
+        await api.isReadyOrError;
+        await action(api);
+      }
+    })();
   } finally {
-    api && api.disconnect();
+    await api.disconnect();
   }
 }
\ No newline at end of file