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

difftreelog

source

pallets/nft/src/lib.rs20.6 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, sender.clone()) + 1;285            <Balance<T>>::insert(collection_id, sender.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            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;313            Self::burn_nft_item(collection_id, item_id)?;314315            // call event316            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));317318            Ok(())319        }320321        #[weight = 0]322        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {323324            let sender = ensure_signed(origin)?;325            Self::check_owner_or_admin_permissions(collection_id, sender)?;326327            let target_collection = <Collection<T>>::get(collection_id);328329            // TODO: implement other modes330            ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");331332            if target_collection.mode == CollectionMode::NFT333            {334                Self::transfer_nft(collection_id, item_id, recipient)?;335            }336337            Ok(())338        }339340        #[weight = 0]341        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {342343            let sender = ensure_signed(origin)?;344345            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);346            if !item_owner347            {348                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;349            }350351            let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);352            if list_exists {353354                let mut list = <ApprovedList<T>>::get(collection_id, item_id);355                let item_contains = list.contains(&approved.clone());356357                if !item_contains {358                    list.push(approved.clone());359                }360            } else {361362                let mut itm = Vec::new();363                itm.push(approved.clone());364                <ApprovedList<T>>::insert(collection_id, item_id, itm);365            }366367            Ok(())368        }369370        #[weight = 0]371        pub fn transfer_from(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, ) -> DispatchResult {372373            let mut approved: bool = false; 374            let sender = ensure_signed(origin)?;375            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);376            if approved_list_exists377            {378                let list_itm = <ApprovedList<T>>::get(collection_id, item_id);379                approved = list_itm.contains(&recipient.clone());380            }381382            if !approved383            {384                Self::check_owner_or_admin_permissions(collection_id, sender)?;385            }386            387            let target_collection = <Collection<T>>::get(collection_id);388389            // TODO: implement other modes390            ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");391392            if target_collection.mode == CollectionMode::NFT393            {394                Self::transfer_nft(collection_id, item_id, recipient)?;395            }396397            Ok(())398        }399400        #[weight = 0]401        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {402403            // let no_perm_mes = "You do not have permissions to modify this collection";404            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);405            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));406            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);407408            // // on_nft_received  call409410            // Self::transfer(origin, collection_id, item_id, new_owner)?;411412            Ok(())413        }414    }415}416417impl<T: Trait> Module<T> {418419    fn collection_exists(collection_id: u64) -> DispatchResult{420        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");421        Ok(())422    }423424    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {425426        Self::collection_exists(collection_id)?;427428        let target_collection = <Collection<T>>::get(collection_id);429        ensure!(subject == target_collection.owner, "You do not own this collection");430431        Ok(())432    }433434    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {435436        Self::collection_exists(collection_id)?;437438        let target_collection = <Collection<T>>::get(collection_id);439        let is_owner = subject == target_collection.owner;440441        let no_perm_mes = "You do not have permissions to modify this collection";442        let exists = <AdminList<T>>::contains_key(collection_id);443444        if !is_owner445        {446            ensure!(exists, no_perm_mes);447            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);448        }449        Ok(())450    }451452    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{453454        let mut result = false;455        let target_collection = <Collection<T>>::get(collection_id);456457        if target_collection.mode == CollectionMode::NFT458        {459            let item = <NftItemList<T>>::get(collection_id, item_id);460            result = item.owner == subject;461        }462463        if target_collection.mode == CollectionMode::Fungible464        {465            let item = <FungibleItemList<T>>::get(collection_id, item_id);466            result = item.owner.contains(&subject);467        }468469        if target_collection.mode == CollectionMode::ReFungible470        {471            let item = <ReFungibleItemList<T>>::get(collection_id, item_id);472            result = item.owner.iter().any(|i| i.owner == subject);473        }474475        result476    }477478    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {479480        let current_index = <ItemListIndex>::get(item.collection)481        .checked_add(1)482        .expect("Item list index id error");483484        Self::add_token_index(item.collection, current_index, item.owner.clone())?;485486        <ItemListIndex>::insert(item.collection, current_index);487        <NftItemList<T>>::insert(item.collection, current_index, item);488489        Ok(())490    }491492    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {493  494        let item = <NftItemList<T>>::get(collection_id, item_id);495        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;496497        // update balance498        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();499        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);500        <NftItemList<T>>::remove(collection_id, item_id);501502        Ok(())503    }504505    fn transfer_nft(collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {506507        let mut item = <NftItemList<T>>::get(collection_id, item_id);508509        // update balance510        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();511        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);512513        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();514        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);515516        // change owner517        let old_owner = item.owner.clone();518        item.owner = new_owner.clone();519        <NftItemList<T>>::insert(collection_id, item_id, item);520521        // update index collection522        Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;523524        // reset approved list525        let itm: Vec<T::AccountId> = Vec::new();526        <ApprovedList<T>>::insert(collection_id, item_id, itm);527528        // remove item529        <NftItemList<T>>::remove(collection_id, item_id);530531        Ok(())532    }533534    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {535        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());536        if list_exists {537            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());538            let item_contains = list.contains(&item_index.clone());539540            if !item_contains {541                list.push(item_index.clone());542            }543544            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);545        } else {546            let mut itm = Vec::new();547            itm.push(item_index.clone());548            <AddressTokens<T>>::insert(collection_id, owner, itm);549        }550551        Ok(())552    }553554    fn remove_token_index(555        collection_id: u64,556        item_index: u64,557        owner: T::AccountId,558    ) -> DispatchResult {559        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());560        if list_exists {561            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());562            let item_contains = list.contains(&item_index.clone());563564            if item_contains {565                list.retain(|&item| item != item_index);566                <AddressTokens<T>>::insert(collection_id, owner, list);567            }568        }569570        Ok(())571    }572573    fn move_token_index(574        collection_id: u64,575        item_index: u64,576        old_owner: T::AccountId,577        new_owner: T::AccountId,578    ) -> DispatchResult {579        Self::remove_token_index(collection_id, item_index, old_owner)?;580        Self::add_token_index(collection_id, item_index, new_owner)?;581582        Ok(())583    }584}