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

difftreelog

feat add burn_nft rmrk proxy

Daniel Shiposha2022-05-23parent: #a0df38d.patch.diff
in: master

1 file changed

modifiedpallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth
before · pallets/proxy-rmrk-core/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use frame_support::{pallet_prelude::*, transactional, BoundedVec, dispatch::DispatchResult};20use frame_system::{pallet_prelude::*, ensure_signed};21use sp_runtime::{DispatchError, Permill, traits::StaticLookup};22use sp_std::vec::Vec;23use up_data_structs::*;24use pallet_common::{Pallet as PalletCommon, Error as CommonError, CollectionHandle, CommonCollectionOperations};25use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle};26use pallet_evm::account::CrossAccountId;2728pub use pallet::*;2930pub mod misc;31pub mod property;3233use misc::*;34pub use property::*;3536#[frame_support::pallet]37pub mod pallet {38    use super::*;39    use pallet_evm::account;4041	#[pallet::config]42	pub trait Config: frame_system::Config43                    + pallet_common::Config44                    + pallet_nonfungible::Config45                    + account::Config {46		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;47	}4849	#[pallet::pallet]50	#[pallet::generate_store(pub(super) trait Store)]51	pub struct Pallet<T>(_);5253	#[pallet::event]54	#[pallet::generate_deposit(pub(super) fn deposit_event)]55	pub enum Event<T: Config> {56        CollectionCreated {57			issuer: T::AccountId,58			collection_id: RmrkCollectionId,59		},60        CollectionDestroyed {61			issuer: T::AccountId,62			collection_id: RmrkCollectionId,63		},64        IssuerChanged {65			old_issuer: T::AccountId,66			new_issuer: T::AccountId,67			collection_id: RmrkCollectionId,68		},69        CollectionLocked {70			issuer: T::AccountId,71			collection_id: RmrkCollectionId,72		},73        NftMinted {74			owner: T::AccountId,75			collection_id: RmrkCollectionId,76			nft_id: RmrkNftId,77		},78	}7980	#[pallet::error]81	pub enum Error<T> {82        /* Unique-specific events */83        CorruptedCollectionType,84        NftTypeEncodeError,85        RmrkPropertyKeyIsTooLong,86        RmrkPropertyValueIsTooLong,8788        /* RMRK compatible events */89        CollectionNotEmpty,90        NoAvailableCollectionId,91        NoAvailableNftId,92        CollectionUnknown,93        NoPermission,94        CollectionFullOrLocked,95	}9697	#[pallet::call]98	impl<T: Config> Pallet<T> {99        #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]100		#[transactional]101		pub fn create_collection(102			origin: OriginFor<T>,103			metadata: RmrkString,104			max: Option<u32>,105			symbol: RmrkCollectionSymbol,106		) -> DispatchResult {107            let sender = ensure_signed(origin)?;108109            let limits = max.map(|max| CollectionLimits {110                token_limit: Some(max),111                ..Default::default()112            });113114            let data = CreateCollectionData {115                limits,116                token_prefix: symbol.into_inner()117                    .try_into()118                    .map_err(|_| <CommonError<T>>::CollectionTokenPrefixLimitExceeded)?,119                ..Default::default()120            };121122            let collection_id_res = <PalletNft<T>>::init_collection(sender.clone(), data);123124            if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {125                return Err(<Error<T>>::NoAvailableCollectionId.into());126            }127128            let collection_id = collection_id_res?;129130            let collection = Self::get_nft_collection(collection_id)?.into_inner();131132            <PalletCommon<T>>::set_scoped_collection_properties(133                &collection,134                PropertyScope::Rmrk,135                [136                    rmrk_property!(Config=T, Metadata: metadata)?,137                    rmrk_property!(Config=T, CollectionType: CollectionType::Regular)?,138                ].into_iter()139            )?;140141            Self::deposit_event(Event::CollectionCreated {142                issuer: sender,143                collection_id: collection_id.0144            });145146            Ok(())147        }148149        #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]150		#[transactional]151		pub fn destroy_collection(152			origin: OriginFor<T>,153			collection_id: RmrkCollectionId,154		) -> DispatchResult {155            let sender = ensure_signed(origin)?;156            let cross_sender = T::CrossAccountId::from_sub(sender.clone());157158            let unique_collection_id = collection_id.into();159160            let collection = Self::get_typed_nft_collection(unique_collection_id, CollectionType::Regular)?;161162            ensure!(collection.total_supply() == 0, <Error<T>>::CollectionNotEmpty);163164            <PalletNft<T>>::destroy_collection(collection, &cross_sender)165                .map_err(Self::map_common_err_to_proxy)?;166167            Self::deposit_event(Event::CollectionDestroyed { issuer: sender, collection_id });168169            Ok(())170        }171172        #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]173		#[transactional]174		pub fn change_collection_issuer(175			origin: OriginFor<T>,176			collection_id: RmrkCollectionId,177			new_issuer: <T::Lookup as StaticLookup>::Source,178		) -> DispatchResult {179            let sender = ensure_signed(origin)?;180181            let new_issuer = T::Lookup::lookup(new_issuer)?;182183            Self::change_collection_owner(184                collection_id.into(),185                CollectionType::Regular,186                sender.clone(),187                new_issuer.clone()188            )?;189190            Self::deposit_event(Event::IssuerChanged {191				old_issuer: sender,192				new_issuer,193				collection_id,194			});195196            Ok(())197        }198199        #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]200		#[transactional]201		pub fn lock_collection(202			origin: OriginFor<T>,203			collection_id: RmrkCollectionId,204		) -> DispatchResult {205            let sender = ensure_signed(origin)?;206            let cross_sender = T::CrossAccountId::from_sub(sender.clone());207208            let collection = Self::get_typed_nft_collection(209                collection_id.into(),210                CollectionType::Regular211            )?;212213            Self::check_collection_owner(&collection, &cross_sender)?;214215            let token_count = collection.total_supply();216217            let mut collection = collection.into_inner();218            collection.limits.token_limit = Some(token_count);219            collection.save()?;220221			Self::deposit_event(Event::CollectionLocked { issuer: sender, collection_id });222223            Ok(())224        }225226        #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]227		#[transactional]228		pub fn mint_nft(229			origin: OriginFor<T>,230			owner: T::AccountId,231			collection_id: RmrkCollectionId,232			recipient: Option<T::AccountId>,233			royalty_amount: Option<Permill>,234			metadata: RmrkString,235		) -> DispatchResult {236            let sender = ensure_signed(origin)?;237            let sender = T::CrossAccountId::from_sub(sender);238            let cross_owner = T::CrossAccountId::from_sub(owner.clone());239240            let royalty_info = royalty_amount.map(|amount| rmrk::RoyaltyInfo {241                recipient: recipient.unwrap_or_else(|| owner.clone()),242                amount243            });244245            let nft_id = Self::create_nft(246                sender,247                cross_owner,248                collection_id.into(),249                CollectionType::Regular,250                NftType::Regular,251                [252                    rmrk_property!(Config=T, RoyaltyInfo: royalty_info)?,253                    rmrk_property!(Config=T, Metadata: metadata)?,254                    rmrk_property!(Config=T, Equipped: false)?,255                    rmrk_property!(Config=T, ResourceCollection: None::<CollectionId>)?,256                    rmrk_property!(Config=T, ResourcePriorities: <Vec<u8>>::new())?,257                ].into_iter()258            )?;259260            Self::deposit_event(Event::NftMinted {261                owner,262                collection_id,263                nft_id: nft_id.0264            });265266            Ok(())267        }268	}269}270271impl<T: Config> Pallet<T> {272    fn create_nft(273        sender: T::CrossAccountId,274        owner: T::CrossAccountId,275        collection_id: CollectionId,276        collection_type: CollectionType,277        nft_type: NftType,278        properties: impl Iterator<Item=Property>279    ) -> Result<TokenId, DispatchError> {280        let collection = Self::get_typed_nft_collection(281            collection_id,282            collection_type283        )?;284285        let data = CreateNftExData {286            const_data: nft_type.encode()287                .try_into()288                .map_err(|_| <Error<T>>::NftTypeEncodeError)?,289            properties: BoundedVec::default(),290            owner,291        };292293        let budget = budget::Value::new(2);294295        <PalletNft<T>>::create_item(296            &collection,297            &sender,298            data,299            &budget,300        ).map_err(Self::map_common_err_to_proxy)?;301302        let nft_id = <PalletNft<T>>::current_token_id(&collection);303304        <PalletNft<T>>::set_scoped_token_properties(305            &collection,306            nft_id,307            PropertyScope::Rmrk,308            properties309        )?;310311        Ok(nft_id)312    }313314    fn change_collection_owner(315        collection_id: CollectionId,316        collection_type: CollectionType,317        sender: T::AccountId,318        new_owner: T::AccountId,319    ) -> DispatchResult {320        let collection = Self::get_typed_nft_collection(321            collection_id,322            collection_type323        )?;324        Self::check_collection_owner(&collection, &T::CrossAccountId::from_sub(sender))?;325326        let mut collection = collection.into_inner();327328        collection.owner = new_owner;329        collection.save()330    }331332    fn check_collection_owner(collection: &NonfungibleHandle<T>, account: &T::CrossAccountId) -> DispatchResult {333        collection.check_is_owner(account)334            .map_err(Self::map_common_err_to_proxy)335    }336337    pub fn get_nft_collection(collection_id: CollectionId) -> Result<NonfungibleHandle<T>, DispatchError> {338        let collection = <CollectionHandle<T>>::try_get(collection_id)339            .map_err(|_| <Error<T>>::CollectionUnknown)?340            .into_nft_collection()?;341342        Ok(collection)343    }344345    pub fn get_collection_property(collection_id: CollectionId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {346        let collection_property = <PalletCommon<T>>::collection_properties(collection_id)347            .get(&rmrk_property!(Config=T, key)?)348            .ok_or(<Error<T>>::CollectionUnknown)?349            .clone();350351        Ok(collection_property)352    }353354    pub fn get_collection_type(collection_id: CollectionId) -> Result<CollectionType, DispatchError> {355        let value = Self::get_collection_property(collection_id, RmrkProperty::CollectionType)?;356        let collection_type: CollectionType = (&value)357            .try_into()358            .map_err(<Error<T>>::from)?;359360        Ok(collection_type)361    }362363    pub fn get_nft_property(collection_id: CollectionId, nft_id: TokenId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {364        let nft_property = <PalletNft<T>>::token_properties((collection_id, nft_id))365            .get(&rmrk_property!(Config=T, key)?)366            .ok_or(<Error<T>>::NoAvailableNftId)?367            .clone();368369        Ok(nft_property)370    }371372    pub fn check_collection_type(collection_id: CollectionId, collection_type: CollectionType) -> DispatchResult {373        let actual_type = Self::get_collection_type(collection_id)?;374        ensure!(actual_type == collection_type, <CommonError<T>>::NoPermission);375376        Ok(())377    }378379    fn get_typed_nft_collection(380        collection_id: CollectionId,381        collection_type: CollectionType382    ) -> Result<NonfungibleHandle<T>, DispatchError> {383        Self::check_collection_type(collection_id, collection_type)?;384385        Self::get_nft_collection(collection_id)386    }387388    fn map_common_err_to_proxy(err: DispatchError) -> DispatchError {389        map_common_err_to_proxy! {390            match err {391                NoPermission => NoPermission,392                CollectionTokenLimitExceeded => CollectionFullOrLocked393            }394        }395    }396}