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

difftreelog

source

pallets/nft/src/lib.rs41.7 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23/// For more guidance on Substrate FRAME, see the example pallet4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs56use codec::{Decode, Encode};7pub use frame_support::{8    decl_event, decl_module, decl_storage,9    construct_runtime, parameter_types,10    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},11    weights::{12        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},13        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,14    },15    StorageValue,16    dispatch::DispatchResult, 17    IsSubType,18    ensure19};2021use frame_system::{self as system, ensure_signed};22use sp_runtime::sp_std::prelude::Vec;23use sp_std::prelude::*;24use sp_runtime::{25	FixedU128, FixedPointOperand, 26	transaction_validity::{27		TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity28	},29	traits::{30        Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,31	},32};3334#[cfg(test)]35mod mock;3637#[cfg(test)]38mod tests;3940#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]41pub enum CollectionMode {42    Invalid,43    // custom data size44    NFT(u32),45    // decimal points46    Fungible(u32),47    // custom data size and decimal points48	ReFungible(u32, u32),49}5051impl Into<u8> for CollectionMode {52    fn into(self) -> u8{53        match self {54            CollectionMode::Invalid => 0,55            CollectionMode::NFT(_) => 1,56            CollectionMode::Fungible(_) => 2,57            CollectionMode::ReFungible(_, _) => 3,58        }59    }60}6162#[derive(Encode, Decode, Debug, Clone, PartialEq)]63pub enum AccessMode {64    Normal,65	WhiteList,66}67impl Default for AccessMode { fn default() -> Self { Self::Normal } }6869impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }7071#[derive(Encode, Decode, Default, Clone, PartialEq)]72#[cfg_attr(feature = "std", derive(Debug))]73pub struct Ownership<AccountId> {74    pub owner: AccountId,75    pub fraction: u12876}7778#[derive(Encode, Decode, Default, Clone, PartialEq)]79#[cfg_attr(feature = "std", derive(Debug))]80pub struct CollectionType<AccountId> {81    pub owner: AccountId,82    pub mode: CollectionMode,83    pub access: AccessMode,84    pub decimal_points: u32,85    pub name: Vec<u16>,        // 64 include null escape char86    pub description: Vec<u16>, // 256 include null escape char87    pub token_prefix: Vec<u8>, // 16 include null escape char88    pub custom_data_size: u32,89    pub offchain_schema: Vec<u8>,90    pub sponsor: AccountId,    // Who pays fees. If set to default address, the fees are applied to the transaction sender91    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship92}9394#[derive(Encode, Decode, Default, Clone, PartialEq)]95#[cfg_attr(feature = "std", derive(Debug))]96pub struct CollectionAdminsType<AccountId> {97    pub admin: AccountId,98    pub collection_id: u64,99}100101#[derive(Encode, Decode, Default, Clone, PartialEq)]102#[cfg_attr(feature = "std", derive(Debug))]103pub struct NftItemType<AccountId> {104    pub collection: u64,105    pub owner: AccountId,106    pub data: Vec<u8>,107}108109#[derive(Encode, Decode, Default, Clone, PartialEq)]110#[cfg_attr(feature = "std", derive(Debug))]111pub struct FungibleItemType<AccountId> {112    pub collection: u64,113    pub owner: AccountId,114    pub value: u128,115}116117#[derive(Encode, Decode, Default, Clone, PartialEq)]118#[cfg_attr(feature = "std", derive(Debug))]119pub struct ReFungibleItemType<AccountId> {120    pub collection: u64,121    pub owner: Vec<Ownership<AccountId>>,122    pub data: Vec<u8>,123}124125#[derive(Encode, Decode, Default, Clone, PartialEq)]126#[cfg_attr(feature = "std", derive(Debug))]127pub struct ApprovePermissions<AccountId> {128    pub approved: AccountId,129    pub amount: u64130}131132pub trait Trait: system::Trait {133    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;134135}136137decl_storage! {138    trait Store for Module<T: Trait> as Nft {139140        // Private members141        NextCollectionID: u64;142        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;143144        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;145        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;146        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;147148        /// Balance owner per collection map149        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;150151        /// second parameter: item id + owner account id152        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;153154        /// Item collections155        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;156        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;157        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;158159        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;160161        // Sponsorship162        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;163        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;164    }165}166167decl_event!(168    pub enum Event<T>169    where170        AccountId = <T as system::Trait>::AccountId,171    {172        Created(u64, u8, AccountId),173        ItemCreated(u64, u64),174        ItemDestroyed(u64, u64),175    }176);177178decl_module! {179    pub struct Module<T: Trait> for enum Call where origin: T::Origin {180181        fn deposit_event() = default;182183        // Create collection of NFT with given parameters184        //185        // @param customDataSz size of custom data in each collection item186        // returns collection ID187        #[weight = 0]188        pub fn create_collection(   origin,189                                    collection_name: Vec<u16>,190                                    collection_description: Vec<u16>,191                                    token_prefix: Vec<u8>,192                                    mode: CollectionMode) -> DispatchResult {193194            // Anyone can create a collection195            let who = ensure_signed(origin)?;196            let custom_data_size = match mode {197                CollectionMode::NFT(size) => size,198                CollectionMode::ReFungible(size, _) => size,199                _ => 0200            };201202            let decimal_points = match mode {203                CollectionMode::Fungible(points) => points,204                CollectionMode::ReFungible(_, points) => points,205                _ => 0206            };207208            // check params209            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4"); 210211            let mut name = collection_name.to_vec();212            name.push(0);213            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");214215            let mut description = collection_description.to_vec();216            description.push(0);217            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");218219            let mut prefix = token_prefix.to_vec();220            prefix.push(0);221            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");222223            // Generate next collection ID224            let next_id = NextCollectionID::get()225                .checked_add(1)226                .expect("collection id error");227228            NextCollectionID::put(next_id);229230            // Create new collection231            let new_collection = CollectionType {232                owner: who.clone(),233                name: name,234                mode: mode.clone(),235                access: AccessMode::Normal,236                description: description,237                decimal_points: decimal_points,238                token_prefix: prefix,239                offchain_schema: Vec::new(),240                custom_data_size: custom_data_size,241                sponsor: T::AccountId::default(),242                unconfirmed_sponsor: T::AccountId::default(),243            };244245            // Add new collection to map246            <Collection<T>>::insert(next_id, new_collection);247248            // call event249            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));250251            Ok(())252        }253254        #[weight = 0]255        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {256257            let sender = ensure_signed(origin)?;258            Self::check_owner_permissions(collection_id, sender)?;259260            // TODO Items remove261            <AddressTokens<T>>::remove_prefix(collection_id);262            <ApprovedList<T>>::remove_prefix(collection_id);263            <Balance<T>>::remove_prefix(collection_id);264            <ItemListIndex>::remove(collection_id);265            <AdminList<T>>::remove(collection_id);266            <Collection<T>>::remove(collection_id);267            <WhiteList<T>>::remove(collection_id);268269            Ok(())270        }271272        #[weight = 0]273        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {274275            let sender = ensure_signed(origin)?;276            Self::check_owner_permissions(collection_id, sender)?;277            let mut target_collection = <Collection<T>>::get(collection_id);278            target_collection.owner = new_owner;279            <Collection<T>>::insert(collection_id, target_collection);280281            Ok(())282        }283284        #[weight = 0]285        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {286287            let sender = ensure_signed(origin)?;288            Self::check_owner_or_admin_permissions(collection_id, sender)?;289            let mut admin_arr: Vec<T::AccountId> = Vec::new();290291            if <AdminList<T>>::contains_key(collection_id)292            {293                admin_arr = <AdminList<T>>::get(collection_id);294                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");295            }296297            admin_arr.push(new_admin_id);298            <AdminList<T>>::insert(collection_id, admin_arr);299300            Ok(())301        }302303        #[weight = 0]304        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {305306            let sender = ensure_signed(origin)?;307            Self::check_owner_or_admin_permissions(collection_id, sender)?;308309            if <AdminList<T>>::contains_key(collection_id)310            {311                let mut admin_arr = <AdminList<T>>::get(collection_id);312                admin_arr.retain(|i| *i != account_id);313                <AdminList<T>>::insert(collection_id, admin_arr);314            }315316            Ok(())317        }318319        #[weight = 0]320        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {321322            let sender = ensure_signed(origin)?;323            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");324325            let mut target_collection = <Collection<T>>::get(collection_id);326            ensure!(sender == target_collection.owner, "You do not own this collection");327328            target_collection.unconfirmed_sponsor = new_sponsor;329            <Collection<T>>::insert(collection_id, target_collection);330331            Ok(())332        }333334        #[weight = 0]335        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {336337            let sender = ensure_signed(origin)?;338            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");339340            let mut target_collection = <Collection<T>>::get(collection_id);341            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");342343            target_collection.sponsor = target_collection.unconfirmed_sponsor;344            target_collection.unconfirmed_sponsor = T::AccountId::default();345            <Collection<T>>::insert(collection_id, target_collection);346347            Ok(())348        }349350        #[weight = 0]351        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {352353            let sender = ensure_signed(origin)?;354            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");355356            let mut target_collection = <Collection<T>>::get(collection_id);357            ensure!(sender == target_collection.owner, "You do not own this collection");358359            target_collection.sponsor = T::AccountId::default();360            <Collection<T>>::insert(collection_id, target_collection);361362            Ok(())363        }364        365        #[weight = 0]366        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {367368            let sender = ensure_signed(origin)?;369            let target_collection = <Collection<T>>::get(collection_id);370            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;371372            // TODO: implement other modes373            match target_collection.mode 374            {375                CollectionMode::NFT(_) => {376377                    // check size378                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");379380                    // Create nft item381                    let item = NftItemType {382                        collection: collection_id,383                        owner: owner,384                        data: properties,385                    };386    387                    Self::add_nft_item(item)?;388    389                },390                CollectionMode::Fungible(_) => {391392                    // check size393                    ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");394395                    let item = FungibleItemType {396                        collection: collection_id,397                        owner: owner,398                        value: (10 as u128).pow(target_collection.decimal_points)399                    };400    401                    Self::add_fungible_item(item)?;402                },403                CollectionMode::ReFungible(_, _) => {404405                    // check size406                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");407408                    let mut owner_list = Vec::new();409                    let value = (10 as u128).pow(target_collection.decimal_points);410                    owner_list.push(Ownership {owner: owner, fraction: value});411412                    let item = ReFungibleItemType {413                        collection: collection_id,414                        owner: owner_list,415                        data: properties416                    };417    418                    Self::add_refungible_item(item)?;419                },420                _ => ()421            };422423            // call event424            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));425426            Ok(())427        }428429        #[weight = 0]430        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {431432            let sender = ensure_signed(origin)?;433            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);434            if !item_owner435            {436                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;437            }438            let target_collection = <Collection<T>>::get(collection_id);439440            match target_collection.mode 441            {442                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,443                CollectionMode::Fungible(_)  => Self::burn_fungible_item(collection_id, item_id)?,444                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,445                _ => ()446            };447448            // call event449            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));450451            Ok(())452        }453454        #[weight = 0]455        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {456457            let sender = ensure_signed(origin)?;458            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");459460            let target_collection = <Collection<T>>::get(collection_id);461462            // TODO: implement other modes463            match target_collection.mode 464            {465                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,466                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,467                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,468                _ => ()469            };470471            Ok(())472        }473474        #[weight = 0]475        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {476477            let sender = ensure_signed(origin)?;478479            // amount param stub480            let amount = 100000000;481482            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");483484            let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));485            if list_exists {486487                let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));488                let item_contains = list.iter().any(|i| i.approved == approved);489490                if !item_contains {491                    list.push(ApprovePermissions { approved: approved.clone(), amount: amount });492                    <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);493                }494            } else {495496                let mut list = Vec::new();497                list.push(ApprovePermissions { approved: approved.clone(), amount: amount });498                <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);499            }500501            Ok(())502        }503504        #[weight = 0]505        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {506507            let sender = ensure_signed(origin)?;508            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));509            if approved_list_exists510            {511                let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));512                let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());513                ensure!(opt_item.is_some(), "No approve found"); 514                ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved"); 515516                // remove approve517                let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))518                    .into_iter().filter(|i| i.approved != sender.clone()).collect();519                <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);520            }521            else522            {523                Self::check_owner_or_admin_permissions(collection_id, sender)?;524            }525            526            let target_collection = <Collection<T>>::get(collection_id);527528            match target_collection.mode529            {530                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,531                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,532                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,533                _ => ()534            };535536            Ok(())537        }538539        #[weight = 0]540        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {541542            // let no_perm_mes = "You do not have permissions to modify this collection";543            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);544            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));545            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);546547            // // on_nft_received  call548549            // Self::transfer(origin, collection_id, item_id, new_owner)?;550551            Ok(())552        }553554        #[weight = 0]555        pub fn set_offchain_schema(556            origin,557            collection_id: u64,558            schema: Vec<u8>559        ) -> DispatchResult {560            let sender = ensure_signed(origin)?;561            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;562            563            let mut target_collection = <Collection<T>>::get(collection_id);564            target_collection.offchain_schema = schema;565            <Collection<T>>::insert(collection_id, target_collection);566567            Ok(())        568        }569    }570}571572impl<T: Trait> Module<T> {573574    fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {575576        let current_index = <ItemListIndex>::get(item.collection)577        .checked_add(1)578        .expect("Item list index id error");579        let itemcopy = item.clone();580        let owner = item.owner.clone();581        let value = item.value as u64;582583        Self::add_token_index(item.collection, current_index, owner.clone())?;584585        <ItemListIndex>::insert(item.collection, current_index);586        <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);  587        588        // Update balance589       let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();590       <Balance<T>>::insert(item.collection, owner.clone(), new_balance);591592        Ok(())593    }594595    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {596597        let current_index = <ItemListIndex>::get(item.collection)598        .checked_add(1)599        .expect("Item list index id error");600        let itemcopy = item.clone();601602        let value = item.owner.first().unwrap().fraction as u64;603        let owner = item.owner.first().unwrap().owner.clone();604605        Self::add_token_index(item.collection, current_index, owner.clone())?;606607        <ItemListIndex>::insert(item.collection, current_index);608        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);  609        610        // Update balance611       let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();612       <Balance<T>>::insert(item.collection, owner.clone(), new_balance);613614        Ok(())615    }616617    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {618619        let current_index = <ItemListIndex>::get(item.collection)620        .checked_add(1)621        .expect("Item list index id error");622623        let item_owner = item.owner.clone();624        let collection_id = item.collection.clone();625        Self::add_token_index(collection_id, current_index, item.owner.clone())?;626627        <ItemListIndex>::insert(collection_id, current_index);628        <NftItemList<T>>::insert(collection_id, current_index, item);629630        // Update balance631        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone()).checked_add(1).unwrap();632        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);633634        Ok(())635    }636637    fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {638  639        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);640        let item = collection.owner.iter().filter(|&i| i.owner == owner).next().unwrap();641        Self::remove_token_index(collection_id, item_id, owner.clone())?;642643        // remove approve list644        <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));645646        // update balance647        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();648        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);649650651        <ReFungibleItemList<T>>::remove(collection_id, item_id);652653        Ok(())654    }655656    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {657  658        let item = <NftItemList<T>>::get(collection_id, item_id);659        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;660661        // remove approve list662        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));663664        // update balance665        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();666        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);667        <NftItemList<T>>::remove(collection_id, item_id);668669        Ok(())670    }671672    fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {673  674        let item = <FungibleItemList<T>>::get(collection_id, item_id);675        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;676677        // remove approve list678        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));679680        // update balance681        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.value as u64).unwrap();682        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);683684        <FungibleItemList<T>>::remove(collection_id, item_id);685686        Ok(())        687    }688689    fn collection_exists(collection_id: u64) -> DispatchResult{690        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");691        Ok(())692    }693694    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {695696        Self::collection_exists(collection_id)?;697698        let target_collection = <Collection<T>>::get(collection_id);699        ensure!(subject == target_collection.owner, "You do not own this collection");700701        Ok(())702    }703704    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {705706        Self::collection_exists(collection_id)?;707708        let target_collection = <Collection<T>>::get(collection_id);709        let is_owner = subject == target_collection.owner;710711        let no_perm_mes = "You do not have permissions to modify this collection";712        let exists = <AdminList<T>>::contains_key(collection_id);713714        if !is_owner715        {716            ensure!(exists, no_perm_mes);717            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);718        }719        Ok(())720    }721722    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{723724        let target_collection = <Collection<T>>::get(collection_id);725726        match target_collection.mode {727            CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,728            CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,729            CollectionMode::ReFungible(_, _)  => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),730            CollectionMode::Invalid => false731        }732    }733734    fn transfer_fungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {735        let full_item = <FungibleItemList<T>>::get(collection_id, item_id);736        let amount = full_item.value;737738        ensure!(amount >= value.into(),"Item balance not enouth");739740        // update balance741        let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone()).checked_sub(value).unwrap();742        <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);743744        let mut new_owner_account_id = 0;745        let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());746        if new_owner_items.len() > 0 {747            new_owner_account_id = new_owner_items[0];748        }749750        let val64 = value.into();751752        // transfer753        if amount == val64 && new_owner_account_id == 0754        {755            // change owner756            // new owner do not have account757            let mut new_full_item = full_item.clone();758            new_full_item.owner = new_owner.clone();759            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);760761            // update balance762            let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();763            <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);764765            // update index collection766            Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;767        }768        else769        {770            let mut new_full_item = full_item.clone();771            new_full_item.value -= val64;772773            // separate amount774            if new_owner_account_id > 0 {775776                // new owner has account777                let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);778                item.value += val64;779780                // update balance781                let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();782                <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);783784                <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);785            }786            else787            {788                // new owner do not have account789                let item = FungibleItemType {790                    collection: collection_id,791                    owner: new_owner.clone(),792                    value: val64793                };794795                Self::add_fungible_item(item)?;796            }797798            if amount == val64{799                Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;800        801                // remove approve list802                <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));803                <FungibleItemList<T>>::remove(collection_id, item_id);804            }805806            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);807        }808809        Ok(())810    }811812    fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {813        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);814        let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();815        let amount = item.fraction;816817        ensure!(amount >= value.into(),"Item balance not enouth");818819        // update balance820        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();821        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);822823        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();824        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);825826        let old_owner = item.owner.clone();827        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);828        let val64 = value.into();829830        // transfer831        if amount == val64 && !new_owner_has_account832        {833            // change owner834            // new owner do not have account835            let mut new_full_item = full_item.clone();836            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();837            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);838839            // update index collection840            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;841        }842        else843        {844            let mut new_full_item = full_item.clone();845            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= val64;846847            // separate amount848            if new_owner_has_account {849                // new owner has account850                new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += val64;851            }852            else853            {854                // new owner do not have account855                new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: val64});856                Self::add_token_index(collection_id, item_id, new_owner.clone())?;857            }858859            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);860        }861862        Ok(())863    }864865    fn transfer_nft(collection_id: u64, item_id: u64, sender: T::AccountId, new_owner: T::AccountId) -> DispatchResult {866867        let mut item = <NftItemList<T>>::get(collection_id, item_id);868869        ensure!(sender == item.owner,"sender parameter and item owner must be equal");870871        // update balance872        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();873        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);874875        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();876        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);877878        // change owner879        let old_owner = item.owner.clone();880        item.owner = new_owner.clone();881        <NftItemList<T>>::insert(collection_id, item_id, item);882883        // update index collection884        Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;885886        // reset approved list887        <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));888        Ok(())889    }890891    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {892        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());893        if list_exists {894            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());895            let item_contains = list.contains(&item_index.clone());896897            if !item_contains {898                list.push(item_index.clone());899            }900901            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);902        } else {903            let mut itm = Vec::new();904            itm.push(item_index.clone());905            <AddressTokens<T>>::insert(collection_id, owner, itm);906        }907908        Ok(())909    }910911    fn remove_token_index(912        collection_id: u64,913        item_index: u64,914        owner: T::AccountId,915    ) -> DispatchResult {916        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());917        if list_exists {918            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());919            let item_contains = list.contains(&item_index.clone());920921            if item_contains {922                list.retain(|&item| item != item_index);923                <AddressTokens<T>>::insert(collection_id, owner, list);924            }925        }926927        Ok(())928    }929930    fn move_token_index(931        collection_id: u64,932        item_index: u64,933        old_owner: T::AccountId,934        new_owner: T::AccountId,935    ) -> DispatchResult {936        Self::remove_token_index(collection_id, item_index, old_owner)?;937        Self::add_token_index(collection_id, item_index, new_owner)?;938939        Ok(())940    }941}942943944////////////////////////////////////////////////////////////////////////////////////////////////////945// Economic models946947/// Fee multiplier.948pub type Multiplier = FixedU128;949950type BalanceOf<T> =951	<<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;952type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<953	<T as system::Trait>::AccountId,>>::NegativeImbalance;954955956957/// Require the transactor pay for themselves and maybe include a tip to gain additional priority958/// in the queue.959#[derive(Encode, Decode, Clone, Eq, PartialEq)]960pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);961962impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {963	#[cfg(feature = "std")]964	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {965		write!(f, "ChargeTransactionPayment<{:?}>", self.0)966	}967	#[cfg(not(feature = "std"))]968	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {969		Ok(())970	}971}972973impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where974	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,975	BalanceOf<T>: Send + Sync + FixedPointOperand,976{977	/// utility constructor. Used only in client/factory code.978	pub fn from(fee: BalanceOf<T>) -> Self {979		Self(fee)980	}981982    pub fn traditional_fee(983        len: usize,984        info: &DispatchInfoOf<T::Call>,985        tip: BalanceOf<T>,986    ) -> BalanceOf<T> where987        T::Call: Dispatchable<Info=DispatchInfo>,988    {989        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)990    }991992	fn withdraw_fee(993		&self,994        who: &T::AccountId,995        call: &T::Call,996		info: &DispatchInfoOf<T::Call>,997		len: usize,998	) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {999        let tip = self.0;10001001        // Set fee based on call type. Creating collection costs 1 Unique.1002        // All other transactions have traditional fees so far1003        let fee = match call.is_sub_type() {1004            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1005            _ => Self::traditional_fee(len, info, tip)10061007            // Flat fee model, use only for testing purposes1008            // _ => <BalanceOf<T>>::from(100)1009        };10101011        // Determine who is paying transaction fee based on ecnomic model1012        // Parse call to extract collection ID and access collection sponsor1013        let sponsor: T::AccountId = match call.is_sub_type() {1014            Some(Call::create_item(collection_id, _properties, _owner)) => {1015                <Collection<T>>::get(collection_id).sponsor1016            },1017            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1018                <Collection<T>>::get(collection_id).sponsor1019            },10201021            _ => T::AccountId::default()1022        };10231024        let mut who_pays_fee: T::AccountId = sponsor.clone();1025        if sponsor == T::AccountId::default() {1026            who_pays_fee = who.clone();1027        }10281029		// Only mess with balances if fee is not zero.1030		if fee.is_zero() {1031			return Ok((fee, None));1032		}10331034		match <T as transaction_payment::Trait>::Currency::withdraw(1035			&who_pays_fee,1036			fee,1037			if tip.is_zero() {1038				WithdrawReason::TransactionPayment.into()1039			} else {1040				WithdrawReason::TransactionPayment | WithdrawReason::Tip1041			},1042			ExistenceRequirement::KeepAlive,1043		) {1044			Ok(imbalance) => Ok((fee, Some(imbalance))),1045			Err(_) => Err(InvalidTransaction::Payment.into()),1046		}1047	}1048}10491050impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where1051    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1052    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,1053{1054	const IDENTIFIER: &'static str = "ChargeTransactionPayment";1055	type AccountId = T::AccountId;1056	type Call = T::Call;1057	type AdditionalSigned = ();1058	type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);1059	fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }10601061	fn validate(1062		&self,1063		who: &Self::AccountId,1064		call: &Self::Call,1065		info: &DispatchInfoOf<Self::Call>,1066		len: usize,1067	) -> TransactionValidity {1068		let (fee, _) = self.withdraw_fee(who, call, info, len)?;10691070		let mut r = ValidTransaction::default();1071		// NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1072		// will be a bit more than setting the priority to tip. For now, this is enough.1073		r.priority = fee.saturated_into::<TransactionPriority>();1074		Ok(r)1075	}10761077	fn pre_dispatch(1078		self,1079		who: &Self::AccountId,1080		call: &Self::Call,1081		info: &DispatchInfoOf<Self::Call>,1082		len: usize1083	) -> Result<Self::Pre, TransactionValidityError> {1084		let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1085		Ok((self.0, who.clone(), imbalance, fee))1086	}10871088	fn post_dispatch(1089		pre: Self::Pre,1090		info: &DispatchInfoOf<Self::Call>,1091		post_info: &PostDispatchInfoOf<Self::Call>,1092		len: usize,1093		_result: &DispatchResult,1094	) -> Result<(), TransactionValidityError> {1095		let (tip, who, imbalance, fee) = pre;1096		if let Some(payed) = imbalance {1097			let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1098				len as u32,1099				info,1100				post_info,1101				tip,1102			);1103			let refund = fee.saturating_sub(actual_fee);1104			let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {1105				Ok(refund_imbalance) => {1106					// The refund cannot be larger than the up front payed max weight.1107					// `PostDispatchInfo::calc_unspent` guards against such a case.1108					match payed.offset(refund_imbalance) {1109						Ok(actual_payment) => actual_payment,1110						Err(_) => return Err(InvalidTransaction::Payment.into()),1111					}1112				}1113				// We do not recreate the account using the refund. The up front payment1114				// is gone in that case.1115				Err(_) => payed,1116			};1117			let imbalances = actual_payment.split(tip);1118			<T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()1119				.chain(Some(imbalances.1)));1120		}1121		Ok(())1122	}1123}