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

difftreelog

CORE-441 Add some properties atcollection creation

Trubnikov Sergey2022-07-11parent: #d4f7a1e.patch.diff
in: master

4 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -430,10 +430,53 @@
 	Ok(())
 }
 
-/// Get the "tokenURI" key as [PropertyKey](up_data_structs::PropertyKey).
-pub fn token_uri_key() -> up_data_structs::PropertyKey {
-	b"tokenURI"
-		.to_vec()
-		.try_into()
-		.expect("length < limit; qed")
+pub mod static_property_key_value {
+	use evm_coder::{
+		execution::{Result, Error},
+	};
+	use alloc::format;
+
+	const EXPECT_CONVERT_ERROR: &str = "length < limit";
+	/// Get the "tokenURI" key as [PropertyKey](up_data_structs::PropertyKey).
+	pub fn token_uri_key() -> up_data_structs::PropertyKey {
+		property_key_from_bytes(b"tokenURI").expect(EXPECT_CONVERT_ERROR)
+	}
+
+	pub fn schema_name_key() -> up_data_structs::PropertyKey {
+		property_key_from_bytes(b"schemaName").expect(EXPECT_CONVERT_ERROR)
+	}
+
+	pub fn base_uri_key() -> up_data_structs::PropertyKey {
+		property_key_from_bytes(b"baseURI").expect(EXPECT_CONVERT_ERROR)
+	}
+
+	pub fn u_key() -> up_data_structs::PropertyKey {
+		property_key_from_bytes(b"u").expect(EXPECT_CONVERT_ERROR)
+	}
+
+	pub fn s_key() -> up_data_structs::PropertyKey {
+		property_key_from_bytes(b"s").expect(EXPECT_CONVERT_ERROR)
+	}
+
+	pub fn erc721_value() -> up_data_structs::PropertyValue {
+		property_value_from_bytes(b"ERC721").expect(EXPECT_CONVERT_ERROR)
+	}
+
+	pub fn property_key_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyKey> {
+		bytes.to_vec().try_into().map_err(|_| {
+			Error::Revert(format!(
+				"Property key is too long. Max length is {}.",
+				up_data_structs::PropertyKey::bound()
+			))
+		})
+	}
+
+	pub fn property_value_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyValue> {
+		bytes.to_vec().try_into().map_err(|_| {
+			Error::Revert(format!(
+				"Property key is too long. Max length is {}.",
+				up_data_structs::PropertyKey::bound()
+			))
+		})
+	}
 }
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -33,7 +33,7 @@
 use pallet_evm_coder_substrate::dispatch_to_evm;
 use sp_std::vec::Vec;
 use pallet_common::{
-	erc::{CommonEvmHandler, PrecompileResult, CollectionCall, token_uri_key},
+	erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property_key_value::*},
 	CollectionHandle, CollectionPropertyPermissions,
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
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, 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	CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,26	MAX_COLLECTION_NAME_LENGTH,27};28use frame_support::traits::Get;29use pallet_common::{30	CollectionById,31	erc::{token_uri_key, 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}4950/// @title Contract, which allows users to operate with collections51#[solidity_interface(name = "CollectionHelpers", events(CollectionHelpersEvents))]52impl<T: Config + pallet_nonfungible::Config> EvmCollectionHelpers<T> {53	/// Create an NFT collection54	/// @param name Name of the collection55	/// @param description Informative description of the collection56	/// @param token_prefix Token prefix to represent the collection tokens in UI and user applications57	/// @return address Address of the newly created collection58	#[weight(<SelfWeightOf<T>>::create_collection())]59	fn create_nonfungible_collection(60		&mut self,61		caller: caller,62		name: string,63		description: string,64		token_prefix: string,65	) -> Result<address> {66		let caller = T::CrossAccountId::from_eth(caller);67		let name = name68			.encode_utf16()69			.collect::<Vec<u16>>()70			.try_into()71			.map_err(|_| error_feild_too_long(stringify!(name), MAX_COLLECTION_NAME_LENGTH))?;72		let description = description73			.encode_utf16()74			.collect::<Vec<u16>>()75			.try_into()76			.map_err(|_| {77				error_feild_too_long(stringify!(description), MAX_COLLECTION_DESCRIPTION_LENGTH)78			})?;79		let token_prefix = token_prefix80			.into_bytes()81			.try_into()82			.map_err(|_| error_feild_too_long(stringify!(token_prefix), MAX_TOKEN_PREFIX_LENGTH))?;8384		let key = token_uri_key();85		let permission = up_data_structs::PropertyPermission {86			mutable: true,87			collection_admin: true,88			token_owner: false,89		};90		let mut token_property_permissions =91			up_data_structs::CollectionPropertiesPermissionsVec::default();92		token_property_permissions93			.try_push(up_data_structs::PropertyKeyPermission { key, permission })94			.map_err(|e| Error::Revert(format!("{:?}", e)))?;9596		let data = CreateCollectionData {97			name,98			description,99			token_prefix,100			token_property_permissions,101			..Default::default()102		};103104		let collection_id =105			<pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, false)106				.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;107108		let address = pallet_common::eth::collection_id_to_address(collection_id);109		Ok(address)110	}111112	/// Check if a collection exists113	/// @param collection_address Address of the collection in question114	/// @return bool Does the collection exist?115	fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {116		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {117			let collection_id = id;118			return Ok(<CollectionById<T>>::contains_key(collection_id));119		}120121		Ok(false)122	}123}124125/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]126pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);127impl<T: Config + pallet_nonfungible::Config> OnMethodCall<T> for CollectionHelpersOnMethodCall<T> {128	fn is_reserved(contract: &sp_core::H160) -> bool {129		contract == &T::ContractAddress::get()130	}131132	fn is_used(contract: &sp_core::H160) -> bool {133		contract == &T::ContractAddress::get()134	}135136	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {137		if handle.code_address() != T::ContractAddress::get() {138			return None;139		}140141		let helpers =142			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));143		pallet_evm_coder_substrate::call(handle, helpers)144	}145146	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {147		(contract == &T::ContractAddress::get())148			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())149	}150}151152generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);153generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);154155fn error_feild_too_long(feild: &str, bound: u32) -> Error {156	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))157}
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -286,6 +286,10 @@
 	}
 }
 
+pub type CollectionName = BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>;
+pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;
+pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;
+
 /// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).
 #[struct_versioning::versioned(version = 2, upper)]
 #[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]