git.delta.rocks / unique-network / refs/commits / 58bdab80d979

difftreelog

source

pallets/unique/src/eth/mod.rs9.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//! 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, CollectionHandle,25	dispatch::CollectionDispatch,26	erc::{27		CollectionHelpersEvents,28		static_property::{key, value as property_value},29	},30	Pallet as PalletCommon,31};32use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};33use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};34use pallet_evm_coder_substrate::dispatch_to_evm;35use up_data_structs::{36	CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,37	CollectionMode, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,38};3940use crate::{Config, SelfWeightOf, weights::WeightInfo};4142use sp_std::{vec, vec::Vec};43use alloc::format;4445/// See [`CollectionHelpersCall`]46pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);47impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {48	fn recorder(&self) -> &SubstrateRecorder<T> {49		&self.050	}5152	fn into_recorder(self) -> SubstrateRecorder<T> {53		self.054	}55}5657fn convert_data<T: Config>(58	caller: caller,59	name: string,60	description: string,61	token_prefix: string,62	base_uri: string,63) -> Result<(64	T::CrossAccountId,65	CollectionName,66	CollectionDescription,67	CollectionTokenPrefix,68	PropertyValue,69)> {70	let caller = T::CrossAccountId::from_eth(caller);71	let name = name72		.encode_utf16()73		.collect::<Vec<u16>>()74		.try_into()75		.map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;76	let description = description77		.encode_utf16()78		.collect::<Vec<u16>>()79		.try_into()80		.map_err(|_| {81			error_field_too_long(stringify!(description), CollectionDescription::bound())82		})?;83	let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {84		error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())85	})?;86	let base_uri_value = base_uri87		.into_bytes()88		.try_into()89		.map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;90	Ok((caller, name, description, token_prefix, base_uri_value))91}9293fn make_data<T: Config>(94	name: CollectionName,95	mode: CollectionMode,96	description: CollectionDescription,97	token_prefix: CollectionTokenPrefix,98	base_uri_value: PropertyValue,99	add_properties: bool,100) -> Result<CreateCollectionData<T::AccountId>> {101	let mut properties = up_data_structs::CollectionPropertiesVec::default();102	let mut token_property_permissions =103		up_data_structs::CollectionPropertiesPermissionsVec::default();104105	token_property_permissions106		.try_push(up_data_structs::PropertyKeyPermission {107			key: key::url(),108			permission: up_data_structs::PropertyPermission {109				mutable: false,110				collection_admin: true,111				token_owner: false,112			},113		})114		.map_err(|e| Error::Revert(format!("{:?}", e)))?;115116	if add_properties {117		token_property_permissions118			.try_push(up_data_structs::PropertyKeyPermission {119				key: key::suffix(),120				permission: up_data_structs::PropertyPermission {121					mutable: false,122					collection_admin: true,123					token_owner: false,124				},125			})126			.map_err(|e| Error::Revert(format!("{:?}", e)))?;127128		properties129			.try_push(up_data_structs::Property {130				key: key::schema_name(),131				value: property_value::erc721(),132			})133			.map_err(|e| Error::Revert(format!("{:?}", e)))?;134135		if !base_uri_value.is_empty() {136			properties137				.try_push(up_data_structs::Property {138					key: key::base_uri(),139					value: base_uri_value,140				})141				.map_err(|e| Error::Revert(format!("{:?}", e)))?;142		}143	}144145	let data = CreateCollectionData {146		name,147		mode,148		description,149		token_prefix,150		token_property_permissions,151		properties,152		..Default::default()153	};154	Ok(data)155}156157fn create_refungible_collection_internal<158	T: Config + pallet_nonfungible::Config + pallet_refungible::Config,159>(160	caller: caller,161	name: string,162	description: string,163	token_prefix: string,164	base_uri: string,165	add_properties: bool,166) -> Result<address> {167	let (caller, name, description, token_prefix, base_uri_value) =168		convert_data::<T>(caller, name, description, token_prefix, base_uri)?;169	let data = make_data::<T>(170		name,171		CollectionMode::ReFungible,172		description,173		token_prefix,174		base_uri_value,175		add_properties,176	)?;177178	let collection_id = T::CollectionDispatch::create(caller.clone(), data)179		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;180	let address = pallet_common::eth::collection_id_to_address(collection_id);181	Ok(address)182}183184/// @title Contract, which allows users to operate with collections185#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]186impl<T> EvmCollectionHelpers<T>187where188	T: Config + pallet_nonfungible::Config + pallet_refungible::Config,189{190	/// Create an NFT collection191	/// @param name Name of the collection192	/// @param description Informative description of the collection193	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications194	/// @return address Address of the newly created collection195	#[weight(<SelfWeightOf<T>>::create_collection())]196	fn create_nonfungible_collection(197		&mut self,198		caller: caller,199		name: string,200		description: string,201		token_prefix: string,202	) -> Result<address> {203		let (caller, name, description, token_prefix, _base_uri_value) =204			convert_data::<T>(caller, name, description, token_prefix, "".into())?;205		let data = make_data::<T>(206			name,207			CollectionMode::NFT,208			description,209			token_prefix,210			Default::default(),211			false,212		)?;213		let collection_id = T::CollectionDispatch::create(caller, data)214			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;215216		let address = pallet_common::eth::collection_id_to_address(collection_id);217		Ok(address)218	}219220	#[weight(<SelfWeightOf<T>>::create_collection())]221	#[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]222	fn create_nonfungible_collection_with_properties(223		&mut self,224		caller: caller,225		name: string,226		description: string,227		token_prefix: string,228		base_uri: string,229	) -> Result<address> {230		let (caller, name, description, token_prefix, base_uri_value) =231			convert_data::<T>(caller, name, description, token_prefix, base_uri)?;232		let data = make_data::<T>(233			name,234			CollectionMode::NFT,235			description,236			token_prefix,237			base_uri_value,238			true,239		)?;240		let collection_id = T::CollectionDispatch::create(caller, data)241			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;242243		let address = pallet_common::eth::collection_id_to_address(collection_id);244		Ok(address)245	}246247	#[weight(<SelfWeightOf<T>>::create_collection())]248	fn create_refungible_collection(249		&mut self,250		caller: caller,251		name: string,252		description: string,253		token_prefix: string,254	) -> Result<address> {255		create_refungible_collection_internal::<T>(256			caller,257			name,258			description,259			token_prefix,260			Default::default(),261			false,262		)263	}264265	#[weight(<SelfWeightOf<T>>::create_collection())]266	#[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]267	fn create_refungible_collection_with_properties(268		&mut self,269		caller: caller,270		name: string,271		description: string,272		token_prefix: string,273		base_uri: string,274	) -> Result<address> {275		create_refungible_collection_internal::<T>(276			caller,277			name,278			description,279			token_prefix,280			base_uri,281			true,282		)283	}284285	/// Check if a collection exists286	/// @param collectionAddress Address of the collection in question287	/// @return bool Does the collection exist?288	fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {289		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {290			let collection_id = id;291			return Ok(<CollectionById<T>>::contains_key(collection_id));292		}293294		Ok(false)295	}296}297298/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]299pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);300impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>301	for CollectionHelpersOnMethodCall<T>302{303	fn is_reserved(contract: &sp_core::H160) -> bool {304		contract == &T::ContractAddress::get()305	}306307	fn is_used(contract: &sp_core::H160) -> bool {308		contract == &T::ContractAddress::get()309	}310311	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {312		if handle.code_address() != T::ContractAddress::get() {313			return None;314		}315316		let helpers =317			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));318		pallet_evm_coder_substrate::call(handle, helpers)319	}320321	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {322		(contract == &T::ContractAddress::get())323			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())324	}325}326327generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);328generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);329330fn error_field_too_long(feild: &str, bound: usize) -> Error {331	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))332}