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

difftreelog

fmt

Trubnikov Sergey2022-08-26parent: #65f94fd.patch.diff
in: master

2 files changed

modifiedpallets/refungible/src/erc_token.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -32,7 +32,8 @@
 use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
 use pallet_common::{
 	CommonWeightInfo,
-	erc::{CommonEvmHandler, PrecompileResult}, eth::collection_id_to_address,
+	erc::{CommonEvmHandler, PrecompileResult},
+	eth::collection_id_to_address,
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
 use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
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 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}156157158fn create_refungible_collection_internal<159	T: Config + pallet_nonfungible::Config + pallet_refungible::Config,160>(161	caller: caller,162	name: string,163	description: string,164	token_prefix: string,165	base_uri: string,166	add_properties: bool,167) -> Result<address> {168	let (caller, name, description, token_prefix, base_uri_value) =169		convert_data::<T>(caller, name, description, token_prefix, base_uri)?;170	let data = make_data::<T>(171		name,172		CollectionMode::ReFungible,173		description,174		token_prefix,175		base_uri_value,176		add_properties,177	)?;178179	let collection_id = T::CollectionDispatch::create(caller.clone(), 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}184185/// @title Contract, which allows users to operate with collections186#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]187impl<T> EvmCollectionHelpers<T>188where189	T: Config + pallet_nonfungible::Config + pallet_refungible::Config,190{191	/// Create an NFT collection192	/// @param name Name of the collection193	/// @param description Informative description of the collection194	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications195	/// @return address Address of the newly created collection196	#[weight(<SelfWeightOf<T>>::create_collection())]197	fn create_nonfungible_collection(198		&mut self,199		caller: caller,200		name: string,201		description: string,202		token_prefix: string,203	) -> Result<address> {204		let (caller, name, description, token_prefix, _base_uri_value) =205			convert_data::<T>(caller, name, description, token_prefix, "".into())?;206		let data = make_data::<T>(207			name,208			CollectionMode::NFT,209			description,210			token_prefix,211			Default::default(),212			false,213		)?;214		let collection_id = T::CollectionDispatch::create(caller, data)215			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;216217		let address = pallet_common::eth::collection_id_to_address(collection_id);218		Ok(address)219	}220221	#[weight(<SelfWeightOf<T>>::create_collection())]222	#[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]223	fn create_nonfungible_collection_with_properties(224		&mut self,225		caller: caller,226		name: string,227		description: string,228		token_prefix: string,229		base_uri: string,230	) -> Result<address> {231		let (caller, name, description, token_prefix, base_uri_value) =232			convert_data::<T>(caller, name, description, token_prefix, base_uri)?;233		let data = make_data::<T>(234			name,235			CollectionMode::NFT,236			description,237			token_prefix,238			base_uri_value,239			true,240		)?;241		let collection_id = T::CollectionDispatch::create(caller, data)242			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;243244		let address = pallet_common::eth::collection_id_to_address(collection_id);245		Ok(address)246	}247248	#[weight(<SelfWeightOf<T>>::create_collection())]249	fn create_refungible_collection(250		&mut self,251		caller: caller,252		name: string,253		description: string,254		token_prefix: string,255	) -> Result<address> {256		create_refungible_collection_internal::<T>(257			caller,258			name,259			description,260			token_prefix,261			Default::default(),262			false,263		)264	}265266	#[weight(<SelfWeightOf<T>>::create_collection())]267	#[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]268	fn create_refungible_collection_with_properties(269		&mut self,270		caller: caller,271		name: string,272		description: string,273		token_prefix: string,274		base_uri: string,275	) -> Result<address> {276		create_refungible_collection_internal::<T>(277			caller,278			name,279			description,280			token_prefix,281			base_uri,282			true,283		)284	}285286	/// Check if a collection exists287	/// @param collectionAddress Address of the collection in question288	/// @return bool Does the collection exist?289	fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {290		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {291			let collection_id = id;292			return Ok(<CollectionById<T>>::contains_key(collection_id));293		}294295		Ok(false)296	}297}298299/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]300pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);301impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>302	for CollectionHelpersOnMethodCall<T>303{304	fn is_reserved(contract: &sp_core::H160) -> bool {305		contract == &T::ContractAddress::get()306	}307308	fn is_used(contract: &sp_core::H160) -> bool {309		contract == &T::ContractAddress::get()310	}311312	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {313		if handle.code_address() != T::ContractAddress::get() {314			return None;315		}316317		let helpers =318			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));319		pallet_evm_coder_substrate::call(handle, helpers)320	}321322	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {323		(contract == &T::ContractAddress::get())324			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())325	}326}327328generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);329generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);330331fn error_field_too_long(feild: &str, bound: usize) -> Error {332	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))333}
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 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}