git.delta.rocks / unique-network / refs/commits / 0e74039449d0

difftreelog

source

pallets/proxy-rmrk-equip/src/lib.rs16.7 KiBsourcehistory
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//! # RMRK Core Proxy Pallet18//!19//! A pallet used as proxy for RMRK Core (<https://rmrk-team.github.io/rmrk-substrate/#/pallets/rmrk-core>).20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Pallet`]24//!25//! ## Overview26//!27//! The RMRK Equip Proxy pallet mirrors the functionality of RMRK Equip,28//! binding its externalities to Unique's own underlying structure.29//! It is purposed to mimic RMRK Equip exactly, allowing seamless integrations30//! of solutions based on RMRK.31//!32//! RMRK Equip itself contains functionality to equip NFTs, and work with Bases,33//! Parts, and Themes. See [Proxy Implementation](#proxy-implementation) for details.34//!35//! Equip Proxy is responsible for a more specific area of RMRK, and heavily relies on the Core.36//! For a more foundational description of proxy implementation, please refer to [`pallet_rmrk_core`].37//!38//! *Note*, that while RMRK itself is subject to active development and restructuring,39//! the proxy may be caught temporarily out of date.40//!41//! ### What is RMRK?42//!43//! RMRK is a set of NFT standards which compose several "NFT 2.0 lego" primitives.44//! Putting these legos together allows a user to create NFT systems of arbitrary complexity.45//!46//! Meaning, RMRK NFTs are dynamic, able to nest into each other and form a hierarchy,47//! make use of specific changeable and partially shared metadata in the form of resources,48//! and more.49//!50//! Visit RMRK documentation and repositories to learn more:51//! - Docs: <https://docs.rmrk.app/getting-started/>52//! - FAQ: <https://coda.io/@rmrk/faq>53//! - Substrate code repository: <https://github.com/rmrk-team/rmrk-substrate>54//! - RMRK spec repository: <https://github.com/rmrk-team/rmrk-spec>55//! 56//! ## Terminology57//! 58//! For more information on RMRK, see RMRK's own documentation.59//! 60//! ### Intro to RMRK61//! 62//! - **Resource:** Additional piece of metadata of an NFT usually serving to add 63//! a piece of media on top of the root metadata (NFT's own), be it a different wing 64//! on the root template bird or something entirely unrelated.65//! 66//! - **Base:** A list of possible "components" - Parts, a combination of which can 67//! be appended/equipped to/on an NFT.68//! 69//! - **Part:** Something that, together with other Parts, can constitute an NFT. 70//! Parts are defined in the Base to which they belong. Parts can be either 71//! of the `slot` type or `fixed` type. Slots are intended for equippables.72//! Note that "part of something" and "Part of a Base" can be easily confused, 73//! and in this documentation these words are distinguished by the capital letter.74//! 75//! - **Theme:** Named objects of variable => value pairs which get interpolated into 76//! the Base's `themable` Parts. Themes can hold any value, but are often represented 77//! in RMRK's examples as colors applied to visible Parts.78//! 79//! ### Peculiarities in Unique80//! 81//! - **Scoped properties:** Properties that are normally obscured from users. 82//! Their purpose is to contain structured metadata that was not included in the Unique standard 83//! for collections and tokens, meant to be operated on by proxies and other outliers. 84//! Scoped properties are prefixed with `some-scope:`, where `some-scope` is 85//! an arbitrary keyword, like "rmrk", and `:` is an unacceptable symbol in user-defined 86//! properties, which, along with other safeguards, makes them impossible to tamper with.87//! 88//! - **Auxiliary properties:** A slightly different structure of properties, 89//! trading universality of use for more convenient storage, writes and access. 90//! Meant to be inaccessible to end users.91//!92//! ## Proxy Implementation93//!94//! An external user is supposed to be able to utilize this proxy as they would95//! utilize RMRK, and get exactly the same results. Normally, Unique transactions96//! are off-limits to RMRK collections and tokens, and vice versa. However,97//! the information stored on chain can be freely interpreted by storage reads and RPCs.98//!99//! ### ID Mapping100//!101//! RMRK's collections' IDs are counted independently of Unique's and start at 0.102//! Note that tokens' IDs still start at 1.103//! The collections themselves, as well as tokens, are stored as Unique collections,104//! and thus RMRK IDs are mapped to Unique IDs (but not vice versa).105//!106//! ### External/Internal Collection Insulation107//!108//! A Unique transaction cannot target collections purposed for RMRK,109//! and they are flagged as `external` to specify that. On the other hand,110//! due to the mapping, RMRK transactions and RPCs simply cannot reach Unique collections.111//!112//! ### Native Properties113//!114//! Many of RMRK's native parameters are stored as scoped properties of a collection115//! or an NFT on the chain. Scoped properties are prefixed with `rmrk:`, where `:`116//! is an unacceptable symbol in user-defined properties, which, along with other safeguards,117//! makes them impossible to tamper with.118//!119//! ### Collection and NFT Types, and Base, Parts and Themes Handling120//!121//! RMRK introduces the concept of a Base, which is a catalgoue of Parts,122//! possible components of an NFT. Due to its similarity with the functionality123//! of a token collection, a Base is stored and handled as one, and the Base's Parts and Themes124//! are the collection's NFTs. See [`CollectionType`](pallet_rmrk_core::misc::CollectionType) and125//! [`NftType`](pallet_rmrk_core::misc::NftType).126//!127//! ## Interface128//!129//! ### Dispatchables130//!131//! - `create_base` - Create a new Base.132//! - `theme_add` - Add a Theme to a Base.133//! - `equippable` - Update the array of Collections allowed to be equipped to a Base's specified Slot Part.134135#![cfg_attr(not(feature = "std"), no_std)]136137use frame_support::{pallet_prelude::*, transactional, BoundedVec, dispatch::DispatchResult};138use frame_system::{pallet_prelude::*, ensure_signed};139use sp_runtime::DispatchError;140use up_data_structs::*;141use pallet_common::{Pallet as PalletCommon, Error as CommonError};142use pallet_rmrk_core::{143	Pallet as PalletCore, Error as CoreError,144	misc::{self, *},145	property::RmrkProperty::*,146};147use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle};148use pallet_evm::account::CrossAccountId;149use weights::WeightInfo;150151pub use pallet::*;152153#[cfg(feature = "runtime-benchmarks")]154pub mod benchmarking;155pub mod rpc;156pub mod weights;157158pub type SelfWeightOf<T> = <T as Config>::WeightInfo;159160#[frame_support::pallet]161pub mod pallet {162	use super::*;163164	#[pallet::config]165	pub trait Config: frame_system::Config + pallet_rmrk_core::Config {166		/// Overarching event type.167		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;168169		/// The weight information of this pallet.170		type WeightInfo: WeightInfo;171	}172173	/// Map of a Base ID and a Part ID to an NFT in the Base collection serving as the Part.174	#[pallet::storage]175	#[pallet::getter(fn internal_part_id)]176	pub type InernalPartId<T: Config> =177		StorageDoubleMap<_, Twox64Concat, CollectionId, Twox64Concat, RmrkPartId, TokenId>;178179	/// Checkmark that a Base has a Theme NFT named "default".180	#[pallet::storage]181	#[pallet::getter(fn base_has_default_theme)]182	pub type BaseHasDefaultTheme<T: Config> =183		StorageMap<_, Twox64Concat, CollectionId, bool, ValueQuery>;184185	#[pallet::pallet]186	#[pallet::generate_store(pub(super) trait Store)]187	pub struct Pallet<T>(_);188189	#[pallet::event]190	#[pallet::generate_deposit(pub(super) fn deposit_event)]191	pub enum Event<T: Config> {192		BaseCreated {193			issuer: T::AccountId,194			base_id: RmrkBaseId,195		},196		EquippablesUpdated {197			base_id: RmrkBaseId,198			slot_id: RmrkSlotId,199		},200	}201202	#[pallet::error]203	pub enum Error<T> {204		/// No permission to perform action.205		PermissionError,206		/// Could not find an ID for a Base collection. It is likely there were too many collections created on the chain, causing an overflow.207		NoAvailableBaseId,208		/// Could not find a suitable ID for a Part, likely too many Part tokens were created in the Base, causing an overflow209		NoAvailablePartId,210		/// Base collection linked to this ID does not exist.211		BaseDoesntExist,212		/// No Theme named "default" is associated with the Base.213		NeedsDefaultThemeFirst,214		/// Part linked to this ID does not exist.215		PartDoesntExist,216		/// Cannot assign equippables to a fixed Part.217		NoEquippableOnFixedPart,218	}219220	#[pallet::call]221	impl<T: Config> Pallet<T> {222		/// Create a new Base.223		///224		/// Modeled after the [Base interaction](https://github.com/rmrk-team/rmrk-spec/blob/master/standards/rmrk2.0.0/interactions/base.md)225		///226		/// # Permissions227		/// - Anyone - will be assigned as the issuer of the Base.228		///229		/// # Arguments:230		/// - `base_type`: Arbitrary media type, e.g. "svg".231		/// - `symbol`: Arbitrary client-chosen symbol.232		/// - `parts`: Array of Fixed and Slot Parts composing the Base,233		/// confined in length by [`RmrkPartsLimit`](up_data_structs::RmrkPartsLimit).234		#[transactional]235		#[pallet::weight(<SelfWeightOf<T>>::create_base(parts.len() as u32))]236		pub fn create_base(237			origin: OriginFor<T>,238			base_type: RmrkString,239			symbol: RmrkBaseSymbol,240			parts: BoundedVec<RmrkPartType, RmrkPartsLimit>,241		) -> DispatchResult {242			let sender = ensure_signed(origin)?;243			let cross_sender = T::CrossAccountId::from_sub(sender.clone());244245			let data = CreateCollectionData {246				limits: None,247				token_prefix: symbol248					.into_inner()249					.try_into()250					.map_err(|_| <CommonError<T>>::CollectionTokenPrefixLimitExceeded)?,251				..Default::default()252			};253254			let collection_id_res =255				<PalletNft<T>>::init_collection(cross_sender.clone(), data, true);256257			if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {258				return Err(<Error<T>>::NoAvailableBaseId.into());259			}260261			let collection_id = collection_id_res?;262263			<PalletCommon<T>>::set_scoped_collection_properties(264				collection_id,265				PropertyScope::Rmrk,266				[267					<PalletCore<T>>::encode_rmrk_property(268						CollectionType,269						&misc::CollectionType::Base,270					)?,271					<PalletCore<T>>::encode_rmrk_property(BaseType, &base_type)?,272				]273				.into_iter(),274			)?;275276			let collection = <PalletCore<T>>::get_nft_collection(collection_id)?;277278			for part in parts {279				Self::create_part(&cross_sender, &collection, part)?;280			}281282			Self::deposit_event(Event::BaseCreated {283				issuer: sender,284				base_id: collection_id.0,285			});286287			Ok(())288		}289290		/// Add a Theme to a Base.291		/// A Theme named "default" is required prior to adding other Themes.292		///293		/// Modeled after [Themeadd interaction](https://github.com/rmrk-team/rmrk-spec/blob/master/standards/rmrk2.0.0/interactions/themeadd.md).294		///295		/// # Permissions:296		/// - Base issuer297		///298		/// # Arguments:299		/// - `base_id`: Base ID containing the Theme to be updated.300		/// - `theme`: Theme to add to the Base.  A Theme has a name and properties, which are an301		///   array of [key, value, inherit].302		///   - `key`: Arbitrary BoundedString, defined by client.303		///   - `value`: Arbitrary BoundedString, defined by client.304		///   - `inherit`: Optional bool.305		#[transactional]306		#[pallet::weight(<SelfWeightOf<T>>::theme_add(theme.properties.len() as u32))]307		pub fn theme_add(308			origin: OriginFor<T>,309			base_id: RmrkBaseId,310			theme: RmrkBoundedTheme,311		) -> DispatchResult {312			let sender = ensure_signed(origin)?;313314			let sender = T::CrossAccountId::from_sub(sender);315			let owner = &sender;316317			let collection_id: CollectionId = base_id.into();318319			let collection = Self::get_base(collection_id)?;320321			if theme.name.as_slice() == b"default" {322				<BaseHasDefaultTheme<T>>::insert(collection_id, true);323			} else if !Self::base_has_default_theme(collection_id) {324				return Err(<Error<T>>::NeedsDefaultThemeFirst.into());325			}326327			let token_id = <PalletCore<T>>::create_nft(328				&sender,329				owner,330				&collection,331				[332					<PalletCore<T>>::encode_rmrk_property(TokenType, &NftType::Theme)?,333					<PalletCore<T>>::encode_rmrk_property(ThemeName, &theme.name)?,334					<PalletCore<T>>::encode_rmrk_property(ThemeInherit, &theme.inherit)?,335				]336				.into_iter(),337			)338			.map_err(|_| <Error<T>>::PermissionError)?;339340			for property in theme.properties {341				<PalletNft<T>>::set_scoped_token_property(342					collection_id,343					token_id,344					PropertyScope::Rmrk,345					<PalletCore<T>>::encode_rmrk_property(346						UserProperty(property.key.as_slice()),347						&property.value,348					)?,349				)?;350			}351352			Ok(())353		}354355		/// Update the array of Collections allowed to be equipped to a Base's specified Slot Part.356		///357		/// Modeled after [equippable interaction](https://github.com/rmrk-team/rmrk-spec/blob/master/standards/rmrk2.0.0/interactions/equippable.md).358		///359		/// # Permissions:360		/// - Base issuer361		///362		/// # Arguments:363		/// - `base_id`: Base containing the Slot Part to be updated.364		/// - `part_id`: Slot Part whose Equippable List is being updated.365		/// - `equippables`: List of equippables that will override the current Equippables list.366		#[transactional]367		#[pallet::weight(<SelfWeightOf<T>>::equippable())]368		pub fn equippable(369			origin: OriginFor<T>,370			base_id: RmrkBaseId,371			slot_id: RmrkSlotId,372			equippables: RmrkEquippableList,373		) -> DispatchResult {374			let sender = ensure_signed(origin)?;375376			let base_collection_id = base_id.into();377			let collection = Self::get_base(base_collection_id)?;378379			<PalletCore<T>>::check_collection_owner(380				&collection,381				&T::CrossAccountId::from_sub(sender),382			)383			.map_err(|err| {384				if err == <CoreError<T>>::NoPermission.into() {385					<Error<T>>::PermissionError.into()386				} else {387					err388				}389			})?;390391			let part_id = Self::internal_part_id(base_collection_id, slot_id)392				.ok_or(<Error<T>>::PartDoesntExist)?;393394			let nft_type = <PalletCore<T>>::get_nft_type(base_collection_id, part_id)395				.map_err(|_| <Error<T>>::PartDoesntExist)?;396397			match nft_type {398				NftType::Regular | NftType::Theme => return Err(<Error<T>>::PermissionError.into()),399				NftType::FixedPart => return Err(<Error<T>>::NoEquippableOnFixedPart.into()),400				NftType::SlotPart => {401					<PalletNft<T>>::set_scoped_token_property(402						base_collection_id,403						part_id,404						PropertyScope::Rmrk,405						<PalletCore<T>>::encode_rmrk_property(EquippableList, &equippables)?,406					)?;407				}408			}409410			Self::deposit_event(Event::EquippablesUpdated { base_id, slot_id });411412			Ok(())413		}414	}415}416417impl<T: Config> Pallet<T> {418	/// Create or renew an NFT serving as a Part.419	fn create_part(420		sender: &T::CrossAccountId,421		collection: &NonfungibleHandle<T>,422		part: RmrkPartType,423	) -> DispatchResult {424		let owner = sender;425426		let part_id = part.id();427		let src = part.src();428		let z_index = part.z_index();429430		let nft_type = match part {431			RmrkPartType::FixedPart(_) => NftType::FixedPart,432			RmrkPartType::SlotPart(_) => NftType::SlotPart,433		};434435		let token_id = match Self::internal_part_id(collection.id, part_id) {436			Some(token_id) => token_id,437			None => {438				let token_id =439					<PalletCore<T>>::create_nft(sender, owner, collection, [].into_iter())440						.map_err(|err| match err {441							DispatchError::Arithmetic(_) => <Error<T>>::NoAvailablePartId.into(),442							err => err,443						})?;444445				<InernalPartId<T>>::insert(collection.id, part_id, token_id);446447				<PalletNft<T>>::set_scoped_token_property(448					collection.id,449					token_id,450					PropertyScope::Rmrk,451					<PalletCore<T>>::encode_rmrk_property(ExternalPartId, &part_id)?,452				)?;453454				token_id455			}456		};457458		<PalletNft<T>>::set_scoped_token_properties(459			collection.id,460			token_id,461			PropertyScope::Rmrk,462			[463				<PalletCore<T>>::encode_rmrk_property(TokenType, &nft_type)?,464				<PalletCore<T>>::encode_rmrk_property(Src, &src)?,465				<PalletCore<T>>::encode_rmrk_property(ZIndex, &z_index)?,466			]467			.into_iter(),468		)?;469470		if let RmrkPartType::SlotPart(part) = part {471			<PalletNft<T>>::set_scoped_token_property(472				collection.id,473				token_id,474				PropertyScope::Rmrk,475				<PalletCore<T>>::encode_rmrk_property(EquippableList, &part.equippable)?,476			)?;477		}478479		Ok(())480	}481482	/// Ensure that the collection under the Base ID is a Base collection,483	/// and fetch it.484	fn get_base(base_id: CollectionId) -> Result<NonfungibleHandle<T>, DispatchError> {485		let collection =486			<PalletCore<T>>::get_typed_nft_collection(base_id, misc::CollectionType::Base)487				.map_err(|err| {488					if err == <CoreError<T>>::CollectionUnknown.into() {489						<Error<T>>::BaseDoesntExist.into()490					} else {491						err492					}493				})?;494		collection.check_is_external()?;495496		Ok(collection)497	}498}