git.delta.rocks / unique-network / refs/commits / 4458a1dde4ff

difftreelog

minor: Fix tokenURI logic.

Trubnikov Sergey2022-07-19parent: #2dd986e.patch.diff
in: master

2 files changed

modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -219,25 +219,34 @@
 	/// @return token's const_metadata
 	#[solidity(rename_selector = "tokenURI")]
 	fn token_uri(&self, token_id: uint256) -> Result<string> {
-		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;	
-
-		if let Ok(shema_name) = get_token_property(self, token_id, &schema_name_key()) {
-			if shema_name != "ERC721" {
-				return Ok("".into());
+		let is_erc721 = || {
+			if let Some(shema_name) = pallet_common::Pallet::<T>::get_collection_property(self.id, &schema_name_key()) {
+				let shema_name = shema_name.into_inner();
+				shema_name == b"ERC721"
+			} else {
+				false
 			}
-		} else {
-			return Ok("".into());
-		}
+		};
+
+		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
 
-		if let Ok(url) = get_token_property(self, token_id, &u_key()) {
+		if let Ok(url) = get_token_property(self, token_id_u32, &u_key()) {
 			if !url.is_empty() {
 				return Ok(url);
 			}
+		} else if !is_erc721() {
+			return Err("tokenURI not set".into());
 		}
 
-		if let Ok(base_uri) = get_token_property(self, token_id, &base_uri_key()) {
+		if let Some(base_uri) = pallet_common::Pallet::<T>::get_collection_property(self.id, &base_uri_key()) {
 			if !base_uri.is_empty() {
-				if let Ok(suffix) = get_token_property(self, token_id, &s_key()) {
+				let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {
+					Error::Revert(alloc::format!(
+						"Can not convert value \"baseURI\" to string with error \"{}\"",
+						e
+					))
+				})?;
+				if let Ok(suffix) = get_token_property(self, token_id_u32, &s_key()) {
 					if !suffix.is_empty() {
 						return Ok(base_uri + suffix.as_str());
 					}
@@ -484,7 +493,7 @@
 		token_id: uint256,
 		token_uri: string,
 	) -> Result<bool> {
-		let key = token_uri_key();
+		let key = u_key();
 		let permission = get_token_permission::<T>(self.id, &key)?;
 		if !permission.collection_admin {
 			return Err("Operation is not allowed".into());
@@ -535,7 +544,11 @@
 	}
 }
 
-fn get_token_property<T: Config>(collection: &CollectionHandle<T>, token_id: u32, key: &up_data_structs::PropertyKey) -> Result<string> {
+fn get_token_property<T: Config>(
+	collection: &CollectionHandle<T>,
+	token_id: u32,
+	key: &up_data_structs::PropertyKey,
+) -> Result<string> {
 	collection.consume_store_reads(1)?;
 	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))
 		.map_err(|_| Error::Revert("Token properties not found".into()))?;
@@ -554,8 +567,11 @@
 		.map_err(|_| Error::Revert("No permissions for collection".into()))?;
 	let a = token_property_permissions
 		.get(key)
-		.map(|p| p.clone())
-		.ok_or_else(|| Error::Revert("No permission".into()))?;
+		.map(Clone::clone)
+		.ok_or_else(|| {
+			let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();
+			Error::Revert(alloc::format!("No permission for key {}", key))
+		})?;
 	Ok(a)
 }
 
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,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}8586fn make_data<T: Config>(87	name: CollectionName,88	mode: CollectionMode,89	description: CollectionDescription,90	token_prefix: CollectionTokenPrefix,91	base_uri_value: PropertyValue,92	add_properties: bool,93) -> Result<CreateCollectionData<T::AccountId>> {94	let mut properties = up_data_structs::CollectionPropertiesVec::default();95	let mut token_property_permissions =96		up_data_structs::CollectionPropertiesPermissionsVec::default();9798	if add_properties {99		token_property_permissions100			.try_push(up_data_structs::PropertyKeyPermission {101				key: token_uri_key(),102				permission: up_data_structs::PropertyPermission {103					mutable: true,104					collection_admin: true,105					token_owner: false,106				},107			})108			.map_err(|e| Error::Revert(format!("{:?}", e)))?;109110		token_property_permissions111			.try_push(up_data_structs::PropertyKeyPermission {112				key: u_key(),113				permission: up_data_structs::PropertyPermission {114					mutable: false,115					collection_admin: true,116					token_owner: false,117				},118			})119			.map_err(|e| Error::Revert(format!("{:?}", e)))?;120121		token_property_permissions122			.try_push(up_data_structs::PropertyKeyPermission {123				key: s_key(),124				permission: up_data_structs::PropertyPermission {125					mutable: false,126					collection_admin: true,127					token_owner: false,128				},129			})130			.map_err(|e| Error::Revert(format!("{:?}", e)))?;131132		properties133			.try_push(up_data_structs::Property {134				key: schema_name_key(),135				value: erc721_value(),136			})137			.map_err(|e| Error::Revert(format!("{:?}", e)))?;138139		if !base_uri_value.is_empty() {140			properties141				.try_push(up_data_structs::Property {142					key: base_uri_key(),143					value: base_uri_value,144				})145				.map_err(|e| Error::Revert(format!("{:?}", e)))?;146		}147	}148149	let data = CreateCollectionData {150		name,151		mode,152		description,153		token_prefix,154		token_property_permissions,155		properties,156		..Default::default()157	};158	Ok(data)159}160161/// @title Contract, which allows users to operate with collections162#[solidity_interface(name = "CollectionHelpers", events(CollectionHelpersEvents))]163impl<T: Config + pallet_nonfungible::Config> EvmCollectionHelpers<T> {164	/// Create an NFT collection165	/// @param name Name of the collection166	/// @param description Informative description of the collection167	/// @param token_prefix Token prefix to represent the collection tokens in UI and user applications168	/// @return address Address of the newly created collection169	#[weight(<SelfWeightOf<T>>::create_collection())]170	fn create_nonfungible_collection(171		&mut self,172		caller: caller,173		name: string,174		description: string,175		token_prefix: string,176	) -> Result<address> {177		let (caller, name, description, token_prefix, _base_uri_value) =178			convert_data::<T>(caller, name, description, token_prefix, "".into())?;179		let data = make_data::<T>(name, CollectionMode::NFT, description, token_prefix, Default::default(), false)?;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>(name, CollectionMode::NFT, description, token_prefix, base_uri_value, true)?;201		let collection_id =202			<pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, false)203				.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;204205		let address = pallet_common::eth::collection_id_to_address(collection_id);206		Ok(address)207	}208209	/// Check if a collection exists210	/// @param collection_address Address of the collection in question211	/// @return bool Does the collection exist?212	fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {213		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {214			let collection_id = id;215			return Ok(<CollectionById<T>>::contains_key(collection_id));216		}217218		Ok(false)219	}220}221222/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]223pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);224impl<T: Config + pallet_nonfungible::Config> OnMethodCall<T> for CollectionHelpersOnMethodCall<T> {225	fn is_reserved(contract: &sp_core::H160) -> bool {226		contract == &T::ContractAddress::get()227	}228229	fn is_used(contract: &sp_core::H160) -> bool {230		contract == &T::ContractAddress::get()231	}232233	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {234		if handle.code_address() != T::ContractAddress::get() {235			return None;236		}237238		let helpers =239			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));240		pallet_evm_coder_substrate::call(handle, helpers)241	}242243	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {244		(contract == &T::ContractAddress::get())245			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())246	}247}248249generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);250generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);251252fn error_feild_too_long(feild: &str, bound: usize) -> Error {253	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))254}
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}8586fn make_data<T: Config>(87	name: CollectionName,88	mode: CollectionMode,89	description: CollectionDescription,90	token_prefix: CollectionTokenPrefix,91	base_uri_value: PropertyValue,92	add_properties: bool,93) -> Result<CreateCollectionData<T::AccountId>> {94	let mut properties = up_data_structs::CollectionPropertiesVec::default();95	let mut token_property_permissions =96		up_data_structs::CollectionPropertiesPermissionsVec::default();9798	token_property_permissions99		.try_push(up_data_structs::PropertyKeyPermission {100			key: u_key(),101			permission: up_data_structs::PropertyPermission {102				mutable: false,103				collection_admin: true,104				token_owner: false,105			},106		})107		.map_err(|e| Error::Revert(format!("{:?}", e)))?;108109	if add_properties {110		token_property_permissions111			.try_push(up_data_structs::PropertyKeyPermission {112				key: s_key(),113				permission: up_data_structs::PropertyPermission {114					mutable: false,115					collection_admin: true,116					token_owner: false,117				},118			})119			.map_err(|e| Error::Revert(format!("{:?}", e)))?;120121		properties122			.try_push(up_data_structs::Property {123				key: schema_name_key(),124				value: erc721_value(),125			})126			.map_err(|e| Error::Revert(format!("{:?}", e)))?;127128		if !base_uri_value.is_empty() {129			properties130				.try_push(up_data_structs::Property {131					key: base_uri_key(),132					value: base_uri_value,133				})134				.map_err(|e| Error::Revert(format!("{:?}", e)))?;135		}136	}137138	let data = CreateCollectionData {139		name,140		mode,141		description,142		token_prefix,143		token_property_permissions,144		properties,145		..Default::default()146	};147	Ok(data)148}149150/// @title Contract, which allows users to operate with collections151#[solidity_interface(name = "CollectionHelpers", events(CollectionHelpersEvents))]152impl<T: Config + pallet_nonfungible::Config> EvmCollectionHelpers<T> {153	/// Create an NFT collection154	/// @param name Name of the collection155	/// @param description Informative description of the collection156	/// @param token_prefix Token prefix to represent the collection tokens in UI and user applications157	/// @return address Address of the newly created collection158	#[weight(<SelfWeightOf<T>>::create_collection())]159	fn create_nonfungible_collection(160		&mut self,161		caller: caller,162		name: string,163		description: string,164		token_prefix: string,165	) -> Result<address> {166		let (caller, name, description, token_prefix, _base_uri_value) =167			convert_data::<T>(caller, name, description, token_prefix, "".into())?;168		let data = make_data::<T>(169			name,170			CollectionMode::NFT,171			description,172			token_prefix,173			Default::default(),174			false,175		)?;176		let collection_id =177			<pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, false)178				.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;179180		let address = pallet_common::eth::collection_id_to_address(collection_id);181		Ok(address)182	}183184	#[weight(<SelfWeightOf<T>>::create_collection())]185	#[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]186	fn create_nonfungible_collection_with_properties(187		&mut self,188		caller: caller,189		name: string,190		description: string,191		token_prefix: string,192		base_uri: string,193	) -> Result<address> {194		let (caller, name, description, token_prefix, base_uri_value) =195			convert_data::<T>(caller, name, description, token_prefix, base_uri)?;196		let data = make_data::<T>(197			name,198			CollectionMode::NFT,199			description,200			token_prefix,201			base_uri_value,202			true,203		)?;204		let collection_id =205			<pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, true)206				.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;207208		let address = pallet_common::eth::collection_id_to_address(collection_id);209		Ok(address)210	}211212	/// Check if a collection exists213	/// @param collection_address Address of the collection in question214	/// @return bool Does the collection exist?215	fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {216		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {217			let collection_id = id;218			return Ok(<CollectionById<T>>::contains_key(collection_id));219		}220221		Ok(false)222	}223}224225/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]226pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);227impl<T: Config + pallet_nonfungible::Config> OnMethodCall<T> for CollectionHelpersOnMethodCall<T> {228	fn is_reserved(contract: &sp_core::H160) -> bool {229		contract == &T::ContractAddress::get()230	}231232	fn is_used(contract: &sp_core::H160) -> bool {233		contract == &T::ContractAddress::get()234	}235236	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {237		if handle.code_address() != T::ContractAddress::get() {238			return None;239		}240241		let helpers =242			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));243		pallet_evm_coder_substrate::call(handle, helpers)244	}245246	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {247		(contract == &T::ContractAddress::get())248			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())249	}250}251252generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);253generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);254255fn error_feild_too_long(feild: &str, bound: usize) -> Error {256	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))257}