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

difftreelog

source

pallets/nft/src/lib.rs20.8 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23/// For more guidance on Substrate FRAME, see the example pallet4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs56use codec::{Decode, Encode};7use frame_support::{decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure};8use frame_system::{self as system, ensure_signed};9use sp_runtime::sp_std::prelude::Vec;1011#[cfg(test)]12mod mock;1314#[cfg(test)]15mod tests;1617#[derive(Encode, Decode, Debug, Clone, PartialEq)]18pub enum AccessMode {19    Normal,20	WhiteList,21}22impl Default for AccessMode { fn default() -> Self { Self::Normal } }2324#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]25pub enum CollectionMode {26    Invalid,27	NFT,28	Fungible,29	ReFungible,30}31impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }3233#[derive(Encode, Decode, Default, Clone, PartialEq)]34#[cfg_attr(feature = "std", derive(Debug))]35pub struct Ownership<AccountId> {36    pub owner: AccountId,37    pub fraction: u12838}3940#[derive(Encode, Decode, Default, Clone, PartialEq)]41#[cfg_attr(feature = "std", derive(Debug))]42pub struct CollectionType<AccountId> {43    pub owner: AccountId,44    pub mode: CollectionMode,45    pub access: AccessMode,46    pub next_item_id: u64,47    pub decimal_points: u32,48    pub name: Vec<u16>,        // 64 include null escape char49    pub description: Vec<u16>, // 256 include null escape char50    pub token_prefix: Vec<u8>, // 16 include null escape char51    pub custom_data_size: u32,52}5354#[derive(Encode, Decode, Default, Clone, PartialEq)]55#[cfg_attr(feature = "std", derive(Debug))]56pub struct CollectionAdminsType<AccountId> {57    pub admin: AccountId,58    pub collection_id: u64,59}6061#[derive(Encode, Decode, Default, Clone, PartialEq)]62#[cfg_attr(feature = "std", derive(Debug))]63pub struct NftItemType<AccountId> {64    pub collection: u64,65    pub owner: AccountId,66    pub data: Vec<u8>,67}6869#[derive(Encode, Decode, Default, Clone, PartialEq)]70#[cfg_attr(feature = "std", derive(Debug))]71pub struct FungibleItemType<AccountId> {72    pub collection: u64,73    pub owner: Vec<AccountId>,74    pub data: Vec<u64>,75}7677#[derive(Encode, Decode, Default, Clone, PartialEq)]78#[cfg_attr(feature = "std", derive(Debug))]79pub struct ReFungibleItemType<AccountId> {80    pub collection: u64,81    pub owner: Vec<Ownership<AccountId>>,82}8384pub trait Trait: system::Trait {85    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;86}8788decl_storage! {89    trait Store for Module<T: Trait> as Nft {9091        // Next available collection ID92        NextCollectionID get(fn next_collection_id): u64;93        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;94        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;9596        // Balance owner per collection map97        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;98        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<T::AccountId>;99100        // Item collections101        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;102        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;103        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;104        ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;105106        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;107    }108}109110decl_event!(111    pub enum Event<T>112    where113        AccountId = <T as system::Trait>::AccountId,114    {115        Created(u64, u8, AccountId),116        ItemCreated(u64, u64),117        ItemDestroyed(u64, u64),118    }119);120121decl_module! {122    pub struct Module<T: Trait> for enum Call where origin: T::Origin {123124        fn deposit_event() = default;125126        // Create collection of NFT with given parameters127        //128        // @param customDataSz size of custom data in each collection item129        // returns collection ID130        #[weight = 0]131        pub fn create_collection(   origin,132                                    collection_name: Vec<u16>,133                                    collection_description: Vec<u16>,134                                    token_prefix: Vec<u8>,135                                    mode: u8,136                                    decimal_points: u32,137                                    custom_data_size: u32) -> DispatchResult {138139            // Anyone can create a collection140            let who = ensure_signed(origin)?;141            let collection_mode: CollectionMode;142            match mode {143                1 => collection_mode = CollectionMode::NFT,144                2 => collection_mode = CollectionMode::Fungible,145                3 => collection_mode = CollectionMode::ReFungible,146                _ => collection_mode = CollectionMode::Invalid147            }148149            // check type150            ensure!((collection_mode == CollectionMode::Fungible || collection_mode == CollectionMode::NFT || collection_mode == CollectionMode::ReFungible), 151                "Collection mode must be Fungible, NFT or ReFungible");          152153            // NFT checks154            if collection_mode == CollectionMode::NFT155            {156                ensure!(decimal_points == 0, "Collection in NFT mode must have zero in decimal_points parameter"); 157            }158159            // Fungible checks160            if collection_mode == CollectionMode::Fungible161            {162                ensure!(custom_data_size == 0, "Collection in Fungible mode must have zero in custom_data_size parameter"); 163                ensure!(decimal_points != 0, "Collection in Fungible mode must have not zero in decimal_points parameter"); 164            }165166            // check params167            ensure!(decimal_points < 100, "decimal_points parameter must be lower than 100"); 168169            let mut name = collection_name.to_vec();170            name.push(0);171            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");172173            let mut description = collection_description.to_vec();174            description.push(0);175            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");176177            let mut prefix = token_prefix.to_vec();178            prefix.push(0);179            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");180181            // Generate next collection ID182            let next_id = NextCollectionID::get()183                .checked_add(1)184                .expect("collection id error");185186            NextCollectionID::put(next_id);187188            // Create new collection189            let new_collection = CollectionType {190                owner: who.clone(),191                name: name,192                mode: collection_mode.clone(),193                access: AccessMode::Normal,194                description: description,195                decimal_points: decimal_points,196                token_prefix: prefix,197                next_item_id: next_id,198                custom_data_size: custom_data_size,199            };200201            // Add new collection to map202            <Collection<T>>::insert(next_id, new_collection);203204            // call event205            Self::deposit_event(RawEvent::Created(next_id, mode, who.clone()));206207            Ok(())208        }209210        #[weight = 0]211        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {212213            let sender = ensure_signed(origin)?;214            Self::check_owner_permissions(collection_id, sender)?;215216            <AddressTokens<T>>::remove_prefix(collection_id);217            <ApprovedList<T>>::remove_prefix(collection_id);218            <Balance<T>>::remove_prefix(collection_id);219            <ItemListIndex>::remove(collection_id);220            <AdminList<T>>::remove(collection_id);221            <Collection<T>>::remove(collection_id);222223            Ok(())224        }225226        #[weight = 0]227        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {228229            let sender = ensure_signed(origin)?;230            Self::check_owner_permissions(collection_id, sender)?;231            let mut target_collection = <Collection<T>>::get(collection_id);232            target_collection.owner = new_owner;233            <Collection<T>>::insert(collection_id, target_collection);234235            Ok(())236        }237238        #[weight = 0]239        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {240241            let sender = ensure_signed(origin)?;242            Self::check_owner_or_admin_permissions(collection_id, sender)?;243            let mut admin_arr: Vec<T::AccountId> = Vec::new();244245            if <AdminList<T>>::contains_key(collection_id)246            {247                admin_arr = <AdminList<T>>::get(collection_id);248                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");249            }250251            admin_arr.push(new_admin_id);252            <AdminList<T>>::insert(collection_id, admin_arr);253254            Ok(())255        }256257        #[weight = 0]258        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {259260            let sender = ensure_signed(origin)?;261            Self::check_owner_or_admin_permissions(collection_id, sender)?;262263            if <AdminList<T>>::contains_key(collection_id)264            {265                let mut admin_arr = <AdminList<T>>::get(collection_id);266                admin_arr.retain(|i| *i != account_id);267                <AdminList<T>>::insert(collection_id, admin_arr);268            }269270            Ok(())271        }272273        #[weight = 0]274        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {275276            let sender = ensure_signed(origin)?;277278            // check size279            let target_collection = <Collection<T>>::get(collection_id);280            ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");281282            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;283284            let new_balance = <Balance<T>>::get(collection_id, owner.clone()) + 1;285            <Balance<T>>::insert(collection_id, owner.clone(), new_balance);286287            // TODO: implement other modes288            ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");289290            if target_collection.mode == CollectionMode::NFT291            {292                // Create nft item293                let item = NftItemType {294                    collection: collection_id,295                    owner: owner,296                    data: properties,297                };298299                Self::add_nft_item(item)?;300            }301302            // call event303            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));304305            Ok(())306        }307308        #[weight = 0]309        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {310311            let sender = ensure_signed(origin)?;312            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);313            if !item_owner314            {315                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;316            }317            318            Self::burn_nft_item(collection_id, item_id)?;319320            // call event321            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));322323            Ok(())324        }325326        #[weight = 0]327        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {328329            let sender = ensure_signed(origin)?;330            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);331            if !item_owner332            {333                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;334            }335336            let target_collection = <Collection<T>>::get(collection_id);337338            // TODO: implement other modes339            ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");340341            if target_collection.mode == CollectionMode::NFT342            {343                Self::transfer_nft(collection_id, item_id, recipient)?;344            }345346            Ok(())347        }348349        #[weight = 0]350        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {351352            let sender = ensure_signed(origin)?;353354            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);355            if !item_owner356            {357                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;358            }359360            let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);361            if list_exists {362363                let mut list = <ApprovedList<T>>::get(collection_id, item_id);364                let item_contains = list.contains(&approved.clone());365366                if !item_contains {367                    list.push(approved.clone());368                }369            } else {370371                let mut itm = Vec::new();372                itm.push(approved.clone());373                <ApprovedList<T>>::insert(collection_id, item_id, itm);374            }375376            Ok(())377        }378379        #[weight = 0]380        pub fn transfer_from(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, ) -> DispatchResult {381382            let mut approved: bool = false; 383            let sender = ensure_signed(origin)?;384            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);385            if approved_list_exists386            {387                let list_itm = <ApprovedList<T>>::get(collection_id, item_id);388                approved = list_itm.contains(&recipient.clone());389            }390391            if !approved392            {393                Self::check_owner_or_admin_permissions(collection_id, sender)?;394            }395            396            let target_collection = <Collection<T>>::get(collection_id);397398            // TODO: implement other modes399            ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");400401            if target_collection.mode == CollectionMode::NFT402            {403                Self::transfer_nft(collection_id, item_id, recipient)?;404            }405406            Ok(())407        }408409        #[weight = 0]410        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {411412            // let no_perm_mes = "You do not have permissions to modify this collection";413            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);414            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));415            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);416417            // // on_nft_received  call418419            // Self::transfer(origin, collection_id, item_id, new_owner)?;420421            Ok(())422        }423    }424}425426impl<T: Trait> Module<T> {427428    fn collection_exists(collection_id: u64) -> DispatchResult{429        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");430        Ok(())431    }432433    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {434435        Self::collection_exists(collection_id)?;436437        let target_collection = <Collection<T>>::get(collection_id);438        ensure!(subject == target_collection.owner, "You do not own this collection");439440        Ok(())441    }442443    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {444445        Self::collection_exists(collection_id)?;446447        let target_collection = <Collection<T>>::get(collection_id);448        let is_owner = subject == target_collection.owner;449450        let no_perm_mes = "You do not have permissions to modify this collection";451        let exists = <AdminList<T>>::contains_key(collection_id);452453        if !is_owner454        {455            ensure!(exists, no_perm_mes);456            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);457        }458        Ok(())459    }460461    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{462463        let mut result = false;464        let target_collection = <Collection<T>>::get(collection_id);465466        if target_collection.mode == CollectionMode::NFT467        {468            let item = <NftItemList<T>>::get(collection_id, item_id);469            result = item.owner == subject;470        }471472        if target_collection.mode == CollectionMode::Fungible473        {474            let item = <FungibleItemList<T>>::get(collection_id, item_id);475            result = item.owner.contains(&subject);476        }477478        if target_collection.mode == CollectionMode::ReFungible479        {480            let item = <ReFungibleItemList<T>>::get(collection_id, item_id);481            result = item.owner.iter().any(|i| i.owner == subject);482        }483484        result485    }486487    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {488489        let current_index = <ItemListIndex>::get(item.collection)490        .checked_add(1)491        .expect("Item list index id error");492493        Self::add_token_index(item.collection, current_index, item.owner.clone())?;494495        <ItemListIndex>::insert(item.collection, current_index);496        <NftItemList<T>>::insert(item.collection, current_index, item);497498        Ok(())499    }500501    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {502  503        let item = <NftItemList<T>>::get(collection_id, item_id);504        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;505506        // update balance507        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();508        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);509        <NftItemList<T>>::remove(collection_id, item_id);510511        Ok(())512    }513514    fn transfer_nft(collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {515516        let mut item = <NftItemList<T>>::get(collection_id, item_id);517518        // update balance519        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();520        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);521522        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();523        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);524525        // change owner526        let old_owner = item.owner.clone();527        item.owner = new_owner.clone();528        <NftItemList<T>>::insert(collection_id, item_id, item);529530        // update index collection531        Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;532533        // reset approved list534        let itm: Vec<T::AccountId> = Vec::new();535        <ApprovedList<T>>::insert(collection_id, item_id, itm);536537        Ok(())538    }539540    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {541        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());542        if list_exists {543            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());544            let item_contains = list.contains(&item_index.clone());545546            if !item_contains {547                list.push(item_index.clone());548            }549550            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);551        } else {552            let mut itm = Vec::new();553            itm.push(item_index.clone());554            <AddressTokens<T>>::insert(collection_id, owner, itm);555        }556557        Ok(())558    }559560    fn remove_token_index(561        collection_id: u64,562        item_index: u64,563        owner: T::AccountId,564    ) -> DispatchResult {565        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());566        if list_exists {567            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());568            let item_contains = list.contains(&item_index.clone());569570            if item_contains {571                list.retain(|&item| item != item_index);572                <AddressTokens<T>>::insert(collection_id, owner, list);573            }574        }575576        Ok(())577    }578579    fn move_token_index(580        collection_id: u64,581        item_index: u64,582        old_owner: T::AccountId,583        new_owner: T::AccountId,584    ) -> DispatchResult {585        Self::remove_token_index(collection_id, item_index, old_owner)?;586        Self::add_token_index(collection_id, item_index, new_owner)?;587588        Ok(())589    }590}