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

difftreelog

Unit tests added

str-mv2020-09-08parent: #aa92af0.patch.diff
in: master

3 files changed

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}124125#[derive(Encode, Decode, Default, Clone, PartialEq)]126#[cfg_attr(feature = "std", derive(Debug))]127pub struct ApprovePermissions<AccountId> {128    pub approved: AccountId,129    pub amount: u64130}131132pub trait Trait: system::Trait {133    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;134135}136137decl_storage! {138    trait Store for Module<T: Trait> as Nft {139140        // Private members141        NextCollectionID: u64;142        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;143144        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;145        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;146        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;147148        /// Balance owner per collection map149        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;150151        /// second parameter: item id + owner account id152        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;153154        /// Item collections155        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;156        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;157        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;158159        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;160161        // Sponsorship162        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;163        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;164    }165}166167decl_event!(168    pub enum Event<T>169    where170        AccountId = <T as system::Trait>::AccountId,171    {172        Created(u64, u8, AccountId),173        ItemCreated(u64, u64),174        ItemDestroyed(u64, u64),175    }176);177178decl_module! {179    pub struct Module<T: Trait> for enum Call where origin: T::Origin {180181        fn deposit_event() = default;182183        // Create collection of NFT with given parameters184        //185        // @param customDataSz size of custom data in each collection item186        // returns collection ID187        #[weight = 0]188        pub fn create_collection(   origin,189                                    collection_name: Vec<u16>,190                                    collection_description: Vec<u16>,191                                    token_prefix: Vec<u8>,192                                    mode: CollectionMode) -> DispatchResult {193194            // Anyone can create a collection195            let who = ensure_signed(origin)?;196            let custom_data_size = match mode {197                CollectionMode::NFT(size) => size,198                CollectionMode::ReFungible(size, _) => size,199                _ => 0200            };201202            let decimal_points = match mode {203                CollectionMode::Fungible(points) => points,204                CollectionMode::ReFungible(_, points) => points,205                _ => 0206            };207208            // check params209            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4"); 210211            let mut name = collection_name.to_vec();212            name.push(0);213            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");214215            let mut description = collection_description.to_vec();216            description.push(0);217            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");218219            let mut prefix = token_prefix.to_vec();220            prefix.push(0);221            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");222223            // Generate next collection ID224            let next_id = NextCollectionID::get()225                .checked_add(1)226                .expect("collection id error");227228            NextCollectionID::put(next_id);229230            // Create new collection231            let new_collection = CollectionType {232                owner: who.clone(),233                name: name,234                mode: mode.clone(),235                access: AccessMode::Normal,236                description: description,237                decimal_points: decimal_points,238                token_prefix: prefix,239                offchain_schema: Vec::new(),240                custom_data_size: custom_data_size,241                sponsor: T::AccountId::default(),242                unconfirmed_sponsor: T::AccountId::default(),243            };244245            // Add new collection to map246            <Collection<T>>::insert(next_id, new_collection);247248            // call event249            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));250251            Ok(())252        }253254        #[weight = 0]255        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {256257            let sender = ensure_signed(origin)?;258            Self::check_owner_permissions(collection_id, sender)?;259260            // TODO Items remove261            <AddressTokens<T>>::remove_prefix(collection_id);262            <ApprovedList<T>>::remove_prefix(collection_id);263            <Balance<T>>::remove_prefix(collection_id);264            <ItemListIndex>::remove(collection_id);265            <AdminList<T>>::remove(collection_id);266            <Collection<T>>::remove(collection_id);267            <WhiteList<T>>::remove(collection_id);268269            Ok(())270        }271272        #[weight = 0]273        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {274275            let sender = ensure_signed(origin)?;276            Self::check_owner_permissions(collection_id, sender)?;277            let mut target_collection = <Collection<T>>::get(collection_id);278            target_collection.owner = new_owner;279            <Collection<T>>::insert(collection_id, target_collection);280281            Ok(())282        }283284        #[weight = 0]285        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {286287            let sender = ensure_signed(origin)?;288            Self::check_owner_or_admin_permissions(collection_id, sender)?;289            let mut admin_arr: Vec<T::AccountId> = Vec::new();290291            if <AdminList<T>>::contains_key(collection_id)292            {293                admin_arr = <AdminList<T>>::get(collection_id);294                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");295            }296297            admin_arr.push(new_admin_id);298            <AdminList<T>>::insert(collection_id, admin_arr);299300            Ok(())301        }302303        #[weight = 0]304        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {305306            let sender = ensure_signed(origin)?;307            Self::check_owner_or_admin_permissions(collection_id, sender)?;308309            if <AdminList<T>>::contains_key(collection_id)310            {311                let mut admin_arr = <AdminList<T>>::get(collection_id);312                admin_arr.retain(|i| *i != account_id);313                <AdminList<T>>::insert(collection_id, admin_arr);314            }315316            Ok(())317        }318319        #[weight = 0]320        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {321322            let sender = ensure_signed(origin)?;323            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");324325            let mut target_collection = <Collection<T>>::get(collection_id);326            ensure!(sender == target_collection.owner, "You do not own this collection");327328            target_collection.unconfirmed_sponsor = new_sponsor;329            <Collection<T>>::insert(collection_id, target_collection);330331            Ok(())332        }333334        #[weight = 0]335        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {336337            let sender = ensure_signed(origin)?;338            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");339340            let mut target_collection = <Collection<T>>::get(collection_id);341            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");342343            target_collection.sponsor = target_collection.unconfirmed_sponsor;344            target_collection.unconfirmed_sponsor = T::AccountId::default();345            <Collection<T>>::insert(collection_id, target_collection);346347            Ok(())348        }349350        #[weight = 0]351        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {352353            let sender = ensure_signed(origin)?;354            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");355356            let mut target_collection = <Collection<T>>::get(collection_id);357            ensure!(sender == target_collection.owner, "You do not own this collection");358359            target_collection.sponsor = T::AccountId::default();360            <Collection<T>>::insert(collection_id, target_collection);361362            Ok(())363        }364        365        #[weight = 0]366        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {367368            let sender = ensure_signed(origin)?;369            let target_collection = <Collection<T>>::get(collection_id);370            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;371372            // TODO: implement other modes373            match target_collection.mode 374            {375                CollectionMode::NFT(_) => {376377                    // check size378                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");379380                    // Create nft item381                    let item = NftItemType {382                        collection: collection_id,383                        owner: owner,384                        data: properties,385                    };386    387                    Self::add_nft_item(item)?;388    389                },390                CollectionMode::Fungible(_) => {391392                    // check size393                    ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");394395                    let item = FungibleItemType {396                        collection: collection_id,397                        owner: owner,398                        value: (10 as u128).pow(target_collection.decimal_points)399                    };400    401                    Self::add_fungible_item(item)?;402                },403                CollectionMode::ReFungible(_, _) => {404405                    // check size406                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");407408                    let mut owner_list = Vec::new();409                    let value = (10 as u128).pow(target_collection.decimal_points);410                    owner_list.push(Ownership {owner: owner, fraction: value});411412                    let item = ReFungibleItemType {413                        collection: collection_id,414                        owner: owner_list,415                        data: properties416                    };417    418                    Self::add_refungible_item(item)?;419                },420                _ => ()421            };422423            // call event424            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));425426            Ok(())427        }428429        #[weight = 0]430        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {431432            let sender = ensure_signed(origin)?;433            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);434            if !item_owner435            {436                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;437            }438            let target_collection = <Collection<T>>::get(collection_id);439440            match target_collection.mode 441            {442                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,443                CollectionMode::Fungible(_)  => Self::burn_fungible_item(collection_id, item_id)?,444                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,445                _ => ()446            };447448            // call event449            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));450451            Ok(())452        }453454        #[weight = 0]455        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {456457            let sender = ensure_signed(origin)?;458            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");459460            let target_collection = <Collection<T>>::get(collection_id);461462            // TODO: implement other modes463            match target_collection.mode 464            {465                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,466                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,467                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,468                _ => ()469            };470471            Ok(())472        }473474        #[weight = 0]475        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {476477            let sender = ensure_signed(origin)?;478479            // amount param stub480            let amount = 100000000;481482            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");483484            let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));485            if list_exists {486487                let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));488                let item_contains = list.iter().any(|i| i.approved == approved);489490                if !item_contains {491                    list.push(ApprovePermissions { approved: approved.clone(), amount: amount });492                    <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);493                }494            } else {495496                let mut list = Vec::new();497                list.push(ApprovePermissions { approved: approved.clone(), amount: amount });498                <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);499            }500501            Ok(())502        }503504        #[weight = 0]505        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {506507            let sender = ensure_signed(origin)?;508            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));509            if approved_list_exists510            {511                let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));512                let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());513                ensure!(opt_item.is_some(), "No approve found"); 514                ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved"); 515516                // remove approve517                let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))518                    .into_iter().filter(|i| i.approved != sender.clone()).collect();519                <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);520            }521            else522            {523                Self::check_owner_or_admin_permissions(collection_id, sender)?;524            }525            526            let target_collection = <Collection<T>>::get(collection_id);527528            match target_collection.mode529            {530                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,531                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,532                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,533                _ => ()534            };535536            Ok(())537        }538539        #[weight = 0]540        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {541542            // let no_perm_mes = "You do not have permissions to modify this collection";543            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);544            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));545            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);546547            // // on_nft_received  call548549            // Self::transfer(origin, collection_id, item_id, new_owner)?;550551            Ok(())552        }553554        #[weight = 0]555        pub fn set_offchain_schema(556            origin,557            collection_id: u64,558            schema: Vec<u8>559        ) -> DispatchResult {560            let sender = ensure_signed(origin)?;561            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;562            563            let mut target_collection = <Collection<T>>::get(collection_id);564            target_collection.offchain_schema = schema;565            <Collection<T>>::insert(collection_id, target_collection);566567            Ok(())        568        }569    }570}571572impl<T: Trait> Module<T> {573574    fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {575576        let current_index = <ItemListIndex>::get(item.collection)577        .checked_add(1)578        .expect("Item list index id error");579        let itemcopy = item.clone();580        let owner = item.owner.clone();581        let value = item.value as u64;582583        Self::add_token_index(item.collection, current_index, owner.clone())?;584585        <ItemListIndex>::insert(item.collection, current_index);586        <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);  587        588        // Update balance589       let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();590       <Balance<T>>::insert(item.collection, owner.clone(), new_balance);591592        Ok(())593    }594595    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {596597        let current_index = <ItemListIndex>::get(item.collection)598        .checked_add(1)599        .expect("Item list index id error");600        let itemcopy = item.clone();601602        let value = item.owner.first().unwrap().fraction as u64;603        let owner = item.owner.first().unwrap().owner.clone();604605        Self::add_token_index(item.collection, current_index, owner.clone())?;606607        <ItemListIndex>::insert(item.collection, current_index);608        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);  609        610        // Update balance611       let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();612       <Balance<T>>::insert(item.collection, owner.clone(), new_balance);613614        Ok(())615    }616617    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {618619        let current_index = <ItemListIndex>::get(item.collection)620        .checked_add(1)621        .expect("Item list index id error");622623        let item_owner = item.owner.clone();624        let collection_id = item.collection.clone();625        Self::add_token_index(collection_id, current_index, item.owner.clone())?;626627        <ItemListIndex>::insert(collection_id, current_index);628        <NftItemList<T>>::insert(collection_id, current_index, item);629630        // Update balance631        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone()).checked_add(1).unwrap();632        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);633634        Ok(())635    }636637    fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {638  639        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);640        let item = collection.owner.iter().filter(|&i| i.owner == owner).next().unwrap();641        Self::remove_token_index(collection_id, item_id, owner.clone())?;642643        // remove approve list644        <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));645646        // update balance647        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();648        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);649650651        <ReFungibleItemList<T>>::remove(collection_id, item_id);652653        Ok(())654    }655656    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {657  658        let item = <NftItemList<T>>::get(collection_id, item_id);659        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;660661        // remove approve list662        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));663664        // update balance665        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();666        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);667        <NftItemList<T>>::remove(collection_id, item_id);668669        Ok(())670    }671672    fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {673  674        let item = <FungibleItemList<T>>::get(collection_id, item_id);675        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;676677        // remove approve list678        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));679680        // update balance681        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.value as u64).unwrap();682        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);683684        <FungibleItemList<T>>::remove(collection_id, item_id);685686        Ok(())        687    }688689    fn collection_exists(collection_id: u64) -> DispatchResult{690        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");691        Ok(())692    }693694    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {695696        Self::collection_exists(collection_id)?;697698        let target_collection = <Collection<T>>::get(collection_id);699        ensure!(subject == target_collection.owner, "You do not own this collection");700701        Ok(())702    }703704    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {705706        Self::collection_exists(collection_id)?;707708        let target_collection = <Collection<T>>::get(collection_id);709        let is_owner = subject == target_collection.owner;710711        let no_perm_mes = "You do not have permissions to modify this collection";712        let exists = <AdminList<T>>::contains_key(collection_id);713714        if !is_owner715        {716            ensure!(exists, no_perm_mes);717            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);718        }719        Ok(())720    }721722    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{723724        let target_collection = <Collection<T>>::get(collection_id);725726        match target_collection.mode {727            CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,728            CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,729            CollectionMode::ReFungible(_, _)  => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),730            CollectionMode::Invalid => false731        }732    }733734    fn transfer_fungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {735        let full_item = <FungibleItemList<T>>::get(collection_id, item_id);736        let amount = full_item.value;737738        ensure!(amount >= value.into(),"Item balance not enouth");739740        // update balance741        let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone()).checked_sub(value).unwrap();742        <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);743744        let mut new_owner_account_id = 0;745        let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());746        if new_owner_items.len() > 0 {747            new_owner_account_id = new_owner_items[0];748        }749750        let val64 = value.into();751752        // transfer753        if amount == val64 && new_owner_account_id == 0754        {755            // change owner756            // new owner do not have account757            let mut new_full_item = full_item.clone();758            new_full_item.owner = new_owner.clone();759            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);760761            // update balance762            let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();763            <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);764765            // update index collection766            Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;767        }768        else769        {770            let mut new_full_item = full_item.clone();771            new_full_item.value -= val64;772773            // separate amount774            if new_owner_account_id > 0 {775776                // new owner has account777                let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);778                item.value += val64;779780                // update balance781                let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();782                <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);783784                <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);785            }786            else787            {788                // new owner do not have account789                let item = FungibleItemType {790                    collection: collection_id,791                    owner: new_owner.clone(),792                    value: val64793                };794795                Self::add_fungible_item(item)?;796            }797798            if amount == val64{799                Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;800        801                // remove approve list802                <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));803                <FungibleItemList<T>>::remove(collection_id, item_id);804            }805806            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);807        }808809        Ok(())810    }811812    fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {813        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);814        let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();815        let amount = item.fraction;816817        ensure!(amount >= value.into(),"Item balance not enouth");818819        // update balance820        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();821        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);822823        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();824        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);825826        let old_owner = item.owner.clone();827        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);828        let val64 = value.into();829830        // transfer831        if amount == val64 && !new_owner_has_account832        {833            // change owner834            // new owner do not have account835            let mut new_full_item = full_item.clone();836            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();837            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);838839            // update index collection840            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;841        }842        else843        {844            let mut new_full_item = full_item.clone();845            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= val64;846847            // separate amount848            if new_owner_has_account {849                // new owner has account850                new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += val64;851            }852            else853            {854                // new owner do not have account855                new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: val64});856                Self::add_token_index(collection_id, item_id, new_owner.clone())?;857            }858859            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);860        }861862        Ok(())863    }864865    fn transfer_nft(collection_id: u64, item_id: u64, sender: T::AccountId, new_owner: T::AccountId) -> DispatchResult {866867        let mut item = <NftItemList<T>>::get(collection_id, item_id);868869        ensure!(sender == item.owner,"sender parameter and item owner must be equal");870871        // update balance872        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();873        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);874875        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();876        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);877878        // change owner879        let old_owner = item.owner.clone();880        item.owner = new_owner.clone();881        <NftItemList<T>>::insert(collection_id, item_id, item);882883        // update index collection884        Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;885886        // reset approved list887        <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));888        Ok(())889    }890891    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {892        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());893        if list_exists {894            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());895            let item_contains = list.contains(&item_index.clone());896897            if !item_contains {898                list.push(item_index.clone());899            }900901            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);902        } else {903            let mut itm = Vec::new();904            itm.push(item_index.clone());905            <AddressTokens<T>>::insert(collection_id, owner, itm);906        }907908        Ok(())909    }910911    fn remove_token_index(912        collection_id: u64,913        item_index: u64,914        owner: T::AccountId,915    ) -> DispatchResult {916        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());917        if list_exists {918            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());919            let item_contains = list.contains(&item_index.clone());920921            if item_contains {922                list.retain(|&item| item != item_index);923                <AddressTokens<T>>::insert(collection_id, owner, list);924            }925        }926927        Ok(())928    }929930    fn move_token_index(931        collection_id: u64,932        item_index: u64,933        old_owner: T::AccountId,934        new_owner: T::AccountId,935    ) -> DispatchResult {936        Self::remove_token_index(collection_id, item_index, old_owner)?;937        Self::add_token_index(collection_id, item_index, new_owner)?;938939        Ok(())940    }941}942943944////////////////////////////////////////////////////////////////////////////////////////////////////945// Economic models946947/// Fee multiplier.948pub type Multiplier = FixedU128;949950type BalanceOf<T> =951	<<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;952type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<953	<T as system::Trait>::AccountId,>>::NegativeImbalance;954955956957/// Require the transactor pay for themselves and maybe include a tip to gain additional priority958/// in the queue.959#[derive(Encode, Decode, Clone, Eq, PartialEq)]960pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);961962impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {963	#[cfg(feature = "std")]964	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {965		write!(f, "ChargeTransactionPayment<{:?}>", self.0)966	}967	#[cfg(not(feature = "std"))]968	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {969		Ok(())970	}971}972973impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where974	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,975	BalanceOf<T>: Send + Sync + FixedPointOperand,976{977	/// utility constructor. Used only in client/factory code.978	pub fn from(fee: BalanceOf<T>) -> Self {979		Self(fee)980	}981982    pub fn traditional_fee(983        len: usize,984        info: &DispatchInfoOf<T::Call>,985        tip: BalanceOf<T>,986    ) -> BalanceOf<T> where987        T::Call: Dispatchable<Info=DispatchInfo>,988    {989        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)990    }991992	fn withdraw_fee(993		&self,994        who: &T::AccountId,995        call: &T::Call,996		info: &DispatchInfoOf<T::Call>,997		len: usize,998	) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {999        let tip = self.0;10001001        // Set fee based on call type. Creating collection costs 1 Unique.1002        // All other transactions have traditional fees so far1003        let fee = match call.is_sub_type() {1004            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1005            _ => Self::traditional_fee(len, info, tip)10061007            // Flat fee model, use only for testing purposes1008            // _ => <BalanceOf<T>>::from(100)1009        };10101011        // Determine who is paying transaction fee based on ecnomic model1012        // Parse call to extract collection ID and access collection sponsor1013        let sponsor: T::AccountId = match call.is_sub_type() {1014            Some(Call::create_item(collection_id, _properties, _owner)) => {1015                <Collection<T>>::get(collection_id).sponsor1016            },1017            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1018                <Collection<T>>::get(collection_id).sponsor1019            },10201021            _ => T::AccountId::default()1022        };10231024        let mut who_pays_fee: T::AccountId = sponsor.clone();1025        if sponsor == T::AccountId::default() {1026            who_pays_fee = who.clone();1027        }10281029		// Only mess with balances if fee is not zero.1030		if fee.is_zero() {1031			return Ok((fee, None));1032		}10331034		match <T as transaction_payment::Trait>::Currency::withdraw(1035			&who_pays_fee,1036			fee,1037			if tip.is_zero() {1038				WithdrawReason::TransactionPayment.into()1039			} else {1040				WithdrawReason::TransactionPayment | WithdrawReason::Tip1041			},1042			ExistenceRequirement::KeepAlive,1043		) {1044			Ok(imbalance) => Ok((fee, Some(imbalance))),1045			Err(_) => Err(InvalidTransaction::Payment.into()),1046		}1047	}1048}10491050impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where1051    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1052    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,1053{1054	const IDENTIFIER: &'static str = "ChargeTransactionPayment";1055	type AccountId = T::AccountId;1056	type Call = T::Call;1057	type AdditionalSigned = ();1058	type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);1059	fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }10601061	fn validate(1062		&self,1063		who: &Self::AccountId,1064		call: &Self::Call,1065		info: &DispatchInfoOf<Self::Call>,1066		len: usize,1067	) -> TransactionValidity {1068		let (fee, _) = self.withdraw_fee(who, call, info, len)?;10691070		let mut r = ValidTransaction::default();1071		// NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1072		// will be a bit more than setting the priority to tip. For now, this is enough.1073		r.priority = fee.saturated_into::<TransactionPriority>();1074		Ok(r)1075	}10761077	fn pre_dispatch(1078		self,1079		who: &Self::AccountId,1080		call: &Self::Call,1081		info: &DispatchInfoOf<Self::Call>,1082		len: usize1083	) -> Result<Self::Pre, TransactionValidityError> {1084		let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1085		Ok((self.0, who.clone(), imbalance, fee))1086	}10871088	fn post_dispatch(1089		pre: Self::Pre,1090		info: &DispatchInfoOf<Self::Call>,1091		post_info: &PostDispatchInfoOf<Self::Call>,1092		len: usize,1093		_result: &DispatchResult,1094	) -> Result<(), TransactionValidityError> {1095		let (tip, who, imbalance, fee) = pre;1096		if let Some(payed) = imbalance {1097			let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1098				len as u32,1099				info,1100				post_info,1101				tip,1102			);1103			let refund = fee.saturating_sub(actual_fee);1104			let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {1105				Ok(refund_imbalance) => {1106					// The refund cannot be larger than the up front payed max weight.1107					// `PostDispatchInfo::calc_unspent` guards against such a case.1108					match payed.offset(refund_imbalance) {1109						Ok(actual_payment) => actual_payment,1110						Err(_) => return Err(InvalidTransaction::Payment.into()),1111					}1112				}1113				// We do not recreate the account using the refund. The up front payment1114				// is gone in that case.1115				Err(_) => payed,1116			};1117			let imbalances = actual_payment.split(tip);1118			<T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()1119				.chain(Some(imbalances.1)));1120		}1121		Ok(())1122	}1123}
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.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}124125#[derive(Encode, Decode, Default, Clone, PartialEq)]126#[cfg_attr(feature = "std", derive(Debug))]127pub struct ApprovePermissions<AccountId> {128    pub approved: AccountId,129    pub amount: u64130}131132#[derive(Encode, Decode, Default, Clone, PartialEq)]133#[cfg_attr(feature = "std", derive(Debug))]134pub struct VestingItem<AccountId, Moment>135{136    pub sender: AccountId,137    pub recipient: AccountId,138    pub collection_id: u64,139    pub item_id: u64,140    pub amount: u64,141    pub vesting_date: Moment142}143144pub trait Trait: system::Trait {145    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;146147}148149decl_storage! {150    trait Store for Module<T: Trait> as Nft {151152        // Private members153        NextCollectionID: u64;154        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;155156        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;157        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;158        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;159160        /// Balance owner per collection map161        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;162163        /// second parameter: item id + owner account id164        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;165166        /// Item collections167        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;168        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;169        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;170171        // Active vesting list172        // pub VestingList get(fn vesting): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => VestingItem<T::AccountId, T::Moment>;173174        /// Index list175        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;176177        // Sponsorship178        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;179        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;180    }181}182183decl_event!(184    pub enum Event<T>185    where186        AccountId = <T as system::Trait>::AccountId,187    {188        Created(u64, u8, AccountId),189        ItemCreated(u64, u64),190        ItemDestroyed(u64, u64),191    }192);193194decl_module! {195    pub struct Module<T: Trait> for enum Call where origin: T::Origin {196197        fn deposit_event() = default;198199        // Create collection of NFT with given parameters200        //201        // @param customDataSz size of custom data in each collection item202        // returns collection ID203        #[weight = 0]204        pub fn create_collection(   origin,205                                    collection_name: Vec<u16>,206                                    collection_description: Vec<u16>,207                                    token_prefix: Vec<u8>,208                                    mode: CollectionMode) -> DispatchResult {209210            // Anyone can create a collection211            let who = ensure_signed(origin)?;212            let custom_data_size = match mode {213                CollectionMode::NFT(size) => size,214                CollectionMode::ReFungible(size, _) => size,215                _ => 0216            };217218            let decimal_points = match mode {219                CollectionMode::Fungible(points) => points,220                CollectionMode::ReFungible(_, points) => points,221                _ => 0222            };223224            // check params225            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4"); 226227            let mut name = collection_name.to_vec();228            name.push(0);229            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");230231            let mut description = collection_description.to_vec();232            description.push(0);233            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");234235            let mut prefix = token_prefix.to_vec();236            prefix.push(0);237            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");238239            // Generate next collection ID240            let next_id = NextCollectionID::get()241                .checked_add(1)242                .expect("collection id error");243244            NextCollectionID::put(next_id);245246            // Create new collection247            let new_collection = CollectionType {248                owner: who.clone(),249                name: name,250                mode: mode.clone(),251                access: AccessMode::Normal,252                description: description,253                decimal_points: decimal_points,254                token_prefix: prefix,255                offchain_schema: Vec::new(),256                custom_data_size: custom_data_size,257                sponsor: T::AccountId::default(),258                unconfirmed_sponsor: T::AccountId::default(),259            };260261            // Add new collection to map262            <Collection<T>>::insert(next_id, new_collection);263264            // call event265            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));266267            Ok(())268        }269270        #[weight = 0]271        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {272273            let sender = ensure_signed(origin)?;274            Self::check_owner_permissions(collection_id, sender)?;275276            // TODO Items remove277            <AddressTokens<T>>::remove_prefix(collection_id);278            <ApprovedList<T>>::remove_prefix(collection_id);279            <Balance<T>>::remove_prefix(collection_id);280            <ItemListIndex>::remove(collection_id);281            <AdminList<T>>::remove(collection_id);282            <Collection<T>>::remove(collection_id);283            <WhiteList<T>>::remove(collection_id);284285            Ok(())286        }287288        #[weight = 0]289        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {290291            let sender = ensure_signed(origin)?;292            Self::check_owner_permissions(collection_id, sender)?;293            let mut target_collection = <Collection<T>>::get(collection_id);294            target_collection.owner = new_owner;295            <Collection<T>>::insert(collection_id, target_collection);296297            Ok(())298        }299300        #[weight = 0]301        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {302303            let sender = ensure_signed(origin)?;304            Self::check_owner_or_admin_permissions(collection_id, sender)?;305            let mut admin_arr: Vec<T::AccountId> = Vec::new();306307            if <AdminList<T>>::contains_key(collection_id)308            {309                admin_arr = <AdminList<T>>::get(collection_id);310                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");311            }312313            admin_arr.push(new_admin_id);314            <AdminList<T>>::insert(collection_id, admin_arr);315316            Ok(())317        }318319        #[weight = 0]320        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {321322            let sender = ensure_signed(origin)?;323            Self::check_owner_or_admin_permissions(collection_id, sender)?;324325            if <AdminList<T>>::contains_key(collection_id)326            {327                let mut admin_arr = <AdminList<T>>::get(collection_id);328                admin_arr.retain(|i| *i != account_id);329                <AdminList<T>>::insert(collection_id, admin_arr);330            }331332            Ok(())333        }334335        #[weight = 0]336        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {337338            let sender = ensure_signed(origin)?;339            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");340341            let mut target_collection = <Collection<T>>::get(collection_id);342            ensure!(sender == target_collection.owner, "You do not own this collection");343344            target_collection.unconfirmed_sponsor = new_sponsor;345            <Collection<T>>::insert(collection_id, target_collection);346347            Ok(())348        }349350        #[weight = 0]351        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {352353            let sender = ensure_signed(origin)?;354            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");355356            let mut target_collection = <Collection<T>>::get(collection_id);357            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");358359            target_collection.sponsor = target_collection.unconfirmed_sponsor;360            target_collection.unconfirmed_sponsor = T::AccountId::default();361            <Collection<T>>::insert(collection_id, target_collection);362363            Ok(())364        }365366        #[weight = 0]367        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {368369            let sender = ensure_signed(origin)?;370            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");371372            let mut target_collection = <Collection<T>>::get(collection_id);373            ensure!(sender == target_collection.owner, "You do not own this collection");374375            target_collection.sponsor = T::AccountId::default();376            <Collection<T>>::insert(collection_id, target_collection);377378            Ok(())379        }380        381        #[weight = 0]382        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {383384            let sender = ensure_signed(origin)?;385            let target_collection = <Collection<T>>::get(collection_id);386            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;387388            // TODO: implement other modes389            match target_collection.mode 390            {391                CollectionMode::NFT(_) => {392393                    // check size394                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");395396                    // Create nft item397                    let item = NftItemType {398                        collection: collection_id,399                        owner: owner,400                        data: properties,401                    };402    403                    Self::add_nft_item(item)?;404    405                },406                CollectionMode::Fungible(_) => {407408                    // check size409                    ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");410411                    let item = FungibleItemType {412                        collection: collection_id,413                        owner: owner,414                        value: (10 as u128).pow(target_collection.decimal_points)415                    };416    417                    Self::add_fungible_item(item)?;418                },419                CollectionMode::ReFungible(_, _) => {420421                    // check size422                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");423424                    let mut owner_list = Vec::new();425                    let value = (10 as u128).pow(target_collection.decimal_points);426                    owner_list.push(Ownership {owner: owner, fraction: value});427428                    let item = ReFungibleItemType {429                        collection: collection_id,430                        owner: owner_list,431                        data: properties432                    };433    434                    Self::add_refungible_item(item)?;435                },436                _ => ()437            };438439            // call event440            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));441442            Ok(())443        }444445        #[weight = 0]446        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {447448            let sender = ensure_signed(origin)?;449            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);450            if !item_owner451            {452                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;453            }454            let target_collection = <Collection<T>>::get(collection_id);455456            match target_collection.mode 457            {458                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,459                CollectionMode::Fungible(_)  => Self::burn_fungible_item(collection_id, item_id)?,460                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,461                _ => ()462            };463464            // call event465            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));466467            Ok(())468        }469470        #[weight = 0]471        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {472473            let sender = ensure_signed(origin)?;474            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");475476            let target_collection = <Collection<T>>::get(collection_id);477478            // TODO: implement other modes479            match target_collection.mode 480            {481                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,482                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,483                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,484                _ => ()485            };486487            Ok(())488        }489490        #[weight = 0]491        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {492493            let sender = ensure_signed(origin)?;494495            // amount param stub496            let amount = 100000000;497498            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");499500            let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));501            if list_exists {502503                let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));504                let item_contains = list.iter().any(|i| i.approved == approved);505506                if !item_contains {507                    list.push(ApprovePermissions { approved: approved.clone(), amount: amount });508                    <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);509                }510            } else {511512                let mut list = Vec::new();513                list.push(ApprovePermissions { approved: approved.clone(), amount: amount });514                <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);515            }516517            Ok(())518        }519520        #[weight = 0]521        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {522523            let sender = ensure_signed(origin)?;524            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));525            if approved_list_exists526            {527                let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));528                let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());529                ensure!(opt_item.is_some(), "No approve found"); 530                ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved"); 531532                // remove approve533                let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))534                    .into_iter().filter(|i| i.approved != sender.clone()).collect();535                <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);536            }537            else538            {539                Self::check_owner_or_admin_permissions(collection_id, sender)?;540            }541            542            let target_collection = <Collection<T>>::get(collection_id);543544            match target_collection.mode545            {546                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,547                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,548                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,549                _ => ()550            };551552            Ok(())553        }554555        #[weight = 0]556        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {557558            // let no_perm_mes = "You do not have permissions to modify this collection";559            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);560            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));561            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);562563            // // on_nft_received  call564565            // Self::transfer(origin, collection_id, item_id, new_owner)?;566567            Ok(())568        }569570        #[weight = 0]571        pub fn set_offchain_schema(572            origin,573            collection_id: u64,574            schema: Vec<u8>575        ) -> DispatchResult {576            let sender = ensure_signed(origin)?;577            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;578            579            let mut target_collection = <Collection<T>>::get(collection_id);580            target_collection.offchain_schema = schema;581            <Collection<T>>::insert(collection_id, target_collection);582583            Ok(())        584        }585    }586}587588impl<T: Trait> Module<T> {589590    fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {591592        let current_index = <ItemListIndex>::get(item.collection)593        .checked_add(1)594        .expect("Item list index id error");595        let itemcopy = item.clone();596        let owner = item.owner.clone();597        let value = item.value as u64;598599        Self::add_token_index(item.collection, current_index, owner.clone())?;600601        <ItemListIndex>::insert(item.collection, current_index);602        <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);  603        604        // Update balance605       let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();606       <Balance<T>>::insert(item.collection, owner.clone(), new_balance);607608        Ok(())609    }610611    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {612613        let current_index = <ItemListIndex>::get(item.collection)614        .checked_add(1)615        .expect("Item list index id error");616        let itemcopy = item.clone();617618        let value = item.owner.first().unwrap().fraction as u64;619        let owner = item.owner.first().unwrap().owner.clone();620621        Self::add_token_index(item.collection, current_index, owner.clone())?;622623        <ItemListIndex>::insert(item.collection, current_index);624        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);  625        626        // Update balance627       let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();628       <Balance<T>>::insert(item.collection, owner.clone(), new_balance);629630        Ok(())631    }632633    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {634635        let current_index = <ItemListIndex>::get(item.collection)636        .checked_add(1)637        .expect("Item list index id error");638639        let item_owner = item.owner.clone();640        let collection_id = item.collection.clone();641        Self::add_token_index(collection_id, current_index, item.owner.clone())?;642643        <ItemListIndex>::insert(collection_id, current_index);644        <NftItemList<T>>::insert(collection_id, current_index, item);645646        // Update balance647        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone()).checked_add(1).unwrap();648        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);649650        Ok(())651    }652653    fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {654  655        ensure!(<ReFungibleItemList<T>>::contains_key(collection_id, item_id), "Item does not exists");656        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);657        let item = collection.owner.iter().filter(|&i| i.owner == owner).next().unwrap();658        Self::remove_token_index(collection_id, item_id, owner.clone())?;659660        // remove approve list661        <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));662663        // update balance664        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();665        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);666667668        <ReFungibleItemList<T>>::remove(collection_id, item_id);669670        Ok(())671    }672673    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {674  675        ensure!(<NftItemList<T>>::contains_key(collection_id, item_id), "Item does not exists");676        let item = <NftItemList<T>>::get(collection_id, item_id);677        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;678679        // remove approve list680        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));681682        // update balance683        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();684        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);685        <NftItemList<T>>::remove(collection_id, item_id);686687        Ok(())688    }689690    fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {691  692        ensure!(<FungibleItemList<T>>::contains_key(collection_id, item_id), "Item does not exists");693        let item = <FungibleItemList<T>>::get(collection_id, item_id);694        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;695696        // remove approve list697        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));698699        // update balance700        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.value as u64).unwrap();701        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);702703        <FungibleItemList<T>>::remove(collection_id, item_id);704705        Ok(())        706    }707708    fn collection_exists(collection_id: u64) -> DispatchResult{709        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");710        Ok(())711    }712713    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {714715        Self::collection_exists(collection_id)?;716717        let target_collection = <Collection<T>>::get(collection_id);718        ensure!(subject == target_collection.owner, "You do not own this collection");719720        Ok(())721    }722723    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {724725        Self::collection_exists(collection_id)?;726727        let target_collection = <Collection<T>>::get(collection_id);728        let is_owner = subject == target_collection.owner;729730        let no_perm_mes = "You do not have permissions to modify this collection";731        let exists = <AdminList<T>>::contains_key(collection_id);732733        if !is_owner734        {735            ensure!(exists, no_perm_mes);736            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);737        }738        Ok(())739    }740741    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{742743        let target_collection = <Collection<T>>::get(collection_id);744745        match target_collection.mode {746            CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,747            CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,748            CollectionMode::ReFungible(_, _)  => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),749            CollectionMode::Invalid => false750        }751    }752753    fn transfer_fungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {754        let full_item = <FungibleItemList<T>>::get(collection_id, item_id);755        let amount = full_item.value;756757        ensure!(amount >= value.into(),"Item balance not enouth");758759        // update balance760        let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone()).checked_sub(value).unwrap();761        <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);762763        let mut new_owner_account_id = 0;764        let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());765        if new_owner_items.len() > 0 {766            new_owner_account_id = new_owner_items[0];767        }768769        let val64 = value.into();770771        // transfer772        if amount == val64 && new_owner_account_id == 0773        {774            // change owner775            // new owner do not have account776            let mut new_full_item = full_item.clone();777            new_full_item.owner = new_owner.clone();778            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);779780            // update balance781            let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();782            <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);783784            // update index collection785            Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;786        }787        else788        {789            let mut new_full_item = full_item.clone();790            new_full_item.value -= val64;791792            // separate amount793            if new_owner_account_id > 0 {794795                // new owner has account796                let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);797                item.value += val64;798799                // update balance800                let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();801                <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);802803                <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);804            }805            else806            {807                // new owner do not have account808                let item = FungibleItemType {809                    collection: collection_id,810                    owner: new_owner.clone(),811                    value: val64812                };813814                Self::add_fungible_item(item)?;815            }816817            if amount == val64{818                Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;819        820                // remove approve list821                <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));822                <FungibleItemList<T>>::remove(collection_id, item_id);823            }824825            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);826        }827828        Ok(())829    }830831    fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {832        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);833        let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();834        let amount = item.fraction;835836        ensure!(amount >= value.into(),"Item balance not enouth");837838        // update balance839        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();840        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);841842        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();843        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);844845        let old_owner = item.owner.clone();846        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);847        let val64 = value.into();848849        // transfer850        if amount == val64 && !new_owner_has_account851        {852            // change owner853            // new owner do not have account854            let mut new_full_item = full_item.clone();855            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();856            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);857858            // update index collection859            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;860        }861        else862        {863            let mut new_full_item = full_item.clone();864            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= val64;865866            // separate amount867            if new_owner_has_account {868                // new owner has account869                new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += val64;870            }871            else872            {873                // new owner do not have account874                new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: val64});875                Self::add_token_index(collection_id, item_id, new_owner.clone())?;876            }877878            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);879        }880881        Ok(())882    }883884    fn transfer_nft(collection_id: u64, item_id: u64, sender: T::AccountId, new_owner: T::AccountId) -> DispatchResult {885886        let mut item = <NftItemList<T>>::get(collection_id, item_id);887888        ensure!(sender == item.owner,"sender parameter and item owner must be equal");889890        // update balance891        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();892        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);893894        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();895        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);896897        // change owner898        let old_owner = item.owner.clone();899        item.owner = new_owner.clone();900        <NftItemList<T>>::insert(collection_id, item_id, item);901902        // update index collection903        Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;904905        // reset approved list906        <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));907        Ok(())908    }909910    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {911        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());912        if list_exists {913            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());914            let item_contains = list.contains(&item_index.clone());915916            if !item_contains {917                list.push(item_index.clone());918            }919920            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);921        } else {922            let mut itm = Vec::new();923            itm.push(item_index.clone());924            <AddressTokens<T>>::insert(collection_id, owner, itm);925        }926927        Ok(())928    }929930    fn remove_token_index(931        collection_id: u64,932        item_index: u64,933        owner: T::AccountId,934    ) -> DispatchResult {935        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());936        if list_exists {937            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());938            let item_contains = list.contains(&item_index.clone());939940            if item_contains {941                list.retain(|&item| item != item_index);942                <AddressTokens<T>>::insert(collection_id, owner, list);943            }944        }945946        Ok(())947    }948949    fn move_token_index(950        collection_id: u64,951        item_index: u64,952        old_owner: T::AccountId,953        new_owner: T::AccountId,954    ) -> DispatchResult {955        Self::remove_token_index(collection_id, item_index, old_owner)?;956        Self::add_token_index(collection_id, item_index, new_owner)?;957958        Ok(())959    }960}961962963////////////////////////////////////////////////////////////////////////////////////////////////////964// Economic models965966/// Fee multiplier.967pub type Multiplier = FixedU128;968969type BalanceOf<T> =970	<<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;971type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<972	<T as system::Trait>::AccountId,>>::NegativeImbalance;973974975976/// Require the transactor pay for themselves and maybe include a tip to gain additional priority977/// in the queue.978#[derive(Encode, Decode, Clone, Eq, PartialEq)]979pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);980981impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {982	#[cfg(feature = "std")]983	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {984		write!(f, "ChargeTransactionPayment<{:?}>", self.0)985	}986	#[cfg(not(feature = "std"))]987	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {988		Ok(())989	}990}991992impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where993	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,994	BalanceOf<T>: Send + Sync + FixedPointOperand,995{996	/// utility constructor. Used only in client/factory code.997	pub fn from(fee: BalanceOf<T>) -> Self {998		Self(fee)999	}10001001    pub fn traditional_fee(1002        len: usize,1003        info: &DispatchInfoOf<T::Call>,1004        tip: BalanceOf<T>,1005    ) -> BalanceOf<T> where1006        T::Call: Dispatchable<Info=DispatchInfo>,1007    {1008        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1009    }10101011	fn withdraw_fee(1012		&self,1013        who: &T::AccountId,1014        call: &T::Call,1015		info: &DispatchInfoOf<T::Call>,1016		len: usize,1017	) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1018        let tip = self.0;10191020        // Set fee based on call type. Creating collection costs 1 Unique.1021        // All other transactions have traditional fees so far1022        let fee = match call.is_sub_type() {1023            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1024            _ => Self::traditional_fee(len, info, tip)10251026            // Flat fee model, use only for testing purposes1027            // _ => <BalanceOf<T>>::from(100)1028        };10291030        // Determine who is paying transaction fee based on ecnomic model1031        // Parse call to extract collection ID and access collection sponsor1032        let sponsor: T::AccountId = match call.is_sub_type() {1033            Some(Call::create_item(collection_id, _properties, _owner)) => {1034                <Collection<T>>::get(collection_id).sponsor1035            },1036            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1037                <Collection<T>>::get(collection_id).sponsor1038            },10391040            _ => T::AccountId::default()1041        };10421043        let mut who_pays_fee: T::AccountId = sponsor.clone();1044        if sponsor == T::AccountId::default() {1045            who_pays_fee = who.clone();1046        }10471048		// Only mess with balances if fee is not zero.1049		if fee.is_zero() {1050			return Ok((fee, None));1051		}10521053		match <T as transaction_payment::Trait>::Currency::withdraw(1054			&who_pays_fee,1055			fee,1056			if tip.is_zero() {1057				WithdrawReason::TransactionPayment.into()1058			} else {1059				WithdrawReason::TransactionPayment | WithdrawReason::Tip1060			},1061			ExistenceRequirement::KeepAlive,1062		) {1063			Ok(imbalance) => Ok((fee, Some(imbalance))),1064			Err(_) => Err(InvalidTransaction::Payment.into()),1065		}1066	}1067}10681069impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where1070    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1071    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,1072{1073	const IDENTIFIER: &'static str = "ChargeTransactionPayment";1074	type AccountId = T::AccountId;1075	type Call = T::Call;1076	type AdditionalSigned = ();1077	type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);1078	fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }10791080	fn validate(1081		&self,1082		who: &Self::AccountId,1083		call: &Self::Call,1084		info: &DispatchInfoOf<Self::Call>,1085		len: usize,1086	) -> TransactionValidity {1087		let (fee, _) = self.withdraw_fee(who, call, info, len)?;10881089		let mut r = ValidTransaction::default();1090		// NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1091		// will be a bit more than setting the priority to tip. For now, this is enough.1092		r.priority = fee.saturated_into::<TransactionPriority>();1093		Ok(r)1094	}10951096	fn pre_dispatch(1097		self,1098		who: &Self::AccountId,1099		call: &Self::Call,1100		info: &DispatchInfoOf<Self::Call>,1101		len: usize1102	) -> Result<Self::Pre, TransactionValidityError> {1103		let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1104		Ok((self.0, who.clone(), imbalance, fee))1105	}11061107	fn post_dispatch(1108		pre: Self::Pre,1109		info: &DispatchInfoOf<Self::Call>,1110		post_info: &PostDispatchInfoOf<Self::Call>,1111		len: usize,1112		_result: &DispatchResult,1113	) -> Result<(), TransactionValidityError> {1114		let (tip, who, imbalance, fee) = pre;1115		if let Some(payed) = imbalance {1116			let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1117				len as u32,1118				info,1119				post_info,1120				tip,1121			);1122			let refund = fee.saturating_sub(actual_fee);1123			let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {1124				Ok(refund_imbalance) => {1125					// The refund cannot be larger than the up front payed max weight.1126					// `PostDispatchInfo::calc_unspent` guards against such a case.1127					match payed.offset(refund_imbalance) {1128						Ok(actual_payment) => actual_payment,1129						Err(_) => return Err(InvalidTransaction::Payment.into()),1130					}1131				}1132				// We do not recreate the account using the refund. The up front payment1133				// is gone in that case.1134				Err(_) => payed,1135			};1136			let imbalances = actual_payment.split(tip);1137			<T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()1138				.chain(Some(imbalances.1)));1139		}1140		Ok(())1141	}1142}
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -183,7 +183,6 @@
     });
 }
 
-
 #[test]
 fn transfer_nft_item() {
     new_test_ext().execute_with(|| {
@@ -364,580 +363,416 @@
     });
 }
 
+#[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);
 
+        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);
+    });
+}
 
+#[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);
 
+        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));
+    });
+}
 
+#[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);
 
+        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::nft_item_id(1,1).data, [1,2,3].to_vec());
 
+        // check balance (collection with id = 1, user id = 1)
+        assert_eq!(TemplateModule::balance_count(1, 1), 1);
 
+        // 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::balance_count(1, 1), 0);
+    });
+}
 
+#[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 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
+        ));
 
+        // check balance (collection with id = 1, user id = 1)
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
 
+        // 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::balance_count(1, 1), 0);
+    });
+}
 
-// #[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();
+#[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);
 
-//         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);
-//     });
-// }
+        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 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_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
+        // 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::change_collection_owner(
-//             origin1.clone(),
-//             1,
-//             2
-//         ));
-//         assert_eq!(TemplateModule::collection(1).owner, 2);
-//     });
-// }
+        // burn item
+        assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1));
+        assert_noop!(
+            TemplateModule::burn_item(origin1.clone(), 1, 1),
+            "Item does not exists"
+        );
 
-// #[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();
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+    });
+}
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
+#[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);
 
-//         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));
-//     });
-// }
-
-// #[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();
-
-//         let size = 1024;
-//         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(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
-//         assert_ok!(TemplateModule::create_item(
-//             origin2.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
-
-//         // check balance (collection with id = 1, user id = 2)
-//         assert_eq!(TemplateModule::balance_count((1, 2)), 1);
-//     });
-// }
-
-// #[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();
-
-//         let size = 1024;
-//         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(),
-//             size
-//         ));
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
-//         assert_ok!(TemplateModule::create_item(
-//             origin2.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
-
-//         // check balance (collection with id = 1, user id = 2)
-//         assert_eq!(TemplateModule::balance_count((1, 2)), 1);
-
-//         // 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::balance_count((1, 1)), 0);
-//     });
-// }
-
-// #[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 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(),
-//             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(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
-
-//         // collection admin
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 3));
-
-//         assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);
-//         assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);
-//     });
-// }
-
-// #[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 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(),
-//             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(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
-
-//         // collection admin
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
-//         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 3));
-
-//         assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);
-//         assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);
-
-//         // remove admin
-//         assert_ok!(TemplateModule::remove_collection_admin(
-//             origin2.clone(),
-//             1,
-//             3
-//         ));
-//         assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), false);
-//     });
-// }
-
-// #[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 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(),
-//             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(2).owner, 2);
-//         assert_eq!(TemplateModule::collection(3).owner, 3);
-
-//         // check balance before
-//         assert_eq!(TemplateModule::balance_count((1, 1)), 0);
-
-//         // create item
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
+        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()
+        ));
 
-//         // 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);
-//     });
-// }
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+        assert_eq!(TemplateModule::collection(2).owner, 2);
+        assert_eq!(TemplateModule::collection(3).owner, 3);
 
-// #[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();
+        // 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()
+        ));
 
-//         // transfer
-//         assert_ok!(TemplateModule::transfer(origin1.clone(), 1, 1, 2));
-//         assert_eq!(TemplateModule::item_id((1, 1)).owner, 2);
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+        assert_eq!(TemplateModule::collection(2).owner, 2);
+        assert_eq!(TemplateModule::collection(3).owner, 3);
 
-//         // balance_of check
-//         assert_eq!(TemplateModule::balance_count((1, 1)), 0);
-//         assert_eq!(TemplateModule::balance_count((1, 2)), 1);
-//     });
-// }
+        // collection admin
+        assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 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();
+        assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);
+        assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
-//         let origin3 = Origin::signed(3);
+        // remove admin
+        assert_ok!(TemplateModule::remove_collection_admin(
+            origin2.clone(),
+            1,
+            3
+        ));
+        assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), false);
+    });
+}
 
-//         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 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);
 
-//         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);
 
-//         // 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(),
+            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()
+        ));
 
-//         // 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, 1);
+        assert_eq!(TemplateModule::collection(3).owner, 1);
 
-// #[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();
+        // 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);
 
-//         let size = 1024;
-//         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(),
+            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
-//         ));
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            2,
+            [].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(),
+            3,
+            [1, 1, 1].to_vec(),
+            1
+        ));
 
-//         // create item
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
+        // 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);
+    });
+}
 
-//         // approve
-//         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
-//         assert_eq!(TemplateModule::approved((1, 1)).contains(&2), true);
-//     });
-// }
+#[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);
 
-// #[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_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            nft_mode.clone()
+        ));
 
-//         let size = 1024;
-//         let origin1 = Origin::signed(1);
-//         let origin2 = Origin::signed(2);
-//         let origin3 = Origin::signed(3);
+        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::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);
+        // approve
+        assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
+        assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);
+    });
+}
 
-//         // create item
-//         assert_ok!(TemplateModule::create_item(
-//             origin1.clone(),
-//             1,
-//             [1, 1, 1].to_vec()
-//         ));
+#[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);
 
-//         // approve
-//         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
-//         assert_ok!(TemplateModule::transfer_from(origin1.clone(), 1, 1, 2));
-//     });
-// }
+        assert_ok!(TemplateModule::create_collection(
+            origin1.clone(),
+            col_name1.clone(),
+            col_desc1.clone(),
+            token_prefix1.clone(),
+            mode
+        ));
 
-// #[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();
+        assert_eq!(TemplateModule::collection(1).owner, 1);
 
-//         let size = 1024;
-//         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(),
+            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
-//         ));
+        // 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));
 
-//         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);
-//     });
-// }
+        // after transfer
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(1, 2), 1);
+    });
+}
modifiedruntime/src/lib.rsdiffbeforeafterboth
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -190,7 +190,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.