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

difftreelog

Merge branch 'dev'

Greg Zaitsev2020-08-05parents: #5b57799 #a55594d.patch.diff
in: master

2 files changed

modifiedREADME.mddiffbeforeafterboth
--- a/README.md
+++ b/README.md
@@ -126,7 +126,6 @@
     "Owner": "AccountId",
     "Mode": "CollectionMode",
     "Access": "u8",
-    "NextItemId": "u64",
     "DecimalPoints": "u32",
     "Name": "Vec<u16>",
     "Description": "Vec<u16>",
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
before · pallets/nft/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23/// For more guidance on Substrate FRAME, see the example pallet4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs56use codec::{Decode, Encode};7pub use frame_support::{8    decl_event, decl_module, decl_storage,9    construct_runtime, parameter_types,10    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},11    weights::{12        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},13        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,14    },15    StorageValue,16    dispatch::DispatchResult, 17    IsSubType,18    ensure19};2021use frame_system::{self as system, ensure_signed};22use sp_runtime::sp_std::prelude::Vec;23use sp_std::prelude::*;24use sp_runtime::{25	FixedU128, FixedPointOperand, 26	transaction_validity::{27		TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity28	},29	traits::{30        Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,31	},32};3334#[cfg(test)]35mod mock;3637#[cfg(test)]38mod tests;3940#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]41pub enum CollectionMode {42    Invalid,43    // custom data size44    NFT(u32),45    // decimal points46    Fungible(u32),47    // custom data size and decimal points48	ReFungible(u32, u32),49}5051impl Into<u8> for CollectionMode {52    fn into(self) -> u8{53        match self {54            CollectionMode::Invalid => 0,55            CollectionMode::NFT(_) => 1,56            CollectionMode::Fungible(_) => 2,57            CollectionMode::ReFungible(_, _) => 3,58        }59    }60}6162#[derive(Encode, Decode, Debug, Clone, PartialEq)]63pub enum AccessMode {64    Normal,65	WhiteList,66}67impl Default for AccessMode { fn default() -> Self { Self::Normal } }6869impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }7071#[derive(Encode, Decode, Default, Clone, PartialEq)]72#[cfg_attr(feature = "std", derive(Debug))]73pub struct Ownership<AccountId> {74    pub owner: AccountId,75    pub fraction: u12876}7778#[derive(Encode, Decode, Default, Clone, PartialEq)]79#[cfg_attr(feature = "std", derive(Debug))]80pub struct CollectionType<AccountId> {81    pub owner: AccountId,82    pub mode: CollectionMode,83    pub access: AccessMode,84    pub next_item_id: u64,85    pub decimal_points: u32,86    pub name: Vec<u16>,        // 64 include null escape char87    pub description: Vec<u16>, // 256 include null escape char88    pub token_prefix: Vec<u8>, // 16 include null escape char89    pub custom_data_size: u32,90    pub offchain_schema: Vec<u8>,91    pub sponsor: AccountId,    // Who pays fees. If set to default address, the fees are applied to the transaction sender92    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship93}9495#[derive(Encode, Decode, Default, Clone, PartialEq)]96#[cfg_attr(feature = "std", derive(Debug))]97pub struct CollectionAdminsType<AccountId> {98    pub admin: AccountId,99    pub collection_id: u64,100}101102#[derive(Encode, Decode, Default, Clone, PartialEq)]103#[cfg_attr(feature = "std", derive(Debug))]104pub struct NftItemType<AccountId> {105    pub collection: u64,106    pub owner: AccountId,107    pub data: Vec<u8>,108}109110#[derive(Encode, Decode, Default, Clone, PartialEq)]111#[cfg_attr(feature = "std", derive(Debug))]112pub struct FungibleItemType<AccountId> {113    pub collection: u64,114    pub owner: AccountId,115    pub value: u128,116}117118#[derive(Encode, Decode, Default, Clone, PartialEq)]119#[cfg_attr(feature = "std", derive(Debug))]120pub struct ReFungibleItemType<AccountId> {121    pub collection: u64,122    pub owner: Vec<Ownership<AccountId>>,123    pub data: Vec<u8>,124}125126pub trait Trait: system::Trait {127    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;128129}130131decl_storage! {132    trait Store for Module<T: Trait> as Nft {133134        // Private members135        NextCollectionID: u64;136        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;137138        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;139        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;140        pub WhiteList get(fn white_list): 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>;152153        // Sponsorship154        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;155        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;156    }157}158159decl_event!(160    pub enum Event<T>161    where162        AccountId = <T as system::Trait>::AccountId,163    {164        Created(u64, u8, AccountId),165        ItemCreated(u64, u64),166        ItemDestroyed(u64, u64),167    }168);169170decl_module! {171    pub struct Module<T: Trait> for enum Call where origin: T::Origin {172173        fn deposit_event() = default;174175        // Create collection of NFT with given parameters176        //177        // @param customDataSz size of custom data in each collection item178        // returns collection ID179        #[weight = 0]180        pub fn create_collection(   origin,181                                    collection_name: Vec<u16>,182                                    collection_description: Vec<u16>,183                                    token_prefix: Vec<u8>,184                                    mode: CollectionMode) -> DispatchResult {185186            // Anyone can create a collection187            let who = ensure_signed(origin)?;188            let custom_data_size = match mode {189                CollectionMode::NFT(size) => size,190                CollectionMode::ReFungible(size, _) => size,191                _ => 0192            };193194            let decimal_points = match mode {195                CollectionMode::Fungible(points) => points,196                CollectionMode::ReFungible(_, points) => points,197                _ => 0198            };199200            // check params201            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4"); 202203            let mut name = collection_name.to_vec();204            name.push(0);205            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");206207            let mut description = collection_description.to_vec();208            description.push(0);209            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");210211            let mut prefix = token_prefix.to_vec();212            prefix.push(0);213            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");214215            // Generate next collection ID216            let next_id = NextCollectionID::get()217                .checked_add(1)218                .expect("collection id error");219220            NextCollectionID::put(next_id);221222            // Create new collection223            let new_collection = CollectionType {224                owner: who.clone(),225                name: name,226                mode: mode.clone(),227                access: AccessMode::Normal,228                description: description,229                decimal_points: decimal_points,230                token_prefix: prefix,231                next_item_id: next_id,232                offchain_schema: Vec::new(),233                custom_data_size: custom_data_size,234                sponsor: T::AccountId::default(),235                unconfirmed_sponsor: T::AccountId::default(),236            };237238            // Add new collection to map239            <Collection<T>>::insert(next_id, new_collection);240241            // call event242            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));243244            Ok(())245        }246247        #[weight = 0]248        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {249250            let sender = ensure_signed(origin)?;251            Self::check_owner_permissions(collection_id, sender)?;252253            <AddressTokens<T>>::remove_prefix(collection_id);254            <ApprovedList<T>>::remove_prefix(collection_id);255            <Balance<T>>::remove_prefix(collection_id);256            <ItemListIndex>::remove(collection_id);257            <AdminList<T>>::remove(collection_id);258            <Collection<T>>::remove(collection_id);259            <WhiteList<T>>::remove(collection_id);260261            Ok(())262        }263264        #[weight = 0]265        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {266267            let sender = ensure_signed(origin)?;268            Self::check_owner_permissions(collection_id, sender)?;269            let mut target_collection = <Collection<T>>::get(collection_id);270            target_collection.owner = new_owner;271            <Collection<T>>::insert(collection_id, target_collection);272273            Ok(())274        }275276        #[weight = 0]277        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {278279            let sender = ensure_signed(origin)?;280            Self::check_owner_or_admin_permissions(collection_id, sender)?;281            let mut admin_arr: Vec<T::AccountId> = Vec::new();282283            if <AdminList<T>>::contains_key(collection_id)284            {285                admin_arr = <AdminList<T>>::get(collection_id);286                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");287            }288289            admin_arr.push(new_admin_id);290            <AdminList<T>>::insert(collection_id, admin_arr);291292            Ok(())293        }294295        #[weight = 0]296        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {297298            let sender = ensure_signed(origin)?;299            Self::check_owner_or_admin_permissions(collection_id, sender)?;300301            if <AdminList<T>>::contains_key(collection_id)302            {303                let mut admin_arr = <AdminList<T>>::get(collection_id);304                admin_arr.retain(|i| *i != account_id);305                <AdminList<T>>::insert(collection_id, admin_arr);306            }307308            Ok(())309        }310311        #[weight = 0]312        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {313314            let sender = ensure_signed(origin)?;315            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");316317            let mut target_collection = <Collection<T>>::get(collection_id);318            ensure!(sender == target_collection.owner, "You do not own this collection");319320            target_collection.unconfirmed_sponsor = new_sponsor;321            <Collection<T>>::insert(collection_id, target_collection);322323            Ok(())324        }325326        #[weight = 0]327        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {328329            let sender = ensure_signed(origin)?;330            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");331332            let mut target_collection = <Collection<T>>::get(collection_id);333            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");334335            target_collection.sponsor = target_collection.unconfirmed_sponsor;336            target_collection.unconfirmed_sponsor = T::AccountId::default();337            <Collection<T>>::insert(collection_id, target_collection);338339            Ok(())340        }341342        #[weight = 0]343        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {344345            let sender = ensure_signed(origin)?;346            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");347348            let mut target_collection = <Collection<T>>::get(collection_id);349            ensure!(sender == target_collection.owner, "You do not own this collection");350351            target_collection.sponsor = T::AccountId::default();352            <Collection<T>>::insert(collection_id, target_collection);353354            Ok(())355        }356        357        #[weight = 0]358        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {359360            let sender = ensure_signed(origin)?;361362            // check size363            let target_collection = <Collection<T>>::get(collection_id);364            ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");365366            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;367368            let new_balance = <Balance<T>>::get(collection_id, owner.clone()).checked_add(1).unwrap();369            <Balance<T>>::insert(collection_id, owner.clone(), new_balance);370371            // TODO: implement other modes372            match target_collection.mode 373            {374                CollectionMode::NFT(_) => {375                // Create nft item376                    let item = NftItemType {377                        collection: collection_id,378                        owner: owner,379                        data: properties,380                    };381    382                    Self::add_nft_item(item)?;383    384                },385                CollectionMode::ReFungible(_, _) => {386                    let mut owner_list = Vec::new();387                    let value = (10 as u128).pow(target_collection.decimal_points);388                    owner_list.push(Ownership {owner: owner, fraction: value});389390                    let item = ReFungibleItemType {391                        collection: collection_id,392                        owner: owner_list,393                        data: properties394                    };395    396                    Self::add_refungible_item(item)?;397                },398                _ => ()399            };400401            // call event402            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));403404            Ok(())405        }406407        #[weight = 0]408        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {409410            let sender = ensure_signed(origin)?;411            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);412            if !item_owner413            {414                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;415            }416            let target_collection = <Collection<T>>::get(collection_id);417418            match target_collection.mode 419            {420                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,421                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,422                _ => ()423            };424425            // call event426            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));427428            Ok(())429        }430431        #[weight = 0]432        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {433434            let sender = ensure_signed(origin)?;435            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");436437            let target_collection = <Collection<T>>::get(collection_id);438439            // TODO: implement other modes440            match target_collection.mode 441            {442                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,443                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,444                _ => ()445            };446447            Ok(())448        }449450        #[weight = 0]451        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {452453            let sender = ensure_signed(origin)?;454455            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);456            if !item_owner457            {458                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;459            }460461            let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);462            if list_exists {463464                let mut list = <ApprovedList<T>>::get(collection_id, item_id);465                let item_contains = list.contains(&approved.clone());466467                if !item_contains {468                    list.push(approved.clone());469                }470            } else {471472                let mut itm = Vec::new();473                itm.push(approved.clone());474                <ApprovedList<T>>::insert(collection_id, item_id, itm);475            }476477            Ok(())478        }479480        #[weight = 0]481        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {482483            let mut approved: bool = false; 484            let sender = ensure_signed(origin)?;485            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);486            if approved_list_exists487            {488                let list_itm = <ApprovedList<T>>::get(collection_id, item_id);489                approved = list_itm.contains(&recipient.clone());490            }491492            if !approved493            {494                Self::check_owner_or_admin_permissions(collection_id, sender)?;495            }496            497            let target_collection = <Collection<T>>::get(collection_id);498499            match target_collection.mode500            {501                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,502                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from, recipient)?,503                // TODO: implement other modes504                _ => ()505            };506507            Ok(())508        }509510        #[weight = 0]511        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {512513            // let no_perm_mes = "You do not have permissions to modify this collection";514            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);515            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));516            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);517518            // // on_nft_received  call519520            // Self::transfer(origin, collection_id, item_id, new_owner)?;521522            Ok(())523        }524525        #[weight = 0]526        pub fn set_offchain_schema(527            origin,528            collection_id: u64,529            schema: Vec<u8>530        ) -> DispatchResult {531            let sender = ensure_signed(origin)?;532            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;533            534            let mut target_collection = <Collection<T>>::get(collection_id);535            target_collection.offchain_schema = schema;536            <Collection<T>>::insert(collection_id, target_collection);537538            Ok(())        539        }540    }541}542543impl<T: Trait> Module<T> {544545    fn collection_exists(collection_id: u64) -> DispatchResult{546        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");547        Ok(())548    }549550    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {551552        Self::collection_exists(collection_id)?;553554        let target_collection = <Collection<T>>::get(collection_id);555        ensure!(subject == target_collection.owner, "You do not own this collection");556557        Ok(())558    }559560    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {561562        Self::collection_exists(collection_id)?;563564        let target_collection = <Collection<T>>::get(collection_id);565        let is_owner = subject == target_collection.owner;566567        let no_perm_mes = "You do not have permissions to modify this collection";568        let exists = <AdminList<T>>::contains_key(collection_id);569570        if !is_owner571        {572            ensure!(exists, no_perm_mes);573            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);574        }575        Ok(())576    }577578    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{579580        let target_collection = <Collection<T>>::get(collection_id);581582        match target_collection.mode {583            CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,584            CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,585            CollectionMode::ReFungible(_, _)  => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),586            CollectionMode::Invalid => false587        }588    }589590    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {591592        let current_index = <ItemListIndex>::get(item.collection)593        .checked_add(1)594        .expect("Item list index id error");595596        Self::add_token_index(item.collection, current_index, item.owner.first().unwrap().owner.clone())?;597598        <ItemListIndex>::insert(item.collection, current_index);599        <ReFungibleItemList<T>>::insert(item.collection, current_index, item);        600601        Ok(())602    }603604    fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {605  606        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);607        let item = collection.owner.iter().filter(|&i| i.owner == owner).next().unwrap();608        Self::remove_token_index(collection_id, item_id, owner)?;609610        // update balance611        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();612        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);613614        // TODO615        <ReFungibleItemList<T>>::remove(collection_id, item_id);616617        Ok(())618    }619620    fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {621622        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);623        let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();624        let amount = item.fraction;625626        ensure!(amount < value.into(),"Item balance not enouth");627628        // update balance629        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();630        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);631632        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();633        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);634635        let old_owner = item.owner.clone();636        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);637638        // transfer639        if amount == value.into() && !new_owner_has_account640        {641            // change owner642            // new owner do not have account643            let mut new_full_item = full_item.clone();644            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();645            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);646647            // update index collection648            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;649        }650        else651        {652            let mut new_full_item = full_item.clone();653            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= amount;654655            // separate amount656            if new_owner_has_account {657                // new owner has account658                new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += amount;659            }660            else661            {662                // new owner do not have account663                new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: amount});664                Self::add_token_index(collection_id, item_id, new_owner.clone())?;665            }666667            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);668        }669670        Ok(())671    }672    673    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {674675        let current_index = <ItemListIndex>::get(item.collection)676        .checked_add(1)677        .expect("Item list index id error");678679        Self::add_token_index(item.collection, current_index, item.owner.clone())?;680681        <ItemListIndex>::insert(item.collection, current_index);682        <NftItemList<T>>::insert(item.collection, current_index, item);683684        Ok(())685    }686687    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {688  689        let item = <NftItemList<T>>::get(collection_id, item_id);690        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;691692        // update balance693        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();694        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);695        <NftItemList<T>>::remove(collection_id, item_id);696697        Ok(())698    }699700    fn transfer_nft(collection_id: u64, item_id: u64, sender: T::AccountId, new_owner: T::AccountId) -> DispatchResult {701702        let mut item = <NftItemList<T>>::get(collection_id, item_id);703704        ensure!(sender == item.owner,"sender parameter and item owner must be equal");705706        // update balance707        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();708        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);709710        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();711        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);712713        // change owner714        let old_owner = item.owner.clone();715        item.owner = new_owner.clone();716        <NftItemList<T>>::insert(collection_id, item_id, item);717718        // update index collection719        Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;720721        // reset approved list722        let itm: Vec<T::AccountId> = Vec::new();723        <ApprovedList<T>>::insert(collection_id, item_id, itm);724725        Ok(())726    }727728    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {729        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());730        if list_exists {731            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());732            let item_contains = list.contains(&item_index.clone());733734            if !item_contains {735                list.push(item_index.clone());736            }737738            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);739        } else {740            let mut itm = Vec::new();741            itm.push(item_index.clone());742            <AddressTokens<T>>::insert(collection_id, owner, itm);743        }744745        Ok(())746    }747748    fn remove_token_index(749        collection_id: u64,750        item_index: u64,751        owner: T::AccountId,752    ) -> DispatchResult {753        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());754        if list_exists {755            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());756            let item_contains = list.contains(&item_index.clone());757758            if item_contains {759                list.retain(|&item| item != item_index);760                <AddressTokens<T>>::insert(collection_id, owner, list);761            }762        }763764        Ok(())765    }766767    fn move_token_index(768        collection_id: u64,769        item_index: u64,770        old_owner: T::AccountId,771        new_owner: T::AccountId,772    ) -> DispatchResult {773        Self::remove_token_index(collection_id, item_index, old_owner)?;774        Self::add_token_index(collection_id, item_index, new_owner)?;775776        Ok(())777    }778}779780781////////////////////////////////////////////////////////////////////////////////////////////////////782// Economic models783784/// Fee multiplier.785pub type Multiplier = FixedU128;786787type BalanceOf<T> =788	<<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;789type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<790	<T as system::Trait>::AccountId,>>::NegativeImbalance;791792793794/// Require the transactor pay for themselves and maybe include a tip to gain additional priority795/// in the queue.796#[derive(Encode, Decode, Clone, Eq, PartialEq)]797pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);798799impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {800	#[cfg(feature = "std")]801	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {802		write!(f, "ChargeTransactionPayment<{:?}>", self.0)803	}804	#[cfg(not(feature = "std"))]805	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {806		Ok(())807	}808}809810impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where811	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,812	BalanceOf<T>: Send + Sync + FixedPointOperand,813{814	/// utility constructor. Used only in client/factory code.815	pub fn from(fee: BalanceOf<T>) -> Self {816		Self(fee)817	}818819    pub fn traditional_fee(820        len: usize,821        info: &DispatchInfoOf<T::Call>,822        tip: BalanceOf<T>,823    ) -> BalanceOf<T> where824        T::Call: Dispatchable<Info=DispatchInfo>,825    {826        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)827    }828829	fn withdraw_fee(830		&self,831        who: &T::AccountId,832        call: &T::Call,833		info: &DispatchInfoOf<T::Call>,834		len: usize,835	) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {836        let tip = self.0;837838        // Set fee based on call type. Creating collection costs 1 Unique.839        // All other transactions have traditional fees so far840        let fee = match call.is_sub_type() {841            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),842            _ => Self::traditional_fee(len, info, tip)843844            // Flat fee model, use only for testing purposes845            // _ => <BalanceOf<T>>::from(100)846        };847848        // Determine who is paying transaction fee based on ecnomic model849        // Parse call to extract collection ID and access collection sponsor850        let sponsor: T::AccountId = match call.is_sub_type() {851            Some(Call::create_item(collection_id, _properties, _owner)) => {852                <Collection<T>>::get(collection_id).sponsor853            },854            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {855                <Collection<T>>::get(collection_id).sponsor856            },857858            _ => T::AccountId::default()859        };860861        let mut who_pays_fee: T::AccountId = sponsor.clone();862        if sponsor == T::AccountId::default() {863            who_pays_fee = who.clone();864        }865866		// Only mess with balances if fee is not zero.867		if fee.is_zero() {868			return Ok((fee, None));869		}870871		match <T as transaction_payment::Trait>::Currency::withdraw(872			&who_pays_fee,873			fee,874			if tip.is_zero() {875				WithdrawReason::TransactionPayment.into()876			} else {877				WithdrawReason::TransactionPayment | WithdrawReason::Tip878			},879			ExistenceRequirement::KeepAlive,880		) {881			Ok(imbalance) => Ok((fee, Some(imbalance))),882			Err(_) => Err(InvalidTransaction::Payment.into()),883		}884	}885}886887impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where888    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,889    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,890{891	const IDENTIFIER: &'static str = "ChargeTransactionPayment";892	type AccountId = T::AccountId;893	type Call = T::Call;894	type AdditionalSigned = ();895	type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);896	fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }897898	fn validate(899		&self,900		who: &Self::AccountId,901		call: &Self::Call,902		info: &DispatchInfoOf<Self::Call>,903		len: usize,904	) -> TransactionValidity {905		let (fee, _) = self.withdraw_fee(who, call, info, len)?;906907		let mut r = ValidTransaction::default();908		// NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which909		// will be a bit more than setting the priority to tip. For now, this is enough.910		r.priority = fee.saturated_into::<TransactionPriority>();911		Ok(r)912	}913914	fn pre_dispatch(915		self,916		who: &Self::AccountId,917		call: &Self::Call,918		info: &DispatchInfoOf<Self::Call>,919		len: usize920	) -> Result<Self::Pre, TransactionValidityError> {921		let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;922		Ok((self.0, who.clone(), imbalance, fee))923	}924925	fn post_dispatch(926		pre: Self::Pre,927		info: &DispatchInfoOf<Self::Call>,928		post_info: &PostDispatchInfoOf<Self::Call>,929		len: usize,930		_result: &DispatchResult,931	) -> Result<(), TransactionValidityError> {932		let (tip, who, imbalance, fee) = pre;933		if let Some(payed) = imbalance {934			let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(935				len as u32,936				info,937				post_info,938				tip,939			);940			let refund = fee.saturating_sub(actual_fee);941			let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {942				Ok(refund_imbalance) => {943					// The refund cannot be larger than the up front payed max weight.944					// `PostDispatchInfo::calc_unspent` guards against such a case.945					match payed.offset(refund_imbalance) {946						Ok(actual_payment) => actual_payment,947						Err(_) => return Err(InvalidTransaction::Payment.into()),948					}949				}950				// We do not recreate the account using the refund. The up front payment951				// is gone in that case.952				Err(_) => payed,953			};954			let imbalances = actual_payment.split(tip);955			<T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()956				.chain(Some(imbalances.1)));957		}958		Ok(())959	}960}
after · pallets/nft/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23/// For more guidance on Substrate FRAME, see the example pallet4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs56use codec::{Decode, Encode};7pub use frame_support::{8    decl_event, decl_module, decl_storage,9    construct_runtime, parameter_types,10    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},11    weights::{12        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},13        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,14    },15    StorageValue,16    dispatch::DispatchResult, 17    IsSubType,18    ensure19};2021use frame_system::{self as system, ensure_signed};22use sp_runtime::sp_std::prelude::Vec;23use sp_std::prelude::*;24use sp_runtime::{25	FixedU128, FixedPointOperand, 26	transaction_validity::{27		TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity28	},29	traits::{30        Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,31	},32};3334#[cfg(test)]35mod mock;3637#[cfg(test)]38mod tests;3940#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]41pub enum CollectionMode {42    Invalid,43    // custom data size44    NFT(u32),45    // decimal points46    Fungible(u32),47    // custom data size and decimal points48	ReFungible(u32, u32),49}5051impl Into<u8> for CollectionMode {52    fn into(self) -> u8{53        match self {54            CollectionMode::Invalid => 0,55            CollectionMode::NFT(_) => 1,56            CollectionMode::Fungible(_) => 2,57            CollectionMode::ReFungible(_, _) => 3,58        }59    }60}6162#[derive(Encode, Decode, Debug, Clone, PartialEq)]63pub enum AccessMode {64    Normal,65	WhiteList,66}67impl Default for AccessMode { fn default() -> Self { Self::Normal } }6869impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }7071#[derive(Encode, Decode, Default, Clone, PartialEq)]72#[cfg_attr(feature = "std", derive(Debug))]73pub struct Ownership<AccountId> {74    pub owner: AccountId,75    pub fraction: u12876}7778#[derive(Encode, Decode, Default, Clone, PartialEq)]79#[cfg_attr(feature = "std", derive(Debug))]80pub struct CollectionType<AccountId> {81    pub owner: AccountId,82    pub mode: CollectionMode,83    pub access: AccessMode,84    pub decimal_points: u32,85    pub name: Vec<u16>,        // 64 include null escape char86    pub description: Vec<u16>, // 256 include null escape char87    pub token_prefix: Vec<u8>, // 16 include null escape char88    pub custom_data_size: u32,89    pub offchain_schema: Vec<u8>,90    pub sponsor: AccountId,    // Who pays fees. If set to default address, the fees are applied to the transaction sender91    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship92}9394#[derive(Encode, Decode, Default, Clone, PartialEq)]95#[cfg_attr(feature = "std", derive(Debug))]96pub struct CollectionAdminsType<AccountId> {97    pub admin: AccountId,98    pub collection_id: u64,99}100101#[derive(Encode, Decode, Default, Clone, PartialEq)]102#[cfg_attr(feature = "std", derive(Debug))]103pub struct NftItemType<AccountId> {104    pub collection: u64,105    pub owner: AccountId,106    pub data: Vec<u8>,107}108109#[derive(Encode, Decode, Default, Clone, PartialEq)]110#[cfg_attr(feature = "std", derive(Debug))]111pub struct FungibleItemType<AccountId> {112    pub collection: u64,113    pub owner: AccountId,114    pub value: u128,115}116117#[derive(Encode, Decode, Default, Clone, PartialEq)]118#[cfg_attr(feature = "std", derive(Debug))]119pub struct ReFungibleItemType<AccountId> {120    pub collection: u64,121    pub owner: Vec<Ownership<AccountId>>,122    pub data: Vec<u8>,123}124125pub trait Trait: system::Trait {126    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;127128}129130decl_storage! {131    trait Store for Module<T: Trait> as Nft {132133        // Private members134        NextCollectionID: u64;135        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;136137        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;138        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;139        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;140141        // Balance owner per collection map142        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;143        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<T::AccountId>;144145        // Item collections146        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;147        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;148        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;149150        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;151152        // Sponsorship153        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;154        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;155    }156}157158decl_event!(159    pub enum Event<T>160    where161        AccountId = <T as system::Trait>::AccountId,162    {163        Created(u64, u8, AccountId),164        ItemCreated(u64, u64),165        ItemDestroyed(u64, u64),166    }167);168169decl_module! {170    pub struct Module<T: Trait> for enum Call where origin: T::Origin {171172        fn deposit_event() = default;173174        // Create collection of NFT with given parameters175        //176        // @param customDataSz size of custom data in each collection item177        // returns collection ID178        #[weight = 0]179        pub fn create_collection(   origin,180                                    collection_name: Vec<u16>,181                                    collection_description: Vec<u16>,182                                    token_prefix: Vec<u8>,183                                    mode: CollectionMode) -> DispatchResult {184185            // Anyone can create a collection186            let who = ensure_signed(origin)?;187            let custom_data_size = match mode {188                CollectionMode::NFT(size) => size,189                CollectionMode::ReFungible(size, _) => size,190                _ => 0191            };192193            let decimal_points = match mode {194                CollectionMode::Fungible(points) => points,195                CollectionMode::ReFungible(_, points) => points,196                _ => 0197            };198199            // check params200            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4"); 201202            let mut name = collection_name.to_vec();203            name.push(0);204            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");205206            let mut description = collection_description.to_vec();207            description.push(0);208            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");209210            let mut prefix = token_prefix.to_vec();211            prefix.push(0);212            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");213214            // Generate next collection ID215            let next_id = NextCollectionID::get()216                .checked_add(1)217                .expect("collection id error");218219            NextCollectionID::put(next_id);220221            // Create new collection222            let new_collection = CollectionType {223                owner: who.clone(),224                name: name,225                mode: mode.clone(),226                access: AccessMode::Normal,227                description: description,228                decimal_points: decimal_points,229                token_prefix: prefix,230                offchain_schema: Vec::new(),231                custom_data_size: custom_data_size,232                sponsor: T::AccountId::default(),233                unconfirmed_sponsor: T::AccountId::default(),234            };235236            // Add new collection to map237            <Collection<T>>::insert(next_id, new_collection);238239            // call event240            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));241242            Ok(())243        }244245        #[weight = 0]246        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {247248            let sender = ensure_signed(origin)?;249            Self::check_owner_permissions(collection_id, sender)?;250251            <AddressTokens<T>>::remove_prefix(collection_id);252            <ApprovedList<T>>::remove_prefix(collection_id);253            <Balance<T>>::remove_prefix(collection_id);254            <ItemListIndex>::remove(collection_id);255            <AdminList<T>>::remove(collection_id);256            <Collection<T>>::remove(collection_id);257            <WhiteList<T>>::remove(collection_id);258259            Ok(())260        }261262        #[weight = 0]263        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {264265            let sender = ensure_signed(origin)?;266            Self::check_owner_permissions(collection_id, sender)?;267            let mut target_collection = <Collection<T>>::get(collection_id);268            target_collection.owner = new_owner;269            <Collection<T>>::insert(collection_id, target_collection);270271            Ok(())272        }273274        #[weight = 0]275        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {276277            let sender = ensure_signed(origin)?;278            Self::check_owner_or_admin_permissions(collection_id, sender)?;279            let mut admin_arr: Vec<T::AccountId> = Vec::new();280281            if <AdminList<T>>::contains_key(collection_id)282            {283                admin_arr = <AdminList<T>>::get(collection_id);284                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");285            }286287            admin_arr.push(new_admin_id);288            <AdminList<T>>::insert(collection_id, admin_arr);289290            Ok(())291        }292293        #[weight = 0]294        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {295296            let sender = ensure_signed(origin)?;297            Self::check_owner_or_admin_permissions(collection_id, sender)?;298299            if <AdminList<T>>::contains_key(collection_id)300            {301                let mut admin_arr = <AdminList<T>>::get(collection_id);302                admin_arr.retain(|i| *i != account_id);303                <AdminList<T>>::insert(collection_id, admin_arr);304            }305306            Ok(())307        }308309        #[weight = 0]310        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {311312            let sender = ensure_signed(origin)?;313            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");314315            let mut target_collection = <Collection<T>>::get(collection_id);316            ensure!(sender == target_collection.owner, "You do not own this collection");317318            target_collection.unconfirmed_sponsor = new_sponsor;319            <Collection<T>>::insert(collection_id, target_collection);320321            Ok(())322        }323324        #[weight = 0]325        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {326327            let sender = ensure_signed(origin)?;328            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");329330            let mut target_collection = <Collection<T>>::get(collection_id);331            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");332333            target_collection.sponsor = target_collection.unconfirmed_sponsor;334            target_collection.unconfirmed_sponsor = T::AccountId::default();335            <Collection<T>>::insert(collection_id, target_collection);336337            Ok(())338        }339340        #[weight = 0]341        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {342343            let sender = ensure_signed(origin)?;344            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");345346            let mut target_collection = <Collection<T>>::get(collection_id);347            ensure!(sender == target_collection.owner, "You do not own this collection");348349            target_collection.sponsor = T::AccountId::default();350            <Collection<T>>::insert(collection_id, target_collection);351352            Ok(())353        }354        355        #[weight = 0]356        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {357358            let sender = ensure_signed(origin)?;359360            // check size361            let target_collection = <Collection<T>>::get(collection_id);362            ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");363364            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;365366            // TODO: implement other modes367            match target_collection.mode 368            {369                CollectionMode::NFT(_) => {370                // Create nft item371                    let item = NftItemType {372                        collection: collection_id,373                        owner: owner,374                        data: properties,375                    };376    377                    Self::add_nft_item(item)?;378    379                },380                CollectionMode::ReFungible(_, _) => {381                    let mut owner_list = Vec::new();382                    let value = (10 as u128).pow(target_collection.decimal_points);383                    owner_list.push(Ownership {owner: owner, fraction: value});384385                    let item = ReFungibleItemType {386                        collection: collection_id,387                        owner: owner_list,388                        data: properties389                    };390    391                    Self::add_refungible_item(item)?;392                },393                _ => ()394            };395396            // call event397            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));398399            Ok(())400        }401402        #[weight = 0]403        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {404405            let sender = ensure_signed(origin)?;406            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);407            if !item_owner408            {409                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;410            }411            let target_collection = <Collection<T>>::get(collection_id);412413            match target_collection.mode 414            {415                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,416                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,417                _ => ()418            };419420            // call event421            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));422423            Ok(())424        }425426        #[weight = 0]427        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {428429            let sender = ensure_signed(origin)?;430            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");431432            let target_collection = <Collection<T>>::get(collection_id);433434            // TODO: implement other modes435            match target_collection.mode 436            {437                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,438                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,439                _ => ()440            };441442            Ok(())443        }444445        #[weight = 0]446        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {447448            let sender = ensure_signed(origin)?;449450            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);451            if !item_owner452            {453                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;454            }455456            let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);457            if list_exists {458459                let mut list = <ApprovedList<T>>::get(collection_id, item_id);460                let item_contains = list.contains(&approved.clone());461462                if !item_contains {463                    list.push(approved.clone());464                }465            } else {466467                let mut itm = Vec::new();468                itm.push(approved.clone());469                <ApprovedList<T>>::insert(collection_id, item_id, itm);470            }471472            Ok(())473        }474475        #[weight = 0]476        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {477478            let mut approved: bool = false; 479            let sender = ensure_signed(origin)?;480            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);481            if approved_list_exists482            {483                let list_itm = <ApprovedList<T>>::get(collection_id, item_id);484                approved = list_itm.contains(&recipient.clone());485            }486487            if !approved488            {489                Self::check_owner_or_admin_permissions(collection_id, sender)?;490            }491            492            let target_collection = <Collection<T>>::get(collection_id);493494            match target_collection.mode495            {496                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,497                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from, recipient)?,498                // TODO: implement other modes499                _ => ()500            };501502            Ok(())503        }504505        #[weight = 0]506        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {507508            // let no_perm_mes = "You do not have permissions to modify this collection";509            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);510            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));511            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);512513            // // on_nft_received  call514515            // Self::transfer(origin, collection_id, item_id, new_owner)?;516517            Ok(())518        }519520        #[weight = 0]521        pub fn set_offchain_schema(522            origin,523            collection_id: u64,524            schema: Vec<u8>525        ) -> DispatchResult {526            let sender = ensure_signed(origin)?;527            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;528            529            let mut target_collection = <Collection<T>>::get(collection_id);530            target_collection.offchain_schema = schema;531            <Collection<T>>::insert(collection_id, target_collection);532533            Ok(())        534        }535    }536}537538impl<T: Trait> Module<T> {539540    fn collection_exists(collection_id: u64) -> DispatchResult{541        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");542        Ok(())543    }544545    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {546547        Self::collection_exists(collection_id)?;548549        let target_collection = <Collection<T>>::get(collection_id);550        ensure!(subject == target_collection.owner, "You do not own this collection");551552        Ok(())553    }554555    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {556557        Self::collection_exists(collection_id)?;558559        let target_collection = <Collection<T>>::get(collection_id);560        let is_owner = subject == target_collection.owner;561562        let no_perm_mes = "You do not have permissions to modify this collection";563        let exists = <AdminList<T>>::contains_key(collection_id);564565        if !is_owner566        {567            ensure!(exists, no_perm_mes);568            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);569        }570        Ok(())571    }572573    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{574575        let target_collection = <Collection<T>>::get(collection_id);576577        match target_collection.mode {578            CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,579            CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,580            CollectionMode::ReFungible(_, _)  => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),581            CollectionMode::Invalid => false582        }583    }584585    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {586587        let current_index = <ItemListIndex>::get(item.collection)588        .checked_add(1)589        .expect("Item list index id error");590591        let value = item.owner.first().unwrap().fraction as u64;592        let owner = item.owner.first().unwrap().owner.clone();593594        Self::add_token_index(item.collection, current_index, owner.clone())?;595596        <ItemListIndex>::insert(item.collection, current_index);597        <ReFungibleItemList<T>>::insert(item.collection, current_index, item);  598        599        // Update balance600        let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();601        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);602603        Ok(())604    }605606    fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {607  608        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);609        let item = collection.owner.iter().filter(|&i| i.owner == owner).next().unwrap();610        Self::remove_token_index(collection_id, item_id, owner)?;611612        // update balance613        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();614        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);615616        // TODO617        <ReFungibleItemList<T>>::remove(collection_id, item_id);618619        Ok(())620    }621622    fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {623624        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);625        let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();626        let amount = item.fraction;627628        ensure!(amount < value.into(),"Item balance not enouth");629630        // update balance631        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();632        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);633634        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();635        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);636637        let old_owner = item.owner.clone();638        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);639640        // transfer641        if amount == value.into() && !new_owner_has_account642        {643            // change owner644            // new owner do not have account645            let mut new_full_item = full_item.clone();646            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();647            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);648649            // update index collection650            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;651        }652        else653        {654            let mut new_full_item = full_item.clone();655            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= amount;656657            // separate amount658            if new_owner_has_account {659                // new owner has account660                new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += amount;661            }662            else663            {664                // new owner do not have account665                new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: amount});666                Self::add_token_index(collection_id, item_id, new_owner.clone())?;667            }668669            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);670        }671672        Ok(())673    }674    675    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {676677        let current_index = <ItemListIndex>::get(item.collection)678        .checked_add(1)679        .expect("Item list index id error");680681        Self::add_token_index(item.collection, current_index, item.owner.clone())?;682683        <ItemListIndex>::insert(item.collection, current_index);684        <NftItemList<T>>::insert(item.collection, current_index, item);685686        // Update balance687        let new_balance = <Balance<T>>::get(item.collection, item.owner.clone()).checked_add(1).unwrap();688        <Balance<T>>::insert(item.collection_id, item.owner.clone(), new_balance);689690        Ok(())691    }692693    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {694  695        let item = <NftItemList<T>>::get(collection_id, item_id);696        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;697698        // update balance699        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();700        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);701        <NftItemList<T>>::remove(collection_id, item_id);702703        Ok(())704    }705706    fn transfer_nft(collection_id: u64, item_id: u64, sender: T::AccountId, new_owner: T::AccountId) -> DispatchResult {707708        let mut item = <NftItemList<T>>::get(collection_id, item_id);709710        ensure!(sender == item.owner,"sender parameter and item owner must be equal");711712        // update balance713        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();714        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);715716        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();717        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);718719        // change owner720        let old_owner = item.owner.clone();721        item.owner = new_owner.clone();722        <NftItemList<T>>::insert(collection_id, item_id, item);723724        // update index collection725        Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;726727        // reset approved list728        let itm: Vec<T::AccountId> = Vec::new();729        <ApprovedList<T>>::insert(collection_id, item_id, itm);730731        Ok(())732    }733734    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {735        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());736        if list_exists {737            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());738            let item_contains = list.contains(&item_index.clone());739740            if !item_contains {741                list.push(item_index.clone());742            }743744            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);745        } else {746            let mut itm = Vec::new();747            itm.push(item_index.clone());748            <AddressTokens<T>>::insert(collection_id, owner, itm);749        }750751        Ok(())752    }753754    fn remove_token_index(755        collection_id: u64,756        item_index: u64,757        owner: T::AccountId,758    ) -> DispatchResult {759        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());760        if list_exists {761            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());762            let item_contains = list.contains(&item_index.clone());763764            if item_contains {765                list.retain(|&item| item != item_index);766                <AddressTokens<T>>::insert(collection_id, owner, list);767            }768        }769770        Ok(())771    }772773    fn move_token_index(774        collection_id: u64,775        item_index: u64,776        old_owner: T::AccountId,777        new_owner: T::AccountId,778    ) -> DispatchResult {779        Self::remove_token_index(collection_id, item_index, old_owner)?;780        Self::add_token_index(collection_id, item_index, new_owner)?;781782        Ok(())783    }784}785786787////////////////////////////////////////////////////////////////////////////////////////////////////788// Economic models789790/// Fee multiplier.791pub type Multiplier = FixedU128;792793type BalanceOf<T> =794	<<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;795type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<796	<T as system::Trait>::AccountId,>>::NegativeImbalance;797798799800/// Require the transactor pay for themselves and maybe include a tip to gain additional priority801/// in the queue.802#[derive(Encode, Decode, Clone, Eq, PartialEq)]803pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);804805impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {806	#[cfg(feature = "std")]807	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {808		write!(f, "ChargeTransactionPayment<{:?}>", self.0)809	}810	#[cfg(not(feature = "std"))]811	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {812		Ok(())813	}814}815816impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where817	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,818	BalanceOf<T>: Send + Sync + FixedPointOperand,819{820	/// utility constructor. Used only in client/factory code.821	pub fn from(fee: BalanceOf<T>) -> Self {822		Self(fee)823	}824825    pub fn traditional_fee(826        len: usize,827        info: &DispatchInfoOf<T::Call>,828        tip: BalanceOf<T>,829    ) -> BalanceOf<T> where830        T::Call: Dispatchable<Info=DispatchInfo>,831    {832        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)833    }834835	fn withdraw_fee(836		&self,837        who: &T::AccountId,838        call: &T::Call,839		info: &DispatchInfoOf<T::Call>,840		len: usize,841	) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {842        let tip = self.0;843844        // Set fee based on call type. Creating collection costs 1 Unique.845        // All other transactions have traditional fees so far846        let fee = match call.is_sub_type() {847            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),848            _ => Self::traditional_fee(len, info, tip)849850            // Flat fee model, use only for testing purposes851            // _ => <BalanceOf<T>>::from(100)852        };853854        // Determine who is paying transaction fee based on ecnomic model855        // Parse call to extract collection ID and access collection sponsor856        let sponsor: T::AccountId = match call.is_sub_type() {857            Some(Call::create_item(collection_id, _properties, _owner)) => {858                <Collection<T>>::get(collection_id).sponsor859            },860            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {861                <Collection<T>>::get(collection_id).sponsor862            },863864            _ => T::AccountId::default()865        };866867        let mut who_pays_fee: T::AccountId = sponsor.clone();868        if sponsor == T::AccountId::default() {869            who_pays_fee = who.clone();870        }871872		// Only mess with balances if fee is not zero.873		if fee.is_zero() {874			return Ok((fee, None));875		}876877		match <T as transaction_payment::Trait>::Currency::withdraw(878			&who_pays_fee,879			fee,880			if tip.is_zero() {881				WithdrawReason::TransactionPayment.into()882			} else {883				WithdrawReason::TransactionPayment | WithdrawReason::Tip884			},885			ExistenceRequirement::KeepAlive,886		) {887			Ok(imbalance) => Ok((fee, Some(imbalance))),888			Err(_) => Err(InvalidTransaction::Payment.into()),889		}890	}891}892893impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where894    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,895    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,896{897	const IDENTIFIER: &'static str = "ChargeTransactionPayment";898	type AccountId = T::AccountId;899	type Call = T::Call;900	type AdditionalSigned = ();901	type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);902	fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }903904	fn validate(905		&self,906		who: &Self::AccountId,907		call: &Self::Call,908		info: &DispatchInfoOf<Self::Call>,909		len: usize,910	) -> TransactionValidity {911		let (fee, _) = self.withdraw_fee(who, call, info, len)?;912913		let mut r = ValidTransaction::default();914		// NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which915		// will be a bit more than setting the priority to tip. For now, this is enough.916		r.priority = fee.saturated_into::<TransactionPriority>();917		Ok(r)918	}919920	fn pre_dispatch(921		self,922		who: &Self::AccountId,923		call: &Self::Call,924		info: &DispatchInfoOf<Self::Call>,925		len: usize926	) -> Result<Self::Pre, TransactionValidityError> {927		let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;928		Ok((self.0, who.clone(), imbalance, fee))929	}930931	fn post_dispatch(932		pre: Self::Pre,933		info: &DispatchInfoOf<Self::Call>,934		post_info: &PostDispatchInfoOf<Self::Call>,935		len: usize,936		_result: &DispatchResult,937	) -> Result<(), TransactionValidityError> {938		let (tip, who, imbalance, fee) = pre;939		if let Some(payed) = imbalance {940			let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(941				len as u32,942				info,943				post_info,944				tip,945			);946			let refund = fee.saturating_sub(actual_fee);947			let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {948				Ok(refund_imbalance) => {949					// The refund cannot be larger than the up front payed max weight.950					// `PostDispatchInfo::calc_unspent` guards against such a case.951					match payed.offset(refund_imbalance) {952						Ok(actual_payment) => actual_payment,953						Err(_) => return Err(InvalidTransaction::Payment.into()),954					}955				}956				// We do not recreate the account using the refund. The up front payment957				// is gone in that case.958				Err(_) => payed,959			};960			let imbalances = actual_payment.split(tip);961			<T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()962				.chain(Some(imbalances.1)));963		}964		Ok(())965	}966}