git.delta.rocks / unique-network / refs/commits / 119e358551de

difftreelog

White list and mint permissions features

str-mv2020-09-22parent: #f765262.patch.diff
in: master

2 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.rs5use codec::{Decode, Encode};6pub use frame_support::{7    construct_runtime, decl_event, decl_module, decl_storage,8    dispatch::DispatchResult,9    ensure, parameter_types,10    traits::{11        Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,12        Randomness, WithdrawReason,13    },14    weights::{15        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},16        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,17        WeightToFeePolynomial,18    },19    IsSubType, StorageValue,20};2122use frame_system::{self as system, ensure_signed};23use sp_runtime::sp_std::prelude::Vec;24use sp_runtime::{25    traits::{26        DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,27        SignedExtension, Zero,28    },29    transaction_validity::{30        InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,31        ValidTransaction,32    },33    FixedPointOperand, FixedU128,34};35use sp_std::prelude::*;3637#[cfg(test)]38mod mock;3940#[cfg(test)]41mod tests;4243#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]44pub enum CollectionMode {45    Invalid,46    // custom data size47    NFT(u32),48    // decimal points49    Fungible(u32),50    // custom data size and decimal points51    ReFungible(u32, u32),52}5354impl Into<u8> for CollectionMode {55    fn into(self) -> u8 {56        match self {57            CollectionMode::Invalid => 0,58            CollectionMode::NFT(_) => 1,59            CollectionMode::Fungible(_) => 2,60            CollectionMode::ReFungible(_, _) => 3,61        }62    }63}6465#[derive(Encode, Decode, Debug, Clone, PartialEq)]66pub enum AccessMode {67    Normal,68    WhiteList,69}70impl Default for AccessMode {71    fn default() -> Self {72        Self::Normal73    }74}7576impl Default for CollectionMode {77    fn default() -> Self {78        Self::Invalid79    }80}8182#[derive(Encode, Decode, Default, Clone, PartialEq)]83#[cfg_attr(feature = "std", derive(Debug))]84pub struct Ownership<AccountId> {85    pub owner: AccountId,86    pub fraction: u128,87}8889#[derive(Encode, Decode, Default, Clone, PartialEq)]90#[cfg_attr(feature = "std", derive(Debug))]91pub struct CollectionType<AccountId> {92    pub owner: AccountId,93    pub mode: CollectionMode,94    pub access: AccessMode,95    pub decimal_points: u32,96    pub name: Vec<u16>,        // 64 include null escape char97    pub description: Vec<u16>, // 256 include null escape char98    pub token_prefix: Vec<u8>, // 16 include null escape char99    pub custom_data_size: u32,100    pub offchain_schema: Vec<u8>,101    pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender102    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship103}104105#[derive(Encode, Decode, Default, Clone, PartialEq)]106#[cfg_attr(feature = "std", derive(Debug))]107pub struct CollectionAdminsType<AccountId> {108    pub admin: AccountId,109    pub collection_id: u64,110}111112#[derive(Encode, Decode, Default, Clone, PartialEq)]113#[cfg_attr(feature = "std", derive(Debug))]114pub struct NftItemType<AccountId> {115    pub collection: u64,116    pub owner: AccountId,117    pub data: Vec<u8>,118}119120#[derive(Encode, Decode, Default, Clone, PartialEq)]121#[cfg_attr(feature = "std", derive(Debug))]122pub struct FungibleItemType<AccountId> {123    pub collection: u64,124    pub owner: AccountId,125    pub value: u128,126}127128#[derive(Encode, Decode, Default, Clone, PartialEq)]129#[cfg_attr(feature = "std", derive(Debug))]130pub struct ReFungibleItemType<AccountId> {131    pub collection: u64,132    pub owner: Vec<Ownership<AccountId>>,133    pub data: Vec<u8>,134}135136#[derive(Encode, Decode, Default, Clone, PartialEq)]137#[cfg_attr(feature = "std", derive(Debug))]138pub struct ApprovePermissions<AccountId> {139    pub approved: AccountId,140    pub amount: u64,141}142143#[derive(Encode, Decode, Default, Clone, PartialEq)]144#[cfg_attr(feature = "std", derive(Debug))]145pub struct VestingItem<AccountId, Moment> {146    pub sender: AccountId,147    pub recipient: AccountId,148    pub collection_id: u64,149    pub item_id: u64,150    pub amount: u64,151    pub vesting_date: Moment,152}153154pub trait Trait: system::Trait {155    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;156}157158decl_storage! {159    trait Store for Module<T: Trait> as Nft {160161        // Private members162        NextCollectionID: u64;163        CreatedCollectionCount: u64;164        ChainVersion: u64;165        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;166167        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;168        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;169        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;170171        /// Balance owner per collection map172        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;173174        /// second parameter: item id + owner account id175        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;176177        /// Item collections178        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;179        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;180        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;181182        // Active vesting list183        // pub VestingList get(fn vesting): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => VestingItem<T::AccountId, T::Moment>;184185        /// Index list186        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;187188        // Sponsorship189        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;190        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;191    }192}193194decl_event!(195    pub enum Event<T>196    where197        AccountId = <T as system::Trait>::AccountId,198    {199        Created(u64, u8, AccountId),200        ItemCreated(u64, u64),201        ItemDestroyed(u64, u64),202    }203);204205decl_module! {206    pub struct Module<T: Trait> for enum Call where origin: T::Origin {207208        fn deposit_event() = default;209210        fn on_initialize(now: T::BlockNumber) -> Weight {211212            if ChainVersion::get() < 2213            {214                let value = NextCollectionID::get();215                CreatedCollectionCount::put(value);216                ChainVersion::put(2);217            }218219            0220        }221222        // Create collection of NFT with given parameters223        //224        // @param customDataSz size of custom data in each collection item225        // returns collection ID226        #[weight = 0]227        pub fn create_collection(   origin,228                                    collection_name: Vec<u16>,229                                    collection_description: Vec<u16>,230                                    token_prefix: Vec<u8>,231                                    mode: CollectionMode) -> DispatchResult {232233            // Anyone can create a collection234            let who = ensure_signed(origin)?;235            let custom_data_size = match mode {236                CollectionMode::NFT(size) => size,237                CollectionMode::ReFungible(size, _) => size,238                _ => 0239            };240241            let decimal_points = match mode {242                CollectionMode::Fungible(points) => points,243                CollectionMode::ReFungible(_, points) => points,244                _ => 0245            };246247            // check params248            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");249250            let mut name = collection_name.to_vec();251            name.push(0);252            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");253254            let mut description = collection_description.to_vec();255            description.push(0);256            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");257258            let mut prefix = token_prefix.to_vec();259            prefix.push(0);260            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");261262            // Generate next collection ID263            let next_id = NextCollectionID::get()264                .checked_add(1)265                .expect("collection id error");266267            NextCollectionID::put(next_id);268269            // Create new collection270            let new_collection = CollectionType {271                owner: who.clone(),272                name: name,273                mode: mode.clone(),274                access: AccessMode::Normal,275                description: description,276                decimal_points: decimal_points,277                token_prefix: prefix,278                offchain_schema: Vec::new(),279                custom_data_size: custom_data_size,280                sponsor: T::AccountId::default(),281                unconfirmed_sponsor: T::AccountId::default(),282            };283284            // Add new collection to map285            <Collection<T>>::insert(next_id, new_collection);286287            // call event288            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));289290            Ok(())291        }292293        #[weight = 0]294        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {295296            let sender = ensure_signed(origin)?;297            Self::check_owner_permissions(collection_id, sender)?;298299            // TODO Items remove300            <AddressTokens<T>>::remove_prefix(collection_id);301            <ApprovedList<T>>::remove_prefix(collection_id);302            <Balance<T>>::remove_prefix(collection_id);303            <ItemListIndex>::remove(collection_id);304            <AdminList<T>>::remove(collection_id);305            <Collection<T>>::remove(collection_id);306            <WhiteList<T>>::remove(collection_id);307308            Ok(())309        }310311        #[weight = 0]312        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {313314            let sender = ensure_signed(origin)?;315            Self::check_owner_permissions(collection_id, sender)?;316            let mut target_collection = <Collection<T>>::get(collection_id);317            target_collection.owner = new_owner;318            <Collection<T>>::insert(collection_id, target_collection);319320            Ok(())321        }322323        #[weight = 0]324        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {325326            let sender = ensure_signed(origin)?;327            Self::check_owner_or_admin_permissions(collection_id, sender)?;328            let mut admin_arr: Vec<T::AccountId> = Vec::new();329330            if <AdminList<T>>::contains_key(collection_id)331            {332                admin_arr = <AdminList<T>>::get(collection_id);333                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");334            }335336            admin_arr.push(new_admin_id);337            <AdminList<T>>::insert(collection_id, admin_arr);338339            Ok(())340        }341342        #[weight = 0]343        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {344345            let sender = ensure_signed(origin)?;346            Self::check_owner_or_admin_permissions(collection_id, sender)?;347348            if <AdminList<T>>::contains_key(collection_id)349            {350                let mut admin_arr = <AdminList<T>>::get(collection_id);351                admin_arr.retain(|i| *i != account_id);352                <AdminList<T>>::insert(collection_id, admin_arr);353            }354355            Ok(())356        }357358        #[weight = 0]359        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {360361            let sender = ensure_signed(origin)?;362            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");363364            let mut target_collection = <Collection<T>>::get(collection_id);365            ensure!(sender == target_collection.owner, "You do not own this collection");366367            target_collection.unconfirmed_sponsor = new_sponsor;368            <Collection<T>>::insert(collection_id, target_collection);369370            Ok(())371        }372373        #[weight = 0]374        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {375376            let sender = ensure_signed(origin)?;377            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");378379            let mut target_collection = <Collection<T>>::get(collection_id);380            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");381382            target_collection.sponsor = target_collection.unconfirmed_sponsor;383            target_collection.unconfirmed_sponsor = T::AccountId::default();384            <Collection<T>>::insert(collection_id, target_collection);385386            Ok(())387        }388389        #[weight = 0]390        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {391392            let sender = ensure_signed(origin)?;393            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");394395            let mut target_collection = <Collection<T>>::get(collection_id);396            ensure!(sender == target_collection.owner, "You do not own this collection");397398            target_collection.sponsor = T::AccountId::default();399            <Collection<T>>::insert(collection_id, target_collection);400401            Ok(())402        }403404        #[weight = 0]405        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {406407            let sender = ensure_signed(origin)?;408            let target_collection = <Collection<T>>::get(collection_id);409            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;410411            match target_collection.mode412            {413                CollectionMode::NFT(_) => {414415                    // check size416                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");417418                    // Create nft item419                    let item = NftItemType {420                        collection: collection_id,421                        owner: owner,422                        data: properties,423                    };424425                    Self::add_nft_item(item)?;426427                },428                CollectionMode::Fungible(_) => {429430                    // check size431                    ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");432433                    let item = FungibleItemType {434                        collection: collection_id,435                        owner: owner,436                        value: (10 as u128).pow(target_collection.decimal_points)437                    };438439                    Self::add_fungible_item(item)?;440                },441                CollectionMode::ReFungible(_, _) => {442443                    // check size444                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");445446                    let mut owner_list = Vec::new();447                    let value = (10 as u128).pow(target_collection.decimal_points);448                    owner_list.push(Ownership {owner: owner, fraction: value});449450                    let item = ReFungibleItemType {451                        collection: collection_id,452                        owner: owner_list,453                        data: properties454                    };455456                    Self::add_refungible_item(item)?;457                },458                _ => ()459            };460461            // call event462            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));463464            Ok(())465        }466467        #[weight = 0]468        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {469470            let sender = ensure_signed(origin)?;471            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);472            if !item_owner473            {474                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;475            }476            let target_collection = <Collection<T>>::get(collection_id);477478            match target_collection.mode479            {480                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,481                CollectionMode::Fungible(_)  => Self::burn_fungible_item(collection_id, item_id)?,482                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,483                _ => ()484            };485486            // call event487            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));488489            Ok(())490        }491492        #[weight = 0]493        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {494495            let sender = ensure_signed(origin)?;496            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");497498            let target_collection = <Collection<T>>::get(collection_id);499500            // TODO: implement other modes501            match target_collection.mode502            {503                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,504                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,505                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,506                _ => ()507            };508509            Ok(())510        }511512        #[weight = 0]513        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {514515            let sender = ensure_signed(origin)?;516517            // amount param stub518            let amount = 100000000;519520            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");521522            let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));523            if list_exists {524525                let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));526                let item_contains = list.iter().any(|i| i.approved == approved);527528                if !item_contains {529                    list.push(ApprovePermissions { approved: approved.clone(), amount: amount });530                    <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);531                }532            } else {533534                let mut list = Vec::new();535                list.push(ApprovePermissions { approved: approved.clone(), amount: amount });536                <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);537            }538539            Ok(())540        }541542        #[weight = 0]543        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {544545            let sender = ensure_signed(origin)?;546            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));547            if approved_list_exists548            {549                let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));550                let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());551                ensure!(opt_item.is_some(), "No approve found");552                ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");553554                // remove approve555                let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))556                    .into_iter().filter(|i| i.approved != sender.clone()).collect();557                <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);558            }559            else560            {561                Self::check_owner_or_admin_permissions(collection_id, sender)?;562            }563564            let target_collection = <Collection<T>>::get(collection_id);565566            match target_collection.mode567            {568                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,569                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,570                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,571                _ => ()572            };573574            Ok(())575        }576577        #[weight = 0]578        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {579580            // let no_perm_mes = "You do not have permissions to modify this collection";581            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);582            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));583            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);584585            // // on_nft_received  call586587            // Self::transfer(origin, collection_id, item_id, new_owner)?;588589            Ok(())590        }591592        #[weight = 0]593        pub fn set_offchain_schema(594            origin,595            collection_id: u64,596            schema: Vec<u8>597        ) -> DispatchResult {598            let sender = ensure_signed(origin)?;599            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;600601            let mut target_collection = <Collection<T>>::get(collection_id);602            target_collection.offchain_schema = schema;603            <Collection<T>>::insert(collection_id, target_collection);604605            Ok(())606        }607    }608}609610impl<T: Trait> Module<T> {611    fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {612        let current_index = <ItemListIndex>::get(item.collection)613            .checked_add(1)614            .expect("Item list index id error");615        let itemcopy = item.clone();616        let owner = item.owner.clone();617        let value = item.value as u64;618619        Self::add_token_index(item.collection, current_index, owner.clone())?;620621        <ItemListIndex>::insert(item.collection, current_index);622        <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);623624        // Update balance625        let new_balance = <Balance<T>>::get(item.collection, owner.clone())626            .checked_add(value)627            .unwrap();628        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);629630        Ok(())631    }632633    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {634        let current_index = <ItemListIndex>::get(item.collection)635            .checked_add(1)636            .expect("Item list index id error");637        let itemcopy = item.clone();638639        let value = item.owner.first().unwrap().fraction as u64;640        let owner = item.owner.first().unwrap().owner.clone();641642        Self::add_token_index(item.collection, current_index, owner.clone())?;643644        <ItemListIndex>::insert(item.collection, current_index);645        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);646647        // Update balance648        let new_balance = <Balance<T>>::get(item.collection, owner.clone())649            .checked_add(value)650            .unwrap();651        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);652653        Ok(())654    }655656    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {657        let current_index = <ItemListIndex>::get(item.collection)658            .checked_add(1)659            .expect("Item list index id error");660661        let item_owner = item.owner.clone();662        let collection_id = item.collection.clone();663        Self::add_token_index(collection_id, current_index, item.owner.clone())?;664665        <ItemListIndex>::insert(collection_id, current_index);666        <NftItemList<T>>::insert(collection_id, current_index, item);667668        // Update balance669        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())670            .checked_add(1)671            .unwrap();672        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);673674        Ok(())675    }676677    fn burn_refungible_item(678        collection_id: u64,679        item_id: u64,680        owner: T::AccountId,681    ) -> DispatchResult {682        ensure!(683            <ReFungibleItemList<T>>::contains_key(collection_id, item_id),684            "Item does not exists"685        );686        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);687        let item = collection688            .owner689            .iter()690            .filter(|&i| i.owner == owner)691            .next()692            .unwrap();693        Self::remove_token_index(collection_id, item_id, owner.clone())?;694695        // remove approve list696        <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));697698        // update balance699        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())700            .checked_sub(item.fraction as u64)701            .unwrap();702        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);703704        <ReFungibleItemList<T>>::remove(collection_id, item_id);705706        Ok(())707    }708709    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {710        ensure!(711            <NftItemList<T>>::contains_key(collection_id, item_id),712            "Item does not exists"713        );714        let item = <NftItemList<T>>::get(collection_id, item_id);715        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;716717        // remove approve list718        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));719720        // update balance721        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())722            .checked_sub(1)723            .unwrap();724        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);725        <NftItemList<T>>::remove(collection_id, item_id);726727        Ok(())728    }729730    fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {731        ensure!(732            <FungibleItemList<T>>::contains_key(collection_id, item_id),733            "Item does not exists"734        );735        let item = <FungibleItemList<T>>::get(collection_id, item_id);736        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;737738        // remove approve list739        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));740741        // update balance742        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())743            .checked_sub(item.value as u64)744            .unwrap();745        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);746747        <FungibleItemList<T>>::remove(collection_id, item_id);748749        Ok(())750    }751752    fn collection_exists(collection_id: u64) -> DispatchResult {753        ensure!(754            <Collection<T>>::contains_key(collection_id),755            "This collection does not exist"756        );757        Ok(())758    }759760    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {761        Self::collection_exists(collection_id)?;762763        let target_collection = <Collection<T>>::get(collection_id);764        ensure!(765            subject == target_collection.owner,766            "You do not own this collection"767        );768769        Ok(())770    }771772    fn check_owner_or_admin_permissions(773        collection_id: u64,774        subject: T::AccountId,775    ) -> DispatchResult {776        Self::collection_exists(collection_id)?;777778        let target_collection = <Collection<T>>::get(collection_id);779        let is_owner = subject == target_collection.owner;780781        let no_perm_mes = "You do not have permissions to modify this collection";782        let exists = <AdminList<T>>::contains_key(collection_id);783784        if !is_owner {785            ensure!(exists, no_perm_mes);786            ensure!(787                <AdminList<T>>::get(collection_id).contains(&subject),788                no_perm_mes789            );790        }791        Ok(())792    }793794    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {795        let target_collection = <Collection<T>>::get(collection_id);796797        match target_collection.mode {798            CollectionMode::NFT(_) => {799                <NftItemList<T>>::get(collection_id, item_id).owner == subject800            }801            CollectionMode::Fungible(_) => {802                <FungibleItemList<T>>::get(collection_id, item_id).owner == subject803            }804            CollectionMode::ReFungible(_, _) => {805                <ReFungibleItemList<T>>::get(collection_id, item_id)806                    .owner807                    .iter()808                    .any(|i| i.owner == subject)809            }810            CollectionMode::Invalid => false,811        }812    }813814    fn transfer_fungible(815        collection_id: u64,816        item_id: u64,817        value: u64,818        owner: T::AccountId,819        new_owner: T::AccountId,820    ) -> DispatchResult {821        let full_item = <FungibleItemList<T>>::get(collection_id, item_id);822        let amount = full_item.value;823824        ensure!(amount >= value.into(), "Item balance not enouth");825826        // update balance827        let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())828            .checked_sub(value)829            .unwrap();830        <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);831832        let mut new_owner_account_id = 0;833        let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());834        if new_owner_items.len() > 0 {835            new_owner_account_id = new_owner_items[0];836        }837838        let val64 = value.into();839840        // transfer841        if amount == val64 && new_owner_account_id == 0 {842            // change owner843            // new owner do not have account844            let mut new_full_item = full_item.clone();845            new_full_item.owner = new_owner.clone();846            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);847848            // update balance849            let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())850                .checked_add(value)851                .unwrap();852            <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);853854            // update index collection855            Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;856        } else {857            let mut new_full_item = full_item.clone();858            new_full_item.value -= val64;859860            // separate amount861            if new_owner_account_id > 0 {862                // new owner has account863                let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);864                item.value += val64;865866                // update balance867                let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())868                    .checked_add(value)869                    .unwrap();870                <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);871872                <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);873            } else {874                // new owner do not have account875                let item = FungibleItemType {876                    collection: collection_id,877                    owner: new_owner.clone(),878                    value: val64,879                };880881                Self::add_fungible_item(item)?;882            }883884            if amount == val64 {885                Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;886887                // remove approve list888                <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));889                <FungibleItemList<T>>::remove(collection_id, item_id);890            }891892            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);893        }894895        Ok(())896    }897898    fn transfer_refungible(899        collection_id: u64,900        item_id: u64,901        value: u64,902        owner: T::AccountId,903        new_owner: T::AccountId,904    ) -> DispatchResult {905        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);906        let item = full_item907            .owner908            .iter()909            .filter(|i| i.owner == owner)910            .next()911            .unwrap();912        let amount = item.fraction;913914        ensure!(amount >= value.into(), "Item balance not enouth");915916        // update balance917        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())918            .checked_sub(value)919            .unwrap();920        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);921922        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())923            .checked_add(value)924            .unwrap();925        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);926927        let old_owner = item.owner.clone();928        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);929        let val64 = value.into();930931        // transfer932        if amount == val64 && !new_owner_has_account {933            // change owner934            // new owner do not have account935            let mut new_full_item = full_item.clone();936            new_full_item937                .owner938                .iter_mut()939                .find(|i| i.owner == owner)940                .unwrap()941                .owner = new_owner.clone();942            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);943944            // update index collection945            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;946        } else {947            let mut new_full_item = full_item.clone();948            new_full_item949                .owner950                .iter_mut()951                .find(|i| i.owner == owner)952                .unwrap()953                .fraction -= val64;954955            // separate amount956            if new_owner_has_account {957                // new owner has account958                new_full_item959                    .owner960                    .iter_mut()961                    .find(|i| i.owner == new_owner)962                    .unwrap()963                    .fraction += val64;964            } else {965                // new owner do not have account966                new_full_item.owner.push(Ownership {967                    owner: new_owner.clone(),968                    fraction: val64,969                });970                Self::add_token_index(collection_id, item_id, new_owner.clone())?;971            }972973            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);974        }975976        Ok(())977    }978979    fn transfer_nft(980        collection_id: u64,981        item_id: u64,982        sender: T::AccountId,983        new_owner: T::AccountId,984    ) -> DispatchResult {985        let mut item = <NftItemList<T>>::get(collection_id, item_id);986987        ensure!(988            sender == item.owner,989            "sender parameter and item owner must be equal"990        );991992        // update balance993        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())994            .checked_sub(1)995            .unwrap();996        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);997998        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())999            .checked_add(1)1000            .unwrap();1001        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10021003        // change owner1004        let old_owner = item.owner.clone();1005        item.owner = new_owner.clone();1006        <NftItemList<T>>::insert(collection_id, item_id, item);10071008        // update index collection1009        Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;10101011        // reset approved list1012        <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1013        Ok(())1014    }10151016    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1017        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1018        if list_exists {1019            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1020            let item_contains = list.contains(&item_index.clone());10211022            if !item_contains {1023                list.push(item_index.clone());1024            }10251026            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1027        } else {1028            let mut itm = Vec::new();1029            itm.push(item_index.clone());1030            <AddressTokens<T>>::insert(collection_id, owner, itm);1031        }10321033        Ok(())1034    }10351036    fn remove_token_index(1037        collection_id: u64,1038        item_index: u64,1039        owner: T::AccountId,1040    ) -> DispatchResult {1041        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1042        if list_exists {1043            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1044            let item_contains = list.contains(&item_index.clone());10451046            if item_contains {1047                list.retain(|&item| item != item_index);1048                <AddressTokens<T>>::insert(collection_id, owner, list);1049            }1050        }10511052        Ok(())1053    }10541055    fn move_token_index(1056        collection_id: u64,1057        item_index: u64,1058        old_owner: T::AccountId,1059        new_owner: T::AccountId,1060    ) -> DispatchResult {1061        Self::remove_token_index(collection_id, item_index, old_owner)?;1062        Self::add_token_index(collection_id, item_index, new_owner)?;10631064        Ok(())1065    }1066}10671068////////////////////////////////////////////////////////////////////////////////////////////////////1069// Economic models10701071/// Fee multiplier.1072pub type Multiplier = FixedU128;10731074type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1075    <T as system::Trait>::AccountId,1076>>::Balance;1077type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1078    <T as system::Trait>::AccountId,1079>>::NegativeImbalance;10801081/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1082/// in the queue.1083#[derive(Encode, Decode, Clone, Eq, PartialEq)]1084pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1085    #[codec(compact)] BalanceOf<T>,1086);10871088impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1089    for ChargeTransactionPayment<T>1090{1091    #[cfg(feature = "std")]1092    fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1093        write!(f, "ChargeTransactionPayment<{:?}>", self.0)1094    }1095    #[cfg(not(feature = "std"))]1096    fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1097        Ok(())1098    }1099}11001101impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1102where1103    T::Call:1104        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1105    BalanceOf<T>: Send + Sync + FixedPointOperand,1106{1107    /// utility constructor. Used only in client/factory code.1108    pub fn from(fee: BalanceOf<T>) -> Self {1109        Self(fee)1110    }11111112    pub fn traditional_fee(1113        len: usize,1114        info: &DispatchInfoOf<T::Call>,1115        tip: BalanceOf<T>,1116    ) -> BalanceOf<T>1117    where1118        T::Call: Dispatchable<Info = DispatchInfo>,1119    {1120        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1121    }11221123    fn withdraw_fee(1124        &self,1125        who: &T::AccountId,1126        call: &T::Call,1127        info: &DispatchInfoOf<T::Call>,1128        len: usize,1129    ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1130        let tip = self.0;11311132        // Set fee based on call type. Creating collection costs 1 Unique.1133        // All other transactions have traditional fees so far1134        let fee = match call.is_sub_type() {1135            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1136            _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1137                                                        // _ => <BalanceOf<T>>::from(100)1138        };11391140        // Determine who is paying transaction fee based on ecnomic model1141        // Parse call to extract collection ID and access collection sponsor1142        let sponsor: T::AccountId = match call.is_sub_type() {1143            Some(Call::create_item(collection_id, _properties, _owner)) => {1144                <Collection<T>>::get(collection_id).sponsor1145            }1146            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1147                <Collection<T>>::get(collection_id).sponsor1148            }11491150            _ => T::AccountId::default(),1151        };11521153        let mut who_pays_fee: T::AccountId = sponsor.clone();1154        if sponsor == T::AccountId::default() {1155            who_pays_fee = who.clone();1156        }11571158        // Only mess with balances if fee is not zero.1159        if fee.is_zero() {1160            return Ok((fee, None));1161        }11621163        match <T as transaction_payment::Trait>::Currency::withdraw(1164            &who_pays_fee,1165            fee,1166            if tip.is_zero() {1167                WithdrawReason::TransactionPayment.into()1168            } else {1169                WithdrawReason::TransactionPayment | WithdrawReason::Tip1170            },1171            ExistenceRequirement::KeepAlive,1172        ) {1173            Ok(imbalance) => Ok((fee, Some(imbalance))),1174            Err(_) => Err(InvalidTransaction::Payment.into()),1175        }1176    }1177}11781179impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1180    for ChargeTransactionPayment<T>1181where1182    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1183    T::Call:1184        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1185{1186    const IDENTIFIER: &'static str = "ChargeTransactionPayment";1187    type AccountId = T::AccountId;1188    type Call = T::Call;1189    type AdditionalSigned = ();1190    type Pre = (1191        BalanceOf<T>,1192        Self::AccountId,1193        Option<NegativeImbalanceOf<T>>,1194        BalanceOf<T>,1195    );1196    fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1197        Ok(())1198    }11991200    fn validate(1201        &self,1202        who: &Self::AccountId,1203        call: &Self::Call,1204        info: &DispatchInfoOf<Self::Call>,1205        len: usize,1206    ) -> TransactionValidity {1207        let (fee, _) = self.withdraw_fee(who, call, info, len)?;12081209        let mut r = ValidTransaction::default();1210        // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1211        // will be a bit more than setting the priority to tip. For now, this is enough.1212        r.priority = fee.saturated_into::<TransactionPriority>();1213        Ok(r)1214    }12151216    fn pre_dispatch(1217        self,1218        who: &Self::AccountId,1219        call: &Self::Call,1220        info: &DispatchInfoOf<Self::Call>,1221        len: usize,1222    ) -> Result<Self::Pre, TransactionValidityError> {1223        let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1224        Ok((self.0, who.clone(), imbalance, fee))1225    }12261227    fn post_dispatch(1228        pre: Self::Pre,1229        info: &DispatchInfoOf<Self::Call>,1230        post_info: &PostDispatchInfoOf<Self::Call>,1231        len: usize,1232        _result: &DispatchResult,1233    ) -> Result<(), TransactionValidityError> {1234        let (tip, who, imbalance, fee) = pre;1235        if let Some(payed) = imbalance {1236            let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1237                len as u32, info, post_info, tip,1238            );1239            let refund = fee.saturating_sub(actual_fee);1240            let actual_payment =1241                match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1242                    &who, refund,1243                ) {1244                    Ok(refund_imbalance) => {1245                        // The refund cannot be larger than the up front payed max weight.1246                        // `PostDispatchInfo::calc_unspent` guards against such a case.1247                        match payed.offset(refund_imbalance) {1248                            Ok(actual_payment) => actual_payment,1249                            Err(_) => return Err(InvalidTransaction::Payment.into()),1250                        }1251                    }1252                    // We do not recreate the account using the refund. The up front payment1253                    // is gone in that case.1254                    Err(_) => payed,1255                };1256            let imbalances = actual_payment.split(tip);1257            <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1258                Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1259            );1260        }1261        Ok(())1262    }1263}
after · pallets/nft/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23/// For more guidance on Substrate FRAME, see the example pallet4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs5use codec::{Decode, Encode};6pub use frame_support::{7    construct_runtime, decl_event, decl_module, decl_storage,8    dispatch::DispatchResult,9    ensure, parameter_types,10    traits::{11        Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,12        Randomness, WithdrawReason,13    },14    weights::{15        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},16        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,17        WeightToFeePolynomial,18    },19    IsSubType, StorageValue,20};2122use frame_system::{self as system, ensure_signed};23use sp_runtime::sp_std::prelude::Vec;24use sp_runtime::{25    traits::{26        DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,27        SignedExtension, Zero,28    },29    transaction_validity::{30        InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,31        ValidTransaction,32    },33    FixedPointOperand, FixedU128,34};35use sp_std::prelude::*;3637#[cfg(test)]38mod mock;3940#[cfg(test)]41mod tests;4243#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]44pub enum CollectionMode {45    Invalid,46    // custom data size47    NFT(u32),48    // decimal points49    Fungible(u32),50    // custom data size and decimal points51    ReFungible(u32, u32),52}5354impl Into<u8> for CollectionMode {55    fn into(self) -> u8 {56        match self {57            CollectionMode::Invalid => 0,58            CollectionMode::NFT(_) => 1,59            CollectionMode::Fungible(_) => 2,60            CollectionMode::ReFungible(_, _) => 3,61        }62    }63}6465#[derive(Encode, Decode, Debug, Clone, PartialEq)]66pub enum AccessMode {67    Normal,68    WhiteList,69}70impl Default for AccessMode {71    fn default() -> Self {72        Self::Normal73    }74}7576impl Default for CollectionMode {77    fn default() -> Self {78        Self::Invalid79    }80}8182#[derive(Encode, Decode, Default, Clone, PartialEq)]83#[cfg_attr(feature = "std", derive(Debug))]84pub struct Ownership<AccountId> {85    pub owner: AccountId,86    pub fraction: u128,87}8889#[derive(Encode, Decode, Default, Clone, PartialEq)]90#[cfg_attr(feature = "std", derive(Debug))]91pub struct CollectionType<AccountId> {92    pub owner: AccountId,93    pub mode: CollectionMode,94    pub access: AccessMode,95    pub decimal_points: u32,96    pub name: Vec<u16>,        // 64 include null escape char97    pub description: Vec<u16>, // 256 include null escape char98    pub token_prefix: Vec<u8>, // 16 include null escape char99    pub custom_data_size: u32,100    pub mint_mode: bool,101    pub offchain_schema: Vec<u8>,102    pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender103    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship104}105106#[derive(Encode, Decode, Default, Clone, PartialEq)]107#[cfg_attr(feature = "std", derive(Debug))]108pub struct CollectionAdminsType<AccountId> {109    pub admin: AccountId,110    pub collection_id: u64,111}112113#[derive(Encode, Decode, Default, Clone, PartialEq)]114#[cfg_attr(feature = "std", derive(Debug))]115pub struct NftItemType<AccountId> {116    pub collection: u64,117    pub owner: AccountId,118    pub data: Vec<u8>,119}120121#[derive(Encode, Decode, Default, Clone, PartialEq)]122#[cfg_attr(feature = "std", derive(Debug))]123pub struct FungibleItemType<AccountId> {124    pub collection: u64,125    pub owner: AccountId,126    pub value: u128,127}128129#[derive(Encode, Decode, Default, Clone, PartialEq)]130#[cfg_attr(feature = "std", derive(Debug))]131pub struct ReFungibleItemType<AccountId> {132    pub collection: u64,133    pub owner: Vec<Ownership<AccountId>>,134    pub data: Vec<u8>,135}136137#[derive(Encode, Decode, Default, Clone, PartialEq)]138#[cfg_attr(feature = "std", derive(Debug))]139pub struct ApprovePermissions<AccountId> {140    pub approved: AccountId,141    pub amount: u64,142}143144#[derive(Encode, Decode, Default, Clone, PartialEq)]145#[cfg_attr(feature = "std", derive(Debug))]146pub struct VestingItem<AccountId, Moment> {147    pub sender: AccountId,148    pub recipient: AccountId,149    pub collection_id: u64,150    pub item_id: u64,151    pub amount: u64,152    pub vesting_date: Moment,153}154155pub trait Trait: system::Trait {156    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;157}158159decl_storage! {160    trait Store for Module<T: Trait> as Nft {161162        // Private members163        NextCollectionID: u64;164        CreatedCollectionCount: u64;165        ChainVersion: u64;166        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;167168        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;169        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;170        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;171172        /// Balance owner per collection map173        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;174175        /// second parameter: item id + owner account id176        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;177178        /// Item collections179        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;180        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;181        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;182183        /// Index list184        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;185186        // Sponsorship187        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;188        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;189    }190}191192decl_event!(193    pub enum Event<T>194    where195        AccountId = <T as system::Trait>::AccountId,196    {197        Created(u64, u8, AccountId),198        ItemCreated(u64, u64),199        ItemDestroyed(u64, u64),200    }201);202203decl_module! {204    pub struct Module<T: Trait> for enum Call where origin: T::Origin {205206        fn deposit_event() = default;207208        fn on_initialize(now: T::BlockNumber) -> Weight {209210            if ChainVersion::get() < 2211            {212                let value = NextCollectionID::get();213                CreatedCollectionCount::put(value);214                ChainVersion::put(2);215            }216217            0218        }219220        // Create collection of NFT with given parameters221        //222        // @param customDataSz size of custom data in each collection item223        // returns collection ID224        #[weight = 0]225        pub fn create_collection(origin,226                                 collection_name: Vec<u16>,227                                 collection_description: Vec<u16>,228                                 token_prefix: Vec<u8>,229                                 mode: CollectionMode) -> DispatchResult {230231            // Anyone can create a collection232            let who = ensure_signed(origin)?;233            let custom_data_size = match mode {234                CollectionMode::NFT(size) => size,235                CollectionMode::ReFungible(size, _) => size,236                _ => 0237            };238239            let decimal_points = match mode {240                CollectionMode::Fungible(points) => points,241                CollectionMode::ReFungible(_, points) => points,242                _ => 0243            };244245            // check params246            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");247248            let mut name = collection_name.to_vec();249            name.push(0);250            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");251252            let mut description = collection_description.to_vec();253            description.push(0);254            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");255256            let mut prefix = token_prefix.to_vec();257            prefix.push(0);258            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");259260            // Generate next collection ID261            let next_id = NextCollectionID::get()262                .checked_add(1)263                .expect("collection id error");264265            NextCollectionID::put(next_id);266267            // Create new collection268            let new_collection = CollectionType {269                owner: who.clone(),270                name: name,271                mode: mode.clone(),272                mint_mode: false,273                access: AccessMode::Normal,274                description: description,275                decimal_points: decimal_points,276                token_prefix: prefix,277                offchain_schema: Vec::new(),278                custom_data_size: custom_data_size,279                sponsor: T::AccountId::default(),280                unconfirmed_sponsor: T::AccountId::default(),281            };282283            // Add new collection to map284            <Collection<T>>::insert(next_id, new_collection);285286            // call event287            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));288289            Ok(())290        }291292        #[weight = 0]293        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {294295            let sender = ensure_signed(origin)?;296            Self::check_owner_permissions(collection_id, sender)?;297298            // TODO Items remove299            <AddressTokens<T>>::remove_prefix(collection_id);300            <ApprovedList<T>>::remove_prefix(collection_id);301            <Balance<T>>::remove_prefix(collection_id);302            <ItemListIndex>::remove(collection_id);303            <AdminList<T>>::remove(collection_id);304            <Collection<T>>::remove(collection_id);305            <WhiteList<T>>::remove(collection_id);306307            Ok(())308        }309310        #[weight = 0]311        pub fn add_to_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{312313            let sender = ensure_signed(origin)?;314            Self::check_owner_or_admin_permissions(collection_id, sender)?;315316            let mut white_list_collection: Vec<T::AccountId>;317            if <WhiteList<T>>::contains_key(collection_id) {318                white_list_collection = <WhiteList<T>>::get(collection_id);319                if !white_list_collection.contains(&address.clone())320                {321                    white_list_collection.push(address.clone());322                }323            }324            else {325                white_list_collection = Vec::new();326                white_list_collection.push(address.clone());327            }328329            <WhiteList<T>>::insert(collection_id, white_list_collection);330            Ok(())331        }332333        #[weight = 0]334        pub fn remove_from_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{335336            let sender = ensure_signed(origin)?;337            Self::check_owner_or_admin_permissions(collection_id, sender)?;338339            if <WhiteList<T>>::contains_key(collection_id) {340                let mut white_list_collection = <WhiteList<T>>::get(collection_id);341                if white_list_collection.contains(&address.clone())342                {343                    white_list_collection.retain(|i| *i != address.clone());344                    <WhiteList<T>>::insert(collection_id, white_list_collection);345                }346            }347348            Ok(())349        }350351        #[weight = 0]352        pub fn set_public_access_mode(origin, collection_id: u64, mode: AccessMode) -> DispatchResult353        {354            let sender = ensure_signed(origin)?;355356            Self::check_owner_permissions(collection_id, sender)?;357            let mut target_collection = <Collection<T>>::get(collection_id);358            target_collection.access = mode;359            <Collection<T>>::insert(collection_id, target_collection);360361            Ok(())362        }363364        #[weight = 0]365        pub fn set_mint_permission(origin, collection_id: u64, mint_permission: bool) -> DispatchResult366        {367            let sender = ensure_signed(origin)?;368369            Self::check_owner_permissions(collection_id, sender)?;370            let mut target_collection = <Collection<T>>::get(collection_id);371            target_collection.mint_mode = mint_permission;372            <Collection<T>>::insert(collection_id, target_collection);373374            Ok(())375        }376377        #[weight = 0]378        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {379380            let sender = ensure_signed(origin)?;381            Self::check_owner_permissions(collection_id, sender)?;382            let mut target_collection = <Collection<T>>::get(collection_id);383            target_collection.owner = new_owner;384            <Collection<T>>::insert(collection_id, target_collection);385386            Ok(())387        }388389        #[weight = 0]390        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {391392            let sender = ensure_signed(origin)?;393            Self::check_owner_or_admin_permissions(collection_id, sender)?;394            let mut admin_arr: Vec<T::AccountId> = Vec::new();395396            if <AdminList<T>>::contains_key(collection_id)397            {398                admin_arr = <AdminList<T>>::get(collection_id);399                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");400            }401402            admin_arr.push(new_admin_id);403            <AdminList<T>>::insert(collection_id, admin_arr);404405            Ok(())406        }407408        #[weight = 0]409        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {410411            let sender = ensure_signed(origin)?;412            Self::check_owner_or_admin_permissions(collection_id, sender)?;413414            if <AdminList<T>>::contains_key(collection_id)415            {416                let mut admin_arr = <AdminList<T>>::get(collection_id);417                admin_arr.retain(|i| *i != account_id);418                <AdminList<T>>::insert(collection_id, admin_arr);419            }420421            Ok(())422        }423424        #[weight = 0]425        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {426427            let sender = ensure_signed(origin)?;428            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");429430            let mut target_collection = <Collection<T>>::get(collection_id);431            ensure!(sender == target_collection.owner, "You do not own this collection");432433            target_collection.unconfirmed_sponsor = new_sponsor;434            <Collection<T>>::insert(collection_id, target_collection);435436            Ok(())437        }438439        #[weight = 0]440        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {441442            let sender = ensure_signed(origin)?;443            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");444445            let mut target_collection = <Collection<T>>::get(collection_id);446            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");447448            target_collection.sponsor = target_collection.unconfirmed_sponsor;449            target_collection.unconfirmed_sponsor = T::AccountId::default();450            <Collection<T>>::insert(collection_id, target_collection);451452            Ok(())453        }454455        #[weight = 0]456        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {457458            let sender = ensure_signed(origin)?;459            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");460461            let mut target_collection = <Collection<T>>::get(collection_id);462            ensure!(sender == target_collection.owner, "You do not own this collection");463464            target_collection.sponsor = T::AccountId::default();465            <Collection<T>>::insert(collection_id, target_collection);466467            Ok(())468        }469470        #[weight = 0]471        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {472473            let sender = ensure_signed(origin)?;474            Self::collection_exists(collection_id)?;475            let target_collection = <Collection<T>>::get(collection_id);476477            if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {478                if target_collection.mint_mode == false {479                    panic!("Collection is not in mint mode");480                }481482                Self::check_white_list(collection_id, owner.clone())?;483            }484485            match target_collection.mode486            {487                CollectionMode::NFT(_) => {488489                    // check size490                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");491492                    // Create nft item493                    let item = NftItemType {494                        collection: collection_id,495                        owner: owner,496                        data: properties,497                    };498499                    Self::add_nft_item(item)?;500501                },502                CollectionMode::Fungible(_) => {503504                    // check size505                    ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");506507                    let item = FungibleItemType {508                        collection: collection_id,509                        owner: owner,510                        value: (10 as u128).pow(target_collection.decimal_points)511                    };512513                    Self::add_fungible_item(item)?;514                },515                CollectionMode::ReFungible(_, _) => {516517                    // check size518                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");519520                    let mut owner_list = Vec::new();521                    let value = (10 as u128).pow(target_collection.decimal_points);522                    owner_list.push(Ownership {owner: owner, fraction: value});523524                    let item = ReFungibleItemType {525                        collection: collection_id,526                        owner: owner_list,527                        data: properties528                    };529530                    Self::add_refungible_item(item)?;531                },532                _ => ()533            };534535            // call event536            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));537538            Ok(())539        }540541        #[weight = 0]542        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {543544            let sender = ensure_signed(origin)?;545            Self::collection_exists(collection_id)?;546            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);547            if !item_owner548            {549                if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {  550                    Self::check_white_list(collection_id, sender.clone())?;551                }552            }553            let target_collection = <Collection<T>>::get(collection_id);554555            match target_collection.mode556            {557                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,558                CollectionMode::Fungible(_)  => Self::burn_fungible_item(collection_id, item_id)?,559                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,560                _ => ()561            };562563            // call event564            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));565566            Ok(())567        }568569        #[weight = 0]570        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {571572            let sender = ensure_signed(origin)?;573574            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);575            if !item_owner {576                Self::check_white_list(collection_id, sender.clone())?;577                Self::check_white_list(collection_id, recipient.clone())?;578            }579580            let target_collection = <Collection<T>>::get(collection_id);581582            match target_collection.mode583            {584                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,585                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,586                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,587                _ => ()588            };589590            Ok(())591        }592593        #[weight = 0]594        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {595596            let sender = ensure_signed(origin)?;597598            // amount param stub599            let amount = 100000000;600601            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);602            if !item_owner {603                Self::check_white_list(collection_id, approved.clone())?;604            }605606            let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));607            if list_exists {608609                let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));610                let item_contains = list.iter().any(|i| i.approved == approved);611612                if !item_contains {613                    list.push(ApprovePermissions { approved: approved.clone(), amount: amount });614                    <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);615                }616            } else {617618                let mut list = Vec::new();619                list.push(ApprovePermissions { approved: approved.clone(), amount: amount });620                <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);621            }622623            Ok(())624        }625626        #[weight = 0]627        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {628629            let sender = ensure_signed(origin)?;630            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));631            if approved_list_exists632            {633                Self::check_white_list(collection_id, from.clone())?;634                Self::check_white_list(collection_id, recipient.clone())?;635636                let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));637                let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());638                ensure!(opt_item.is_some(), "No approve found");639                ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");640641                // remove approve642                let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))643                    .into_iter().filter(|i| i.approved != sender.clone()).collect();644                <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);645            }646            else647            {648                panic!("Only approved addresses can call this method");649            }650651            let target_collection = <Collection<T>>::get(collection_id);652653            match target_collection.mode654            {655                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,656                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,657                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,658                _ => ()659            };660661            Ok(())662        }663664        #[weight = 0]665        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {666667            // let no_perm_mes = "You do not have permissions to modify this collection";668            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);669            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));670            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);671672            // // on_nft_received  call673674            // Self::transfer(origin, collection_id, item_id, new_owner)?;675676            Ok(())677        }678679        #[weight = 0]680        pub fn set_offchain_schema(681            origin,682            collection_id: u64,683            schema: Vec<u8>684        ) -> DispatchResult {685            let sender = ensure_signed(origin)?;686            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;687688            let mut target_collection = <Collection<T>>::get(collection_id);689            target_collection.offchain_schema = schema;690            <Collection<T>>::insert(collection_id, target_collection);691692            Ok(())693        }694    }695}696697impl<T: Trait> Module<T> {698    fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {699        let current_index = <ItemListIndex>::get(item.collection)700            .checked_add(1)701            .expect("Item list index id error");702        let itemcopy = item.clone();703        let owner = item.owner.clone();704        let value = item.value as u64;705706        Self::add_token_index(item.collection, current_index, owner.clone())?;707708        <ItemListIndex>::insert(item.collection, current_index);709        <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);710711        // Update balance712        let new_balance = <Balance<T>>::get(item.collection, owner.clone())713            .checked_add(value)714            .unwrap();715        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);716717        Ok(())718    }719720    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {721        let current_index = <ItemListIndex>::get(item.collection)722            .checked_add(1)723            .expect("Item list index id error");724        let itemcopy = item.clone();725726        let value = item.owner.first().unwrap().fraction as u64;727        let owner = item.owner.first().unwrap().owner.clone();728729        Self::add_token_index(item.collection, current_index, owner.clone())?;730731        <ItemListIndex>::insert(item.collection, current_index);732        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);733734        // Update balance735        let new_balance = <Balance<T>>::get(item.collection, owner.clone())736            .checked_add(value)737            .unwrap();738        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);739740        Ok(())741    }742743    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {744        let current_index = <ItemListIndex>::get(item.collection)745            .checked_add(1)746            .expect("Item list index id error");747748        let item_owner = item.owner.clone();749        let collection_id = item.collection.clone();750        Self::add_token_index(collection_id, current_index, item.owner.clone())?;751752        <ItemListIndex>::insert(collection_id, current_index);753        <NftItemList<T>>::insert(collection_id, current_index, item);754755        // Update balance756        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())757            .checked_add(1)758            .unwrap();759        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);760761        Ok(())762    }763764    fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {765        ensure!(766            <ReFungibleItemList<T>>::contains_key(collection_id, item_id),767            "Item does not exists"768        );769        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);770        let item = collection771            .owner772            .iter()773            .filter(|&i| i.owner == owner)774            .next()775            .unwrap();776        Self::remove_token_index(collection_id, item_id, owner.clone())?;777778        // remove approve list779        <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));780781        // update balance782        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())783            .checked_sub(item.fraction as u64)784            .unwrap();785        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);786787        <ReFungibleItemList<T>>::remove(collection_id, item_id);788789        Ok(())790    }791792    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {793        ensure!(794            <NftItemList<T>>::contains_key(collection_id, item_id),795            "Item does not exists"796        );797        let item = <NftItemList<T>>::get(collection_id, item_id);798        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;799800        // remove approve list801        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));802803        // update balance804        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())805            .checked_sub(1)806            .unwrap();807        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);808        <NftItemList<T>>::remove(collection_id, item_id);809810        Ok(())811    }812813    fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {814        ensure!(815            <FungibleItemList<T>>::contains_key(collection_id, item_id),816            "Item does not exists"817        );818        let item = <FungibleItemList<T>>::get(collection_id, item_id);819        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;820821        // remove approve list822        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));823824        // update balance825        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())826            .checked_sub(item.value as u64)827            .unwrap();828        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);829830        <FungibleItemList<T>>::remove(collection_id, item_id);831832        Ok(())833    }834835    fn collection_exists(collection_id: u64) -> DispatchResult {836        ensure!(837            <Collection<T>>::contains_key(collection_id),838            "This collection does not exist"839        );840        Ok(())841    }842843    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {844        Self::collection_exists(collection_id)?;845846        let target_collection = <Collection<T>>::get(collection_id);847        ensure!(848            subject == target_collection.owner,849            "You do not own this collection"850        );851852        Ok(())853    }854855    fn is_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> bool {856857        let target_collection = <Collection<T>>::get(collection_id);858        let mut result: bool = subject == target_collection.owner;859        let exists = <AdminList<T>>::contains_key(collection_id);860861        if !result & exists {862            if <AdminList<T>>::get(collection_id).contains(&subject) {863                result = true864            }865        }866867        result868    }869870    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {871        872        Self::collection_exists(collection_id)?;873        let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());874875        if result == true {876            Ok(())877        } else {878            panic!("You do not have permissions to modify this collection")879        }880    }881882    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {883        let target_collection = <Collection<T>>::get(collection_id);884885        match target_collection.mode {886            CollectionMode::NFT(_) => {887                <NftItemList<T>>::get(collection_id, item_id).owner == subject888            }889            CollectionMode::Fungible(_) => {890                <FungibleItemList<T>>::get(collection_id, item_id).owner == subject891            }892            CollectionMode::ReFungible(_, _) => {893                <ReFungibleItemList<T>>::get(collection_id, item_id)894                    .owner895                    .iter()896                    .any(|i| i.owner == subject)897            }898            CollectionMode::Invalid => false,899        }900    }901902    fn check_white_list(collection_id: u64, address: T::AccountId) -> DispatchResult {903904        let mes = "Address is not in white list";905        if <WhiteList<T>>::contains_key(collection_id){906            let wl = <WhiteList<T>>::get(collection_id);907            if !wl.contains(&address.clone()) {908                panic!(mes);909            }910        }911        else {912            panic!(mes);913        }914        Ok(())915    }916917    fn transfer_fungible(918        collection_id: u64,919        item_id: u64,920        value: u64,921        owner: T::AccountId,922        new_owner: T::AccountId,923    ) -> DispatchResult {924        let full_item = <FungibleItemList<T>>::get(collection_id, item_id);925        let amount = full_item.value;926927        ensure!(amount >= value.into(), "Item balance not enouth");928929        // update balance930        let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())931            .checked_sub(value)932            .unwrap();933        <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);934935        let mut new_owner_account_id = 0;936        let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());937        if new_owner_items.len() > 0 {938            new_owner_account_id = new_owner_items[0];939        }940941        let val64 = value.into();942943        // transfer944        if amount == val64 && new_owner_account_id == 0 {945            // change owner946            // new owner do not have account947            let mut new_full_item = full_item.clone();948            new_full_item.owner = new_owner.clone();949            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);950951            // update balance952            let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())953                .checked_add(value)954                .unwrap();955            <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);956957            // update index collection958            Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;959        } else {960            let mut new_full_item = full_item.clone();961            new_full_item.value -= val64;962963            // separate amount964            if new_owner_account_id > 0 {965                // new owner has account966                let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);967                item.value += val64;968969                // update balance970                let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())971                    .checked_add(value)972                    .unwrap();973                <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);974975                <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);976            } else {977                // new owner do not have account978                let item = FungibleItemType {979                    collection: collection_id,980                    owner: new_owner.clone(),981                    value: val64,982                };983984                Self::add_fungible_item(item)?;985            }986987            if amount == val64 {988                Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;989990                // remove approve list991                <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));992                <FungibleItemList<T>>::remove(collection_id, item_id);993            }994995            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);996        }997998        Ok(())999    }10001001    fn transfer_refungible(1002        collection_id: u64,1003        item_id: u64,1004        value: u64,1005        owner: T::AccountId,1006        new_owner: T::AccountId,1007    ) -> DispatchResult {1008        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);1009        let item = full_item1010            .owner1011            .iter()1012            .filter(|i| i.owner == owner)1013            .next()1014            .unwrap();1015        let amount = item.fraction;10161017        ensure!(amount >= value.into(), "Item balance not enouth");10181019        // update balance1020        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1021            .checked_sub(value)1022            .unwrap();1023        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);10241025        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1026            .checked_add(value)1027            .unwrap();1028        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10291030        let old_owner = item.owner.clone();1031        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);1032        let val64 = value.into();10331034        // transfer1035        if amount == val64 && !new_owner_has_account {1036            // change owner1037            // new owner do not have account1038            let mut new_full_item = full_item.clone();1039            new_full_item1040                .owner1041                .iter_mut()1042                .find(|i| i.owner == owner)1043                .unwrap()1044                .owner = new_owner.clone();1045            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);10461047            // update index collection1048            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;1049        } else {1050            let mut new_full_item = full_item.clone();1051            new_full_item1052                .owner1053                .iter_mut()1054                .find(|i| i.owner == owner)1055                .unwrap()1056                .fraction -= val64;10571058            // separate amount1059            if new_owner_has_account {1060                // new owner has account1061                new_full_item1062                    .owner1063                    .iter_mut()1064                    .find(|i| i.owner == new_owner)1065                    .unwrap()1066                    .fraction += val64;1067            } else {1068                // new owner do not have account1069                new_full_item.owner.push(Ownership {1070                    owner: new_owner.clone(),1071                    fraction: val64,1072                });1073                Self::add_token_index(collection_id, item_id, new_owner.clone())?;1074            }10751076            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1077        }10781079        Ok(())1080    }10811082    fn transfer_nft(1083        collection_id: u64,1084        item_id: u64,1085        sender: T::AccountId,1086        new_owner: T::AccountId,1087    ) -> DispatchResult {1088        let mut item = <NftItemList<T>>::get(collection_id, item_id);10891090        ensure!(1091            sender == item.owner,1092            "sender parameter and item owner must be equal"1093        );10941095        // update balance1096        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1097            .checked_sub(1)1098            .unwrap();1099        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);11001101        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1102            .checked_add(1)1103            .unwrap();1104        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);11051106        // change owner1107        let old_owner = item.owner.clone();1108        item.owner = new_owner.clone();1109        <NftItemList<T>>::insert(collection_id, item_id, item);11101111        // update index collection1112        Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;11131114        // reset approved list1115        <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1116        Ok(())1117    }11181119    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1120        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1121        if list_exists {1122            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1123            let item_contains = list.contains(&item_index.clone());11241125            if !item_contains {1126                list.push(item_index.clone());1127            }11281129            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1130        } else {1131            let mut itm = Vec::new();1132            itm.push(item_index.clone());1133            <AddressTokens<T>>::insert(collection_id, owner, itm);1134        }11351136        Ok(())1137    }11381139    fn remove_token_index(1140        collection_id: u64,1141        item_index: u64,1142        owner: T::AccountId,1143    ) -> DispatchResult {1144        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1145        if list_exists {1146            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1147            let item_contains = list.contains(&item_index.clone());11481149            if item_contains {1150                list.retain(|&item| item != item_index);1151                <AddressTokens<T>>::insert(collection_id, owner, list);1152            }1153        }11541155        Ok(())1156    }11571158    fn move_token_index(1159        collection_id: u64,1160        item_index: u64,1161        old_owner: T::AccountId,1162        new_owner: T::AccountId,1163    ) -> DispatchResult {1164        Self::remove_token_index(collection_id, item_index, old_owner)?;1165        Self::add_token_index(collection_id, item_index, new_owner)?;11661167        Ok(())1168    }1169}11701171////////////////////////////////////////////////////////////////////////////////////////////////////1172// Economic models11731174/// Fee multiplier.1175pub type Multiplier = FixedU128;11761177type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1178    <T as system::Trait>::AccountId,1179>>::Balance;1180type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1181    <T as system::Trait>::AccountId,1182>>::NegativeImbalance;11831184/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1185/// in the queue.1186#[derive(Encode, Decode, Clone, Eq, PartialEq)]1187pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1188    #[codec(compact)] BalanceOf<T>,1189);11901191impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1192    for ChargeTransactionPayment<T>1193{1194    #[cfg(feature = "std")]1195    fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1196        write!(f, "ChargeTransactionPayment<{:?}>", self.0)1197    }1198    #[cfg(not(feature = "std"))]1199    fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1200        Ok(())1201    }1202}12031204impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1205where1206    T::Call:1207        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1208    BalanceOf<T>: Send + Sync + FixedPointOperand,1209{1210    /// utility constructor. Used only in client/factory code.1211    pub fn from(fee: BalanceOf<T>) -> Self {1212        Self(fee)1213    }12141215    pub fn traditional_fee(1216        len: usize,1217        info: &DispatchInfoOf<T::Call>,1218        tip: BalanceOf<T>,1219    ) -> BalanceOf<T>1220    where1221        T::Call: Dispatchable<Info = DispatchInfo>,1222    {1223        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1224    }12251226    fn withdraw_fee(1227        &self,1228        who: &T::AccountId,1229        call: &T::Call,1230        info: &DispatchInfoOf<T::Call>,1231        len: usize,1232    ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1233        let tip = self.0;12341235        // Set fee based on call type. Creating collection costs 1 Unique.1236        // All other transactions have traditional fees so far1237        let fee = match call.is_sub_type() {1238            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1239            _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1240                                                        // _ => <BalanceOf<T>>::from(100)1241        };12421243        // Determine who is paying transaction fee based on ecnomic model1244        // Parse call to extract collection ID and access collection sponsor1245        let sponsor: T::AccountId = match call.is_sub_type() {1246            Some(Call::create_item(collection_id, _properties, _owner)) => {1247                <Collection<T>>::get(collection_id).sponsor1248            }1249            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1250                <Collection<T>>::get(collection_id).sponsor1251            }12521253            _ => T::AccountId::default(),1254        };12551256        let mut who_pays_fee: T::AccountId = sponsor.clone();1257        if sponsor == T::AccountId::default() {1258            who_pays_fee = who.clone();1259        }12601261        // Only mess with balances if fee is not zero.1262        if fee.is_zero() {1263            return Ok((fee, None));1264        }12651266        match <T as transaction_payment::Trait>::Currency::withdraw(1267            &who_pays_fee,1268            fee,1269            if tip.is_zero() {1270                WithdrawReason::TransactionPayment.into()1271            } else {1272                WithdrawReason::TransactionPayment | WithdrawReason::Tip1273            },1274            ExistenceRequirement::KeepAlive,1275        ) {1276            Ok(imbalance) => Ok((fee, Some(imbalance))),1277            Err(_) => Err(InvalidTransaction::Payment.into()),1278        }1279    }1280}12811282impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1283    for ChargeTransactionPayment<T>1284where1285    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1286    T::Call:1287        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1288{1289    const IDENTIFIER: &'static str = "ChargeTransactionPayment";1290    type AccountId = T::AccountId;1291    type Call = T::Call;1292    type AdditionalSigned = ();1293    type Pre = (1294        BalanceOf<T>,1295        Self::AccountId,1296        Option<NegativeImbalanceOf<T>>,1297        BalanceOf<T>,1298    );1299    fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1300        Ok(())1301    }13021303    fn validate(1304        &self,1305        who: &Self::AccountId,1306        call: &Self::Call,1307        info: &DispatchInfoOf<Self::Call>,1308        len: usize,1309    ) -> TransactionValidity {1310        let (fee, _) = self.withdraw_fee(who, call, info, len)?;13111312        let mut r = ValidTransaction::default();1313        // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1314        // will be a bit more than setting the priority to tip. For now, this is enough.1315        r.priority = fee.saturated_into::<TransactionPriority>();1316        Ok(r)1317    }13181319    fn pre_dispatch(1320        self,1321        who: &Self::AccountId,1322        call: &Self::Call,1323        info: &DispatchInfoOf<Self::Call>,1324        len: usize,1325    ) -> Result<Self::Pre, TransactionValidityError> {1326        let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1327        Ok((self.0, who.clone(), imbalance, fee))1328    }13291330    fn post_dispatch(1331        pre: Self::Pre,1332        info: &DispatchInfoOf<Self::Call>,1333        post_info: &PostDispatchInfoOf<Self::Call>,1334        len: usize,1335        _result: &DispatchResult,1336    ) -> Result<(), TransactionValidityError> {1337        let (tip, who, imbalance, fee) = pre;1338        if let Some(payed) = imbalance {1339            let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1340                len as u32, info, post_info, tip,1341            );1342            let refund = fee.saturating_sub(actual_fee);1343            let actual_payment =1344                match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1345                    &who, refund,1346                ) {1347                    Ok(refund_imbalance) => {1348                        // The refund cannot be larger than the up front payed max weight.1349                        // `PostDispatchInfo::calc_unspent` guards against such a case.1350                        match payed.offset(refund_imbalance) {1351                            Ok(actual_payment) => actual_payment,1352                            Err(_) => return Err(InvalidTransaction::Payment.into()),1353                        }1354                    }1355                    // We do not recreate the account using the refund. The up front payment1356                    // is gone in that case.1357                    Err(_) => payed,1358                };1359            let imbalances = actual_payment.split(tip);1360            <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1361                Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1362            );1363        }1364        Ok(())1365    }1366}
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -1,6 +1,6 @@
 // Tests to be written here
 use crate::mock::*;
-use crate::{ApprovePermissions, CollectionMode, Ownership};
+use crate::{ApprovePermissions, CollectionMode, AccessMode, Ownership};
 use frame_support::{assert_noop, assert_ok};
 
 #[test]
@@ -321,10 +321,11 @@
         assert_eq!(TemplateModule::balance_count(1, 1), 1);
         assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
-        assert_noop!(
-            TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
-            "You do not have permissions to modify this collection"
-        );
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
 
         // do approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
@@ -390,10 +391,11 @@
         assert_eq!(TemplateModule::balance_count(1, 1), 1000);
         assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
-        assert_noop!(
-            TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
-            "You do not have permissions to modify this collection"
-        );
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
 
         // do approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
@@ -461,10 +463,11 @@
         assert_eq!(TemplateModule::balance_count(1, 1), 1000);
         assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
-        assert_noop!(
-            TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
-            "You do not have permissions to modify this collection"
-        );
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
 
         // do approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
@@ -573,7 +576,6 @@
         let mode: CollectionMode = CollectionMode::NFT(2000);
 
         let origin1 = Origin::signed(1);
-        let origin2 = Origin::signed(2);
         assert_ok!(TemplateModule::create_collection(
             origin1.clone(),
             col_name1.clone(),
@@ -583,7 +585,7 @@
         ));
         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
         assert_ok!(TemplateModule::create_item(
-            origin2.clone(),
+            origin1.clone(),
             1,
             [1, 2, 3].to_vec(),
             1
@@ -614,7 +616,6 @@
         let mode: CollectionMode = CollectionMode::Fungible(3);
 
         let origin1 = Origin::signed(1);
-        let origin2 = Origin::signed(2);
         assert_ok!(TemplateModule::create_collection(
             origin1.clone(),
             col_name1.clone(),
@@ -624,7 +625,7 @@
         ));
         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
         assert_ok!(TemplateModule::create_item(
-            origin2.clone(),
+            origin1.clone(),
             1,
             [].to_vec(),
             1
@@ -661,6 +662,11 @@
             token_prefix1.clone(),
             mode
         ));
+        
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+
         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
         assert_ok!(TemplateModule::create_item(
             origin2.clone(),
@@ -928,6 +934,13 @@
         // approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
         assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);
+
+        assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+        assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+        assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
+
         assert_ok!(TemplateModule::transfer_from(
             origin2.clone(),
             1,