git.delta.rocks / unique-network / refs/commits / 55a89b2cf989

difftreelog

source

pallets/nft/src/lib.rs20.2 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, CollectionMode, 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: CollectionMode,136                                    decimal_points: u32,137                                    custom_data_size: u32) -> DispatchResult {138139            // Anyone can create a collection140            let who = ensure_signed(origin)?;141142            // check type143            ensure!((mode == CollectionMode::Fungible || mode == CollectionMode::NFT || mode == CollectionMode::ReFungible), 144                "Collection mode must be Fungible, NFT or ReFungible");          145146            // NFT checks147            if mode == CollectionMode::NFT148            {149                ensure!(decimal_points == 0, "Collection in NFT mode must have zero in decimal_points parameter"); 150            }151152            // Fungible checks153            if mode == CollectionMode::Fungible154            {155                ensure!(custom_data_size == 0, "Collection in Fungible mode must have zero in custom_data_size parameter"); 156                ensure!(decimal_points != 0, "Collection in Fungible mode must have not zero in decimal_points parameter"); 157            }158159            // check params160            ensure!(decimal_points < 100, "decimal_points parameter must be lower than 100"); 161162            let mut name = collection_name.to_vec();163            name.push(0);164            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");165166            let mut description = collection_description.to_vec();167            description.push(0);168            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");169170            let mut prefix = token_prefix.to_vec();171            prefix.push(0);172            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");173174            // Generate next collection ID175            let next_id = NextCollectionID::get()176                .checked_add(1)177                .expect("collection id error");178179            NextCollectionID::put(next_id);180181            // Create new collection182            let new_collection = CollectionType {183                owner: who.clone(),184                name: name,185                mode: mode.clone(),186                access: AccessMode::Normal,187                description: description,188                decimal_points: decimal_points,189                token_prefix: prefix,190                next_item_id: next_id,191                custom_data_size: custom_data_size,192            };193194            // Add new collection to map195            <Collection<T>>::insert(next_id, new_collection);196197            // call event198            Self::deposit_event(RawEvent::Created(next_id, mode.clone(), who.clone()));199200            Ok(())201        }202203        #[weight = 0]204        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {205206            let sender = ensure_signed(origin)?;207            Self::check_owner_permissions(collection_id, sender)?;208209            <AddressTokens<T>>::remove_prefix(collection_id);210            <ApprovedList<T>>::remove_prefix(collection_id);211            <Balance<T>>::remove_prefix(collection_id);212            <ItemListIndex>::remove(collection_id);213            <AdminList<T>>::remove(collection_id);214            <Collection<T>>::remove(collection_id);215216            Ok(())217        }218219        #[weight = 0]220        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {221222            let sender = ensure_signed(origin)?;223            Self::check_owner_permissions(collection_id, sender)?;224            let mut target_collection = <Collection<T>>::get(collection_id);225            target_collection.owner = new_owner;226            <Collection<T>>::insert(collection_id, target_collection);227228            Ok(())229        }230231        #[weight = 0]232        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {233234            let sender = ensure_signed(origin)?;235            Self::check_owner_or_admin_permissions(collection_id, sender)?;236            let mut admin_arr: Vec<T::AccountId> = Vec::new();237238            if <AdminList<T>>::contains_key(collection_id)239            {240                admin_arr = <AdminList<T>>::get(collection_id);241                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");242            }243244            admin_arr.push(new_admin_id);245            <AdminList<T>>::insert(collection_id, admin_arr);246247            Ok(())248        }249250        #[weight = 0]251        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {252253            let sender = ensure_signed(origin)?;254            Self::check_owner_or_admin_permissions(collection_id, sender)?;255256            if <AdminList<T>>::contains_key(collection_id)257            {258                let mut admin_arr = <AdminList<T>>::get(collection_id);259                admin_arr.retain(|i| *i != account_id);260                <AdminList<T>>::insert(collection_id, admin_arr);261            }262263            Ok(())264        }265266        #[weight = 0]267        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {268269            let sender = ensure_signed(origin)?;270271            // check size272            let target_collection = <Collection<T>>::get(collection_id);273            ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");274275            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;276277            let new_balance = <Balance<T>>::get(collection_id, sender.clone()) + 1;278            <Balance<T>>::insert(collection_id, sender.clone(), new_balance);279280            // TODO: implement other modes281            ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");282283            if target_collection.mode == CollectionMode::NFT284            {285                // Create nft item286                let item = NftItemType {287                    collection: collection_id,288                    owner: owner,289                    data: properties,290                };291292                Self::add_nft_item(item)?;293            }294295            // call event296            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));297298            Ok(())299        }300301        #[weight = 0]302        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {303304            let sender = ensure_signed(origin)?;305            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;306            Self::burn_nft_item(collection_id, item_id)?;307308            // call event309            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));310311            Ok(())312        }313314        #[weight = 0]315        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {316317            let sender = ensure_signed(origin)?;318            Self::check_owner_or_admin_permissions(collection_id, sender)?;319320            let target_collection = <Collection<T>>::get(collection_id);321322            // TODO: implement other modes323            ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");324325            if target_collection.mode == CollectionMode::NFT326            {327                Self::transfer_nft(collection_id, item_id, recipient)?;328            }329330            Ok(())331        }332333        #[weight = 0]334        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {335336            let sender = ensure_signed(origin)?;337338            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);339            if !item_owner340            {341                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;342            }343344            let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);345            if list_exists {346347                let mut list = <ApprovedList<T>>::get(collection_id, item_id);348                let item_contains = list.contains(&approved.clone());349350                if !item_contains {351                    list.push(approved.clone());352                }353            } else {354355                let mut itm = Vec::new();356                itm.push(approved.clone());357                <ApprovedList<T>>::insert(collection_id, item_id, itm);358            }359360            Ok(())361        }362363        #[weight = 0]364        pub fn transfer_from(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, ) -> DispatchResult {365366            let mut approved: bool = false; 367            let sender = ensure_signed(origin)?;368            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);369            if approved_list_exists370            {371                let list_itm = <ApprovedList<T>>::get(collection_id, item_id);372                approved = list_itm.contains(&recipient.clone());373            }374375            if !approved376            {377                Self::check_owner_or_admin_permissions(collection_id, sender)?;378            }379            380            let target_collection = <Collection<T>>::get(collection_id);381382            // TODO: implement other modes383            ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");384385            if target_collection.mode == CollectionMode::NFT386            {387                Self::transfer_nft(collection_id, item_id, recipient)?;388            }389390            Ok(())391        }392393        #[weight = 0]394        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {395396            // let no_perm_mes = "You do not have permissions to modify this collection";397            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);398            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));399            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);400401            // // on_nft_received  call402403            // Self::transfer(origin, collection_id, item_id, new_owner)?;404405            Ok(())406        }407    }408}409410impl<T: Trait> Module<T> {411412    fn collection_exists(collection_id: u64) -> DispatchResult{413        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");414        Ok(())415    }416417    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {418419        Self::collection_exists(collection_id)?;420421        let target_collection = <Collection<T>>::get(collection_id);422        ensure!(subject == target_collection.owner, "You do not own this collection");423424        Ok(())425    }426427    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {428429        Self::collection_exists(collection_id)?;430431        let target_collection = <Collection<T>>::get(collection_id);432        let is_owner = subject == target_collection.owner;433434        let no_perm_mes = "You do not have permissions to modify this collection";435        let exists = <AdminList<T>>::contains_key(collection_id);436437        if !is_owner438        {439            ensure!(exists, no_perm_mes);440            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);441        }442        Ok(())443    }444445    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{446447        let mut result = false;448        let target_collection = <Collection<T>>::get(collection_id);449450        if target_collection.mode == CollectionMode::NFT451        {452            let item = <NftItemList<T>>::get(collection_id, item_id);453            result = item.owner == subject;454        }455456        if target_collection.mode == CollectionMode::Fungible457        {458            let item = <FungibleItemList<T>>::get(collection_id, item_id);459            result = item.owner.contains(&subject);460        }461462        if target_collection.mode == CollectionMode::ReFungible463        {464            let item = <ReFungibleItemList<T>>::get(collection_id, item_id);465            result = item.owner.iter().any(|i| i.owner == subject);466        }467468        result469    }470471    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {472473        let current_index = <ItemListIndex>::get(item.collection)474        .checked_add(1)475        .expect("Item list index id error");476477        Self::add_token_index(item.collection, current_index, item.owner.clone())?;478479        <ItemListIndex>::insert(item.collection, current_index);480        <NftItemList<T>>::insert(item.collection, current_index, item);481482        Ok(())483    }484485    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {486  487        let item = <NftItemList<T>>::get(collection_id, item_id);488        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;489490        // update balance491        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();492        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);493        <NftItemList<T>>::remove(collection_id, item_id);494495        Ok(())496    }497498    fn transfer_nft(collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {499500        let mut item = <NftItemList<T>>::get(collection_id, item_id);501502        // update balance503        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();504        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);505506        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();507        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);508509        // change owner510        let old_owner = item.owner.clone();511        item.owner = new_owner.clone();512        <NftItemList<T>>::insert(collection_id, item_id, item);513514        // update index collection515        Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;516517        // reset approved list518        let itm: Vec<T::AccountId> = Vec::new();519        <ApprovedList<T>>::insert(collection_id, item_id, itm);520521        // remove item522        <NftItemList<T>>::remove(collection_id, item_id);523524        Ok(())525    }526527    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {528        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());529        if list_exists {530            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());531            let item_contains = list.contains(&item_index.clone());532533            if !item_contains {534                list.push(item_index.clone());535            }536537            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);538        } else {539            let mut itm = Vec::new();540            itm.push(item_index.clone());541            <AddressTokens<T>>::insert(collection_id, owner, itm);542        }543544        Ok(())545    }546547    fn remove_token_index(548        collection_id: u64,549        item_index: u64,550        owner: T::AccountId,551    ) -> DispatchResult {552        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());553        if list_exists {554            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());555            let item_contains = list.contains(&item_index.clone());556557            if item_contains {558                list.retain(|&item| item != item_index);559                <AddressTokens<T>>::insert(collection_id, owner, list);560            }561        }562563        Ok(())564    }565566    fn move_token_index(567        collection_id: u64,568        item_index: u64,569        old_owner: T::AccountId,570        new_owner: T::AccountId,571    ) -> DispatchResult {572        Self::remove_token_index(collection_id, item_index, old_owner)?;573        Self::add_token_index(collection_id, item_index, new_owner)?;574575        Ok(())576    }577}