git.delta.rocks / unique-network / refs/commits / 57eaceedfd43

difftreelog

source

pallets/unique/src/eth/mod.rs10.8 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//! Implementation of CollectionHelpers contract.1819use core::marker::PhantomData;20use ethereum as _;21use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};22use frame_support::traits::Get;23use pallet_common::{24	CollectionById,25	dispatch::CollectionDispatch,26	erc::{27		CollectionHelpersEvents,28		static_property::{key, value as property_value},29	},30};31use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};32use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};33use up_data_structs::{34	CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,35	CollectionMode, PropertyValue,36};3738use crate::{Config, SelfWeightOf, weights::WeightInfo};3940use sp_std::vec::Vec;41use alloc::format;4243/// See [`CollectionHelpersCall`]44pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);45impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {46	fn recorder(&self) -> &SubstrateRecorder<T> {47		&self.048	}4950	fn into_recorder(self) -> SubstrateRecorder<T> {51		self.052	}53}5455fn convert_data<T: Config>(56	caller: caller,57	name: string,58	description: string,59	token_prefix: string,60	base_uri: string,61) -> Result<(62	T::CrossAccountId,63	CollectionName,64	CollectionDescription,65	CollectionTokenPrefix,66	PropertyValue,67)> {68	let caller = T::CrossAccountId::from_eth(caller);69	let name = name70		.encode_utf16()71		.collect::<Vec<u16>>()72		.try_into()73		.map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;74	let description = description75		.encode_utf16()76		.collect::<Vec<u16>>()77		.try_into()78		.map_err(|_| {79			error_field_too_long(stringify!(description), CollectionDescription::bound())80		})?;81	let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {82		error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())83	})?;84	let base_uri_value = base_uri85		.into_bytes()86		.try_into()87		.map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;88	Ok((caller, name, description, token_prefix, base_uri_value))89}9091fn make_data<T: Config>(92	name: CollectionName,93	mode: CollectionMode,94	description: CollectionDescription,95	token_prefix: CollectionTokenPrefix,96	base_uri_value: PropertyValue,97	add_properties: bool,98) -> Result<CreateCollectionData<T::AccountId>> {99	let mut properties = up_data_structs::CollectionPropertiesVec::default();100	let mut token_property_permissions =101		up_data_structs::CollectionPropertiesPermissionsVec::default();102103	token_property_permissions104		.try_push(up_data_structs::PropertyKeyPermission {105			key: key::url(),106			permission: up_data_structs::PropertyPermission {107				mutable: false,108				collection_admin: true,109				token_owner: false,110			},111		})112		.map_err(|e| Error::Revert(format!("{:?}", e)))?;113114	if add_properties {115		token_property_permissions116			.try_push(up_data_structs::PropertyKeyPermission {117				key: key::suffix(),118				permission: up_data_structs::PropertyPermission {119					mutable: false,120					collection_admin: true,121					token_owner: false,122				},123			})124			.map_err(|e| Error::Revert(format!("{:?}", e)))?;125126		properties127			.try_push(up_data_structs::Property {128				key: key::schema_name(),129				value: property_value::erc721(),130			})131			.map_err(|e| Error::Revert(format!("{:?}", e)))?;132133		if !base_uri_value.is_empty() {134			properties135				.try_push(up_data_structs::Property {136					key: key::base_uri(),137					value: base_uri_value,138				})139				.map_err(|e| Error::Revert(format!("{:?}", e)))?;140		}141	}142143	let data = CreateCollectionData {144		name,145		mode,146		description,147		token_prefix,148		token_property_permissions,149		properties,150		..Default::default()151	};152	Ok(data)153}154155fn create_refungible_collection_internal<156	T: Config + pallet_nonfungible::Config + pallet_refungible::Config,157>(158	caller: caller,159	value: value,160	name: string,161	description: string,162	token_prefix: string,163	base_uri: string,164	add_properties: bool,165) -> Result<address> {166	let (caller, name, description, token_prefix, base_uri_value) =167		convert_data::<T>(caller, name, description, token_prefix, base_uri)?;168	let data = make_data::<T>(169		name,170		CollectionMode::ReFungible,171		description,172		token_prefix,173		base_uri_value,174		add_properties,175	)?;176	check_sent_amount_equals_collection_creation_price::<T>(value)?;177	let collection_helpers_address =  T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());178179	let collection_id = T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)180		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;181	let address = pallet_common::eth::collection_id_to_address(collection_id);182	Ok(address)183}184185fn check_sent_amount_equals_collection_creation_price<T: Config>(value: value) -> Result<()> {186	let value = value.as_u128();187	let creation_price: u128 = T::CollectionCreationPrice::get()188		.try_into()189		.map_err(|_| ()) // workaround for `expect` requiring `Debug` trait190		.expect("Collection creation price should be convertible to u128");191	if value != creation_price {192		return Err(format!("Sent amount not equals to collection creation price ({0})", creation_price).into());193	}194	Ok(())195}196197/// @title Contract, which allows users to operate with collections198#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]199impl<T> EvmCollectionHelpers<T>200where201	T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,202{203	/// Create an NFT collection204	/// @param name Name of the collection205	/// @param description Informative description of the collection206	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications207	/// @return address Address of the newly created collection208	#[weight(<SelfWeightOf<T>>::create_collection())]209	fn create_nonfungible_collection(210		&mut self,211		caller: caller,212		value: value,213		name: string,214		description: string,215		token_prefix: string,216	) -> Result<address> {217		let (caller, name, description, token_prefix, _base_uri_value) =218			convert_data::<T>(caller, name, description, token_prefix, "".into())?;219		let data = make_data::<T>(220			name,221			CollectionMode::NFT,222			description,223			token_prefix,224			Default::default(),225			false,226		)?;227		check_sent_amount_equals_collection_creation_price::<T>(value)?;228		let collection_helpers_address =  T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());229		let collection_id =230			T::CollectionDispatch::create(caller, collection_helpers_address, data).map_err(dispatch_to_evm::<T>)?;231232		let address = pallet_common::eth::collection_id_to_address(collection_id);233		Ok(address)234	}235236	#[weight(<SelfWeightOf<T>>::create_collection())]237	#[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]238	fn create_nonfungible_collection_with_properties(239		&mut self,240		caller: caller,241		value: value,242		name: string,243		description: string,244		token_prefix: string,245		base_uri: string,246	) -> Result<address> {247		let (caller, name, description, token_prefix, base_uri_value) =248			convert_data::<T>(caller, name, description, token_prefix, base_uri)?;249		let data = make_data::<T>(250			name,251			CollectionMode::NFT,252			description,253			token_prefix,254			base_uri_value,255			true,256		)?;257		check_sent_amount_equals_collection_creation_price::<T>(value)?;258		let collection_helpers_address =  T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());259		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)260			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;261262		let address = pallet_common::eth::collection_id_to_address(collection_id);263		Ok(address)264	}265266	#[weight(<SelfWeightOf<T>>::create_collection())]267	#[solidity(rename_selector = "createRFTCollection")]268	fn create_refungible_collection(269		&mut self,270		caller: caller,271		value: value,272		name: string,273		description: string,274		token_prefix: string,275	) -> Result<address> {276		create_refungible_collection_internal::<T>(277			caller,278			value,279			name,280			description,281			token_prefix,282			Default::default(),283			false,284		)285	}286287	#[weight(<SelfWeightOf<T>>::create_collection())]288	#[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]289	fn create_refungible_collection_with_properties(290		&mut self,291		caller: caller,292		value: value,293		name: string,294		description: string,295		token_prefix: string,296		base_uri: string,297	) -> Result<address> {298		create_refungible_collection_internal::<T>(299			caller,300			value,301			name,302			description,303			token_prefix,304			base_uri,305			true,306		)307	}308309	/// Check if a collection exists310	/// @param collectionAddress Address of the collection in question311	/// @return bool Does the collection exist?312	fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {313		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {314			let collection_id = id;315			return Ok(<CollectionById<T>>::contains_key(collection_id));316		}317318		Ok(false)319	}320}321322/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]323pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);324impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>325	for CollectionHelpersOnMethodCall<T>326{327	fn is_reserved(contract: &sp_core::H160) -> bool {328		contract == &T::ContractAddress::get()329	}330331	fn is_used(contract: &sp_core::H160) -> bool {332		contract == &T::ContractAddress::get()333	}334335	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {336		if handle.code_address() != T::ContractAddress::get() {337			return None;338		}339340		let helpers =341			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));342		pallet_evm_coder_substrate::call(handle, helpers)343	}344345	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {346		(contract == &T::ContractAddress::get())347			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())348	}349}350351generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);352generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);353354fn error_field_too_long(feild: &str, bound: usize) -> Error {355	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))356}