git.delta.rocks / unique-network / refs/commits / fea73f40565c

difftreelog

source

pallets/unique/src/eth/mod.rs9.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/>.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::{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	name: string,160	description: string,161	token_prefix: string,162	base_uri: string,163	add_properties: bool,164) -> Result<address> {165	let (caller, name, description, token_prefix, base_uri_value) =166		convert_data::<T>(caller, name, description, token_prefix, base_uri)?;167	let data = make_data::<T>(168		name,169		CollectionMode::ReFungible,170		description,171		token_prefix,172		base_uri_value,173		add_properties,174	)?;175176	let collection_id = T::CollectionDispatch::create(caller.clone(), data)177		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;178	let address = pallet_common::eth::collection_id_to_address(collection_id);179	Ok(address)180}181182/// @title Contract, which allows users to operate with collections183#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]184impl<T> EvmCollectionHelpers<T>185where186	T: Config + pallet_nonfungible::Config + pallet_refungible::Config,187{188	/// Create an NFT collection189	/// @param name Name of the collection190	/// @param description Informative description of the collection191	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications192	/// @return address Address of the newly created collection193	#[weight(<SelfWeightOf<T>>::create_collection())]194	fn create_nonfungible_collection(195		&mut self,196		caller: caller,197		value: value,198		name: string,199		description: string,200		token_prefix: string,201	) -> Result<address> {202		let (caller, name, description, token_prefix, _base_uri_value) =203			convert_data::<T>(caller, name, description, token_prefix, "".into())?;204		let data = make_data::<T>(205			name,206			CollectionMode::NFT,207			description,208			token_prefix,209			Default::default(),210			false,211		)?;212		let collection_id = T::CollectionDispatch::create(caller, data)213			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;214215		let address = pallet_common::eth::collection_id_to_address(collection_id);216		Ok(address)217	}218219	#[weight(<SelfWeightOf<T>>::create_collection())]220	#[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]221	fn create_nonfungible_collection_with_properties(222		&mut self,223		caller: caller,224		name: string,225		description: string,226		token_prefix: string,227		base_uri: string,228	) -> Result<address> {229		let (caller, name, description, token_prefix, base_uri_value) =230			convert_data::<T>(caller, name, description, token_prefix, base_uri)?;231		let data = make_data::<T>(232			name,233			CollectionMode::NFT,234			description,235			token_prefix,236			base_uri_value,237			true,238		)?;239		let collection_id = T::CollectionDispatch::create(caller, data)240			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;241242		let address = pallet_common::eth::collection_id_to_address(collection_id);243		Ok(address)244	}245246	#[weight(<SelfWeightOf<T>>::create_collection())]247	#[solidity(rename_selector = "createRFTCollection")]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}