git.delta.rocks / unique-network / refs/commits / 49a238852f14

difftreelog

White list state updated

str-mv2020-08-03parent: #256d067.patch.diff
in: master

1 file changed

modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
before · pallets/nft/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23/// For more guidance on Substrate FRAME, see the example pallet4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs56use codec::{Decode, Encode};7pub use frame_support::{8    decl_event, decl_module, decl_storage,9    construct_runtime, parameter_types,10    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},11    weights::{12        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},13        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,14    },15    StorageValue,16    dispatch::DispatchResult, 17    IsSubType,18    ensure19};2021use frame_system::{self as system, ensure_signed};22use sp_runtime::sp_std::prelude::Vec;23use sp_std::prelude::*;24use sp_runtime::{25	FixedU128, FixedPointOperand, 26	transaction_validity::{27		TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity28	},29	traits::{30        Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,31	},32};3334#[cfg(test)]35mod mock;3637#[cfg(test)]38mod tests;3940#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]41pub enum CollectionMode {42    Invalid,43    // custom data size44    NFT(u32),45    // amount46	Fungible(u32),47	ReFungible,48}4950impl Into<u8> for CollectionMode {51    fn into(self) -> u8{52        match self {53            CollectionMode::Invalid => 0,54            CollectionMode::NFT(_) => 1,55            CollectionMode::Fungible(_) => 2,56            CollectionMode::ReFungible => 3,57        }58    }59}6061#[derive(Encode, Decode, Debug, Clone, PartialEq)]62pub enum AccessMode {63    Normal,64	WhiteList,65}66impl Default for AccessMode { fn default() -> Self { Self::Normal } }6768impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }6970#[derive(Encode, Decode, Default, Clone, PartialEq)]71#[cfg_attr(feature = "std", derive(Debug))]72pub struct Ownership<AccountId> {73    pub owner: AccountId,74    pub fraction: u12875}7677#[derive(Encode, Decode, Default, Clone, PartialEq)]78#[cfg_attr(feature = "std", derive(Debug))]79pub struct CollectionType<AccountId> {80    pub owner: AccountId,81    pub mode: CollectionMode,82    pub access: AccessMode,83    pub next_item_id: u64,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<<<<<<< HEAD90    pub offchain_schema: Vec<u8>,91=======92>>>>>>> 10c381b426801d64ec3dcf8623de6b7e279067a293    pub sponsor: AccountId,    // Who pays fees. If set to default address, the fees are applied to the transaction sender94    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship95}9697#[derive(Encode, Decode, Default, Clone, PartialEq)]98#[cfg_attr(feature = "std", derive(Debug))]99pub struct CollectionAdminsType<AccountId> {100    pub admin: AccountId,101    pub collection_id: u64,102}103104#[derive(Encode, Decode, Default, Clone, PartialEq)]105#[cfg_attr(feature = "std", derive(Debug))]106pub struct NftItemType<AccountId> {107    pub collection: u64,108    pub owner: AccountId,109    pub data: Vec<u8>,110}111112#[derive(Encode, Decode, Default, Clone, PartialEq)]113#[cfg_attr(feature = "std", derive(Debug))]114pub struct FungibleItemType<AccountId> {115    pub collection: u64,116    pub owner: Vec<AccountId>,117    pub data: Vec<u64>,118}119120#[derive(Encode, Decode, Default, Clone, PartialEq)]121#[cfg_attr(feature = "std", derive(Debug))]122pub struct ReFungibleItemType<AccountId> {123    pub collection: u64,124    pub owner: Vec<Ownership<AccountId>>,125}126127pub trait Trait: system::Trait {128    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;129130}131132decl_storage! {133    trait Store for Module<T: Trait> as Nft {134135        // Private members136        NextCollectionID: u64;137        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;138139        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;140        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;141142        // Balance owner per collection map143        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;144        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<T::AccountId>;145146        // Item collections147        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;148        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;149        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;150151        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;152    }153}154155decl_event!(156    pub enum Event<T>157    where158        AccountId = <T as system::Trait>::AccountId,159    {160        Created(u64, u8, AccountId),161        ItemCreated(u64, u64),162        ItemDestroyed(u64, u64),163    }164);165166decl_module! {167    pub struct Module<T: Trait> for enum Call where origin: T::Origin {168169        fn deposit_event() = default;170171        // Create collection of NFT with given parameters172        //173        // @param customDataSz size of custom data in each collection item174        // returns collection ID175        #[weight = 0]176        pub fn create_collection(   origin,177                                    collection_name: Vec<u16>,178                                    collection_description: Vec<u16>,179                                    token_prefix: Vec<u8>,180                                    mode: CollectionMode) -> DispatchResult {181182            // Anyone can create a collection183            let who = ensure_signed(origin)?;184            let custom_data_size = match mode {185                CollectionMode::NFT(size) => size,186                _ => 0187            };188189            let decimal_points = match mode {190                CollectionMode::Fungible(points) => points,191                _ => 0192            };193194            // check params195            ensure!(decimal_points < 100, "decimal_points parameter must be lower than 100"); 196197            let mut name = collection_name.to_vec();198            name.push(0);199            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");200201            let mut description = collection_description.to_vec();202            description.push(0);203            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");204205            let mut prefix = token_prefix.to_vec();206            prefix.push(0);207            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");208209            // Generate next collection ID210            let next_id = NextCollectionID::get()211                .checked_add(1)212                .expect("collection id error");213214            NextCollectionID::put(next_id);215216            // Create new collection217            let new_collection = CollectionType {218                owner: who.clone(),219                name: name,220                mode: mode.clone(),221                access: AccessMode::Normal,222                description: description,223                decimal_points: decimal_points,224                token_prefix: prefix,225                next_item_id: next_id,226                offchain_schema: Vec::new(),227                custom_data_size: custom_data_size,228                sponsor: T::AccountId::default(),229                unconfirmed_sponsor: T::AccountId::default(),230            };231232            // Add new collection to map233            <Collection<T>>::insert(next_id, new_collection);234235            // call event236            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));237238            Ok(())239        }240241        #[weight = 0]242        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {243244            let sender = ensure_signed(origin)?;245            Self::check_owner_permissions(collection_id, sender)?;246247            <AddressTokens<T>>::remove_prefix(collection_id);248            <ApprovedList<T>>::remove_prefix(collection_id);249            <Balance<T>>::remove_prefix(collection_id);250            <ItemListIndex>::remove(collection_id);251            <AdminList<T>>::remove(collection_id);252            <Collection<T>>::remove(collection_id);253254            Ok(())255        }256257        #[weight = 0]258        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {259260            let sender = ensure_signed(origin)?;261            Self::check_owner_permissions(collection_id, sender)?;262            let mut target_collection = <Collection<T>>::get(collection_id);263            target_collection.owner = new_owner;264            <Collection<T>>::insert(collection_id, target_collection);265266            Ok(())267        }268269        #[weight = 0]270        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {271272            let sender = ensure_signed(origin)?;273            Self::check_owner_or_admin_permissions(collection_id, sender)?;274            let mut admin_arr: Vec<T::AccountId> = Vec::new();275276            if <AdminList<T>>::contains_key(collection_id)277            {278                admin_arr = <AdminList<T>>::get(collection_id);279                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");280            }281282            admin_arr.push(new_admin_id);283            <AdminList<T>>::insert(collection_id, admin_arr);284285            Ok(())286        }287288        #[weight = 0]289        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {290291            let sender = ensure_signed(origin)?;292            Self::check_owner_or_admin_permissions(collection_id, sender)?;293294            if <AdminList<T>>::contains_key(collection_id)295            {296                let mut admin_arr = <AdminList<T>>::get(collection_id);297                admin_arr.retain(|i| *i != account_id);298                <AdminList<T>>::insert(collection_id, admin_arr);299            }300301            Ok(())302        }303304        #[weight = 0]305        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {306307            let sender = ensure_signed(origin)?;308            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");309310            let mut target_collection = <Collection<T>>::get(collection_id);311            ensure!(sender == target_collection.owner, "You do not own this collection");312313            target_collection.unconfirmed_sponsor = new_sponsor;314            <Collection<T>>::insert(collection_id, target_collection);315316            Ok(())317        }318319        #[weight = 0]320        pub fn confirm_sponsorship(origin, collection_id: u64) -> 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.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");327328            target_collection.sponsor = target_collection.unconfirmed_sponsor;329            target_collection.unconfirmed_sponsor = T::AccountId::default();330            <Collection<T>>::insert(collection_id, target_collection);331332            Ok(())333        }334335        #[weight = 0]336        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {337338            let sender = ensure_signed(origin)?;339            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");340341            let mut target_collection = <Collection<T>>::get(collection_id);342            ensure!(sender == target_collection.owner, "You do not own this collection");343344            target_collection.sponsor = T::AccountId::default();345            <Collection<T>>::insert(collection_id, target_collection);346347            Ok(())348        }349        350        #[weight = 0]351        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {352353            let sender = ensure_signed(origin)?;354355            // check size356            let target_collection = <Collection<T>>::get(collection_id);357            ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");358359            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;360361            let new_balance = <Balance<T>>::get(collection_id, owner.clone()) + 1;362            <Balance<T>>::insert(collection_id, owner.clone(), new_balance);363364            // TODO: implement other modes365            match target_collection.mode 366            {367                CollectionMode::NFT(_) => {368                // Create nft item369                    let item = NftItemType {370                        collection: collection_id,371                        owner: owner,372                        data: properties,373                    };374    375                    Self::add_nft_item(item)?;376    377                },378                _ => ()379            };380381            // call event382            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));383384            Ok(())385        }386387        #[weight = 0]388        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {389390            let sender = ensure_signed(origin)?;391            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);392            if !item_owner393            {394                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;395            }396            397            Self::burn_nft_item(collection_id, item_id)?;398399            // call event400            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));401402            Ok(())403        }404405        #[weight = 0]406        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {407408            let sender = ensure_signed(origin)?;409            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);410            if !item_owner411            {412                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;413            }414415            let target_collection = <Collection<T>>::get(collection_id);416417            // TODO: implement other modes418            match target_collection.mode 419            {420                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, recipient)?,421                _ => ()422            };423424            Ok(())425        }426427        #[weight = 0]428        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {429430            let sender = ensure_signed(origin)?;431432            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);433            if !item_owner434            {435                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;436            }437438            let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);439            if list_exists {440441                let mut list = <ApprovedList<T>>::get(collection_id, item_id);442                let item_contains = list.contains(&approved.clone());443444                if !item_contains {445                    list.push(approved.clone());446                }447            } else {448449                let mut itm = Vec::new();450                itm.push(approved.clone());451                <ApprovedList<T>>::insert(collection_id, item_id, itm);452            }453454            Ok(())455        }456457        #[weight = 0]458        pub fn transfer_from(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, ) -> DispatchResult {459460            let mut approved: bool = false; 461            let sender = ensure_signed(origin)?;462            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);463            if approved_list_exists464            {465                let list_itm = <ApprovedList<T>>::get(collection_id, item_id);466                approved = list_itm.contains(&recipient.clone());467            }468469            if !approved470            {471                Self::check_owner_or_admin_permissions(collection_id, sender)?;472            }473            474            let target_collection = <Collection<T>>::get(collection_id);475476            match target_collection.mode477            {478                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, recipient)?,479                // TODO: implement other modes480                _ => ()481            };482483            Ok(())484        }485486        #[weight = 0]487        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {488489            // let no_perm_mes = "You do not have permissions to modify this collection";490            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);491            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));492            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);493494            // // on_nft_received  call495496            // Self::transfer(origin, collection_id, item_id, new_owner)?;497498            Ok(())499        }500501        #[weight = 0]502        pub fn set_offchain_schema(503            origin,504            collection_id: u64,505            schema: Vec<u8>506        ) -> DispatchResult {507            let sender = ensure_signed(origin)?;508            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;509            510            let mut target_collection = <Collection<T>>::get(collection_id);511            target_collection.offchain_schema = schema;512            <Collection<T>>::insert(collection_id, target_collection);513514            Ok(())        515        }516    }517}518519impl<T: Trait> Module<T> {520521    fn collection_exists(collection_id: u64) -> DispatchResult{522        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");523        Ok(())524    }525526    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {527528        Self::collection_exists(collection_id)?;529530        let target_collection = <Collection<T>>::get(collection_id);531        ensure!(subject == target_collection.owner, "You do not own this collection");532533        Ok(())534    }535536    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {537538        Self::collection_exists(collection_id)?;539540        let target_collection = <Collection<T>>::get(collection_id);541        let is_owner = subject == target_collection.owner;542543        let no_perm_mes = "You do not have permissions to modify this collection";544        let exists = <AdminList<T>>::contains_key(collection_id);545546        if !is_owner547        {548            ensure!(exists, no_perm_mes);549            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);550        }551        Ok(())552    }553554    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{555556        let target_collection = <Collection<T>>::get(collection_id);557558        match target_collection.mode {559            CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,560            CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner.contains(&subject),561            CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),562            CollectionMode::Invalid => false563        }564    }565566    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {567568        let current_index = <ItemListIndex>::get(item.collection)569        .checked_add(1)570        .expect("Item list index id error");571572        Self::add_token_index(item.collection, current_index, item.owner.clone())?;573574        <ItemListIndex>::insert(item.collection, current_index);575        <NftItemList<T>>::insert(item.collection, current_index, item);576577        Ok(())578    }579580    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {581  582        let item = <NftItemList<T>>::get(collection_id, item_id);583        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;584585        // update balance586        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();587        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);588        <NftItemList<T>>::remove(collection_id, item_id);589590        Ok(())591    }592593    fn transfer_nft(collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {594595        let mut item = <NftItemList<T>>::get(collection_id, item_id);596597        // update balance598        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();599        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);600601        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();602        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);603604        // change owner605        let old_owner = item.owner.clone();606        item.owner = new_owner.clone();607        <NftItemList<T>>::insert(collection_id, item_id, item);608609        // update index collection610        Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;611612        // reset approved list613        let itm: Vec<T::AccountId> = Vec::new();614        <ApprovedList<T>>::insert(collection_id, item_id, itm);615616        Ok(())617    }618619    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {620        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());621        if list_exists {622            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());623            let item_contains = list.contains(&item_index.clone());624625            if !item_contains {626                list.push(item_index.clone());627            }628629            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);630        } else {631            let mut itm = Vec::new();632            itm.push(item_index.clone());633            <AddressTokens<T>>::insert(collection_id, owner, itm);634        }635636        Ok(())637    }638639    fn remove_token_index(640        collection_id: u64,641        item_index: u64,642        owner: T::AccountId,643    ) -> DispatchResult {644        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());645        if list_exists {646            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());647            let item_contains = list.contains(&item_index.clone());648649            if item_contains {650                list.retain(|&item| item != item_index);651                <AddressTokens<T>>::insert(collection_id, owner, list);652            }653        }654655        Ok(())656    }657658    fn move_token_index(659        collection_id: u64,660        item_index: u64,661        old_owner: T::AccountId,662        new_owner: T::AccountId,663    ) -> DispatchResult {664        Self::remove_token_index(collection_id, item_index, old_owner)?;665        Self::add_token_index(collection_id, item_index, new_owner)?;666667        Ok(())668    }669}670671672////////////////////////////////////////////////////////////////////////////////////////////////////673// Economic models674675/// Fee multiplier.676pub type Multiplier = FixedU128;677678type BalanceOf<T> =679	<<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;680type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<681	<T as system::Trait>::AccountId,>>::NegativeImbalance;682683684685/// Require the transactor pay for themselves and maybe include a tip to gain additional priority686/// in the queue.687#[derive(Encode, Decode, Clone, Eq, PartialEq)]688pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);689690impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {691	#[cfg(feature = "std")]692	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {693		write!(f, "ChargeTransactionPayment<{:?}>", self.0)694	}695	#[cfg(not(feature = "std"))]696	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {697		Ok(())698	}699}700701impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where702	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,703	BalanceOf<T>: Send + Sync + FixedPointOperand,704{705	/// utility constructor. Used only in client/factory code.706	pub fn from(fee: BalanceOf<T>) -> Self {707		Self(fee)708	}709710    pub fn traditional_fee(711        len: usize,712        info: &DispatchInfoOf<T::Call>,713        tip: BalanceOf<T>,714    ) -> BalanceOf<T> where715        T::Call: Dispatchable<Info=DispatchInfo>,716    {717        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)718    }719720	fn withdraw_fee(721		&self,722        who: &T::AccountId,723        call: &T::Call,724		info: &DispatchInfoOf<T::Call>,725		len: usize,726	) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {727        let tip = self.0;728729        // Set fee based on call type. Creating collection costs 1 Unique.730        // All other transactions have traditional fees so far731        let fee = match call.is_sub_type() {732            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),733            _ => Self::traditional_fee(len, info, tip)734735            // Flat fee model, use only for testing purposes736            // _ => <BalanceOf<T>>::from(100)737        };738739        // Determine who is paying transaction fee based on ecnomic model740        // Parse call to extract collection ID and access collection sponsor741        let sponsor: T::AccountId = match call.is_sub_type() {742            Some(Call::create_item(collection_id, _properties, _owner)) => {743                <Collection<T>>::get(collection_id).sponsor744            },745            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {746                <Collection<T>>::get(collection_id).sponsor747            },748749            _ => T::AccountId::default()750        };751752        let mut who_pays_fee: T::AccountId = sponsor.clone();753        if sponsor == T::AccountId::default() {754            who_pays_fee = who.clone();755        }756757		// Only mess with balances if fee is not zero.758		if fee.is_zero() {759			return Ok((fee, None));760		}761762		match <T as transaction_payment::Trait>::Currency::withdraw(763			&who_pays_fee,764			fee,765			if tip.is_zero() {766				WithdrawReason::TransactionPayment.into()767			} else {768				WithdrawReason::TransactionPayment | WithdrawReason::Tip769			},770			ExistenceRequirement::KeepAlive,771		) {772			Ok(imbalance) => Ok((fee, Some(imbalance))),773			Err(_) => Err(InvalidTransaction::Payment.into()),774		}775	}776}777778impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where779    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,780    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,781{782	const IDENTIFIER: &'static str = "ChargeTransactionPayment";783	type AccountId = T::AccountId;784	type Call = T::Call;785	type AdditionalSigned = ();786	type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);787	fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }788789	fn validate(790		&self,791		who: &Self::AccountId,792		call: &Self::Call,793		info: &DispatchInfoOf<Self::Call>,794		len: usize,795	) -> TransactionValidity {796		let (fee, _) = self.withdraw_fee(who, call, info, len)?;797798		let mut r = ValidTransaction::default();799		// NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which800		// will be a bit more than setting the priority to tip. For now, this is enough.801		r.priority = fee.saturated_into::<TransactionPriority>();802		Ok(r)803	}804805	fn pre_dispatch(806		self,807		who: &Self::AccountId,808		call: &Self::Call,809		info: &DispatchInfoOf<Self::Call>,810		len: usize811	) -> Result<Self::Pre, TransactionValidityError> {812		let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;813		Ok((self.0, who.clone(), imbalance, fee))814	}815816	fn post_dispatch(817		pre: Self::Pre,818		info: &DispatchInfoOf<Self::Call>,819		post_info: &PostDispatchInfoOf<Self::Call>,820		len: usize,821		_result: &DispatchResult,822	) -> Result<(), TransactionValidityError> {823		let (tip, who, imbalance, fee) = pre;824		if let Some(payed) = imbalance {825			let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(826				len as u32,827				info,828				post_info,829				tip,830			);831			let refund = fee.saturating_sub(actual_fee);832			let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {833				Ok(refund_imbalance) => {834					// The refund cannot be larger than the up front payed max weight.835					// `PostDispatchInfo::calc_unspent` guards against such a case.836					match payed.offset(refund_imbalance) {837						Ok(actual_payment) => actual_payment,838						Err(_) => return Err(InvalidTransaction::Payment.into()),839					}840				}841				// We do not recreate the account using the refund. The up front payment842				// is gone in that case.843				Err(_) => payed,844			};845			let imbalances = actual_payment.split(tip);846			<T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()847				.chain(Some(imbalances.1)));848		}849		Ok(())850	}851}
after · pallets/nft/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23/// For more guidance on Substrate FRAME, see the example pallet4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs56use codec::{Decode, Encode};7pub use frame_support::{8    decl_event, decl_module, decl_storage,9    construct_runtime, parameter_types,10    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},11    weights::{12        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},13        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,14    },15    StorageValue,16    dispatch::DispatchResult, 17    IsSubType,18    ensure19};2021use frame_system::{self as system, ensure_signed};22use sp_runtime::sp_std::prelude::Vec;23use sp_std::prelude::*;24use sp_runtime::{25	FixedU128, FixedPointOperand, 26	transaction_validity::{27		TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity28	},29	traits::{30        Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,31	},32};3334#[cfg(test)]35mod mock;3637#[cfg(test)]38mod tests;3940#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]41pub enum CollectionMode {42    Invalid,43    // custom data size44    NFT(u32),45    // amount46	Fungible(u32),47	ReFungible,48}4950impl Into<u8> for CollectionMode {51    fn into(self) -> u8{52        match self {53            CollectionMode::Invalid => 0,54            CollectionMode::NFT(_) => 1,55            CollectionMode::Fungible(_) => 2,56            CollectionMode::ReFungible => 3,57        }58    }59}6061#[derive(Encode, Decode, Debug, Clone, PartialEq)]62pub enum AccessMode {63    Normal,64	WhiteList,65}66impl Default for AccessMode { fn default() -> Self { Self::Normal } }6768impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }6970#[derive(Encode, Decode, Default, Clone, PartialEq)]71#[cfg_attr(feature = "std", derive(Debug))]72pub struct Ownership<AccountId> {73    pub owner: AccountId,74    pub fraction: u12875}7677#[derive(Encode, Decode, Default, Clone, PartialEq)]78#[cfg_attr(feature = "std", derive(Debug))]79pub struct CollectionType<AccountId> {80    pub owner: AccountId,81    pub mode: CollectionMode,82    pub access: AccessMode,83    pub next_item_id: u64,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: Vec<AccountId>,114    pub data: Vec<u64>,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}123124pub trait Trait: system::Trait {125    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;126127}128129decl_storage! {130    trait Store for Module<T: Trait> as Nft {131132        // Private members133        NextCollectionID: u64;134        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;135136        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;137        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;138        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;139140        // Balance owner per collection map141        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;142        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<T::AccountId>;143144        // Item collections145        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;146        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;147        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;148149        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;150    }151}152153decl_event!(154    pub enum Event<T>155    where156        AccountId = <T as system::Trait>::AccountId,157    {158        Created(u64, u8, AccountId),159        ItemCreated(u64, u64),160        ItemDestroyed(u64, u64),161    }162);163164decl_module! {165    pub struct Module<T: Trait> for enum Call where origin: T::Origin {166167        fn deposit_event() = default;168169        // Create collection of NFT with given parameters170        //171        // @param customDataSz size of custom data in each collection item172        // returns collection ID173        #[weight = 0]174        pub fn create_collection(   origin,175                                    collection_name: Vec<u16>,176                                    collection_description: Vec<u16>,177                                    token_prefix: Vec<u8>,178                                    mode: CollectionMode) -> DispatchResult {179180            // Anyone can create a collection181            let who = ensure_signed(origin)?;182            let custom_data_size = match mode {183                CollectionMode::NFT(size) => size,184                _ => 0185            };186187            let decimal_points = match mode {188                CollectionMode::Fungible(points) => points,189                _ => 0190            };191192            // check params193            ensure!(decimal_points < 100, "decimal_points parameter must be lower than 100"); 194195            let mut name = collection_name.to_vec();196            name.push(0);197            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");198199            let mut description = collection_description.to_vec();200            description.push(0);201            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");202203            let mut prefix = token_prefix.to_vec();204            prefix.push(0);205            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");206207            // Generate next collection ID208            let next_id = NextCollectionID::get()209                .checked_add(1)210                .expect("collection id error");211212            NextCollectionID::put(next_id);213214            // Create new collection215            let new_collection = CollectionType {216                owner: who.clone(),217                name: name,218                mode: mode.clone(),219                access: AccessMode::Normal,220                description: description,221                decimal_points: decimal_points,222                token_prefix: prefix,223                next_item_id: next_id,224                offchain_schema: Vec::new(),225                custom_data_size: custom_data_size,226                sponsor: T::AccountId::default(),227                unconfirmed_sponsor: T::AccountId::default(),228            };229230            // Add new collection to map231            <Collection<T>>::insert(next_id, new_collection);232233            // call event234            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));235236            Ok(())237        }238239        #[weight = 0]240        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {241242            let sender = ensure_signed(origin)?;243            Self::check_owner_permissions(collection_id, sender)?;244245            <AddressTokens<T>>::remove_prefix(collection_id);246            <ApprovedList<T>>::remove_prefix(collection_id);247            <Balance<T>>::remove_prefix(collection_id);248            <ItemListIndex>::remove(collection_id);249            <AdminList<T>>::remove(collection_id);250            <Collection<T>>::remove(collection_id);251            <WhiteList<T>>::remove(collection_id);252253            Ok(())254        }255256        #[weight = 0]257        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {258259            let sender = ensure_signed(origin)?;260            Self::check_owner_permissions(collection_id, sender)?;261            let mut target_collection = <Collection<T>>::get(collection_id);262            target_collection.owner = new_owner;263            <Collection<T>>::insert(collection_id, target_collection);264265            Ok(())266        }267268        #[weight = 0]269        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {270271            let sender = ensure_signed(origin)?;272            Self::check_owner_or_admin_permissions(collection_id, sender)?;273            let mut admin_arr: Vec<T::AccountId> = Vec::new();274275            if <AdminList<T>>::contains_key(collection_id)276            {277                admin_arr = <AdminList<T>>::get(collection_id);278                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");279            }280281            admin_arr.push(new_admin_id);282            <AdminList<T>>::insert(collection_id, admin_arr);283284            Ok(())285        }286287        #[weight = 0]288        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {289290            let sender = ensure_signed(origin)?;291            Self::check_owner_or_admin_permissions(collection_id, sender)?;292293            if <AdminList<T>>::contains_key(collection_id)294            {295                let mut admin_arr = <AdminList<T>>::get(collection_id);296                admin_arr.retain(|i| *i != account_id);297                <AdminList<T>>::insert(collection_id, admin_arr);298            }299300            Ok(())301        }302303        #[weight = 0]304        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {305306            let sender = ensure_signed(origin)?;307            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");308309            let mut target_collection = <Collection<T>>::get(collection_id);310            ensure!(sender == target_collection.owner, "You do not own this collection");311312            target_collection.unconfirmed_sponsor = new_sponsor;313            <Collection<T>>::insert(collection_id, target_collection);314315            Ok(())316        }317318        #[weight = 0]319        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {320321            let sender = ensure_signed(origin)?;322            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");323324            let mut target_collection = <Collection<T>>::get(collection_id);325            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");326327            target_collection.sponsor = target_collection.unconfirmed_sponsor;328            target_collection.unconfirmed_sponsor = T::AccountId::default();329            <Collection<T>>::insert(collection_id, target_collection);330331            Ok(())332        }333334        #[weight = 0]335        pub fn remove_collection_sponsor(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.owner, "You do not own this collection");342343            target_collection.sponsor = T::AccountId::default();344            <Collection<T>>::insert(collection_id, target_collection);345346            Ok(())347        }348        349        #[weight = 0]350        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {351352            let sender = ensure_signed(origin)?;353354            // check size355            let target_collection = <Collection<T>>::get(collection_id);356            ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");357358            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;359360            let new_balance = <Balance<T>>::get(collection_id, owner.clone()) + 1;361            <Balance<T>>::insert(collection_id, owner.clone(), new_balance);362363            // TODO: implement other modes364            match target_collection.mode 365            {366                CollectionMode::NFT(_) => {367                // Create nft item368                    let item = NftItemType {369                        collection: collection_id,370                        owner: owner,371                        data: properties,372                    };373    374                    Self::add_nft_item(item)?;375    376                },377                _ => ()378            };379380            // call event381            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));382383            Ok(())384        }385386        #[weight = 0]387        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {388389            let sender = ensure_signed(origin)?;390            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);391            if !item_owner392            {393                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;394            }395            396            Self::burn_nft_item(collection_id, item_id)?;397398            // call event399            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));400401            Ok(())402        }403404        #[weight = 0]405        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {406407            let sender = ensure_signed(origin)?;408            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);409            if !item_owner410            {411                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;412            }413414            let target_collection = <Collection<T>>::get(collection_id);415416            // TODO: implement other modes417            match target_collection.mode 418            {419                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, recipient)?,420                _ => ()421            };422423            Ok(())424        }425426        #[weight = 0]427        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {428429            let sender = ensure_signed(origin)?;430431            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);432            if !item_owner433            {434                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;435            }436437            let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);438            if list_exists {439440                let mut list = <ApprovedList<T>>::get(collection_id, item_id);441                let item_contains = list.contains(&approved.clone());442443                if !item_contains {444                    list.push(approved.clone());445                }446            } else {447448                let mut itm = Vec::new();449                itm.push(approved.clone());450                <ApprovedList<T>>::insert(collection_id, item_id, itm);451            }452453            Ok(())454        }455456        #[weight = 0]457        pub fn transfer_from(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, ) -> DispatchResult {458459            let mut approved: bool = false; 460            let sender = ensure_signed(origin)?;461            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);462            if approved_list_exists463            {464                let list_itm = <ApprovedList<T>>::get(collection_id, item_id);465                approved = list_itm.contains(&recipient.clone());466            }467468            if !approved469            {470                Self::check_owner_or_admin_permissions(collection_id, sender)?;471            }472            473            let target_collection = <Collection<T>>::get(collection_id);474475            match target_collection.mode476            {477                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, recipient)?,478                // TODO: implement other modes479                _ => ()480            };481482            Ok(())483        }484485        #[weight = 0]486        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {487488            // let no_perm_mes = "You do not have permissions to modify this collection";489            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);490            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));491            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);492493            // // on_nft_received  call494495            // Self::transfer(origin, collection_id, item_id, new_owner)?;496497            Ok(())498        }499500        #[weight = 0]501        pub fn set_offchain_schema(502            origin,503            collection_id: u64,504            schema: Vec<u8>505        ) -> DispatchResult {506            let sender = ensure_signed(origin)?;507            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;508            509            let mut target_collection = <Collection<T>>::get(collection_id);510            target_collection.offchain_schema = schema;511            <Collection<T>>::insert(collection_id, target_collection);512513            Ok(())        514        }515    }516}517518impl<T: Trait> Module<T> {519520    fn collection_exists(collection_id: u64) -> DispatchResult{521        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");522        Ok(())523    }524525    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {526527        Self::collection_exists(collection_id)?;528529        let target_collection = <Collection<T>>::get(collection_id);530        ensure!(subject == target_collection.owner, "You do not own this collection");531532        Ok(())533    }534535    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {536537        Self::collection_exists(collection_id)?;538539        let target_collection = <Collection<T>>::get(collection_id);540        let is_owner = subject == target_collection.owner;541542        let no_perm_mes = "You do not have permissions to modify this collection";543        let exists = <AdminList<T>>::contains_key(collection_id);544545        if !is_owner546        {547            ensure!(exists, no_perm_mes);548            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);549        }550        Ok(())551    }552553    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{554555        let target_collection = <Collection<T>>::get(collection_id);556557        match target_collection.mode {558            CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,559            CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner.contains(&subject),560            CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),561            CollectionMode::Invalid => false562        }563    }564565    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {566567        let current_index = <ItemListIndex>::get(item.collection)568        .checked_add(1)569        .expect("Item list index id error");570571        Self::add_token_index(item.collection, current_index, item.owner.clone())?;572573        <ItemListIndex>::insert(item.collection, current_index);574        <NftItemList<T>>::insert(item.collection, current_index, item);575576        Ok(())577    }578579    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {580  581        let item = <NftItemList<T>>::get(collection_id, item_id);582        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;583584        // update balance585        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();586        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);587        <NftItemList<T>>::remove(collection_id, item_id);588589        Ok(())590    }591592    fn transfer_nft(collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {593594        let mut item = <NftItemList<T>>::get(collection_id, item_id);595596        // update balance597        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();598        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);599600        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();601        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);602603        // change owner604        let old_owner = item.owner.clone();605        item.owner = new_owner.clone();606        <NftItemList<T>>::insert(collection_id, item_id, item);607608        // update index collection609        Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;610611        // reset approved list612        let itm: Vec<T::AccountId> = Vec::new();613        <ApprovedList<T>>::insert(collection_id, item_id, itm);614615        Ok(())616    }617618    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {619        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());620        if list_exists {621            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());622            let item_contains = list.contains(&item_index.clone());623624            if !item_contains {625                list.push(item_index.clone());626            }627628            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);629        } else {630            let mut itm = Vec::new();631            itm.push(item_index.clone());632            <AddressTokens<T>>::insert(collection_id, owner, itm);633        }634635        Ok(())636    }637638    fn remove_token_index(639        collection_id: u64,640        item_index: u64,641        owner: T::AccountId,642    ) -> DispatchResult {643        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());644        if list_exists {645            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());646            let item_contains = list.contains(&item_index.clone());647648            if item_contains {649                list.retain(|&item| item != item_index);650                <AddressTokens<T>>::insert(collection_id, owner, list);651            }652        }653654        Ok(())655    }656657    fn move_token_index(658        collection_id: u64,659        item_index: u64,660        old_owner: T::AccountId,661        new_owner: T::AccountId,662    ) -> DispatchResult {663        Self::remove_token_index(collection_id, item_index, old_owner)?;664        Self::add_token_index(collection_id, item_index, new_owner)?;665666        Ok(())667    }668}669670671////////////////////////////////////////////////////////////////////////////////////////////////////672// Economic models673674/// Fee multiplier.675pub type Multiplier = FixedU128;676677type BalanceOf<T> =678	<<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;679type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<680	<T as system::Trait>::AccountId,>>::NegativeImbalance;681682683684/// Require the transactor pay for themselves and maybe include a tip to gain additional priority685/// in the queue.686#[derive(Encode, Decode, Clone, Eq, PartialEq)]687pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);688689impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {690	#[cfg(feature = "std")]691	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {692		write!(f, "ChargeTransactionPayment<{:?}>", self.0)693	}694	#[cfg(not(feature = "std"))]695	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {696		Ok(())697	}698}699700impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where701	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,702	BalanceOf<T>: Send + Sync + FixedPointOperand,703{704	/// utility constructor. Used only in client/factory code.705	pub fn from(fee: BalanceOf<T>) -> Self {706		Self(fee)707	}708709    pub fn traditional_fee(710        len: usize,711        info: &DispatchInfoOf<T::Call>,712        tip: BalanceOf<T>,713    ) -> BalanceOf<T> where714        T::Call: Dispatchable<Info=DispatchInfo>,715    {716        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)717    }718719	fn withdraw_fee(720		&self,721        who: &T::AccountId,722        call: &T::Call,723		info: &DispatchInfoOf<T::Call>,724		len: usize,725	) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {726        let tip = self.0;727728        // Set fee based on call type. Creating collection costs 1 Unique.729        // All other transactions have traditional fees so far730        let fee = match call.is_sub_type() {731            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),732            _ => Self::traditional_fee(len, info, tip)733734            // Flat fee model, use only for testing purposes735            // _ => <BalanceOf<T>>::from(100)736        };737738        // Determine who is paying transaction fee based on ecnomic model739        // Parse call to extract collection ID and access collection sponsor740        let sponsor: T::AccountId = match call.is_sub_type() {741            Some(Call::create_item(collection_id, _properties, _owner)) => {742                <Collection<T>>::get(collection_id).sponsor743            },744            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {745                <Collection<T>>::get(collection_id).sponsor746            },747748            _ => T::AccountId::default()749        };750751        let mut who_pays_fee: T::AccountId = sponsor.clone();752        if sponsor == T::AccountId::default() {753            who_pays_fee = who.clone();754        }755756		// Only mess with balances if fee is not zero.757		if fee.is_zero() {758			return Ok((fee, None));759		}760761		match <T as transaction_payment::Trait>::Currency::withdraw(762			&who_pays_fee,763			fee,764			if tip.is_zero() {765				WithdrawReason::TransactionPayment.into()766			} else {767				WithdrawReason::TransactionPayment | WithdrawReason::Tip768			},769			ExistenceRequirement::KeepAlive,770		) {771			Ok(imbalance) => Ok((fee, Some(imbalance))),772			Err(_) => Err(InvalidTransaction::Payment.into()),773		}774	}775}776777impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where778    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,779    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,780{781	const IDENTIFIER: &'static str = "ChargeTransactionPayment";782	type AccountId = T::AccountId;783	type Call = T::Call;784	type AdditionalSigned = ();785	type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);786	fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }787788	fn validate(789		&self,790		who: &Self::AccountId,791		call: &Self::Call,792		info: &DispatchInfoOf<Self::Call>,793		len: usize,794	) -> TransactionValidity {795		let (fee, _) = self.withdraw_fee(who, call, info, len)?;796797		let mut r = ValidTransaction::default();798		// NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which799		// will be a bit more than setting the priority to tip. For now, this is enough.800		r.priority = fee.saturated_into::<TransactionPriority>();801		Ok(r)802	}803804	fn pre_dispatch(805		self,806		who: &Self::AccountId,807		call: &Self::Call,808		info: &DispatchInfoOf<Self::Call>,809		len: usize810	) -> Result<Self::Pre, TransactionValidityError> {811		let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;812		Ok((self.0, who.clone(), imbalance, fee))813	}814815	fn post_dispatch(816		pre: Self::Pre,817		info: &DispatchInfoOf<Self::Call>,818		post_info: &PostDispatchInfoOf<Self::Call>,819		len: usize,820		_result: &DispatchResult,821	) -> Result<(), TransactionValidityError> {822		let (tip, who, imbalance, fee) = pre;823		if let Some(payed) = imbalance {824			let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(825				len as u32,826				info,827				post_info,828				tip,829			);830			let refund = fee.saturating_sub(actual_fee);831			let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {832				Ok(refund_imbalance) => {833					// The refund cannot be larger than the up front payed max weight.834					// `PostDispatchInfo::calc_unspent` guards against such a case.835					match payed.offset(refund_imbalance) {836						Ok(actual_payment) => actual_payment,837						Err(_) => return Err(InvalidTransaction::Payment.into()),838					}839				}840				// We do not recreate the account using the refund. The up front payment841				// is gone in that case.842				Err(_) => payed,843			};844			let imbalances = actual_payment.split(tip);845			<T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()846				.chain(Some(imbalances.1)));847		}848		Ok(())849	}850}