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

difftreelog

source

pallets/nft/src/lib.rs19.0 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23/// A FRAME pallet template with necessary imports45/// Feel free to remove or edit this file as needed.6/// If you change the name of this file, make sure to update its references in runtime/src/lib.rs7/// If you remove this file, you can remove those references89/// For more guidance on Substrate FRAME, see the example pallet10/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs1112use codec::{Decode, Encode};1314use frame_support::{decl_module, decl_storage, decl_event, decl_error, dispatch::DispatchResult, ensure};15use frame_system::{self as system, ensure_signed};16use sp_runtime::sp_std::prelude::Vec;1718#[cfg(test)]19mod mock;2021#[cfg(test)]22mod tests;2324#[derive(Encode, Decode, Default, Clone, PartialEq)]25#[cfg_attr(feature = "std", derive(Debug))]26pub struct CollectionType<AccountId> {27    pub owner: AccountId,28    pub next_item_id: u64,29    pub name: Vec<u16>, // 64 include null escape char30    pub description: Vec<u16>, // 256 include null escape char31    pub token_prefix: Vec<u8>, // 16 include null escape char32    pub custom_data_size: u32,33}3435#[derive(Encode, Decode, Default, Clone, PartialEq)]36#[cfg_attr(feature = "std", derive(Debug))]37pub struct CollectionAdminsType<AccountId> {38    pub admin: AccountId,39    pub collection_id: u64,40}4142#[derive(Encode, Decode, Default, Clone, PartialEq)]43#[cfg_attr(feature = "std", derive(Debug))]44pub struct NftItemType<AccountId> {45    pub collection: u64,46    pub owner: AccountId,47    pub data: Vec<u8>,48}4950/// The pallet's configuration trait.51pub trait Trait: system::Trait {52	// Add other types and constants required to configure this pallet.5354	/// The overarching event type.55	type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;56}5758// This pallet's storage items.59decl_storage! {60	// It is important to update your storage name so that your pallet's61	// storage items are isolated from other pallets.62    trait Store for Module<T: Trait> as Nft {6364        /// Next available collection ID65        pub NextCollectionID get(fn next_collection_id): u64;66        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;67        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;6869        /// Balance owner per collection map70        pub Balance get(fn balance_count): map hasher(blake2_128_concat) (u64, T::AccountId) => u64;71        pub ApprovedList get(fn approved): map hasher(blake2_128_concat) (u64, u64) => Vec<T::AccountId>;7273        pub ItemList get(fn item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;74        pub ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;7576        pub AddressTokens get(fn address_tokens): map hasher(blake2_128_concat) (u64, T::AccountId) => Vec<u64>;7778    }79}8081// The pallet's events82decl_event!(83    pub enum Event<T>84    where85        AccountId = <T as system::Trait>::AccountId,86    {87        Created(u64, AccountId),88        ItemCreated(u64),89        ItemDestroyed(u64, u64),90    }91);9293// The pallet's errors94decl_error! {95	pub enum Error for Module<T: Trait> {96		/// Value was None97		NoneValue,98		/// Value reached maximum and cannot be incremented further99		StorageOverflow,100	}101}102103// The pallet's dispatchable functions.104decl_module! {105    /// The module declaration.106    pub struct Module<T: Trait> for enum Call where origin: T::Origin {107108        // Initializing events109        // this is needed only if you are using events in your pallet110        fn deposit_event() = default;111112        // Create collection of NFT with given parameters113        //114        // @param customDataSz size of custom data in each collection item115        // returns collection ID116117        // Create collection of NFT with given parameters118        //119        // @param customDataSz size of custom data in each collection item120        // returns collection ID121        // TODO: later versions use "#[weight = 0]"122        #[weight = frame_support::weights::SimpleDispatchInfo::default()]123        pub fn create_collection(   origin, 124                                    collection_name: Vec<u16>, 125                                    collection_description: Vec<u16>, 126                                    token_prefix: Vec<u8>, 127                                    custom_data_sz: u32) -> DispatchResult {128129            // Anyone can create a collection130            let who = ensure_signed(origin)?;131132            // check params 133            let mut name = collection_name.to_vec();134            name.push(0);135            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");136137            let mut description = collection_description.to_vec();138            description.push(0);139            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");140141            let mut prefix = token_prefix.to_vec();142            prefix.push(0);143            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");144145            // Generate next collection ID146            let next_id = NextCollectionID::get()147                .checked_add(1)148                .expect("collection id error");149150            NextCollectionID::put(next_id);151152            // Create new collection153            let new_collection = CollectionType {154                owner: who.clone(),155                name: name,156                description: description,157                token_prefix: prefix,158                next_item_id: next_id,159                custom_data_size: custom_data_sz,160            };161162            // Add new collection to map163            <Collection<T>>::insert(next_id, new_collection);164165            // call event166            Self::deposit_event(RawEvent::Created(next_id, who.clone()));167168            Ok(())169        }170171        #[weight = frame_support::weights::SimpleDispatchInfo::default()]172        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {173174            let sender = ensure_signed(origin)?;175            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");176177            let owner = <Collection<T>>::get(collection_id).owner;178            ensure!(sender == owner, "You do not own this collection");179            <Collection<T>>::remove(collection_id);180181            Ok(())182        }183184        #[weight = frame_support::weights::SimpleDispatchInfo::default()]185        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {186187            let sender = ensure_signed(origin)?;188            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");189190            let mut target_collection = <Collection<T>>::get(collection_id);191            ensure!(sender == target_collection.owner, "You do not own this collection");192193            target_collection.owner = new_owner;194            <Collection<T>>::insert(collection_id, target_collection);195196            Ok(())197        }198199        #[weight = frame_support::weights::SimpleDispatchInfo::default()]200        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {201202            let sender = ensure_signed(origin)?;203            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");204205            let target_collection = <Collection<T>>::get(collection_id);206            let is_owner = sender == target_collection.owner;207208            let no_perm_mes = "You do not have permissions to modify this collection";209            let exists = <AdminList<T>>::contains_key(collection_id);210211            if !is_owner212            {213                 ensure!(exists, no_perm_mes);214                 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);215            }216217            let mut admin_arr: Vec<T::AccountId> = Vec::new();218            if exists219            {220                admin_arr = <AdminList<T>>::get(collection_id);221                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");222            }223224            admin_arr.push(new_admin_id);225            <AdminList<T>>::insert(collection_id, admin_arr);226227            Ok(())228        }229230        #[weight = frame_support::weights::SimpleDispatchInfo::default()]231        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {232233            let sender = ensure_signed(origin)?;234            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");235236            let target_collection = <Collection<T>>::get(collection_id);237            let is_owner = sender == target_collection.owner;238239            let no_perm_mes = "You do not have permissions to modify this collection";240            let exists = <AdminList<T>>::contains_key(collection_id);241242            if !is_owner243            {244                ensure!(exists, no_perm_mes);245                ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);246            }247248            if exists249            {250                let mut admin_arr = <AdminList<T>>::get(collection_id);251                admin_arr.retain(|i| *i != account_id);252                <AdminList<T>>::insert(collection_id, admin_arr);253            }254255            Ok(())256        }257258        #[weight = frame_support::weights::SimpleDispatchInfo::default()]259        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>) -> DispatchResult {260261            let sender = ensure_signed(origin)?;262            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");263264            let target_collection = <Collection<T>>::get(collection_id);265            ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");266            let is_owner = sender == target_collection.owner;267268            let no_perm_mes = "You do not have permissions to modify this collection";269            let exists = <AdminList<T>>::contains_key(collection_id);270271            if !is_owner272            {273                ensure!(exists, no_perm_mes);274                ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);275            }276277            let new_balance = <Balance<T>>::get((collection_id, sender.clone())) + 1;278            <Balance<T>>::insert((collection_id, sender.clone()), new_balance);279280            // Create new item281            let new_item = NftItemType {282                collection: collection_id,283                owner: sender,284                data: properties,285            };286287288            let current_index = <ItemListIndex>::get(collection_id)289                .checked_add(1)290                .expect("Item list index id error");291292            Self::add_token_index(collection_id, current_index, new_item.owner.clone())?;293294            <ItemListIndex>::insert(collection_id, current_index);295            <ItemList<T>>::insert((collection_id, current_index), new_item);296297            // call event298            Self::deposit_event(RawEvent::ItemCreated(collection_id));299300            Ok(())301        }302303        #[weight = frame_support::weights::SimpleDispatchInfo::default()]304        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {305306            let sender = ensure_signed(origin)?;307            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");308309            let target_collection = <Collection<T>>::get(collection_id);310            let is_owner = sender == target_collection.owner;311312            ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");313            let item = <ItemList<T>>::get((collection_id, item_id));314315            if !is_owner316            {317                // check if item owner318                if item.owner != sender319                {320                    let no_perm_mes = "You do not have permissions to modify this collection";321322                    ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);323                    ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);324                }325            }326            <ItemList<T>>::remove((collection_id, item_id));327328            Self::remove_token_index(collection_id, item_id, item.owner.clone())?;329330            // update balance331            let new_balance = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;332            <Balance<T>>::insert((collection_id, item.owner.clone()), new_balance);333334            // call event335            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));336337            Ok(())338        }339340        #[weight = frame_support::weights::SimpleDispatchInfo::default()]341        pub fn transfer(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {342343            let sender = ensure_signed(origin)?;344            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");345346            let target_collection = <Collection<T>>::get(collection_id);347            let is_owner = sender == target_collection.owner;348349            ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");350            let mut item = <ItemList<T>>::get((collection_id, item_id));351352            if !is_owner353            {354                // check if item owner355                if item.owner != sender356                {357                    let no_perm_mes = "You do not have permissions to modify this collection";358359                    ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);360                    ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);361                }362            }363            <ItemList<T>>::remove((collection_id, item_id));364365            // update balance366            let balance_old_owner = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;367            <Balance<T>>::insert((collection_id, item.owner.clone()), balance_old_owner);368369            let balance_new_owner = <Balance<T>>::get((collection_id, new_owner.clone())) + 1;370            <Balance<T>>::insert((collection_id, new_owner.clone()), balance_new_owner);371372            // change owner373            let old_owner = item.owner.clone();374            item.owner = new_owner.clone();375            <ItemList<T>>::insert((collection_id, item_id), item);376377            // update index collection378            Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;379380            // reset approved list381            let itm: Vec<T::AccountId> = Vec::new();382            <ApprovedList<T>>::insert((collection_id, item_id), itm);383384            Ok(())385        }386387        #[weight = frame_support::weights::SimpleDispatchInfo::default()]388        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {389390            let sender = ensure_signed(origin)?;391            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");392393            let target_collection = <Collection<T>>::get(collection_id);394            let is_owner = sender == target_collection.owner;395396            ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");397            let item = <ItemList<T>>::get((collection_id, item_id));398399            if !is_owner400            {401                // check if item owner402                if item.owner != sender403                {404                    let no_perm_mes = "You do not have permissions to modify this collection";405406                    ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);407                    ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);408                }409            }410411            let list_exists = <ApprovedList<T>>::contains_key((collection_id, item_id));412            if list_exists {413414                let mut list = <ApprovedList<T>>::get((collection_id, item_id));415                let item_contains = list.contains(&approved.clone());416417                if !item_contains {418                    list.push(approved.clone());419                }420            } else {421422                let mut itm = Vec::new();423                itm.push(approved.clone());424                <ApprovedList<T>>::insert((collection_id, item_id), itm);425            }426427            Ok(())428        }429430        #[weight = frame_support::weights::SimpleDispatchInfo::default()]431        pub fn transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {432433            let no_perm_mes = "You do not have permissions to modify this collection";434            ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);435            let list_itm = <ApprovedList<T>>::get((collection_id, item_id));436            ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);437438            Self::transfer(origin, collection_id, item_id, new_owner)?;439440            Ok(())441        }442443        #[weight = frame_support::weights::SimpleDispatchInfo::default()]444        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {445446            let no_perm_mes = "You do not have permissions to modify this collection";447            ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);448            let list_itm = <ApprovedList<T>>::get((collection_id, item_id));449            ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);450451            // on_nft_received  call452453            Self::transfer(origin, collection_id, item_id, new_owner)?;454455            Ok(())456        }457    }458}459460impl<T: Trait> Module<T> {461    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {462        463        let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));464        if list_exists {465466            let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));467            let item_contains = list.contains(&item_index.clone());468469            if !item_contains {470                list.push(item_index.clone());471            }472473            <AddressTokens<T>>::insert((collection_id, owner.clone()), list);474475        } else {476477            let mut itm = Vec::new();478            itm.push(item_index.clone());479            <AddressTokens<T>>::insert((collection_id, owner), itm);480        }481482        Ok(())483    }484485    fn remove_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {486        487        let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));488        if list_exists {489490            let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));491            let item_contains = list.contains(&item_index.clone());492493            if item_contains {494                list.retain(|&item| item != item_index);495                <AddressTokens<T>>::insert((collection_id, owner), list);496            }497        }498499        Ok(())500    }501502    fn move_token_index(collection_id: u64, item_index: u64, old_owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {503        504        Self::remove_token_index(collection_id, item_index, old_owner)?;505        Self::add_token_index(collection_id, item_index, new_owner)?;506        507        Ok(())508    }509}