git.delta.rocks / unique-network / refs/commits / 3fa58894bbf0

difftreelog

source

pallets/refungible/src/common.rs12.6 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/>.1617use core::marker::PhantomData;1819use sp_std::collections::btree_map::BTreeMap;20use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};21use up_data_structs::{22	CollectionId, TokenId, CreateItemExData, CreateRefungibleExData, budget::Budget, Property,23	PropertyKey, PropertyValue, PropertyKeyPermission, CreateItemData, CollectionPropertiesVec,24};25use pallet_common::{26	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,27	weights::WeightInfo as _,28};29use pallet_structure::Error as StructureError;30use sp_runtime::{DispatchError};31use sp_std::{vec::Vec, vec};3233use crate::{34	AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,35	SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted, TotalSupply,36};3738macro_rules! max_weight_of {39	($($method:ident ($($args:tt)*)),*) => {40		041		$(42			.max(<SelfWeightOf<T>>::$method($($args)*))43		)*44	};45}4647fn properties_weight<T: Config>(properties: &CollectionPropertiesVec) -> u64 {48	if properties.len() > 0 {49		<CommonWeights<T>>::set_token_properties(properties.len() as u32)50	} else {51		052	}53}5455pub struct CommonWeights<T: Config>(PhantomData<T>);56impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {57	fn create_item() -> Weight {58		<SelfWeightOf<T>>::create_item()59	}6061	fn create_multiple_items(data: &[CreateItemData]) -> Weight {62		<SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(63			data.iter()64				.map(|data| match data {65					CreateItemData::ReFungible(rft_data) => {66						properties_weight::<T>(&rft_data.properties)67					}68					_ => 0,69				})70				.fold(0, |a, b| a.saturating_add(b)),71		)72	}7374	fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {75		match call {76			CreateItemExData::RefungibleMultipleOwners(i) => {77				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)78					.saturating_add(properties_weight::<T>(&i.properties))79			}80			CreateItemExData::RefungibleMultipleItems(i) => {81				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)82					.saturating_add(83						i.iter()84							.map(|d| properties_weight::<T>(&d.properties))85							.fold(0, |a, b| a.saturating_add(b)),86					)87			}88			_ => 0,89		}90	}9192	fn burn_item() -> Weight {93		max_weight_of!(burn_item_partial(), burn_item_fully())94	}9596	fn set_collection_properties(amount: u32) -> Weight {97		<pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)98	}99100	fn delete_collection_properties(amount: u32) -> Weight {101		<pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)102	}103104	fn set_token_properties(amount: u32) -> Weight {105		<SelfWeightOf<T>>::set_token_properties(amount)106	}107108	fn delete_token_properties(amount: u32) -> Weight {109		<SelfWeightOf<T>>::delete_token_properties(amount)110	}111112	fn set_token_property_permissions(amount: u32) -> Weight {113		<SelfWeightOf<T>>::set_token_property_permissions(amount)114	}115116	fn transfer() -> Weight {117		max_weight_of!(118			transfer_normal(),119			transfer_creating(),120			transfer_removing(),121			transfer_creating_removing()122		)123	}124125	fn approve() -> Weight {126		<SelfWeightOf<T>>::approve()127	}128129	fn transfer_from() -> Weight {130		max_weight_of!(131			transfer_from_normal(),132			transfer_from_creating(),133			transfer_from_removing(),134			transfer_from_creating_removing()135		)136	}137138	fn burn_from() -> Weight {139		<SelfWeightOf<T>>::burn_from()140	}141142	fn burn_recursively_self_raw() -> Weight {143		// Read to get total balance144		Self::burn_item() + T::DbWeight::get().reads(1)145	}146	fn burn_recursively_breadth_raw(_amount: u32) -> Weight {147		// Refungible token can't have children148		0149	}150}151152fn map_create_data<T: Config>(153	data: up_data_structs::CreateItemData,154	to: &T::CrossAccountId,155) -> Result<CreateRefungibleExData<T::CrossAccountId>, DispatchError> {156	match data {157		up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateRefungibleExData {158			users: {159				let mut out = BTreeMap::new();160				out.insert(to.clone(), data.pieces);161				out.try_into().expect("limit > 0")162			},163			properties: data.properties,164		}),165		_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),166	}167}168169/// Implementation of `CommonCollectionOperations` for `RefungibleHandle`. It wraps Refungible Pallete170/// methods and adds weight info.171impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {172	fn create_item(173		&self,174		sender: T::CrossAccountId,175		to: T::CrossAccountId,176		data: up_data_structs::CreateItemData,177		nesting_budget: &dyn Budget,178	) -> DispatchResultWithPostInfo {179		with_weight(180			<Pallet<T>>::create_item(181				self,182				&sender,183				map_create_data::<T>(data, &to)?,184				nesting_budget,185			),186			<CommonWeights<T>>::create_item(),187		)188	}189190	fn create_multiple_items(191		&self,192		sender: T::CrossAccountId,193		to: T::CrossAccountId,194		data: Vec<up_data_structs::CreateItemData>,195		nesting_budget: &dyn Budget,196	) -> DispatchResultWithPostInfo {197		let weight = <CommonWeights<T>>::create_multiple_items(&data);198		let data = data199			.into_iter()200			.map(|d| map_create_data::<T>(d, &to))201			.collect::<Result<Vec<_>, DispatchError>>()?;202203		with_weight(204			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),205			weight,206		)207	}208209	fn create_multiple_items_ex(210		&self,211		sender: <T>::CrossAccountId,212		data: CreateItemExData<T::CrossAccountId>,213		nesting_budget: &dyn Budget,214	) -> DispatchResultWithPostInfo {215		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);216		let data = match data {217			CreateItemExData::RefungibleMultipleOwners(r) => vec![r],218			CreateItemExData::RefungibleMultipleItems(r)219				if r.iter().all(|i| i.users.len() == 1) =>220			{221				r.into_inner()222			}223			_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),224		};225226		with_weight(227			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),228			weight,229		)230	}231232	fn burn_item(233		&self,234		sender: T::CrossAccountId,235		token: TokenId,236		amount: u128,237	) -> DispatchResultWithPostInfo {238		with_weight(239			<Pallet<T>>::burn(self, &sender, token, amount),240			<CommonWeights<T>>::burn_item(),241		)242	}243244	fn burn_item_recursively(245		&self,246		sender: T::CrossAccountId,247		token: TokenId,248		self_budget: &dyn Budget,249		_breadth_budget: &dyn Budget,250	) -> DispatchResultWithPostInfo {251		ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);252		with_weight(253			<Pallet<T>>::burn(254				self,255				&sender,256				token,257				<Balance<T>>::get((self.id, token, &sender)),258			),259			<CommonWeights<T>>::burn_recursively_self_raw(),260		)261	}262263	fn transfer(264		&self,265		from: T::CrossAccountId,266		to: T::CrossAccountId,267		token: TokenId,268		amount: u128,269		nesting_budget: &dyn Budget,270	) -> DispatchResultWithPostInfo {271		with_weight(272			<Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),273			<CommonWeights<T>>::transfer(),274		)275	}276277	fn approve(278		&self,279		sender: T::CrossAccountId,280		spender: T::CrossAccountId,281		token: TokenId,282		amount: u128,283	) -> DispatchResultWithPostInfo {284		with_weight(285			<Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),286			<CommonWeights<T>>::approve(),287		)288	}289290	fn transfer_from(291		&self,292		sender: T::CrossAccountId,293		from: T::CrossAccountId,294		to: T::CrossAccountId,295		token: TokenId,296		amount: u128,297		nesting_budget: &dyn Budget,298	) -> DispatchResultWithPostInfo {299		with_weight(300			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),301			<CommonWeights<T>>::transfer_from(),302		)303	}304305	fn burn_from(306		&self,307		sender: T::CrossAccountId,308		from: T::CrossAccountId,309		token: TokenId,310		amount: u128,311		nesting_budget: &dyn Budget,312	) -> DispatchResultWithPostInfo {313		with_weight(314			<Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),315			<CommonWeights<T>>::burn_from(),316		)317	}318319	fn set_collection_properties(320		&self,321		sender: T::CrossAccountId,322		properties: Vec<Property>,323	) -> DispatchResultWithPostInfo {324		let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);325326		with_weight(327			<Pallet<T>>::set_collection_properties(self, &sender, properties),328			weight,329		)330	}331332	fn delete_collection_properties(333		&self,334		sender: &T::CrossAccountId,335		property_keys: Vec<PropertyKey>,336	) -> DispatchResultWithPostInfo {337		let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);338339		with_weight(340			<Pallet<T>>::delete_collection_properties(self, sender, property_keys),341			weight,342		)343	}344345	fn set_token_properties(346		&self,347		sender: T::CrossAccountId,348		token_id: TokenId,349		properties: Vec<Property>,350		nesting_budget: &dyn Budget,351	) -> DispatchResultWithPostInfo {352		let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);353354		with_weight(355			<Pallet<T>>::set_token_properties(356				self,357				&sender,358				token_id,359				properties.into_iter(),360				false,361				nesting_budget,362			),363			weight,364		)365	}366367	fn set_token_property_permissions(368		&self,369		sender: &T::CrossAccountId,370		property_permissions: Vec<PropertyKeyPermission>,371	) -> DispatchResultWithPostInfo {372		let weight =373			<CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);374375		with_weight(376			<Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),377			weight,378		)379	}380381	fn delete_token_properties(382		&self,383		sender: T::CrossAccountId,384		token_id: TokenId,385		property_keys: Vec<PropertyKey>,386		nesting_budget: &dyn Budget,387	) -> DispatchResultWithPostInfo {388		let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);389390		with_weight(391			<Pallet<T>>::delete_token_properties(392				self,393				&sender,394				token_id,395				property_keys.into_iter(),396				nesting_budget,397			),398			weight,399		)400	}401402	fn check_nesting(403		&self,404		_sender: <T>::CrossAccountId,405		_from: (CollectionId, TokenId),406		_under: TokenId,407		_nesting_budget: &dyn Budget,408	) -> sp_runtime::DispatchResult {409		fail!(<Error<T>>::RefungibleDisallowsNesting)410	}411412	fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}413414	fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}415416	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {417		<Owned<T>>::iter_prefix((self.id, account))418			.map(|(id, _)| id)419			.collect()420	}421422	fn collection_tokens(&self) -> Vec<TokenId> {423		<TotalSupply<T>>::iter_prefix((self.id,))424			.map(|(id, _)| id)425			.collect()426	}427428	fn token_exists(&self, token: TokenId) -> bool {429		<Pallet<T>>::token_exists(self, token)430	}431432	fn last_token_id(&self) -> TokenId {433		TokenId(<TokensMinted<T>>::get(self.id))434	}435436	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {437		<Pallet<T>>::token_owner(self.id, token)438	}439440	/// Returns 10 token in no particular order.441	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {442		<Pallet<T>>::token_owners(self.id, token).unwrap_or_default()443	}444445	fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {446		None447	}448449	fn token_properties(450		&self,451		_token_id: TokenId,452		_keys: Option<Vec<PropertyKey>>,453	) -> Vec<Property> {454		Vec::new()455	}456457	fn total_supply(&self) -> u32 {458		<Pallet<T>>::total_supply(self)459	}460461	fn account_balance(&self, account: T::CrossAccountId) -> u32 {462		<AccountBalance<T>>::get((self.id, account))463	}464465	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {466		<Balance<T>>::get((self.id, token, account))467	}468469	fn allowance(470		&self,471		sender: T::CrossAccountId,472		spender: T::CrossAccountId,473		token: TokenId,474	) -> u128 {475		<Allowance<T>>::get((self.id, token, sender, spender))476	}477478	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {479		Some(self)480	}481482	fn total_pieces(&self, token: TokenId) -> Option<u128> {483		<Pallet<T>>::total_pieces(self.id, token)484	}485}486487impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {488	fn repartition(489		&self,490		owner: &T::CrossAccountId,491		token: TokenId,492		amount: u128,493	) -> DispatchResultWithPostInfo {494		with_weight(495			<Pallet<T>>::repartition(self, owner, token, amount),496			<SelfWeightOf<T>>::repartition_item(),497		)498	}499}