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

difftreelog

Merge pull request #4 from usetech-llc/release/v1.0.1

str-mv2020-09-22parents: #357788d #8d30d14.patch.diff
in: master
Release/v1.0.1

10 files changed

modifiedREADME.mddiffbeforeafterboth
--- a/README.md
+++ b/README.md
@@ -171,6 +171,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",
modifiednode/src/cli.rsdiffbeforeafterboth
--- a/node/src/cli.rs
+++ b/node/src/cli.rs
@@ -3,9 +3,9 @@
 
 #[derive(Debug, StructOpt)]
 pub struct Cli {
-	#[structopt(subcommand)]
-	pub subcommand: Option<Subcommand>,
+    #[structopt(subcommand)]
+    pub subcommand: Option<Subcommand>,
 
-	#[structopt(flatten)]
-	pub run: RunCmd,
+    #[structopt(flatten)]
+    pub run: RunCmd,
 }
modifiednode/src/command.rsdiffbeforeafterboth
--- a/node/src/command.rs
+++ b/node/src/command.rs
@@ -21,61 +21,57 @@
 use sc_cli::SubstrateCli;
 
 impl SubstrateCli for Cli {
-	fn impl_name() -> &'static str {
-		"Substrate Node"
-	}
+    fn impl_name() -> &'static str {
+        "Substrate Node"
+    }
 
-	fn impl_version() -> &'static str {
-		env!("SUBSTRATE_CLI_IMPL_VERSION")
-	}
+    fn impl_version() -> &'static str {
+        env!("SUBSTRATE_CLI_IMPL_VERSION")
+    }
 
-	fn description() -> &'static str {
-		env!("CARGO_PKG_DESCRIPTION")
-	}
+    fn description() -> &'static str {
+        env!("CARGO_PKG_DESCRIPTION")
+    }
 
-	fn author() -> &'static str {
-		env!("CARGO_PKG_AUTHORS")
-	}
+    fn author() -> &'static str {
+        env!("CARGO_PKG_AUTHORS")
+    }
 
-	fn support_url() -> &'static str {
-		"support.anonymous.an"
-	}
+    fn support_url() -> &'static str {
+        "support.anonymous.an"
+    }
 
-	fn copyright_start_year() -> i32 {
-		2017
-	}
+    fn copyright_start_year() -> i32 {
+        2017
+    }
 
-	fn executable_name() -> &'static str {
-		env!("CARGO_PKG_NAME")
-	}
+    fn executable_name() -> &'static str {
+        env!("CARGO_PKG_NAME")
+    }
 
-	fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
-		Ok(match id {
-			"dev" => Box::new(chain_spec::development_config()),
-			"" | "local" => Box::new(chain_spec::local_testnet_config()),
-			path => Box::new(chain_spec::ChainSpec::from_json_file(
-				std::path::PathBuf::from(path),
-			)?),
-		})
-	}
+    fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
+        Ok(match id {
+            "dev" => Box::new(chain_spec::development_config()),
+            "" | "local" => Box::new(chain_spec::local_testnet_config()),
+            path => Box::new(chain_spec::ChainSpec::from_json_file(
+                std::path::PathBuf::from(path),
+            )?),
+        })
+    }
 }
 
 /// Parse and run command line arguments
 pub fn run() -> sc_cli::Result<()> {
-	let cli = Cli::from_args();
+    let cli = Cli::from_args();
 
-	match &cli.subcommand {
-		Some(subcommand) => {
-			let runner = cli.create_runner(subcommand)?;
-			runner.run_subcommand(subcommand, |config| Ok(new_full_start!(config).0))
-		}
-		None => {
-			let runner = cli.create_runner(&cli.run)?;
-			runner.run_node(
-				service::new_light,
-				service::new_full,
-				nft_runtime::VERSION
-			)
-		}
-	}
-}
\ No newline at end of file
+    match &cli.subcommand {
+        Some(subcommand) => {
+            let runner = cli.create_runner(subcommand)?;
+            runner.run_subcommand(subcommand, |config| Ok(new_full_start!(config).0))
+        }
+        None => {
+            let runner = cli.create_runner(&cli.run)?;
+            runner.run_node(service::new_light, service::new_full, nft_runtime::VERSION)
+        }
+    }
+}
modifiednode/src/main.rsdiffbeforeafterboth
--- a/node/src/main.rs
+++ b/node/src/main.rs
@@ -8,5 +8,5 @@
 mod command;
 
 fn main() -> sc_cli::Result<()> {
-	command::run()
+    command::run()
 }
modifiednode/src/service.rsdiffbeforeafterboth
--- a/node/src/service.rs
+++ b/node/src/service.rs
@@ -188,7 +188,7 @@
             prometheus_registry: service.prometheus_registry(),
             shared_voter_state: SharedVoterState::empty(),
         };
-        
+
         // the GRANDPA voter task is considered infallible, i.e.
         // if it fails we take down the service with it.
         service.spawn_essential_task_handle().spawn_blocking(
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.rs56use codec::{Decode, Encode};7pub use frame_support::{8    decl_event, decl_module, decl_storage,9    construct_runtime, parameter_types,10    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},11    weights::{12        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},13        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,14    },15    StorageValue,16    dispatch::DispatchResult, 17    IsSubType,18    ensure19};2021use frame_system::{self as system, ensure_signed};22use sp_runtime::sp_std::prelude::Vec;23use sp_std::prelude::*;24use sp_runtime::{25	FixedU128, FixedPointOperand, 26	transaction_validity::{27		TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity28	},29	traits::{30        Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,31	},32};3334#[cfg(test)]35mod mock;3637#[cfg(test)]38mod tests;3940#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]41pub enum CollectionMode {42    Invalid,43    // custom data size44    NFT(u32),45    // decimal points46    Fungible(u32),47    // custom data size and decimal points48	ReFungible(u32, u32),49}5051impl Into<u8> for CollectionMode {52    fn into(self) -> u8{53        match self {54            CollectionMode::Invalid => 0,55            CollectionMode::NFT(_) => 1,56            CollectionMode::Fungible(_) => 2,57            CollectionMode::ReFungible(_, _) => 3,58        }59    }60}6162#[derive(Encode, Decode, Debug, Clone, PartialEq)]63pub enum AccessMode {64    Normal,65	WhiteList,66}67impl Default for AccessMode { fn default() -> Self { Self::Normal } }6869impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }7071#[derive(Encode, Decode, Default, Clone, PartialEq)]72#[cfg_attr(feature = "std", derive(Debug))]73pub struct Ownership<AccountId> {74    pub owner: AccountId,75    pub fraction: u12876}7778#[derive(Encode, Decode, Default, Clone, PartialEq)]79#[cfg_attr(feature = "std", derive(Debug))]80pub struct CollectionType<AccountId> {81    pub owner: AccountId,82    pub mode: CollectionMode,83    pub access: AccessMode,84    pub decimal_points: u32,85    pub name: Vec<u16>,        // 64 include null escape char86    pub description: Vec<u16>, // 256 include null escape char87    pub token_prefix: Vec<u8>, // 16 include null escape char88    pub custom_data_size: u32,89    pub offchain_schema: Vec<u8>,90    pub sponsor: AccountId,    // Who pays fees. If set to default address, the fees are applied to the transaction sender91    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship92}9394#[derive(Encode, Decode, Default, Clone, PartialEq)]95#[cfg_attr(feature = "std", derive(Debug))]96pub struct CollectionAdminsType<AccountId> {97    pub admin: AccountId,98    pub collection_id: u64,99}100101#[derive(Encode, Decode, Default, Clone, PartialEq)]102#[cfg_attr(feature = "std", derive(Debug))]103pub struct NftItemType<AccountId> {104    pub collection: u64,105    pub owner: AccountId,106    pub data: Vec<u8>,107}108109#[derive(Encode, Decode, Default, Clone, PartialEq)]110#[cfg_attr(feature = "std", derive(Debug))]111pub struct FungibleItemType<AccountId> {112    pub collection: u64,113    pub owner: AccountId,114    pub value: u128,115}116117#[derive(Encode, Decode, Default, Clone, PartialEq)]118#[cfg_attr(feature = "std", derive(Debug))]119pub struct ReFungibleItemType<AccountId> {120    pub collection: u64,121    pub owner: Vec<Ownership<AccountId>>,122    pub data: Vec<u8>,123}124125pub trait Trait: system::Trait {126    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;127128}129130decl_storage! {131    trait Store for Module<T: Trait> as Nft {132133        // Private members134        CreatedCollectionCount: u64;135        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;136137        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;138        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;139        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;140141        // Balance owner per collection map142        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;143        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<T::AccountId>;144145        // Item collections146        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;147        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;148        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;149150        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;151152        // Sponsorship153        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;154        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;155    }156}157158decl_event!(159    pub enum Event<T>160    where161        AccountId = <T as system::Trait>::AccountId,162    {163        Created(u64, u8, AccountId),164        ItemCreated(u64, u64),165        ItemDestroyed(u64, u64),166    }167);168169decl_module! {170    pub struct Module<T: Trait> for enum Call where origin: T::Origin {171172        fn deposit_event() = default;173174        // Create collection of NFT with given parameters175        //176        // @param customDataSz size of custom data in each collection item177        // returns collection ID178        #[weight = 0]179        pub fn create_collection(   origin,180                                    collection_name: Vec<u16>,181                                    collection_description: Vec<u16>,182                                    token_prefix: Vec<u8>,183                                    mode: CollectionMode) -> DispatchResult {184185            // Anyone can create a collection186            let who = ensure_signed(origin)?;187            let custom_data_size = match mode {188                CollectionMode::NFT(size) => size,189                CollectionMode::ReFungible(size, _) => size,190                _ => 0191            };192193            let decimal_points = match mode {194                CollectionMode::Fungible(points) => points,195                CollectionMode::ReFungible(_, points) => points,196                _ => 0197            };198199            // check params200            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4"); 201202            let mut name = collection_name.to_vec();203            name.push(0);204            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");205206            let mut description = collection_description.to_vec();207            description.push(0);208            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");209210            let mut prefix = token_prefix.to_vec();211            prefix.push(0);212            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");213214            // Generate next collection ID215            let next_id = CreatedCollectionCount::get()216                .checked_add(1)217                .expect("collection id error");218219            CreatedCollectionCount::put(next_id);220221            // Create new collection222            let new_collection = CollectionType {223                owner: who.clone(),224                name: name,225                mode: mode.clone(),226                access: AccessMode::Normal,227                description: description,228                decimal_points: decimal_points,229                token_prefix: prefix,230                offchain_schema: Vec::new(),231                custom_data_size: custom_data_size,232                sponsor: T::AccountId::default(),233                unconfirmed_sponsor: T::AccountId::default(),234            };235236            // Add new collection to map237            <Collection<T>>::insert(next_id, new_collection);238239            // call event240            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));241242            Ok(())243        }244245        #[weight = 0]246        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {247248            let sender = ensure_signed(origin)?;249            Self::check_owner_permissions(collection_id, sender)?;250251            <AddressTokens<T>>::remove_prefix(collection_id);252            <ApprovedList<T>>::remove_prefix(collection_id);253            <Balance<T>>::remove_prefix(collection_id);254            <ItemListIndex>::remove(collection_id);255            <AdminList<T>>::remove(collection_id);256            <Collection<T>>::remove(collection_id);257            <WhiteList<T>>::remove(collection_id);258259            Ok(())260        }261262        #[weight = 0]263        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {264265            let sender = ensure_signed(origin)?;266            Self::check_owner_permissions(collection_id, sender)?;267            let mut target_collection = <Collection<T>>::get(collection_id);268            target_collection.owner = new_owner;269            <Collection<T>>::insert(collection_id, target_collection);270271            Ok(())272        }273274        #[weight = 0]275        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {276277            let sender = ensure_signed(origin)?;278            Self::check_owner_or_admin_permissions(collection_id, sender)?;279            let mut admin_arr: Vec<T::AccountId> = Vec::new();280281            if <AdminList<T>>::contains_key(collection_id)282            {283                admin_arr = <AdminList<T>>::get(collection_id);284                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");285            }286287            admin_arr.push(new_admin_id);288            <AdminList<T>>::insert(collection_id, admin_arr);289290            Ok(())291        }292293        #[weight = 0]294        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {295296            let sender = ensure_signed(origin)?;297            Self::check_owner_or_admin_permissions(collection_id, sender)?;298299            if <AdminList<T>>::contains_key(collection_id)300            {301                let mut admin_arr = <AdminList<T>>::get(collection_id);302                admin_arr.retain(|i| *i != account_id);303                <AdminList<T>>::insert(collection_id, admin_arr);304            }305306            Ok(())307        }308309        #[weight = 0]310        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {311312            let sender = ensure_signed(origin)?;313            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");314315            let mut target_collection = <Collection<T>>::get(collection_id);316            ensure!(sender == target_collection.owner, "You do not own this collection");317318            target_collection.unconfirmed_sponsor = new_sponsor;319            <Collection<T>>::insert(collection_id, target_collection);320321            Ok(())322        }323324        #[weight = 0]325        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {326327            let sender = ensure_signed(origin)?;328            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");329330            let mut target_collection = <Collection<T>>::get(collection_id);331            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");332333            target_collection.sponsor = target_collection.unconfirmed_sponsor;334            target_collection.unconfirmed_sponsor = T::AccountId::default();335            <Collection<T>>::insert(collection_id, target_collection);336337            Ok(())338        }339340        #[weight = 0]341        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {342343            let sender = ensure_signed(origin)?;344            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");345346            let mut target_collection = <Collection<T>>::get(collection_id);347            ensure!(sender == target_collection.owner, "You do not own this collection");348349            target_collection.sponsor = T::AccountId::default();350            <Collection<T>>::insert(collection_id, target_collection);351352            Ok(())353        }354        355        #[weight = 0]356        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {357358            let sender = ensure_signed(origin)?;359360            // check size361            let target_collection = <Collection<T>>::get(collection_id);362            ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");363364            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;365366            // TODO: implement other modes367            match target_collection.mode 368            {369                CollectionMode::NFT(_) => {370                // Create nft item371                    let item = NftItemType {372                        collection: collection_id,373                        owner: owner,374                        data: properties.clone(),375                    };376    377                    Self::add_nft_item(item)?;378    379                },380                CollectionMode::ReFungible(_, _) => {381                    let mut owner_list = Vec::new();382                    let value = (10 as u128).pow(target_collection.decimal_points);383                    owner_list.push(Ownership {owner: owner.clone(), fraction: value});384385                    let item = ReFungibleItemType {386                        collection: collection_id,387                        owner: owner_list,388                        data: properties.clone()389                    };390    391                    Self::add_refungible_item(item)?;392                },393                _ => { ensure!(1 == 0,"just error"); }394395            };396397            // call event398            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));399400            Ok(())401        }402403        #[weight = 0]404        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {405406            let sender = ensure_signed(origin)?;407            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);408            if !item_owner409            {410                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;411            }412            let target_collection = <Collection<T>>::get(collection_id);413414            match target_collection.mode 415            {416                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,417                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,418                _ => ()419            };420421            // call event422            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));423424            Ok(())425        }426427        #[weight = 0]428        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {429430            let sender = ensure_signed(origin)?;431            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");432433            let target_collection = <Collection<T>>::get(collection_id);434435            // TODO: implement other modes436            match target_collection.mode 437            {438                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,439                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,440                _ => ()441            };442443            Ok(())444        }445446        #[weight = 0]447        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {448449            let sender = ensure_signed(origin)?;450451            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);452            if !item_owner453            {454                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;455            }456457            let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);458            if list_exists {459460                let mut list = <ApprovedList<T>>::get(collection_id, item_id);461                let item_contains = list.contains(&approved.clone());462463                if !item_contains {464                    list.push(approved.clone());465                }466            } else {467468                let mut itm = Vec::new();469                itm.push(approved.clone());470                <ApprovedList<T>>::insert(collection_id, item_id, itm);471            }472473            Ok(())474        }475476        #[weight = 0]477        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {478479            let mut approved: bool = false; 480            let sender = ensure_signed(origin)?;481            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);482            if approved_list_exists483            {484                let list_itm = <ApprovedList<T>>::get(collection_id, item_id);485                approved = list_itm.contains(&recipient.clone());486            }487488            if !approved489            {490                Self::check_owner_or_admin_permissions(collection_id, sender)?;491            }492            493            let target_collection = <Collection<T>>::get(collection_id);494495            match target_collection.mode496            {497                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,498                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from, recipient)?,499                // TODO: implement other modes500                _ => ()501            };502503            Ok(())504        }505506        #[weight = 0]507        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {508509            // let no_perm_mes = "You do not have permissions to modify this collection";510            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);511            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));512            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);513514            // // on_nft_received  call515516            // Self::transfer(origin, collection_id, item_id, new_owner)?;517518            Ok(())519        }520521        #[weight = 0]522        pub fn set_offchain_schema(523            origin,524            collection_id: u64,525            schema: Vec<u8>526        ) -> DispatchResult {527            let sender = ensure_signed(origin)?;528            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;529            530            let mut target_collection = <Collection<T>>::get(collection_id);531            target_collection.offchain_schema = schema;532            <Collection<T>>::insert(collection_id, target_collection);533534            Ok(())        535        }536    }537}538539impl<T: Trait> Module<T> {540541    fn collection_exists(collection_id: u64) -> DispatchResult{542        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");543        Ok(())544    }545546    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {547548        Self::collection_exists(collection_id)?;549550        let target_collection = <Collection<T>>::get(collection_id);551        ensure!(subject == target_collection.owner, "You do not own this collection");552553        Ok(())554    }555556    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {557558        Self::collection_exists(collection_id)?;559560        let target_collection = <Collection<T>>::get(collection_id);561        let is_owner = subject == target_collection.owner;562563        let no_perm_mes = "You do not have permissions to modify this collection";564        let exists = <AdminList<T>>::contains_key(collection_id);565566        if !is_owner567        {568            ensure!(exists, no_perm_mes);569            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);570        }571        Ok(())572    }573574    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{575576        let target_collection = <Collection<T>>::get(collection_id);577578        match target_collection.mode {579            CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,580            CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,581            CollectionMode::ReFungible(_, _)  => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),582            CollectionMode::Invalid => false583        }584    }585586    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {587588        let current_index = <ItemListIndex>::get(item.collection)589        .checked_add(1)590        .expect("Item list index id error");591        let itemcopy = item.clone();592593        let value = item.owner.first().unwrap().fraction as u64;594        let owner = item.owner.first().unwrap().owner.clone();595596        Self::add_token_index(item.collection, current_index, owner.clone())?;597598        <ItemListIndex>::insert(item.collection, current_index);599        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);  600        601        // Update balance602       let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();603       <Balance<T>>::insert(item.collection, owner.clone(), new_balance);604605        Ok(())606    }607608    fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {609  610        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);611        let item = collection.owner.iter().filter(|&i| i.owner == owner).next().unwrap();612        Self::remove_token_index(collection_id, item_id, owner)?;613614        // update balance615        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();616        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);617618        // TODO619        <ReFungibleItemList<T>>::remove(collection_id, item_id);620621        Ok(())622    }623624    fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {625626        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);627        let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();628        let amount = item.fraction;629630        ensure!(amount >= value.into(),"Item balance not enouth");631632        // update balance633        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();634        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);635636        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();637        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);638639        let old_owner = item.owner.clone();640        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);641        let val64 = value.into();642643        // transfer644        if amount == val64 && !new_owner_has_account645        {646            // change owner647            // new owner do not have account648            let mut new_full_item = full_item.clone();649            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();650            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);651652            // update index collection653            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;654        }655        else656        {657            let mut new_full_item = full_item.clone();658            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= val64;659660            // separate amount661            if new_owner_has_account {662                // new owner has account663                new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += val64;664            }665            else666            {667                // new owner do not have account668                new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: val64});669                Self::add_token_index(collection_id, item_id, new_owner.clone())?;670            }671672            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);673        }674675        Ok(())676    }677    678    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {679680        let current_index = <ItemListIndex>::get(item.collection)681        .checked_add(1)682        .expect("Item list index id error");683        let itemcopy = item.clone();684685        Self::add_token_index(item.collection, current_index, item.owner.clone())?;686687        <ItemListIndex>::insert(item.collection, current_index);688        <NftItemList<T>>::insert(item.collection, current_index, item);689690        // Update balance691        let new_balance = <Balance<T>>::get(itemcopy.collection, itemcopy.owner.clone()).checked_add(1).unwrap();692        <Balance<T>>::insert(itemcopy.collection, itemcopy.owner.clone(), new_balance);693694        Ok(())695    }696697    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {698  699        let item = <NftItemList<T>>::get(collection_id, item_id);700        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;701702        // update balance703        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();704        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);705        <NftItemList<T>>::remove(collection_id, item_id);706707        Ok(())708    }709710    fn transfer_nft(collection_id: u64, item_id: u64, sender: T::AccountId, new_owner: T::AccountId) -> DispatchResult {711712        let mut item = <NftItemList<T>>::get(collection_id, item_id);713714        ensure!(sender == item.owner,"sender parameter and item owner must be equal");715716        // update balance717        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();718        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);719720        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();721        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);722723        // change owner724        let old_owner = item.owner.clone();725        item.owner = new_owner.clone();726        <NftItemList<T>>::insert(collection_id, item_id, item);727728        // update index collection729        Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;730731        // reset approved list732        let itm: Vec<T::AccountId> = Vec::new();733        <ApprovedList<T>>::insert(collection_id, item_id, itm);734735        Ok(())736    }737738    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {739        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());740        if list_exists {741            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());742            let item_contains = list.contains(&item_index.clone());743744            if !item_contains {745                list.push(item_index.clone());746            }747748            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);749        } else {750            let mut itm = Vec::new();751            itm.push(item_index.clone());752            <AddressTokens<T>>::insert(collection_id, owner, itm);753        }754755        Ok(())756    }757758    fn remove_token_index(759        collection_id: u64,760        item_index: u64,761        owner: T::AccountId,762    ) -> DispatchResult {763        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());764        if list_exists {765            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());766            let item_contains = list.contains(&item_index.clone());767768            if item_contains {769                list.retain(|&item| item != item_index);770                <AddressTokens<T>>::insert(collection_id, owner, list);771            }772        }773774        Ok(())775    }776777    fn move_token_index(778        collection_id: u64,779        item_index: u64,780        old_owner: T::AccountId,781        new_owner: T::AccountId,782    ) -> DispatchResult {783        Self::remove_token_index(collection_id, item_index, old_owner)?;784        Self::add_token_index(collection_id, item_index, new_owner)?;785786        Ok(())787    }788}789790791////////////////////////////////////////////////////////////////////////////////////////////////////792// Economic models793794/// Fee multiplier.795pub type Multiplier = FixedU128;796797type BalanceOf<T> =798	<<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;799type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<800	<T as system::Trait>::AccountId,>>::NegativeImbalance;801802803804/// Require the transactor pay for themselves and maybe include a tip to gain additional priority805/// in the queue.806#[derive(Encode, Decode, Clone, Eq, PartialEq)]807pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);808809impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {810	#[cfg(feature = "std")]811	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {812		write!(f, "ChargeTransactionPayment<{:?}>", self.0)813	}814	#[cfg(not(feature = "std"))]815	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {816		Ok(())817	}818}819820impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where821	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,822	BalanceOf<T>: Send + Sync + FixedPointOperand,823{824	/// utility constructor. Used only in client/factory code.825	pub fn from(fee: BalanceOf<T>) -> Self {826		Self(fee)827	}828829    pub fn traditional_fee(830        len: usize,831        info: &DispatchInfoOf<T::Call>,832        tip: BalanceOf<T>,833    ) -> BalanceOf<T> where834        T::Call: Dispatchable<Info=DispatchInfo>,835    {836        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)837    }838839	fn withdraw_fee(840		&self,841        who: &T::AccountId,842        call: &T::Call,843		info: &DispatchInfoOf<T::Call>,844		len: usize,845	) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {846        let tip = self.0;847848        // Set fee based on call type. Creating collection costs 1 Unique.849        // All other transactions have traditional fees so far850        let fee = match call.is_sub_type() {851            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),852            _ => Self::traditional_fee(len, info, tip)853854            // Flat fee model, use only for testing purposes855            // _ => <BalanceOf<T>>::from(100)856        };857858        // Determine who is paying transaction fee based on ecnomic model859        // Parse call to extract collection ID and access collection sponsor860        let sponsor: T::AccountId = match call.is_sub_type() {861            Some(Call::create_item(collection_id, _properties, _owner)) => {862                <Collection<T>>::get(collection_id).sponsor863            },864            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {865                <Collection<T>>::get(collection_id).sponsor866            },867868            _ => T::AccountId::default()869        };870871        let mut who_pays_fee: T::AccountId = sponsor.clone();872        if sponsor == T::AccountId::default() {873            who_pays_fee = who.clone();874        }875876		// Only mess with balances if fee is not zero.877		if fee.is_zero() {878			return Ok((fee, None));879		}880881		match <T as transaction_payment::Trait>::Currency::withdraw(882			&who_pays_fee,883			fee,884			if tip.is_zero() {885				WithdrawReason::TransactionPayment.into()886			} else {887				WithdrawReason::TransactionPayment | WithdrawReason::Tip888			},889			ExistenceRequirement::KeepAlive,890		) {891			Ok(imbalance) => Ok((fee, Some(imbalance))),892			Err(_) => Err(InvalidTransaction::Payment.into()),893		}894	}895}896897impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where898    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,899    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,900{901	const IDENTIFIER: &'static str = "ChargeTransactionPayment";902	type AccountId = T::AccountId;903	type Call = T::Call;904	type AdditionalSigned = ();905	type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);906	fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }907908	fn validate(909		&self,910		who: &Self::AccountId,911		call: &Self::Call,912		info: &DispatchInfoOf<Self::Call>,913		len: usize,914	) -> TransactionValidity {915		let (fee, _) = self.withdraw_fee(who, call, info, len)?;916917		let mut r = ValidTransaction::default();918		// NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which919		// will be a bit more than setting the priority to tip. For now, this is enough.920		r.priority = fee.saturated_into::<TransactionPriority>();921		Ok(r)922	}923924	fn pre_dispatch(925		self,926		who: &Self::AccountId,927		call: &Self::Call,928		info: &DispatchInfoOf<Self::Call>,929		len: usize930	) -> Result<Self::Pre, TransactionValidityError> {931		let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;932		Ok((self.0, who.clone(), imbalance, fee))933	}934935	fn post_dispatch(936		pre: Self::Pre,937		info: &DispatchInfoOf<Self::Call>,938		post_info: &PostDispatchInfoOf<Self::Call>,939		len: usize,940		_result: &DispatchResult,941	) -> Result<(), TransactionValidityError> {942		let (tip, who, imbalance, fee) = pre;943		if let Some(payed) = imbalance {944			let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(945				len as u32,946				info,947				post_info,948				tip,949			);950			let refund = fee.saturating_sub(actual_fee);951			let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {952				Ok(refund_imbalance) => {953					// The refund cannot be larger than the up front payed max weight.954					// `PostDispatchInfo::calc_unspent` guards against such a case.955					match payed.offset(refund_imbalance) {956						Ok(actual_payment) => actual_payment,957						Err(_) => return Err(InvalidTransaction::Payment.into()),958					}959				}960				// We do not recreate the account using the refund. The up front payment961				// is gone in that case.962				Err(_) => payed,963			};964			let imbalances = actual_payment.split(tip);965			<T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()966				.chain(Some(imbalances.1)));967		}968		Ok(())969	}970}
after · 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}
modifiedpallets/nft/src/mock.rsdiffbeforeafterboth
--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -1,19 +1,19 @@
 // Creating mock runtime here
 
 use crate::{Module, Trait};
+use frame_support::{
+    impl_outer_origin, parameter_types,
+    weights::{
+        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
+        Weight,
+    },
+};
 use frame_system as system;
 use sp_core::H256;
 use sp_runtime::{
     testing::Header,
     traits::{BlakeTwo256, IdentityLookup, Saturating},
     Perbill,
-};
-use frame_support::{
-    parameter_types, impl_outer_origin,
-    weights::{
-        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
-        Weight,
-    },
 };
 
 impl_outer_origin! {
@@ -49,9 +49,9 @@
     type MaximumBlockWeight = MaximumBlockWeight;
     type MaximumBlockLength = MaximumBlockLength;
     type AvailableBlockRatio = AvailableBlockRatio;
-    type BaseCallFilter = (); 
-    type DbWeight = RocksDbWeight; 
-    type BlockExecutionWeight = BlockExecutionWeight; 
+    type BaseCallFilter = ();
+    type DbWeight = RocksDbWeight;
+    type BlockExecutionWeight = BlockExecutionWeight;
     type ExtrinsicBaseWeight = ExtrinsicBaseWeight;
     type MaximumExtrinsicWeight = MaximumExtrinsicWeight;
     type Version = ();
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -1,6 +1,6 @@
 // Tests to be written here
 use crate::mock::*;
-use crate::{CollectionMode, Ownership};
+use crate::{ApprovePermissions, CollectionMode, Ownership};
 use frame_support::{assert_noop, assert_ok};
 
 #[test]
@@ -21,9 +21,13 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
-
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
-        assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
     });
 }
 
@@ -45,10 +49,111 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).data,
+            [1, 2, 3].to_vec()
+        );
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 1,
+                fraction: 1000
+            }
+        );
+    });
+}
+
+#[test]
+fn create_fungible_item() {
+    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::Fungible(3);
+
+        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,
+            [].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 1);
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+    });
+}
+
+#[test]
+fn transfer_fungible_item() {
+    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::Fungible(3);
+
+        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_eq!(TemplateModule::collection(1).owner, 1);
+
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 1);
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+
+        // change owner scenario
+        assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 2);
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 1000);
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(1, 2), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), []);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
 
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });
+        // split item scenario
+        assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 500));
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 2);
+        assert_eq!(TemplateModule::fungible_item_id(1, 2).owner, 3);
+        assert_eq!(TemplateModule::balance_count(1, 2), 500);
+        assert_eq!(TemplateModule::balance_count(1, 3), 500);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
+
+        // split item and new owner has account scenario
+        assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 200));
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 300);
+        assert_eq!(TemplateModule::fungible_item_id(1, 2).value, 700);
+        assert_eq!(TemplateModule::balance_count(1, 2), 300);
+        assert_eq!(TemplateModule::balance_count(1, 3), 700);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
     });
 }
 
@@ -71,40 +176,83 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });
-        assert_eq!(TemplateModule::balance_count(1,1), 1000);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).data,
+            [1, 2, 3].to_vec()
+        );
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 1,
+                fraction: 1000
+            }
+        );
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
         // change owner scenario
         assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 1000 });
-        assert_eq!(TemplateModule::balance_count(1,1), 0);
-        assert_eq!(TemplateModule::balance_count(1,2), 1000);
-        assert_eq!(TemplateModule::address_tokens(1,1), []);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]);
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 2,
+                fraction: 1000
+            }
+        );
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(1, 2), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), []);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
 
         // split item scenario
         assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 500));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 500 });
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[1], Ownership { owner: 3, fraction: 500 });
-        assert_eq!(TemplateModule::balance_count(1,2), 500);
-        assert_eq!(TemplateModule::balance_count(1,3), 500);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]);
-        assert_eq!(TemplateModule::address_tokens(1,3), [1]);
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 2,
+                fraction: 500
+            }
+        );
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[1],
+            Ownership {
+                owner: 3,
+                fraction: 500
+            }
+        );
+        assert_eq!(TemplateModule::balance_count(1, 2), 500);
+        assert_eq!(TemplateModule::balance_count(1, 3), 500);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
 
         // split item and new owner has account scenario
         assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 200));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 300 });
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[1], Ownership { owner: 3, fraction: 700 });
-        assert_eq!(TemplateModule::balance_count(1,2), 300);
-        assert_eq!(TemplateModule::balance_count(1,3), 700);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]);
-        assert_eq!(TemplateModule::address_tokens(1,3), [1]);
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 2,
+                fraction: 300
+            }
+        );
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[1],
+            Ownership {
+                owner: 3,
+                fraction: 700
+            }
+        );
+        assert_eq!(TemplateModule::balance_count(1, 2), 300);
+        assert_eq!(TemplateModule::balance_count(1, 3), 700);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
     });
 }
-
 
 #[test]
 fn transfer_nft_item() {
@@ -124,582 +272,673 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
-
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
-        assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());
-        assert_eq!(TemplateModule::balance_count(1,1), 1);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
+        assert_eq!(TemplateModule::balance_count(1, 1), 1);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
         // default scenario
         assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));
-        assert_eq!(TemplateModule::nft_item_id(1,1).owner, 2);
-        assert_eq!(TemplateModule::balance_count(1,1), 0);
-        assert_eq!(TemplateModule::balance_count(1,2), 1);
-        assert_eq!(TemplateModule::address_tokens(1,1), []);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]); 
+        assert_eq!(TemplateModule::nft_item_id(1, 1).owner, 2);
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(1, 2), 1);
+        assert_eq!(TemplateModule::address_tokens(1, 1), []);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
     });
 }
 
+#[test]
+fn nft_approve_and_transfer_from() {
+    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);
 
-// #[test]
-// fn create_collection_test() {
-//     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 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_eq!(TemplateModule::collection(1).owner, 1);
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_eq!(TemplateModule::collection(1).owner, 1);
-//     });
-// }
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
+        assert_eq!(TemplateModule::balance_count(1, 1), 1);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
-// #[test]
-// fn change_collection_owner() {
-//     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();
+        assert_noop!(
+            TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
+            "You do not have permissions to modify this collection"
+        );
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
+        // 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_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
+        assert_eq!(
+            TemplateModule::approved(1, (1, 1))[0],
+            ApprovePermissions {
+                approved: 2,
+                amount: 100000000
+            }
+        );
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::change_collection_owner(
-//             origin1.clone(),
-//             1,
-//             2
-//         ));
-//         assert_eq!(TemplateModule::collection(1).owner, 2);
-//     });
-// }
+        assert_ok!(TemplateModule::transfer_from(
+            origin2.clone(),
+            1,
+            3,
+            1,
+            1,
+            1
+        ));
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 0);
+    });
+}
 
-// #[test]
-// fn destroy_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();
+#[test]
+fn refungible_approve_and_transfer_from() {
+    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::ReFungible(2000, 3);
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
+        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_eq!(TemplateModule::collection(1).owner, 1);
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::destroy_collection(origin1.clone(), 1));
-//     });
-// }
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).data,
+            [1, 2, 3].to_vec()
+        );
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 1,
+                fraction: 1000
+            }
+        );
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
-// #[test]
-// fn create_item() {
-//     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();
+        assert_noop!(
+            TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
+            "You do not have permissions to modify this collection"
+        );
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
+        // 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_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
+        assert_eq!(
+            TemplateModule::approved(1, (1, 1))[0],
+            ApprovePermissions {
+                approved: 2,
+                amount: 100000000
+            }
+        );
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
-//         assert_ok!(TemplateModule::create_item(
-//             origin2.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
+        assert_ok!(TemplateModule::transfer_from(
+            origin2.clone(),
+            1,
+            3,
+            1,
+            1,
+            100
+        ));
+        assert_eq!(TemplateModule::balance_count(1, 1), 900);
+        assert_eq!(TemplateModule::balance_count(1, 3), 100);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
 
-//         // check balance (collection with id = 1, user id = 2)
-//         assert_eq!(TemplateModule::balance_count((1, 2)), 1);
-//     });
-// }
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
+        assert_eq!(
+            TemplateModule::approved(1, (1, 1))[0],
+            ApprovePermissions {
+                approved: 10,
+                amount: 100000000
+            }
+        );
+    });
+}
 
-// #[test]
-// fn burn_item() {
-//     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();
+#[test]
+fn fungible_approve_and_transfer_from() {
+    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::Fungible(3);
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
+        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_eq!(TemplateModule::collection(1).owner, 1);
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
-//         assert_ok!(TemplateModule::create_item(
-//             origin2.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 1);
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
-//         // check balance (collection with id = 1, user id = 2)
-//         assert_eq!(TemplateModule::balance_count((1, 2)), 1);
+        assert_noop!(
+            TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
+            "You do not have permissions to modify this collection"
+        );
 
-//         // burn item
-//         assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1));
-//         assert_noop!(
-//             TemplateModule::burn_item(origin1.clone(), 1, 1),
-//             "Item does not exists"
-//         );
+        // 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_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
+        assert_eq!(
+            TemplateModule::approved(1, (1, 1))[0],
+            ApprovePermissions {
+                approved: 2,
+                amount: 100000000
+            }
+        );
 
-//         assert_eq!(TemplateModule::balance_count((1, 1)), 0);
-//     });
-// }
+        assert_ok!(TemplateModule::transfer_from(
+            origin2.clone(),
+            1,
+            3,
+            1,
+            1,
+            100
+        ));
+        assert_eq!(TemplateModule::balance_count(1, 1), 900);
+        assert_eq!(TemplateModule::balance_count(1, 3), 100);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
 
-// #[test]
-// fn add_collection_admin() {
-//     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();
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
+        assert_eq!(
+            TemplateModule::approved(1, (1, 1))[0],
+            ApprovePermissions {
+                approved: 10,
+                amount: 100000000
+            }
+        );
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
-//         let origin3 = Origin::signed(3);
+        assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
+        assert_ok!(TemplateModule::transfer_from(
+            origin2.clone(),
+            1,
+            3,
+            1,
+            1,
+            900
+        ));
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(1, 3), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), []);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin2.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin3.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 0);
+    });
+}
 
-//         assert_eq!(TemplateModule::collection(1).owner, 1);
-//         assert_eq!(TemplateModule::collection(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
+#[test]
+fn change_collection_owner() {
+    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);
 
-//         // collection admin
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 3));
+        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::change_collection_owner(
+            origin1.clone(),
+            1,
+            2
+        ));
+        assert_eq!(TemplateModule::collection(1).owner, 2);
+    });
+}
 
-//         assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);
-//         assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);
-//     });
-// }
+#[test]
+fn destroy_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);
 
-// #[test]
-// fn remove_collection_admin() {
-//     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 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));
+    });
+}
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
-//         let origin3 = Origin::signed(3);
+#[test]
+fn burn_nft_item() {
+    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);
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin2.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin3.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
+        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::create_item(
+            origin2.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
 
-//         assert_eq!(TemplateModule::collection(1).owner, 1);
-//         assert_eq!(TemplateModule::collection(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
+        assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
 
-//         // collection admin
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 3));
+        // check balance (collection with id = 1, user id = 1)
+        assert_eq!(TemplateModule::balance_count(1, 1), 1);
 
-//         assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);
-//         assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);
+        // burn item
+        assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1));
+        assert_noop!(
+            TemplateModule::burn_item(origin1.clone(), 1, 1),
+            "Item does not exists"
+        );
 
-//         // remove admin
-//         assert_ok!(TemplateModule::remove_collection_admin(
-//             origin2.clone(),
-//             1,
-//             3
-//         ));
-//         assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), false);
-//     });
-// }
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+    });
+}
 
-// #[test]
-// fn balance_of() {
-//     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();
+#[test]
+fn burn_fungible_item() {
+    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::Fungible(3);
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
-//         let origin3 = Origin::signed(3);
+        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::create_item(
+            origin2.clone(),
+            1,
+            [].to_vec(),
+            1
+        ));
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin2.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin3.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
+        // check balance (collection with id = 1, user id = 1)
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
 
-//         assert_eq!(TemplateModule::collection(1).owner, 1);
-//         assert_eq!(TemplateModule::collection(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
+        // burn item
+        assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1));
+        assert_noop!(
+            TemplateModule::burn_item(origin1.clone(), 1, 1),
+            "Item does not exists"
+        );
 
-//         // check balance before
-//         assert_eq!(TemplateModule::balance_count((1, 1)), 0);
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+    });
+}
 
-//         // create item
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
+#[test]
+fn burn_refungible_item() {
+    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::ReFungible(200, 3);
 
-//         // check balance (collection with id = 1, user id = 2)
-//         assert_eq!(TemplateModule::balance_count((1, 1)), 1);
-//         assert_eq!(TemplateModule::item_id((1, 1)).owner, 1);
-//     });
-// }
+        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::create_item(
+            origin2.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
 
-// #[test]
-// fn transfer() {
-//     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();
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).data,
+            [1, 2, 3].to_vec()
+        );
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
-//         let origin3 = Origin::signed(3);
+        // check balance (collection with id = 1, user id = 2)
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin2.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin3.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
+        // burn item
+        assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1));
+        assert_noop!(
+            TemplateModule::burn_item(origin1.clone(), 1, 1),
+            "Item does not exists"
+        );
 
-//         assert_eq!(TemplateModule::collection(1).owner, 1);
-//         assert_eq!(TemplateModule::collection(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+    });
+}
 
-//         // create item
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
+#[test]
+fn add_collection_admin() {
+    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);
 
-//         // transfer
-//         assert_ok!(TemplateModule::transfer(origin1.clone(), 1, 1, 2));
-//         assert_eq!(TemplateModule::item_id((1, 1)).owner, 2);
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+        let origin3 = Origin::signed(3);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode.clone()
+        ));
+        assert_ok!(TemplateModule::create_collection(
+            origin2.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode.clone()
+        ));
+        assert_ok!(TemplateModule::create_collection(
+            origin3.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode.clone()
+        ));
 
-//         // balance_of check
-//         assert_eq!(TemplateModule::balance_count((1, 1)), 0);
-//         assert_eq!(TemplateModule::balance_count((1, 2)), 1);
-//     });
-// }
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+        assert_eq!(TemplateModule::collection(2).owner, 2);
+        assert_eq!(TemplateModule::collection(3).owner, 3);
 
-// #[test]
-// fn approve() {
-//     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();
+        // collection admin
+        assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 3));
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
-//         let origin3 = Origin::signed(3);
+        assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);
+        assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);
+    });
+}
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin2.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin3.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
+#[test]
+fn remove_collection_admin() {
+    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);
 
-//         assert_eq!(TemplateModule::collection(1).owner, 1);
-//         assert_eq!(TemplateModule::collection(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+        let origin3 = Origin::signed(3);
 
-//         // create item
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode.clone()
+        ));
+        assert_ok!(TemplateModule::create_collection(
+            origin2.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode.clone()
+        ));
+        assert_ok!(TemplateModule::create_collection(
+            origin3.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode.clone()
+        ));
 
-//         // approve
-//         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
-//         assert_eq!(TemplateModule::approved((1, 1)).contains(&2), true);
-//     });
-// }
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+        assert_eq!(TemplateModule::collection(2).owner, 2);
+        assert_eq!(TemplateModule::collection(3).owner, 3);
 
-// #[test]
-// fn get_approved() {
-//     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();
+        // collection admin
+        assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 3));
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
-//         let origin3 = Origin::signed(3);
+        assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);
+        assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin2.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin3.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
+        // remove admin
+        assert_ok!(TemplateModule::remove_collection_admin(
+            origin2.clone(),
+            1,
+            3
+        ));
+        assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), false);
+    });
+}
 
-//         assert_eq!(TemplateModule::collection(1).owner, 1);
-//         assert_eq!(TemplateModule::collection(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
+#[test]
+fn balance_of() {
+    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 nft_mode: CollectionMode = CollectionMode::NFT(2000);
+        let furg_mode: CollectionMode = CollectionMode::Fungible(3);
+        let refung_mode: CollectionMode = CollectionMode::ReFungible(2000, 3);
 
-//         // create item
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
+        let origin1 = Origin::signed(1);
 
-//         // approve
-//         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
-//         assert_eq!(TemplateModule::approved((1, 1)).contains(&2), true);
-//     });
-// }
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            nft_mode.clone()
+        ));
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            furg_mode.clone()
+        ));
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            refung_mode.clone()
+        ));
 
-// #[test]
-// fn transfer_from() {
-//     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();
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+        assert_eq!(TemplateModule::collection(2).owner, 1);
+        assert_eq!(TemplateModule::collection(3).owner, 1);
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
-//         let origin3 = Origin::signed(3);
+        // check balance before
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(2, 1), 0);
+        assert_eq!(TemplateModule::balance_count(3, 1), 0);
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin2.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin3.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
+        // create item
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 1, 1].to_vec(),
+            1
+        ));
 
-//         assert_eq!(TemplateModule::collection(1).owner, 1);
-//         assert_eq!(TemplateModule::collection(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            2,
+            [].to_vec(),
+            1
+        ));
 
-//         // create item
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            3,
+            [1, 1, 1].to_vec(),
+            1
+        ));
 
-//         // approve
-//         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
-//         assert_ok!(TemplateModule::transfer_from(origin1.clone(), 1, 1, 2));
-//     });
-// }
+        // check balance (collection with id = 1, user id = 1)
+        assert_eq!(TemplateModule::balance_count(1, 1), 1);
+        assert_eq!(TemplateModule::balance_count(2, 1), 1000);
+        assert_eq!(TemplateModule::balance_count(3, 1), 1000);
+        assert_eq!(TemplateModule::nft_item_id(1, 1).owner, 1);
+        assert_eq!(TemplateModule::fungible_item_id(2, 1).owner, 1);
+        assert_eq!(TemplateModule::refungible_item_id(3, 1).owner[0].owner, 1);
+    });
+}
 
-// #[test]
-// fn index_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();
+#[test]
+fn approve() {
+    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 nft_mode: CollectionMode = CollectionMode::NFT(2000);
+        let origin1 = Origin::signed(1);
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
-//         let origin3 = Origin::signed(3);
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            nft_mode.clone()
+        ));
 
-//         assert_ok!(TemplateModule::create_collection(
-//             origin1.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin2.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::create_collection(
-//             origin3.clone(),
-//             col_name1.clone(),
-//             col_desc1.clone(),
-//             token_prefix1.clone(),
-//             size
-//         ));
+        assert_eq!(TemplateModule::collection(1).owner, 1);
 
-//         assert_eq!(TemplateModule::collection(1).owner, 1);
-//         assert_eq!(TemplateModule::collection(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
-//         // create items
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 1, 2].to_vec()
-//         ));
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 2, 3].to_vec()
-//         ));
-//         assert_eq!(TemplateModule::address_tokens((1, 1)).len(), 3);
-//         // burn one
-//         assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 2));
-//         assert_eq!(TemplateModule::address_tokens((1, 1)).len(), 2);
-//         // burn another one
-//         assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 3));
-//         assert_eq!(TemplateModule::address_tokens((1, 1))[0], 1);
-//     });
-// }
+        // create item
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 1, 1].to_vec(),
+            1
+        ));
+
+        // approve
+        assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
+        assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);
+    });
+}
+
+#[test]
+fn transfer_from() {
+    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_eq!(TemplateModule::collection(1).owner, 1);
+
+        // create item
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 1, 1].to_vec(),
+            1
+        ));
+
+        // approve
+        assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
+        assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);
+        assert_ok!(TemplateModule::transfer_from(
+            origin2.clone(),
+            1,
+            2,
+            1,
+            1,
+            1
+        ));
+
+        // after transfer
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(1, 2), 1);
+    });
+}
modifiedruntime/build.rsdiffbeforeafterboth
--- a/runtime/build.rs
+++ b/runtime/build.rs
@@ -1,10 +1,10 @@
 use wasm_builder_runner::WasmBuilder;
 
 fn main() {
-	WasmBuilder::new()
-		.with_current_project()
-		.with_wasm_builder_from_crates("1.0.11")
-		.export_heap_base()
-		.import_memory()
-		.build()
+    WasmBuilder::new()
+        .with_current_project()
+        .with_wasm_builder_from_crates("1.0.11")
+        .export_heap_base()
+        .import_memory()
+        .build()
 }
modifiedruntime/src/lib.rsdiffbeforeafterboth
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -16,11 +16,12 @@
 use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
 use sp_runtime::{
     create_runtime_str, generic, impl_opaque_keys,
+    traits::{
+        BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating,
+        Verify,
+    },
     transaction_validity::{TransactionSource, TransactionValidity},
     ApplyExtrinsicResult, MultiSignature,
-	traits::{
-        BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,
-	},
 };
 use sp_std::prelude::*;
 #[cfg(feature = "std")]
@@ -31,22 +32,24 @@
 pub use balances::Call as BalancesCall;
 pub use contracts::Schedule as ContractsSchedule;
 pub use frame_support::{
-    construct_runtime, parameter_types,
-    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason},
+    construct_runtime,
+    dispatch::DispatchResult,
+    parameter_types,
+    traits::{
+        Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,
+        WithdrawReason,
+    },
     weights::{
-        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
-        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,
+        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
+        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
+        WeightToFeePolynomial,
     },
     StorageValue,
-	dispatch::DispatchResult,
 };
-use system::{self as system};
 #[cfg(any(feature = "std", test))]
 pub use sp_runtime::BuildStorage;
-use sp_runtime::{
-	Perbill,
-};
-
+use sp_runtime::Perbill;
+use system::{self as system};
 
 pub use timestamp::Call as TimestampCall;
 
@@ -190,7 +193,6 @@
     /// Version of the runtime.
     type Version = Version;
     /// Converts a module to the index of the module in `construct_runtime!`.
-    ///
     /// This type is being generated by `construct_runtime!`.
     type ModuleToIndex = ModuleToIndex;
     /// What to do if a new account is created.
@@ -493,4 +495,3 @@
         }
     }
 }
-