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

difftreelog

misc: fix after rebase

Trubnikov Sergey2022-07-22parent: #ce8edd2.patch.diff
in: master

1 file changed

modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
before · pallets/unique/src/eth/mod.rs
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 evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};21use ethereum as _;22use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};23use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId, PrecompileHandle};24use up_data_structs::{25	CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,26	CollectionMode, PropertyValue, CollectionTokenPrefix,27};28use frame_support::traits::Get;29use pallet_common::{30	CollectionById,31	erc::{static_property_key_value::*, CollectionHelpersEvents},32};33use crate::{SelfWeightOf, Config, weights::WeightInfo};3435use sp_std::vec::Vec;36use alloc::format;3738/// See [`CollectionHelpersCall`]39pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);40impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {41	fn recorder(&self) -> &SubstrateRecorder<T> {42		&self.043	}4445	fn into_recorder(self) -> SubstrateRecorder<T> {46		self.047	}48}4950fn convert_data<T: Config>(51	caller: caller,52	name: string,53	description: string,54	token_prefix: string,55	base_uri: string,56) -> Result<(57	T::CrossAccountId,58	CollectionName,59	CollectionDescription,60	CollectionTokenPrefix,61	PropertyValue,62)> {63	let caller = T::CrossAccountId::from_eth(caller);64	let name = name65		.encode_utf16()66		.collect::<Vec<u16>>()67		.try_into()68		.map_err(|_| error_feild_too_long(stringify!(name), CollectionName::bound()))?;69	let description = description70		.encode_utf16()71		.collect::<Vec<u16>>()72		.try_into()73		.map_err(|_| {74			error_feild_too_long(stringify!(description), CollectionDescription::bound())75		})?;76	let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {77		error_feild_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())78	})?;79	let base_uri_value = base_uri80		.into_bytes()81		.try_into()82		.map_err(|_| error_feild_too_long(stringify!(token_prefix), PropertyValue::bound()))?;83	Ok((caller, name, description, token_prefix, base_uri_value))84}8586//87fn make_data<T: Config>(88	name: CollectionName,89	mode: CollectionMode,90	description: CollectionDescription,91	token_prefix: CollectionTokenPrefix,92	base_uri_value: PropertyValue,93	add_properties: bool,94) -> Result<CreateCollectionData<T::AccountId>> {95	let mut properties = up_data_structs::CollectionPropertiesVec::default();96	let mut token_property_permissions =97		up_data_structs::CollectionPropertiesPermissionsVec::default();9899	token_property_permissions100		.try_push(up_data_structs::PropertyKeyPermission {101			key: url_key(),102			permission: up_data_structs::PropertyPermission {103				mutable: false,104				collection_admin: true,105				token_owner: false,106			},107		})108		.map_err(|e| Error::Revert(format!("{:?}", e)))?;109110	if add_properties {111		token_property_permissions112			.try_push(up_data_structs::PropertyKeyPermission {113				key: suffix_key(),114				permission: up_data_structs::PropertyPermission {115					mutable: false,116					collection_admin: true,117					token_owner: false,118				},119			})120			.map_err(|e| Error::Revert(format!("{:?}", e)))?;121122		properties123			.try_push(up_data_structs::Property {124				key: schema_name_key(),125				value: erc721_value(),126			})127			.map_err(|e| Error::Revert(format!("{:?}", e)))?;128129		if !base_uri_value.is_empty() {130			properties131				.try_push(up_data_structs::Property {132					key: base_uri_key(),133					value: base_uri_value,134				})135				.map_err(|e| Error::Revert(format!("{:?}", e)))?;136		}137	}138139	let data = CreateCollectionData {140		name,141		mode,142		description,143		token_prefix,144		token_property_permissions,145		properties,146		..Default::default()147	};148	Ok(data)149}150151/// @title Contract, which allows users to operate with collections152#[solidity_interface(name = "CollectionHelpers", events(CollectionHelpersEvents))]153impl<T: Config + pallet_nonfungible::Config> EvmCollectionHelpers<T> {154	/// Create an NFT collection155	/// @param name Name of the collection156	/// @param description Informative description of the collection157	/// @param token_prefix Token prefix to represent the collection tokens in UI and user applications158	/// @return address Address of the newly created collection159	#[weight(<SelfWeightOf<T>>::create_collection())]160	fn create_nonfungible_collection(161		&mut self,162		caller: caller,163		name: string,164		description: string,165		token_prefix: string,166	) -> Result<address> {167		let (caller, name, description, token_prefix, _base_uri_value) =168			convert_data::<T>(caller, name, description, token_prefix, "".into())?;169		let data = make_data::<T>(170			name,171			CollectionMode::NFT,172			description,173			token_prefix,174			Default::default(),175			false,176		)?;177		let collection_id =178			<pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, false)179				.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;180181		let address = pallet_common::eth::collection_id_to_address(collection_id);182		Ok(address)183	}184185	#[weight(<SelfWeightOf<T>>::create_collection())]186	#[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]187	fn create_nonfungible_collection_with_properties(188		&mut self,189		caller: caller,190		name: string,191		description: string,192		token_prefix: string,193		base_uri: string,194	) -> Result<address> {195		let (caller, name, description, token_prefix, base_uri_value) =196			convert_data::<T>(caller, name, description, token_prefix, base_uri)?;197		let data = make_data::<T>(198			name,199			CollectionMode::NFT,200			description,201			token_prefix,202			base_uri_value,203			true,204		)?;205		let collection_id =206			<pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, true)207				.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;208209		let address = pallet_common::eth::collection_id_to_address(collection_id);210		Ok(address)211	}212213	#[weight(<SelfWeightOf<T>>::create_collection())]214	fn create_refungible_collection(215		&self,216		caller: caller,217		name: string,218		description: string,219		token_prefix: string,220	) -> Result<address> {221		let (caller, name, description, token_prefix) =222			convert_data::<T>(caller, name, description, token_prefix)?;223		let data = make_data::<T>(name, CollectionMode::ReFungible, description, token_prefix)?;224		let collection_id = <pallet_refungible::Pallet<T>>::init_collection(caller.clone(), data)225			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;226227		let address = pallet_common::eth::collection_id_to_address(collection_id);228		Ok(address)229	}230231	/// Check if a collection exists232	/// @param collection_address Address of the collection in question233	/// @return bool Does the collection exist?234	fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {235		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {236			let collection_id = id;237			return Ok(<CollectionById<T>>::contains_key(collection_id));238		}239240		Ok(false)241	}242}243244/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]245pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);246impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>247	for CollectionHelpersOnMethodCall<T>248{249	fn is_reserved(contract: &sp_core::H160) -> bool {250		contract == &T::ContractAddress::get()251	}252253	fn is_used(contract: &sp_core::H160) -> bool {254		contract == &T::ContractAddress::get()255	}256257	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {258		if handle.code_address() != T::ContractAddress::get() {259			return None;260		}261262		let helpers =263			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));264		pallet_evm_coder_substrate::call(handle, helpers)265	}266267	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {268		(contract == &T::ContractAddress::get())269			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())270	}271}272273generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);274generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);275276fn error_feild_too_long(feild: &str, bound: usize) -> Error {277	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))278}
after · pallets/unique/src/eth/mod.rs
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 evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};21use ethereum as _;22use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};23use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId, PrecompileHandle};24use up_data_structs::{25	CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,26	CollectionMode, PropertyValue,27};28use frame_support::traits::Get;29use pallet_common::{30	CollectionById,31	erc::{static_property_key_value::*, CollectionHelpersEvents},32};33use crate::{SelfWeightOf, Config, weights::WeightInfo};3435use sp_std::vec::Vec;36use alloc::format;3738/// See [`CollectionHelpersCall`]39pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);40impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {41	fn recorder(&self) -> &SubstrateRecorder<T> {42		&self.043	}4445	fn into_recorder(self) -> SubstrateRecorder<T> {46		self.047	}48}4950fn convert_data<T: Config>(51	caller: caller,52	name: string,53	description: string,54	token_prefix: string,55	base_uri: string,56) -> Result<(57	T::CrossAccountId,58	CollectionName,59	CollectionDescription,60	CollectionTokenPrefix,61	PropertyValue,62)> {63	let caller = T::CrossAccountId::from_eth(caller);64	let name = name65		.encode_utf16()66		.collect::<Vec<u16>>()67		.try_into()68		.map_err(|_| error_feild_too_long(stringify!(name), CollectionName::bound()))?;69	let description = description70		.encode_utf16()71		.collect::<Vec<u16>>()72		.try_into()73		.map_err(|_| {74			error_feild_too_long(stringify!(description), CollectionDescription::bound())75		})?;76	let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {77		error_feild_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())78	})?;79	let base_uri_value = base_uri80		.into_bytes()81		.try_into()82		.map_err(|_| error_feild_too_long(stringify!(token_prefix), PropertyValue::bound()))?;83	Ok((caller, name, description, token_prefix, base_uri_value))84}8586//87fn make_data<T: Config>(88	name: CollectionName,89	mode: CollectionMode,90	description: CollectionDescription,91	token_prefix: CollectionTokenPrefix,92	base_uri_value: PropertyValue,93	add_properties: bool,94) -> Result<CreateCollectionData<T::AccountId>> {95	let mut properties = up_data_structs::CollectionPropertiesVec::default();96	let mut token_property_permissions =97		up_data_structs::CollectionPropertiesPermissionsVec::default();9899	token_property_permissions100		.try_push(up_data_structs::PropertyKeyPermission {101			key: url_key(),102			permission: up_data_structs::PropertyPermission {103				mutable: false,104				collection_admin: true,105				token_owner: false,106			},107		})108		.map_err(|e| Error::Revert(format!("{:?}", e)))?;109110	if add_properties {111		token_property_permissions112			.try_push(up_data_structs::PropertyKeyPermission {113				key: suffix_key(),114				permission: up_data_structs::PropertyPermission {115					mutable: false,116					collection_admin: true,117					token_owner: false,118				},119			})120			.map_err(|e| Error::Revert(format!("{:?}", e)))?;121122		properties123			.try_push(up_data_structs::Property {124				key: schema_name_key(),125				value: erc721_value(),126			})127			.map_err(|e| Error::Revert(format!("{:?}", e)))?;128129		if !base_uri_value.is_empty() {130			properties131				.try_push(up_data_structs::Property {132					key: base_uri_key(),133					value: base_uri_value,134				})135				.map_err(|e| Error::Revert(format!("{:?}", e)))?;136		}137	}138139	let data = CreateCollectionData {140		name,141		mode,142		description,143		token_prefix,144		token_property_permissions,145		properties,146		..Default::default()147	};148	Ok(data)149}150151/// @title Contract, which allows users to operate with collections152#[solidity_interface(name = "CollectionHelpers", events(CollectionHelpersEvents))]153impl<T> EvmCollectionHelpers<T>154where155	T: Config + pallet_nonfungible::Config + pallet_refungible::Config 156{157	/// Create an NFT collection158	/// @param name Name of the collection159	/// @param description Informative description of the collection160	/// @param token_prefix Token prefix to represent the collection tokens in UI and user applications161	/// @return address Address of the newly created collection162	#[weight(<SelfWeightOf<T>>::create_collection())]163	fn create_nonfungible_collection(164		&mut self,165		caller: caller,166		name: string,167		description: string,168		token_prefix: string,169	) -> Result<address> {170		let (caller, name, description, token_prefix, _base_uri_value) =171			convert_data::<T>(caller, name, description, token_prefix, "".into())?;172		let data = make_data::<T>(173			name,174			CollectionMode::NFT,175			description,176			token_prefix,177			Default::default(),178			false,179		)?;180		let collection_id =181			<pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, false)182				.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;183184		let address = pallet_common::eth::collection_id_to_address(collection_id);185		Ok(address)186	}187188	#[weight(<SelfWeightOf<T>>::create_collection())]189	#[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]190	fn create_nonfungible_collection_with_properties(191		&mut self,192		caller: caller,193		name: string,194		description: string,195		token_prefix: string,196		base_uri: string,197	) -> Result<address> {198		let (caller, name, description, token_prefix, base_uri_value) =199			convert_data::<T>(caller, name, description, token_prefix, base_uri)?;200		let data = make_data::<T>(201			name,202			CollectionMode::NFT,203			description,204			token_prefix,205			base_uri_value,206			true,207		)?;208		let collection_id =209			<pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, true)210				.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;211212		let address = pallet_common::eth::collection_id_to_address(collection_id);213		Ok(address)214	}215216	#[weight(<SelfWeightOf<T>>::create_collection())]217	fn create_refungible_collection(218		&self,219		caller: caller,220		name: string,221		description: string,222		token_prefix: string,223	) -> Result<address> {224		let (caller, name, description, token_prefix, _base_uri) =225			convert_data::<T>(caller, name, description, token_prefix, "".into())?;226		let data = make_data::<T>(227			name,228			CollectionMode::ReFungible,229			description,230			token_prefix,231			Default::default(),232			false,233		)?;234		let collection_id = <pallet_refungible::Pallet<T>>::init_collection(caller.clone(), data)235			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;236237		let address = pallet_common::eth::collection_id_to_address(collection_id);238		Ok(address)239	}240241	/// Check if a collection exists242	/// @param collection_address Address of the collection in question243	/// @return bool Does the collection exist?244	fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {245		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {246			let collection_id = id;247			return Ok(<CollectionById<T>>::contains_key(collection_id));248		}249250		Ok(false)251	}252}253254/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]255pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);256impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>257	for CollectionHelpersOnMethodCall<T>258{259	fn is_reserved(contract: &sp_core::H160) -> bool {260		contract == &T::ContractAddress::get()261	}262263	fn is_used(contract: &sp_core::H160) -> bool {264		contract == &T::ContractAddress::get()265	}266267	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {268		if handle.code_address() != T::ContractAddress::get() {269			return None;270		}271272		let helpers =273			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));274		pallet_evm_coder_substrate::call(handle, helpers)275	}276277	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {278		(contract == &T::ContractAddress::get())279			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())280	}281}282283generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);284generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);285286fn error_feild_too_long(feild: &str, bound: usize) -> Error {287	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))288}