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

difftreelog

refactor move erc721metadata to flags

Yaroslav Bolyukin2022-10-13parent: #d4f43b6.patch.diff
in: master

6 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -706,9 +706,6 @@
 		/// Value "ERC721Metadata".
 		pub const ERC721_METADATA: &[u8] = b"ERC721Metadata";
 
-		/// Value "1" ERC721 metadata supported.
-		pub const ERC721_METADATA_SUPPORTED: &[u8] = b"1";
-
 		/// Value for [`ERC721_METADATA`].
 		pub fn erc721() -> up_data_structs::PropertyValue {
 			property_value_from_bytes(ERC721_METADATA).expect(EXPECT_CONVERT_ERROR)
@@ -717,11 +714,6 @@
 		/// Value for [`SCHEMA_VERSION`].
 		pub fn schema_version() -> up_data_structs::PropertyValue {
 			property_value_from_bytes(SCHEMA_VERSION).expect(EXPECT_CONVERT_ERROR)
-		}
-
-		/// Value for [`ERC721_METADATA_SUPPORTED`].
-		pub fn erc721_metadata_supported() -> up_data_structs::PropertyValue {
-			property_value_from_bytes(ERC721_METADATA_SUPPORTED).expect(EXPECT_CONVERT_ERROR)
 		}
 	}
 
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -71,6 +71,7 @@
 	Collection,
 	RpcCollection,
 	CollectionFlags,
+	RpcCollectionFlags,
 	CollectionId,
 	CreateItemData,
 	MAX_TOKEN_PREFIX_LENGTH,
@@ -824,7 +825,11 @@
 			token_property_permissions,
 			properties,
 			read_only: flags.external,
-			foreign: flags.foreign,
+
+			flags: RpcCollectionFlags {
+				foreign: flags.foreign,
+				erc721metadata: flags.erc721metadata,
+			},
 		})
 	}
 }
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
before · pallets/nonfungible/src/erc.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//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24	char::{REPLACEMENT_CHARACTER, decode_utf16},25	convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30	TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31	CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36	erc::{37		CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key,38		static_property::value,39	},40	CollectionHandle, CollectionPropertyPermissions,41};42use pallet_evm::{account::CrossAccountId, PrecompileHandle};43use pallet_evm_coder_substrate::call;44use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};4546use crate::{47	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,48	SelfWeightOf, weights::WeightInfo, TokenProperties,49};5051/// @title A contract that allows to set and delete token properties and change token property permissions.52#[solidity_interface(name = TokenProperties)]53impl<T: Config> NonfungibleHandle<T> {54	/// @notice Set permissions for token property.55	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.56	/// @param key Property key.57	/// @param isMutable Permission to mutate property.58	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.59	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.60	fn set_token_property_permission(61		&mut self,62		caller: caller,63		key: string,64		is_mutable: bool,65		collection_admin: bool,66		token_owner: bool,67	) -> Result<()> {68		let caller = T::CrossAccountId::from_eth(caller);69		<Pallet<T>>::set_property_permission(70			self,71			&caller,72			PropertyKeyPermission {73				key: <Vec<u8>>::from(key)74					.try_into()75					.map_err(|_| "too long key")?,76				permission: PropertyPermission {77					mutable: is_mutable,78					collection_admin,79					token_owner,80				},81			},82		)83		.map_err(dispatch_to_evm::<T>)84	}8586	/// @notice Set token property value.87	/// @dev Throws error if `msg.sender` has no permission to edit the property.88	/// @param tokenId ID of the token.89	/// @param key Property key.90	/// @param value Property value.91	fn set_property(92		&mut self,93		caller: caller,94		token_id: uint256,95		key: string,96		value: bytes,97	) -> Result<()> {98		let caller = T::CrossAccountId::from_eth(caller);99		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;100		let key = <Vec<u8>>::from(key)101			.try_into()102			.map_err(|_| "key too long")?;103		let value = value.try_into().map_err(|_| "value too long")?;104105		let nesting_budget = self106			.recorder107			.weight_calls_budget(<StructureWeight<T>>::find_parent());108109		<Pallet<T>>::set_token_property(110			self,111			&caller,112			TokenId(token_id),113			Property { key, value },114			&nesting_budget,115		)116		.map_err(dispatch_to_evm::<T>)117	}118119	/// @notice Delete token property value.120	/// @dev Throws error if `msg.sender` has no permission to edit the property.121	/// @param tokenId ID of the token.122	/// @param key Property key.123	fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {124		let caller = T::CrossAccountId::from_eth(caller);125		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;126		let key = <Vec<u8>>::from(key)127			.try_into()128			.map_err(|_| "key too long")?;129130		let nesting_budget = self131			.recorder132			.weight_calls_budget(<StructureWeight<T>>::find_parent());133134		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)135			.map_err(dispatch_to_evm::<T>)136	}137138	/// @notice Get token property value.139	/// @dev Throws error if key not found140	/// @param tokenId ID of the token.141	/// @param key Property key.142	/// @return Property value bytes143	fn property(&self, token_id: uint256, key: string) -> Result<bytes> {144		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;145		let key = <Vec<u8>>::from(key)146			.try_into()147			.map_err(|_| "key too long")?;148149		let props = <TokenProperties<T>>::get((self.id, token_id));150		let prop = props.get(&key).ok_or("key not found")?;151152		Ok(prop.to_vec())153	}154}155156#[derive(ToLog)]157pub enum ERC721Events {158	/// @dev This emits when ownership of any NFT changes by any mechanism.159	///  This event emits when NFTs are created (`from` == 0) and destroyed160	///  (`to` == 0). Exception: during contract creation, any number of NFTs161	///  may be created and assigned without emitting Transfer. At the time of162	///  any transfer, the approved address for that NFT (if any) is reset to none.163	Transfer {164		#[indexed]165		from: address,166		#[indexed]167		to: address,168		#[indexed]169		token_id: uint256,170	},171	/// @dev This emits when the approved address for an NFT is changed or172	///  reaffirmed. The zero address indicates there is no approved address.173	///  When a Transfer event emits, this also indicates that the approved174	///  address for that NFT (if any) is reset to none.175	Approval {176		#[indexed]177		owner: address,178		#[indexed]179		approved: address,180		#[indexed]181		token_id: uint256,182	},183	/// @dev This emits when an operator is enabled or disabled for an owner.184	///  The operator can manage all NFTs of the owner.185	#[allow(dead_code)]186	ApprovalForAll {187		#[indexed]188		owner: address,189		#[indexed]190		operator: address,191		approved: bool,192	},193}194195#[derive(ToLog)]196pub enum ERC721MintableEvents {197	#[allow(dead_code)]198	MintingFinished {},199}200201/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension202/// @dev See https://eips.ethereum.org/EIPS/eip-721203#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]204impl<T: Config> NonfungibleHandle<T> {205	/// @notice A descriptive name for a collection of NFTs in this contract206	fn name(&self) -> Result<string> {207		Ok(decode_utf16(self.name.iter().copied())208			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))209			.collect::<string>())210	}211212	/// @notice An abbreviated name for NFTs in this contract213	fn symbol(&self) -> Result<string> {214		Ok(string::from_utf8_lossy(&self.token_prefix).into())215	}216217	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.218	///219	/// @dev If the token has a `url` property and it is not empty, it is returned.220	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.221	///  If the collection property `baseURI` is empty or absent, return "" (empty string)222	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix223	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).224	///225	/// @return token's const_metadata226	#[solidity(rename_selector = "tokenURI")]227	fn token_uri(&self, token_id: uint256) -> Result<string> {228		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;229230		match get_token_property(self, token_id_u32, &key::url()).as_deref() {231			Err(_) | Ok("") => (),232			Ok(url) => {233				return Ok(url.into());234			}235		};236237		let base_uri =238			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())239				.map(BoundedVec::into_inner)240				.map(string::from_utf8)241				.transpose()242				.map_err(|e| {243					Error::Revert(alloc::format!(244						"Can not convert value \"baseURI\" to string with error \"{}\"",245						e246					))247				})?;248249		let base_uri = match base_uri.as_deref() {250			None | Some("") => {251				return Ok("".into());252			}253			Some(base_uri) => base_uri.into(),254		};255256		Ok(257			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {258				Err(_) | Ok("") => base_uri,259				Ok(suffix) => base_uri + suffix,260			},261		)262	}263}264265/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension266/// @dev See https://eips.ethereum.org/EIPS/eip-721267#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]268impl<T: Config> NonfungibleHandle<T> {269	/// @notice Enumerate valid NFTs270	/// @param index A counter less than `totalSupply()`271	/// @return The token identifier for the `index`th NFT,272	///  (sort order not specified)273	fn token_by_index(&self, index: uint256) -> Result<uint256> {274		Ok(index)275	}276277	/// @dev Not implemented278	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {279		// TODO: Not implemetable280		Err("not implemented".into())281	}282283	/// @notice Count NFTs tracked by this contract284	/// @return A count of valid NFTs tracked by this contract, where each one of285	///  them has an assigned and queryable owner not equal to the zero address286	fn total_supply(&self) -> Result<uint256> {287		self.consume_store_reads(1)?;288		Ok(<Pallet<T>>::total_supply(self).into())289	}290}291292/// @title ERC-721 Non-Fungible Token Standard293/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md294#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]295impl<T: Config> NonfungibleHandle<T> {296	/// @notice Count all NFTs assigned to an owner297	/// @dev NFTs assigned to the zero address are considered invalid, and this298	///  function throws for queries about the zero address.299	/// @param owner An address for whom to query the balance300	/// @return The number of NFTs owned by `owner`, possibly zero301	fn balance_of(&self, owner: address) -> Result<uint256> {302		self.consume_store_reads(1)?;303		let owner = T::CrossAccountId::from_eth(owner);304		let balance = <AccountBalance<T>>::get((self.id, owner));305		Ok(balance.into())306	}307	/// @notice Find the owner of an NFT308	/// @dev NFTs assigned to zero address are considered invalid, and queries309	///  about them do throw.310	/// @param tokenId The identifier for an NFT311	/// @return The address of the owner of the NFT312	fn owner_of(&self, token_id: uint256) -> Result<address> {313		self.consume_store_reads(1)?;314		let token: TokenId = token_id.try_into()?;315		Ok(*<TokenData<T>>::get((self.id, token))316			.ok_or("token not found")?317			.owner318			.as_eth())319	}320	/// @dev Not implemented321	#[solidity(rename_selector = "safeTransferFrom")]322	fn safe_transfer_from_with_data(323		&mut self,324		_from: address,325		_to: address,326		_token_id: uint256,327		_data: bytes,328	) -> Result<void> {329		// TODO: Not implemetable330		Err("not implemented".into())331	}332	/// @dev Not implemented333	fn safe_transfer_from(334		&mut self,335		_from: address,336		_to: address,337		_token_id: uint256,338	) -> Result<void> {339		// TODO: Not implemetable340		Err("not implemented".into())341	}342343	/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE344	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE345	///  THEY MAY BE PERMANENTLY LOST346	/// @dev Throws unless `msg.sender` is the current owner or an authorized347	///  operator for this NFT. Throws if `from` is not the current owner. Throws348	///  if `to` is the zero address. Throws if `tokenId` is not a valid NFT.349	/// @param from The current owner of the NFT350	/// @param to The new owner351	/// @param tokenId The NFT to transfer352	#[weight(<SelfWeightOf<T>>::transfer_from())]353	fn transfer_from(354		&mut self,355		caller: caller,356		from: address,357		to: address,358		token_id: uint256,359	) -> Result<void> {360		let caller = T::CrossAccountId::from_eth(caller);361		let from = T::CrossAccountId::from_eth(from);362		let to = T::CrossAccountId::from_eth(to);363		let token = token_id.try_into()?;364		let budget = self365			.recorder366			.weight_calls_budget(<StructureWeight<T>>::find_parent());367368		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)369			.map_err(dispatch_to_evm::<T>)?;370		Ok(())371	}372373	/// @notice Set or reaffirm the approved address for an NFT374	/// @dev The zero address indicates there is no approved address.375	/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized376	///  operator of the current owner.377	/// @param approved The new approved NFT controller378	/// @param tokenId The NFT to approve379	#[weight(<SelfWeightOf<T>>::approve())]380	fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {381		let caller = T::CrossAccountId::from_eth(caller);382		let approved = T::CrossAccountId::from_eth(approved);383		let token = token_id.try_into()?;384385		<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))386			.map_err(dispatch_to_evm::<T>)?;387		Ok(())388	}389390	/// @dev Not implemented391	fn set_approval_for_all(392		&mut self,393		_caller: caller,394		_operator: address,395		_approved: bool,396	) -> Result<void> {397		// TODO: Not implemetable398		Err("not implemented".into())399	}400401	/// @dev Not implemented402	fn get_approved(&self, _token_id: uint256) -> Result<address> {403		// TODO: Not implemetable404		Err("not implemented".into())405	}406407	/// @dev Not implemented408	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {409		// TODO: Not implemetable410		Err("not implemented".into())411	}412}413414/// @title ERC721 Token that can be irreversibly burned (destroyed).415#[solidity_interface(name = ERC721Burnable)]416impl<T: Config> NonfungibleHandle<T> {417	/// @notice Burns a specific ERC721 token.418	/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized419	///  operator of the current owner.420	/// @param tokenId The NFT to approve421	#[weight(<SelfWeightOf<T>>::burn_item())]422	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {423		let caller = T::CrossAccountId::from_eth(caller);424		let token = token_id.try_into()?;425426		<Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;427		Ok(())428	}429}430431/// @title ERC721 minting logic.432#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]433impl<T: Config> NonfungibleHandle<T> {434	fn minting_finished(&self) -> Result<bool> {435		Ok(false)436	}437438	/// @notice Function to mint token.439	/// @dev `tokenId` should be obtained with `nextTokenId` method,440	///  unlike standard, you can't specify it manually441	/// @param to The new owner442	/// @param tokenId ID of the minted NFT443	#[weight(<SelfWeightOf<T>>::create_item())]444	fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {445		let caller = T::CrossAccountId::from_eth(caller);446		let to = T::CrossAccountId::from_eth(to);447		let token_id: u32 = token_id.try_into()?;448		let budget = self449			.recorder450			.weight_calls_budget(<StructureWeight<T>>::find_parent());451452		if <TokensMinted<T>>::get(self.id)453			.checked_add(1)454			.ok_or("item id overflow")?455			!= token_id456		{457			return Err("item id should be next".into());458		}459460		<Pallet<T>>::create_item(461			self,462			&caller,463			CreateItemData::<T> {464				properties: BoundedVec::default(),465				owner: to,466			},467			&budget,468		)469		.map_err(dispatch_to_evm::<T>)?;470471		Ok(true)472	}473474	/// @notice Function to mint token with the given tokenUri.475	/// @dev `tokenId` should be obtained with `nextTokenId` method,476	///  unlike standard, you can't specify it manually477	/// @param to The new owner478	/// @param tokenId ID of the minted NFT479	/// @param tokenUri Token URI that would be stored in the NFT properties480	#[solidity(rename_selector = "mintWithTokenURI")]481	#[weight(<SelfWeightOf<T>>::create_item())]482	fn mint_with_token_uri(483		&mut self,484		caller: caller,485		to: address,486		token_id: uint256,487		token_uri: string,488	) -> Result<bool> {489		let key = key::url();490		let permission = get_token_permission::<T>(self.id, &key)?;491		if !permission.collection_admin {492			return Err("Operation is not allowed".into());493		}494495		let caller = T::CrossAccountId::from_eth(caller);496		let to = T::CrossAccountId::from_eth(to);497		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;498		let budget = self499			.recorder500			.weight_calls_budget(<StructureWeight<T>>::find_parent());501502		if <TokensMinted<T>>::get(self.id)503			.checked_add(1)504			.ok_or("item id overflow")?505			!= token_id506		{507			return Err("item id should be next".into());508		}509510		let mut properties = CollectionPropertiesVec::default();511		properties512			.try_push(Property {513				key,514				value: token_uri515					.into_bytes()516					.try_into()517					.map_err(|_| "token uri is too long")?,518			})519			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;520521		<Pallet<T>>::create_item(522			self,523			&caller,524			CreateItemData::<T> {525				properties,526				owner: to,527			},528			&budget,529		)530		.map_err(dispatch_to_evm::<T>)?;531		Ok(true)532	}533534	/// @dev Not implemented535	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {536		Err("not implementable".into())537	}538}539540fn get_token_property<T: Config>(541	collection: &CollectionHandle<T>,542	token_id: u32,543	key: &up_data_structs::PropertyKey,544) -> Result<string> {545	collection.consume_store_reads(1)?;546	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))547		.map_err(|_| Error::Revert("Token properties not found".into()))?;548	if let Some(property) = properties.get(key) {549		return Ok(string::from_utf8_lossy(property).into());550	}551552	Err("Property tokenURI not found".into())553}554555fn get_token_permission<T: Config>(556	collection_id: CollectionId,557	key: &PropertyKey,558) -> Result<PropertyPermission> {559	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)560		.map_err(|_| Error::Revert("No permissions for collection".into()))?;561	let a = token_property_permissions562		.get(key)563		.map(Clone::clone)564		.ok_or_else(|| {565			let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();566			Error::Revert(alloc::format!("No permission for key {}", key))567		})?;568	Ok(a)569}570571/// @title Unique extensions for ERC721.572#[solidity_interface(name = ERC721UniqueExtensions)]573impl<T: Config> NonfungibleHandle<T> {574	/// @notice Transfer ownership of an NFT575	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`576	///  is the zero address. Throws if `tokenId` is not a valid NFT.577	/// @param to The new owner578	/// @param tokenId The NFT to transfer579	#[weight(<SelfWeightOf<T>>::transfer())]580	fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {581		let caller = T::CrossAccountId::from_eth(caller);582		let to = T::CrossAccountId::from_eth(to);583		let token = token_id.try_into()?;584		let budget = self585			.recorder586			.weight_calls_budget(<StructureWeight<T>>::find_parent());587588		<Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;589		Ok(())590	}591592	/// @notice Burns a specific ERC721 token.593	/// @dev Throws unless `msg.sender` is the current owner or an authorized594	///  operator for this NFT. Throws if `from` is not the current owner. Throws595	///  if `to` is the zero address. Throws if `tokenId` is not a valid NFT.596	/// @param from The current owner of the NFT597	/// @param tokenId The NFT to transfer598	#[weight(<SelfWeightOf<T>>::burn_from())]599	fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {600		let caller = T::CrossAccountId::from_eth(caller);601		let from = T::CrossAccountId::from_eth(from);602		let token = token_id.try_into()?;603		let budget = self604			.recorder605			.weight_calls_budget(<StructureWeight<T>>::find_parent());606607		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)608			.map_err(dispatch_to_evm::<T>)?;609		Ok(())610	}611612	/// @notice Returns next free NFT ID.613	fn next_token_id(&self) -> Result<uint256> {614		self.consume_store_reads(1)?;615		Ok(<TokensMinted<T>>::get(self.id)616			.checked_add(1)617			.ok_or("item id overflow")?618			.into())619	}620621	/// @notice Function to mint multiple tokens.622	/// @dev `tokenIds` should be an array of consecutive numbers and first number623	///  should be obtained with `nextTokenId` method624	/// @param to The new owner625	/// @param tokenIds IDs of the minted NFTs626	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]627	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {628		let caller = T::CrossAccountId::from_eth(caller);629		let to = T::CrossAccountId::from_eth(to);630		let mut expected_index = <TokensMinted<T>>::get(self.id)631			.checked_add(1)632			.ok_or("item id overflow")?;633		let budget = self634			.recorder635			.weight_calls_budget(<StructureWeight<T>>::find_parent());636637		let total_tokens = token_ids.len();638		for id in token_ids.into_iter() {639			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;640			if id != expected_index {641				return Err("item id should be next".into());642			}643			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;644		}645		let data = (0..total_tokens)646			.map(|_| CreateItemData::<T> {647				properties: BoundedVec::default(),648				owner: to.clone(),649			})650			.collect();651652		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)653			.map_err(dispatch_to_evm::<T>)?;654		Ok(true)655	}656657	/// @notice Function to mint multiple tokens with the given tokenUris.658	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive659	///  numbers and first number should be obtained with `nextTokenId` method660	/// @param to The new owner661	/// @param tokens array of pairs of token ID and token URI for minted tokens662	#[solidity(rename_selector = "mintBulkWithTokenURI")]663	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]664	fn mint_bulk_with_token_uri(665		&mut self,666		caller: caller,667		to: address,668		tokens: Vec<(uint256, string)>,669	) -> Result<bool> {670		let key = key::url();671		let caller = T::CrossAccountId::from_eth(caller);672		let to = T::CrossAccountId::from_eth(to);673		let mut expected_index = <TokensMinted<T>>::get(self.id)674			.checked_add(1)675			.ok_or("item id overflow")?;676		let budget = self677			.recorder678			.weight_calls_budget(<StructureWeight<T>>::find_parent());679680		let mut data = Vec::with_capacity(tokens.len());681		for (id, token_uri) in tokens {682			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;683			if id != expected_index {684				return Err("item id should be next".into());685			}686			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;687688			let mut properties = CollectionPropertiesVec::default();689			properties690				.try_push(Property {691					key: key.clone(),692					value: token_uri693						.into_bytes()694						.try_into()695						.map_err(|_| "token uri is too long")?,696				})697				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;698699			data.push(CreateItemData::<T> {700				properties,701				owner: to.clone(),702			});703		}704705		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)706			.map_err(dispatch_to_evm::<T>)?;707		Ok(true)708	}709}710711impl<T: Config> NonfungibleHandle<T> {712	pub fn supports_metadata(&self) -> bool {713		let has_metadata_support_enabled = if let Some(erc721_metadata) =714			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::erc721_metadata())715		{716			*erc721_metadata.into_inner() == *value::ERC721_METADATA_SUPPORTED717		} else {718			false719		};720721		let has_url_property_permissions = get_token_permission::<T>(self.id, &key::url()).is_ok();722723		has_metadata_support_enabled && has_url_property_permissions724	}725}726727#[solidity_interface(728	name = UniqueNFT,729	is(730		ERC721,731		ERC721Enumerable,732		ERC721UniqueExtensions,733		ERC721Mintable,734		ERC721Burnable,735		Collection(via(common_mut returns CollectionHandle<T>)),736		TokenProperties,737		ERC721Metadata(if(this.supports_metadata())),738	)739)]740impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}741742// Not a tests, but code generators743generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);744generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);745746impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>747where748	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,749{750	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");751752	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {753		call::<T, UniqueNFTCall<T>, _, _>(handle, self)754	}755}
after · pallets/nonfungible/src/erc.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//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24	char::{REPLACEMENT_CHARACTER, decode_utf16},25	convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30	TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31	CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36	erc::{37		CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key,38		static_property::value,39	},40	CollectionHandle, CollectionPropertyPermissions,41};42use pallet_evm::{account::CrossAccountId, PrecompileHandle};43use pallet_evm_coder_substrate::call;44use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};4546use crate::{47	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,48	SelfWeightOf, weights::WeightInfo, TokenProperties,49};5051/// @title A contract that allows to set and delete token properties and change token property permissions.52#[solidity_interface(name = TokenProperties)]53impl<T: Config> NonfungibleHandle<T> {54	/// @notice Set permissions for token property.55	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.56	/// @param key Property key.57	/// @param isMutable Permission to mutate property.58	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.59	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.60	fn set_token_property_permission(61		&mut self,62		caller: caller,63		key: string,64		is_mutable: bool,65		collection_admin: bool,66		token_owner: bool,67	) -> Result<()> {68		let caller = T::CrossAccountId::from_eth(caller);69		<Pallet<T>>::set_property_permission(70			self,71			&caller,72			PropertyKeyPermission {73				key: <Vec<u8>>::from(key)74					.try_into()75					.map_err(|_| "too long key")?,76				permission: PropertyPermission {77					mutable: is_mutable,78					collection_admin,79					token_owner,80				},81			},82		)83		.map_err(dispatch_to_evm::<T>)84	}8586	/// @notice Set token property value.87	/// @dev Throws error if `msg.sender` has no permission to edit the property.88	/// @param tokenId ID of the token.89	/// @param key Property key.90	/// @param value Property value.91	fn set_property(92		&mut self,93		caller: caller,94		token_id: uint256,95		key: string,96		value: bytes,97	) -> Result<()> {98		let caller = T::CrossAccountId::from_eth(caller);99		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;100		let key = <Vec<u8>>::from(key)101			.try_into()102			.map_err(|_| "key too long")?;103		let value = value.try_into().map_err(|_| "value too long")?;104105		let nesting_budget = self106			.recorder107			.weight_calls_budget(<StructureWeight<T>>::find_parent());108109		<Pallet<T>>::set_token_property(110			self,111			&caller,112			TokenId(token_id),113			Property { key, value },114			&nesting_budget,115		)116		.map_err(dispatch_to_evm::<T>)117	}118119	/// @notice Delete token property value.120	/// @dev Throws error if `msg.sender` has no permission to edit the property.121	/// @param tokenId ID of the token.122	/// @param key Property key.123	fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {124		let caller = T::CrossAccountId::from_eth(caller);125		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;126		let key = <Vec<u8>>::from(key)127			.try_into()128			.map_err(|_| "key too long")?;129130		let nesting_budget = self131			.recorder132			.weight_calls_budget(<StructureWeight<T>>::find_parent());133134		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)135			.map_err(dispatch_to_evm::<T>)136	}137138	/// @notice Get token property value.139	/// @dev Throws error if key not found140	/// @param tokenId ID of the token.141	/// @param key Property key.142	/// @return Property value bytes143	fn property(&self, token_id: uint256, key: string) -> Result<bytes> {144		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;145		let key = <Vec<u8>>::from(key)146			.try_into()147			.map_err(|_| "key too long")?;148149		let props = <TokenProperties<T>>::get((self.id, token_id));150		let prop = props.get(&key).ok_or("key not found")?;151152		Ok(prop.to_vec())153	}154}155156#[derive(ToLog)]157pub enum ERC721Events {158	/// @dev This emits when ownership of any NFT changes by any mechanism.159	///  This event emits when NFTs are created (`from` == 0) and destroyed160	///  (`to` == 0). Exception: during contract creation, any number of NFTs161	///  may be created and assigned without emitting Transfer. At the time of162	///  any transfer, the approved address for that NFT (if any) is reset to none.163	Transfer {164		#[indexed]165		from: address,166		#[indexed]167		to: address,168		#[indexed]169		token_id: uint256,170	},171	/// @dev This emits when the approved address for an NFT is changed or172	///  reaffirmed. The zero address indicates there is no approved address.173	///  When a Transfer event emits, this also indicates that the approved174	///  address for that NFT (if any) is reset to none.175	Approval {176		#[indexed]177		owner: address,178		#[indexed]179		approved: address,180		#[indexed]181		token_id: uint256,182	},183	/// @dev This emits when an operator is enabled or disabled for an owner.184	///  The operator can manage all NFTs of the owner.185	#[allow(dead_code)]186	ApprovalForAll {187		#[indexed]188		owner: address,189		#[indexed]190		operator: address,191		approved: bool,192	},193}194195#[derive(ToLog)]196pub enum ERC721MintableEvents {197	#[allow(dead_code)]198	MintingFinished {},199}200201/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension202/// @dev See https://eips.ethereum.org/EIPS/eip-721203#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]204impl<T: Config> NonfungibleHandle<T> {205	/// @notice A descriptive name for a collection of NFTs in this contract206	fn name(&self) -> Result<string> {207		Ok(decode_utf16(self.name.iter().copied())208			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))209			.collect::<string>())210	}211212	/// @notice An abbreviated name for NFTs in this contract213	fn symbol(&self) -> Result<string> {214		Ok(string::from_utf8_lossy(&self.token_prefix).into())215	}216217	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.218	///219	/// @dev If the token has a `url` property and it is not empty, it is returned.220	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.221	///  If the collection property `baseURI` is empty or absent, return "" (empty string)222	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix223	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).224	///225	/// @return token's const_metadata226	#[solidity(rename_selector = "tokenURI")]227	fn token_uri(&self, token_id: uint256) -> Result<string> {228		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;229230		match get_token_property(self, token_id_u32, &key::url()).as_deref() {231			Err(_) | Ok("") => (),232			Ok(url) => {233				return Ok(url.into());234			}235		};236237		let base_uri =238			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())239				.map(BoundedVec::into_inner)240				.map(string::from_utf8)241				.transpose()242				.map_err(|e| {243					Error::Revert(alloc::format!(244						"Can not convert value \"baseURI\" to string with error \"{}\"",245						e246					))247				})?;248249		let base_uri = match base_uri.as_deref() {250			None | Some("") => {251				return Ok("".into());252			}253			Some(base_uri) => base_uri.into(),254		};255256		Ok(257			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {258				Err(_) | Ok("") => base_uri,259				Ok(suffix) => base_uri + suffix,260			},261		)262	}263}264265/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension266/// @dev See https://eips.ethereum.org/EIPS/eip-721267#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]268impl<T: Config> NonfungibleHandle<T> {269	/// @notice Enumerate valid NFTs270	/// @param index A counter less than `totalSupply()`271	/// @return The token identifier for the `index`th NFT,272	///  (sort order not specified)273	fn token_by_index(&self, index: uint256) -> Result<uint256> {274		Ok(index)275	}276277	/// @dev Not implemented278	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {279		// TODO: Not implemetable280		Err("not implemented".into())281	}282283	/// @notice Count NFTs tracked by this contract284	/// @return A count of valid NFTs tracked by this contract, where each one of285	///  them has an assigned and queryable owner not equal to the zero address286	fn total_supply(&self) -> Result<uint256> {287		self.consume_store_reads(1)?;288		Ok(<Pallet<T>>::total_supply(self).into())289	}290}291292/// @title ERC-721 Non-Fungible Token Standard293/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md294#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]295impl<T: Config> NonfungibleHandle<T> {296	/// @notice Count all NFTs assigned to an owner297	/// @dev NFTs assigned to the zero address are considered invalid, and this298	///  function throws for queries about the zero address.299	/// @param owner An address for whom to query the balance300	/// @return The number of NFTs owned by `owner`, possibly zero301	fn balance_of(&self, owner: address) -> Result<uint256> {302		self.consume_store_reads(1)?;303		let owner = T::CrossAccountId::from_eth(owner);304		let balance = <AccountBalance<T>>::get((self.id, owner));305		Ok(balance.into())306	}307	/// @notice Find the owner of an NFT308	/// @dev NFTs assigned to zero address are considered invalid, and queries309	///  about them do throw.310	/// @param tokenId The identifier for an NFT311	/// @return The address of the owner of the NFT312	fn owner_of(&self, token_id: uint256) -> Result<address> {313		self.consume_store_reads(1)?;314		let token: TokenId = token_id.try_into()?;315		Ok(*<TokenData<T>>::get((self.id, token))316			.ok_or("token not found")?317			.owner318			.as_eth())319	}320	/// @dev Not implemented321	#[solidity(rename_selector = "safeTransferFrom")]322	fn safe_transfer_from_with_data(323		&mut self,324		_from: address,325		_to: address,326		_token_id: uint256,327		_data: bytes,328	) -> Result<void> {329		// TODO: Not implemetable330		Err("not implemented".into())331	}332	/// @dev Not implemented333	fn safe_transfer_from(334		&mut self,335		_from: address,336		_to: address,337		_token_id: uint256,338	) -> Result<void> {339		// TODO: Not implemetable340		Err("not implemented".into())341	}342343	/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE344	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE345	///  THEY MAY BE PERMANENTLY LOST346	/// @dev Throws unless `msg.sender` is the current owner or an authorized347	///  operator for this NFT. Throws if `from` is not the current owner. Throws348	///  if `to` is the zero address. Throws if `tokenId` is not a valid NFT.349	/// @param from The current owner of the NFT350	/// @param to The new owner351	/// @param tokenId The NFT to transfer352	#[weight(<SelfWeightOf<T>>::transfer_from())]353	fn transfer_from(354		&mut self,355		caller: caller,356		from: address,357		to: address,358		token_id: uint256,359	) -> Result<void> {360		let caller = T::CrossAccountId::from_eth(caller);361		let from = T::CrossAccountId::from_eth(from);362		let to = T::CrossAccountId::from_eth(to);363		let token = token_id.try_into()?;364		let budget = self365			.recorder366			.weight_calls_budget(<StructureWeight<T>>::find_parent());367368		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)369			.map_err(dispatch_to_evm::<T>)?;370		Ok(())371	}372373	/// @notice Set or reaffirm the approved address for an NFT374	/// @dev The zero address indicates there is no approved address.375	/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized376	///  operator of the current owner.377	/// @param approved The new approved NFT controller378	/// @param tokenId The NFT to approve379	#[weight(<SelfWeightOf<T>>::approve())]380	fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {381		let caller = T::CrossAccountId::from_eth(caller);382		let approved = T::CrossAccountId::from_eth(approved);383		let token = token_id.try_into()?;384385		<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))386			.map_err(dispatch_to_evm::<T>)?;387		Ok(())388	}389390	/// @dev Not implemented391	fn set_approval_for_all(392		&mut self,393		_caller: caller,394		_operator: address,395		_approved: bool,396	) -> Result<void> {397		// TODO: Not implemetable398		Err("not implemented".into())399	}400401	/// @dev Not implemented402	fn get_approved(&self, _token_id: uint256) -> Result<address> {403		// TODO: Not implemetable404		Err("not implemented".into())405	}406407	/// @dev Not implemented408	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {409		// TODO: Not implemetable410		Err("not implemented".into())411	}412}413414/// @title ERC721 Token that can be irreversibly burned (destroyed).415#[solidity_interface(name = ERC721Burnable)]416impl<T: Config> NonfungibleHandle<T> {417	/// @notice Burns a specific ERC721 token.418	/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized419	///  operator of the current owner.420	/// @param tokenId The NFT to approve421	#[weight(<SelfWeightOf<T>>::burn_item())]422	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {423		let caller = T::CrossAccountId::from_eth(caller);424		let token = token_id.try_into()?;425426		<Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;427		Ok(())428	}429}430431/// @title ERC721 minting logic.432#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]433impl<T: Config> NonfungibleHandle<T> {434	fn minting_finished(&self) -> Result<bool> {435		Ok(false)436	}437438	/// @notice Function to mint token.439	/// @dev `tokenId` should be obtained with `nextTokenId` method,440	///  unlike standard, you can't specify it manually441	/// @param to The new owner442	/// @param tokenId ID of the minted NFT443	#[weight(<SelfWeightOf<T>>::create_item())]444	fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {445		let caller = T::CrossAccountId::from_eth(caller);446		let to = T::CrossAccountId::from_eth(to);447		let token_id: u32 = token_id.try_into()?;448		let budget = self449			.recorder450			.weight_calls_budget(<StructureWeight<T>>::find_parent());451452		if <TokensMinted<T>>::get(self.id)453			.checked_add(1)454			.ok_or("item id overflow")?455			!= token_id456		{457			return Err("item id should be next".into());458		}459460		<Pallet<T>>::create_item(461			self,462			&caller,463			CreateItemData::<T> {464				properties: BoundedVec::default(),465				owner: to,466			},467			&budget,468		)469		.map_err(dispatch_to_evm::<T>)?;470471		Ok(true)472	}473474	/// @notice Function to mint token with the given tokenUri.475	/// @dev `tokenId` should be obtained with `nextTokenId` method,476	///  unlike standard, you can't specify it manually477	/// @param to The new owner478	/// @param tokenId ID of the minted NFT479	/// @param tokenUri Token URI that would be stored in the NFT properties480	#[solidity(rename_selector = "mintWithTokenURI")]481	#[weight(<SelfWeightOf<T>>::create_item())]482	fn mint_with_token_uri(483		&mut self,484		caller: caller,485		to: address,486		token_id: uint256,487		token_uri: string,488	) -> Result<bool> {489		let key = key::url();490		let permission = get_token_permission::<T>(self.id, &key)?;491		if !permission.collection_admin {492			return Err("Operation is not allowed".into());493		}494495		let caller = T::CrossAccountId::from_eth(caller);496		let to = T::CrossAccountId::from_eth(to);497		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;498		let budget = self499			.recorder500			.weight_calls_budget(<StructureWeight<T>>::find_parent());501502		if <TokensMinted<T>>::get(self.id)503			.checked_add(1)504			.ok_or("item id overflow")?505			!= token_id506		{507			return Err("item id should be next".into());508		}509510		let mut properties = CollectionPropertiesVec::default();511		properties512			.try_push(Property {513				key,514				value: token_uri515					.into_bytes()516					.try_into()517					.map_err(|_| "token uri is too long")?,518			})519			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;520521		<Pallet<T>>::create_item(522			self,523			&caller,524			CreateItemData::<T> {525				properties,526				owner: to,527			},528			&budget,529		)530		.map_err(dispatch_to_evm::<T>)?;531		Ok(true)532	}533534	/// @dev Not implemented535	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {536		Err("not implementable".into())537	}538}539540fn get_token_property<T: Config>(541	collection: &CollectionHandle<T>,542	token_id: u32,543	key: &up_data_structs::PropertyKey,544) -> Result<string> {545	collection.consume_store_reads(1)?;546	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))547		.map_err(|_| Error::Revert("Token properties not found".into()))?;548	if let Some(property) = properties.get(key) {549		return Ok(string::from_utf8_lossy(property).into());550	}551552	Err("Property tokenURI not found".into())553}554555fn get_token_permission<T: Config>(556	collection_id: CollectionId,557	key: &PropertyKey,558) -> Result<PropertyPermission> {559	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)560		.map_err(|_| Error::Revert("No permissions for collection".into()))?;561	let a = token_property_permissions562		.get(key)563		.map(Clone::clone)564		.ok_or_else(|| {565			let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();566			Error::Revert(alloc::format!("No permission for key {}", key))567		})?;568	Ok(a)569}570571/// @title Unique extensions for ERC721.572#[solidity_interface(name = ERC721UniqueExtensions)]573impl<T: Config> NonfungibleHandle<T> {574	/// @notice Transfer ownership of an NFT575	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`576	///  is the zero address. Throws if `tokenId` is not a valid NFT.577	/// @param to The new owner578	/// @param tokenId The NFT to transfer579	#[weight(<SelfWeightOf<T>>::transfer())]580	fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {581		let caller = T::CrossAccountId::from_eth(caller);582		let to = T::CrossAccountId::from_eth(to);583		let token = token_id.try_into()?;584		let budget = self585			.recorder586			.weight_calls_budget(<StructureWeight<T>>::find_parent());587588		<Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;589		Ok(())590	}591592	/// @notice Burns a specific ERC721 token.593	/// @dev Throws unless `msg.sender` is the current owner or an authorized594	///  operator for this NFT. Throws if `from` is not the current owner. Throws595	///  if `to` is the zero address. Throws if `tokenId` is not a valid NFT.596	/// @param from The current owner of the NFT597	/// @param tokenId The NFT to transfer598	#[weight(<SelfWeightOf<T>>::burn_from())]599	fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {600		let caller = T::CrossAccountId::from_eth(caller);601		let from = T::CrossAccountId::from_eth(from);602		let token = token_id.try_into()?;603		let budget = self604			.recorder605			.weight_calls_budget(<StructureWeight<T>>::find_parent());606607		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)608			.map_err(dispatch_to_evm::<T>)?;609		Ok(())610	}611612	/// @notice Returns next free NFT ID.613	fn next_token_id(&self) -> Result<uint256> {614		self.consume_store_reads(1)?;615		Ok(<TokensMinted<T>>::get(self.id)616			.checked_add(1)617			.ok_or("item id overflow")?618			.into())619	}620621	/// @notice Function to mint multiple tokens.622	/// @dev `tokenIds` should be an array of consecutive numbers and first number623	///  should be obtained with `nextTokenId` method624	/// @param to The new owner625	/// @param tokenIds IDs of the minted NFTs626	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]627	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {628		let caller = T::CrossAccountId::from_eth(caller);629		let to = T::CrossAccountId::from_eth(to);630		let mut expected_index = <TokensMinted<T>>::get(self.id)631			.checked_add(1)632			.ok_or("item id overflow")?;633		let budget = self634			.recorder635			.weight_calls_budget(<StructureWeight<T>>::find_parent());636637		let total_tokens = token_ids.len();638		for id in token_ids.into_iter() {639			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;640			if id != expected_index {641				return Err("item id should be next".into());642			}643			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;644		}645		let data = (0..total_tokens)646			.map(|_| CreateItemData::<T> {647				properties: BoundedVec::default(),648				owner: to.clone(),649			})650			.collect();651652		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)653			.map_err(dispatch_to_evm::<T>)?;654		Ok(true)655	}656657	/// @notice Function to mint multiple tokens with the given tokenUris.658	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive659	///  numbers and first number should be obtained with `nextTokenId` method660	/// @param to The new owner661	/// @param tokens array of pairs of token ID and token URI for minted tokens662	#[solidity(rename_selector = "mintBulkWithTokenURI")]663	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]664	fn mint_bulk_with_token_uri(665		&mut self,666		caller: caller,667		to: address,668		tokens: Vec<(uint256, string)>,669	) -> Result<bool> {670		let key = key::url();671		let caller = T::CrossAccountId::from_eth(caller);672		let to = T::CrossAccountId::from_eth(to);673		let mut expected_index = <TokensMinted<T>>::get(self.id)674			.checked_add(1)675			.ok_or("item id overflow")?;676		let budget = self677			.recorder678			.weight_calls_budget(<StructureWeight<T>>::find_parent());679680		let mut data = Vec::with_capacity(tokens.len());681		for (id, token_uri) in tokens {682			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;683			if id != expected_index {684				return Err("item id should be next".into());685			}686			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;687688			let mut properties = CollectionPropertiesVec::default();689			properties690				.try_push(Property {691					key: key.clone(),692					value: token_uri693						.into_bytes()694						.try_into()695						.map_err(|_| "token uri is too long")?,696				})697				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;698699			data.push(CreateItemData::<T> {700				properties,701				owner: to.clone(),702			});703		}704705		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)706			.map_err(dispatch_to_evm::<T>)?;707		Ok(true)708	}709}710711#[solidity_interface(712	name = UniqueNFT,713	is(714		ERC721,715		ERC721Enumerable,716		ERC721UniqueExtensions,717		ERC721Mintable,718		ERC721Burnable,719		ERC721Metadata(if(this.flags.erc721metadata)),720		Collection(via(common_mut returns CollectionHandle<T>)),721		TokenProperties,722	)723)]724impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}725726// Not a tests, but code generators727generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);728generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);729730impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>731where732	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,733{734	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");735736	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {737		call::<T, UniqueNFTCall<T>, _, _>(handle, self)738	}739}
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -764,22 +764,6 @@
 	}
 }
 
-impl<T: Config> RefungibleHandle<T> {
-	pub fn supports_metadata(&self) -> bool {
-		let has_metadata_support_enabled = if let Some(erc721_metadata) =
-			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::erc721_metadata())
-		{
-			*erc721_metadata.into_inner() == *value::ERC721_METADATA_SUPPORTED
-		} else {
-			false
-		};
-
-		let has_url_property_permissions = get_token_permission::<T>(self.id, &key::url()).is_ok();
-
-		has_metadata_support_enabled && has_url_property_permissions
-	}
-}
-
 #[solidity_interface(
 	name = UniqueRefungible,
 	is(
@@ -788,9 +772,9 @@
 		ERC721UniqueExtensions,
 		ERC721Mintable,
 		ERC721Burnable,
+		ERC721Metadata(if(this.flags.erc721metadata)),
 		Collection(via(common_mut returns CollectionHandle<T>)),
 		TokenProperties,
-		ERC721Metadata(if(this.supports_metadata())),
 	)
 )]
 impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -89,6 +89,26 @@
 	Ok((caller, name, description, token_prefix, base_uri_value))
 }
 
+fn default_url_pkp() -> up_data_structs::PropertyKeyPermission {
+	up_data_structs::PropertyKeyPermission {
+		key: key::url(),
+		permission: up_data_structs::PropertyPermission {
+			mutable: true,
+			collection_admin: true,
+			token_owner: false,
+		},
+	}
+}
+fn default_suffix_pkp() -> up_data_structs::PropertyKeyPermission {
+	up_data_structs::PropertyKeyPermission {
+		key: key::suffix(),
+		permission: up_data_structs::PropertyPermission {
+			mutable: true,
+			collection_admin: true,
+			token_owner: false,
+		},
+	}
+}
 fn make_data<T: Config>(
 	name: CollectionName,
 	mode: CollectionMode,
@@ -98,26 +118,9 @@
 	add_properties: bool,
 ) -> Result<CreateCollectionData<T::AccountId>> {
 	let token_property_permissions = if add_properties {
-		vec![
-			up_data_structs::PropertyKeyPermission {
-				key: key::url(),
-				permission: up_data_structs::PropertyPermission {
-					mutable: true,
-					collection_admin: true,
-					token_owner: false,
-				},
-			},
-			up_data_structs::PropertyKeyPermission {
-				key: key::suffix(),
-				permission: up_data_structs::PropertyPermission {
-					mutable: true,
-					collection_admin: true,
-					token_owner: false,
-				},
-			},
-		]
-		.try_into()
-		.map_err(|e| Error::Revert(format!("{:?}", e)))?
+		vec![default_url_pkp(), default_suffix_pkp()]
+			.try_into()
+			.map_err(|e| Error::Revert(format!("{:?}", e)))?
 	} else {
 		up_data_structs::CollectionPropertiesPermissionsVec::default()
 	};
@@ -130,10 +133,6 @@
 			up_data_structs::Property {
 				key: key::schema_version(),
 				value: property_value::schema_version(),
-			},
-			up_data_structs::Property {
-				key: key::erc721_metadata(),
-				value: property_value::erc721_metadata_supported(),
 			},
 		];
 		if !base_uri_value.is_empty() {
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -365,11 +365,14 @@
 	/// Tokens in foreign collections can be transferred, but not burnt
 	#[bondrewd(bits = "0..1")]
 	pub foreign: bool,
+	/// Supports ERC721Metadata
+	#[bondrewd(bits = "1..2")]
+	pub erc721metadata: bool,
 	/// External collections can't be managed using `unique` api
 	#[bondrewd(bits = "7..8")]
 	pub external: bool,
 
-	#[bondrewd(reserve, bits = "1..7")]
+	#[bondrewd(reserve, bits = "2..7")]
 	pub reserved: u8,
 }
 bondrewd_codec!(CollectionFlags);
@@ -434,6 +437,15 @@
 	pub meta_update_permission: MetaUpdatePermission,
 }
 
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct RpcCollectionFlags {
+	/// Is collection is foreign.
+	pub foreign: bool,
+	/// Collection supports ERC721Metadata.
+	pub erc721metadata: bool,
+}
+
 /// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).
 #[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
@@ -471,8 +483,8 @@
 	/// Is collection read only.
 	pub read_only: bool,
 
-	/// Is collection is foreign.
-	pub foreign: bool,
+	/// Extra collection flags
+	pub flags: RpcCollectionFlags,
 }
 
 /// Data used for create collection.