git.delta.rocks / unique-network / refs/commits / 450f13af06cb

difftreelog

source

pallets/unique/src/eth/mod.rs11.1 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 =178		T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());179180	let collection_id =181		T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)182			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;183	let address = pallet_common::eth::collection_id_to_address(collection_id);184	Ok(address)185}186187fn check_sent_amount_equals_collection_creation_price<T: Config>(value: value) -> Result<()> {188	let value = value.as_u128();189	let creation_price: u128 = T::CollectionCreationPrice::get()190		.try_into()191		.map_err(|_| ()) // workaround for `expect` requiring `Debug` trait192		.expect("Collection creation price should be convertible to u128");193	if value != creation_price {194		return Err(format!(195			"Sent amount not equals to collection creation price ({0})",196			creation_price197		)198		.into());199	}200	Ok(())201}202203/// @title Contract, which allows users to operate with collections204#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]205impl<T> EvmCollectionHelpers<T>206where207	T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,208{209	/// Create an NFT collection210	/// @param name Name of the collection211	/// @param description Informative description of the collection212	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications213	/// @return address Address of the newly created collection214	#[weight(<SelfWeightOf<T>>::create_collection())]215	fn create_nonfungible_collection(216		&mut self,217		caller: caller,218		value: value,219		name: string,220		description: string,221		token_prefix: string,222	) -> Result<address> {223		let (caller, name, description, token_prefix, _base_uri_value) =224			convert_data::<T>(caller, name, description, token_prefix, "".into())?;225		let data = make_data::<T>(226			name,227			CollectionMode::NFT,228			description,229			token_prefix,230			Default::default(),231			false,232		)?;233		check_sent_amount_equals_collection_creation_price::<T>(value)?;234		let collection_helpers_address =235			T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());236		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)237			.map_err(dispatch_to_evm::<T>)?;238239		let address = pallet_common::eth::collection_id_to_address(collection_id);240		Ok(address)241	}242243	#[weight(<SelfWeightOf<T>>::create_collection())]244	#[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]245	fn create_nonfungible_collection_with_properties(246		&mut self,247		caller: caller,248		value: value,249		name: string,250		description: string,251		token_prefix: string,252		base_uri: string,253	) -> Result<address> {254		let (caller, name, description, token_prefix, base_uri_value) =255			convert_data::<T>(caller, name, description, token_prefix, base_uri)?;256		let data = make_data::<T>(257			name,258			CollectionMode::NFT,259			description,260			token_prefix,261			base_uri_value,262			true,263		)?;264		check_sent_amount_equals_collection_creation_price::<T>(value)?;265		let collection_helpers_address =266			T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());267		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)268			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;269270		let address = pallet_common::eth::collection_id_to_address(collection_id);271		Ok(address)272	}273274	#[weight(<SelfWeightOf<T>>::create_collection())]275	#[solidity(rename_selector = "createRFTCollection")]276	fn create_refungible_collection(277		&mut self,278		caller: caller,279		value: value,280		name: string,281		description: string,282		token_prefix: string,283	) -> Result<address> {284		create_refungible_collection_internal::<T>(285			caller,286			value,287			name,288			description,289			token_prefix,290			Default::default(),291			false,292		)293	}294295	#[weight(<SelfWeightOf<T>>::create_collection())]296	#[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]297	fn create_refungible_collection_with_properties(298		&mut self,299		caller: caller,300		value: value,301		name: string,302		description: string,303		token_prefix: string,304		base_uri: string,305	) -> Result<address> {306		create_refungible_collection_internal::<T>(307			caller,308			value,309			name,310			description,311			token_prefix,312			base_uri,313			true,314		)315	}316317	/// Check if a collection exists318	/// @param collectionAddress Address of the collection in question319	/// @return bool Does the collection exist?320	fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {321		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {322			let collection_id = id;323			return Ok(<CollectionById<T>>::contains_key(collection_id));324		}325326		Ok(false)327	}328329	fn collection_creation_fee(&self) -> Result<value> {330		let price: u128 = T::CollectionCreationPrice::get()331			.try_into()332			.map_err(|_| ()) // workaround for `expect` requiring `Debug` trait333			.expect("Collection creation price should be convertible to u128");334		Ok(price.into())335	}336}337338/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]339pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);340impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>341	for CollectionHelpersOnMethodCall<T>342{343	fn is_reserved(contract: &sp_core::H160) -> bool {344		contract == &T::ContractAddress::get()345	}346347	fn is_used(contract: &sp_core::H160) -> bool {348		contract == &T::ContractAddress::get()349	}350351	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {352		if handle.code_address() != T::ContractAddress::get() {353			return None;354		}355356		let helpers =357			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));358		pallet_evm_coder_substrate::call(handle, helpers)359	}360361	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {362		(contract == &T::ContractAddress::get())363			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())364	}365}366367generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);368generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);369370fn error_field_too_long(feild: &str, bound: usize) -> Error {371	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))372}