git.delta.rocks / unique-network / refs/commits / 630fc898d4e4

difftreelog

fix use lowercase letters in EVM errors

Daniel Shiposha2023-10-02parent: #6b27551.patch.diff
in: master

3 files changed

modifiedpallets/balances-adapter/src/erc.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/erc.rs
+++ b/pallets/balances-adapter/src/erc.rs
@@ -25,7 +25,7 @@
 	}
 
 	fn approve(&mut self, _caller: Caller, _spender: Address, _amount: U256) -> Result<bool> {
-		Err("Approve not supported".into())
+		Err("approve not supported".into())
 	}
 
 	fn balance_of(&self, owner: Address) -> Result<U256> {
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -273,7 +273,7 @@
 			.map_err(|_| "key too long")?;
 
 		let props =
-			<TokenProperties<T>>::get((self.id, token_id)).ok_or("Token properties not found")?;
+			<TokenProperties<T>>::get((self.id, token_id)).ok_or("token properties not found")?;
 		let prop = props.get(&key).ok_or("key not found")?;
 
 		Ok(prop.to_vec().into())
@@ -367,7 +367,7 @@
 				.transpose()
 				.map_err(|e| {
 					Error::Revert(alloc::format!(
-						"Can not convert value \"baseURI\" to string with error \"{e}\""
+						"can not convert value \"baseURI\" to string with error \"{e}\""
 					))
 				})?;
 
@@ -658,7 +658,7 @@
 		let key = key::url();
 		let permission = get_token_permission::<T>(self.id, &key)?;
 		if !permission.collection_admin {
-			return Err("Operation is not allowed".into());
+			return Err("operation is not allowed".into());
 		}
 
 		let caller = T::CrossAccountId::from_eth(caller);
@@ -685,7 +685,7 @@
 					.try_into()
 					.map_err(|_| "token uri is too long")?,
 			})
-			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
+			.map_err(|e| Error::Revert(alloc::format!("can't add property: {e:?}")))?;
 
 		<Pallet<T>>::create_item(
 			self,
@@ -708,12 +708,12 @@
 ) -> 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()))?;
+		.map_err(|_| Error::Revert("token properties not found".into()))?;
 	if let Some(property) = properties.get(key) {
 		return Ok(String::from_utf8_lossy(property).into());
 	}
 
-	Err("Property tokenURI not found".into())
+	Err("property tokenURI not found".into())
 }
 
 fn get_token_permission<T: Config>(
@@ -721,13 +721,13 @@
 	key: &PropertyKey,
 ) -> Result<PropertyPermission> {
 	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)
-		.map_err(|_| Error::Revert("No permissions for collection".into()))?;
+		.map_err(|_| Error::Revert("no permissions for collection".into()))?;
 	let a = token_property_permissions
 		.get(key)
 		.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}"))
+			Error::Revert(alloc::format!("no permission for key {key}"))
 		})?;
 	Ok(a)
 }
@@ -1058,7 +1058,7 @@
 						.try_into()
 						.map_err(|_| "token uri is too long")?,
 				})
-				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
+				.map_err(|e| Error::Revert(alloc::format!("can't add property: {e:?}")))?;
 
 			data.push(CreateItemData::<T> {
 				properties,
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
before · pallets/refungible/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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26	char::{REPLACEMENT_CHARACTER, decode_utf16},27	convert::TryInto,28};29use evm_coder::{abi::AbiType, AbiCoder, ToLog, generate_stubgen, solidity_interface, types::*};30use frame_support::{BoundedBTreeMap, BoundedVec};31use pallet_common::{32	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,33	Error as CommonError,34	erc::{CommonEvmHandler, CollectionCall, static_property::key},35	eth::{self, TokenUri},36};37use pallet_evm::{account::CrossAccountId, PrecompileHandle};38use pallet_evm_coder_substrate::{39	call, dispatch_to_evm,40	execution::{PreDispatch, Result, Error},41	frontier_contract,42};43use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};44use sp_core::{H160, U256, Get};45use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};46use up_data_structs::{47	CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,48	PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,49};5051use crate::{52	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, TokenProperties,53	TokensMinted, TotalSupply, SelfWeightOf, weights::WeightInfo,54};5556frontier_contract! {57	macro_rules! RefungibleHandle_result {...}58	impl<T: Config> Contract for RefungibleHandle<T> {...}59}6061pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);6263/// Rft events.64#[derive(ToLog)]65pub enum ERC721TokenEvent {66	/// The token has been changed.67	TokenChanged {68		/// Token ID.69		#[indexed]70		token_id: U256,71	},72}7374/// Token minting parameters75#[derive(AbiCoder, Default, Debug)]76pub struct OwnerPieces {77	/// Minted token owner78	pub owner: eth::CrossAddress,79	/// Number of token pieces80	pub pieces: u128,81}8283/// Token minting parameters84#[derive(AbiCoder, Default, Debug)]85pub struct MintTokenData {86	/// Minted token owner and number of pieces87	pub owners: Vec<OwnerPieces>,88	/// Minted token properties89	pub properties: Vec<eth::Property>,90}9192/// @title A contract that allows to set and delete token properties and change token property permissions.93#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]94impl<T: Config> RefungibleHandle<T> {95	/// @notice Set permissions for token property.96	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.97	/// @param key Property key.98	/// @param isMutable Permission to mutate property.99	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.100	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.101	#[solidity(hide)]102	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]103	fn set_token_property_permission(104		&mut self,105		caller: Caller,106		key: String,107		is_mutable: bool,108		collection_admin: bool,109		token_owner: bool,110	) -> Result<()> {111		let caller = T::CrossAccountId::from_eth(caller);112		<Pallet<T>>::set_token_property_permissions(113			self,114			&caller,115			vec![PropertyKeyPermission {116				key: <Vec<u8>>::from(key)117					.try_into()118					.map_err(|_| "too long key")?,119				permission: PropertyPermission {120					mutable: is_mutable,121					collection_admin,122					token_owner,123				},124			}],125		)126		.map_err(dispatch_to_evm::<T>)127	}128129	/// @notice Set permissions for token property.130	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.131	/// @param permissions Permissions for keys.132	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]133	fn set_token_property_permissions(134		&mut self,135		caller: Caller,136		permissions: Vec<eth::TokenPropertyPermission>,137	) -> Result<()> {138		let caller = T::CrossAccountId::from_eth(caller);139		let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;140141		<Pallet<T>>::set_token_property_permissions(self, &caller, perms)142			.map_err(dispatch_to_evm::<T>)143	}144145	/// @notice Get permissions for token properties.146	fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {147		let perms = <Pallet<T>>::token_property_permission(self.id);148		Ok(perms149			.into_iter()150			.map(eth::TokenPropertyPermission::from)151			.collect())152	}153154	/// @notice Set token property value.155	/// @dev Throws error if `msg.sender` has no permission to edit the property.156	/// @param tokenId ID of the token.157	/// @param key Property key.158	/// @param value Property value.159	#[solidity(hide)]160	#[weight(<SelfWeightOf<T>>::set_token_properties(1))]161	fn set_property(162		&mut self,163		caller: Caller,164		token_id: U256,165		key: String,166		value: Bytes,167	) -> Result<()> {168		let caller = T::CrossAccountId::from_eth(caller);169		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;170		let key = <Vec<u8>>::from(key)171			.try_into()172			.map_err(|_| "key too long")?;173		let value = value.0.try_into().map_err(|_| "value too long")?;174175		let nesting_budget = self176			.recorder177			.weight_calls_budget(<StructureWeight<T>>::find_parent());178179		<Pallet<T>>::set_token_property(180			self,181			&caller,182			TokenId(token_id),183			Property { key, value },184			&nesting_budget,185		)186		.map_err(dispatch_to_evm::<T>)187	}188189	/// @notice Set token properties value.190	/// @dev Throws error if `msg.sender` has no permission to edit the property.191	/// @param tokenId ID of the token.192	/// @param properties settable properties193	#[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]194	fn set_properties(195		&mut self,196		caller: Caller,197		token_id: U256,198		properties: Vec<eth::Property>,199	) -> Result<()> {200		let caller = T::CrossAccountId::from_eth(caller);201		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;202203		let nesting_budget = self204			.recorder205			.weight_calls_budget(<StructureWeight<T>>::find_parent());206207		let properties = properties208			.into_iter()209			.map(eth::Property::try_into)210			.collect::<Result<Vec<_>>>()?;211212		<Pallet<T>>::set_token_properties(213			self,214			&caller,215			TokenId(token_id),216			properties.into_iter(),217			&nesting_budget,218		)219		.map_err(dispatch_to_evm::<T>)220	}221222	/// @notice Delete token property value.223	/// @dev Throws error if `msg.sender` has no permission to edit the property.224	/// @param tokenId ID of the token.225	/// @param key Property key.226	#[solidity(hide)]227	#[weight(<SelfWeightOf<T>>::delete_token_properties(1))]228	fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {229		let caller = T::CrossAccountId::from_eth(caller);230		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;231		let key = <Vec<u8>>::from(key)232			.try_into()233			.map_err(|_| "key too long")?;234235		let nesting_budget = self236			.recorder237			.weight_calls_budget(<StructureWeight<T>>::find_parent());238239		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)240			.map_err(dispatch_to_evm::<T>)241	}242243	/// @notice Delete token properties value.244	/// @dev Throws error if `msg.sender` has no permission to edit the property.245	/// @param tokenId ID of the token.246	/// @param keys Properties key.247	#[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]248	fn delete_properties(249		&mut self,250		token_id: U256,251		caller: Caller,252		keys: Vec<String>,253	) -> Result<()> {254		let caller = T::CrossAccountId::from_eth(caller);255		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;256		let keys = keys257			.into_iter()258			.map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))259			.collect::<Result<Vec<_>>>()?;260261		let nesting_budget = self262			.recorder263			.weight_calls_budget(<StructureWeight<T>>::find_parent());264265		<Pallet<T>>::delete_token_properties(266			self,267			&caller,268			TokenId(token_id),269			keys.into_iter(),270			&nesting_budget,271		)272		.map_err(dispatch_to_evm::<T>)273	}274275	/// @notice Get token property value.276	/// @dev Throws error if key not found277	/// @param tokenId ID of the token.278	/// @param key Property key.279	/// @return Property value bytes280	fn property(&self, token_id: U256, key: String) -> Result<Bytes> {281		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;282		let key = <Vec<u8>>::from(key)283			.try_into()284			.map_err(|_| "key too long")?;285286		let props =287			<TokenProperties<T>>::get((self.id, token_id)).ok_or("Token properties not found")?;288		let prop = props.get(&key).ok_or("key not found")?;289290		Ok(prop.to_vec().into())291	}292}293294#[derive(ToLog)]295pub enum ERC721Events {296	/// @dev This event emits when NFTs are created (`from` == 0) and destroyed297	///  (`to` == 0). Exception: during contract creation, any number of RFTs298	///  may be created and assigned without emitting Transfer.299	Transfer {300		#[indexed]301		from: Address,302		#[indexed]303		to: Address,304		#[indexed]305		token_id: U256,306	},307	/// @dev Not supported308	Approval {309		#[indexed]310		owner: Address,311		#[indexed]312		approved: Address,313		#[indexed]314		token_id: U256,315	},316	/// @dev Not supported317	#[allow(dead_code)]318	ApprovalForAll {319		#[indexed]320		owner: Address,321		#[indexed]322		operator: Address,323		approved: bool,324	},325}326327/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension328/// @dev See https://eips.ethereum.org/EIPS/eip-721329#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]330impl<T: Config> RefungibleHandle<T>331where332	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,333{334	/// @notice A descriptive name for a collection of NFTs in this contract335	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`336	#[solidity(hide, rename_selector = "name")]337	fn name_proxy(&self) -> Result<String> {338		self.name()339	}340341	/// @notice An abbreviated name for NFTs in this contract342	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`343	#[solidity(hide, rename_selector = "symbol")]344	fn symbol_proxy(&self) -> Result<String> {345		self.symbol()346	}347348	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.349	///350	/// @dev If the token has a `url` property and it is not empty, it is returned.351	///  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`.352	///  If the collection property `baseURI` is empty or absent, return "" (empty string)353	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix354	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).355	///356	/// @return token's const_metadata357	#[solidity(rename_selector = "tokenURI")]358	fn token_uri(&self, token_id: U256) -> Result<String> {359		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;360361		match get_token_property(self, token_id_u32, &key::url()).as_deref() {362			Err(_) | Ok("") => (),363			Ok(url) => {364				return Ok(url.into());365			}366		};367368		let base_uri =369			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())370				.map(BoundedVec::into_inner)371				.map(String::from_utf8)372				.transpose()373				.map_err(|e| {374					Error::Revert(alloc::format!(375						"Can not convert value \"baseURI\" to string with error \"{e}\""376					))377				})?;378379		let base_uri = match base_uri.as_deref() {380			None | Some("") => {381				return Ok("".into());382			}383			Some(base_uri) => base_uri.into(),384		};385386		Ok(387			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {388				Err(_) | Ok("") => base_uri,389				Ok(suffix) => base_uri + suffix,390			},391		)392	}393}394395/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension396/// @dev See https://eips.ethereum.org/EIPS/eip-721397#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]398impl<T: Config> RefungibleHandle<T> {399	/// @notice Enumerate valid RFTs400	/// @param index A counter less than `totalSupply()`401	/// @return The token identifier for the `index`th NFT,402	///  (sort order not specified)403	fn token_by_index(&self, index: U256) -> U256 {404		index405	}406407	/// Not implemented408	fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {409		// TODO: Not implemetable410		Err("not implemented".into())411	}412413	/// @notice Count RFTs tracked by this contract414	/// @return A count of valid RFTs tracked by this contract, where each one of415	///  them has an assigned and queryable owner not equal to the zero address416	fn total_supply(&self) -> Result<U256> {417		self.consume_store_reads(1)?;418		Ok(<Pallet<T>>::total_supply(self).into())419	}420}421422/// @title ERC-721 Non-Fungible Token Standard423/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md424#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]425impl<T: Config> RefungibleHandle<T> {426	/// @notice Count all RFTs assigned to an owner427	/// @dev RFTs assigned to the zero address are considered invalid, and this428	///  function throws for queries about the zero address.429	/// @param owner An address for whom to query the balance430	/// @return The number of RFTs owned by `owner`, possibly zero431	fn balance_of(&self, owner: Address) -> Result<U256> {432		self.consume_store_reads(1)?;433		let owner = T::CrossAccountId::from_eth(owner);434		let balance = <AccountBalance<T>>::get((self.id, owner));435		Ok(balance.into())436	}437438	/// @notice Find the owner of an RFT439	/// @dev RFTs assigned to zero address are considered invalid, and queries440	///  about them do throw.441	///  Returns special 0xffffffffffffffffffffffffffffffffffffffff address for442	///  the tokens that are partially owned.443	/// @param tokenId The identifier for an RFT444	/// @return The address of the owner of the RFT445	fn owner_of(&self, token_id: U256) -> Result<Address> {446		self.consume_store_reads(2)?;447		let token = token_id.try_into()?;448		let owner = <Pallet<T>>::token_owner(self.id, token);449		owner450			.map(|address| *address.as_eth())451			.or_else(|err| match err {452				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),453				TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),454			})455	}456457	/// @dev Not implemented458	#[solidity(rename_selector = "safeTransferFrom")]459	fn safe_transfer_from_with_data(460		&mut self,461		_from: Address,462		_to: Address,463		_token_id: U256,464		_data: Bytes,465	) -> Result<()> {466		// TODO: Not implemetable467		Err("not implemented".into())468	}469470	/// @dev Not implemented471	#[solidity(rename_selector = "safeTransferFrom")]472	fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {473		// TODO: Not implemetable474		Err("not implemented".into())475	}476477	/// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE478	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE479	///  THEY MAY BE PERMANENTLY LOST480	/// @dev Throws unless `msg.sender` is the current owner or an authorized481	///  operator for this RFT. Throws if `from` is not the current owner. Throws482	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.483	///  Throws if RFT pieces have multiple owners.484	/// @param from The current owner of the NFT485	/// @param to The new owner486	/// @param tokenId The NFT to transfer487	#[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]488	fn transfer_from(489		&mut self,490		caller: Caller,491		from: Address,492		to: Address,493		token_id: U256,494	) -> Result<()> {495		let caller = T::CrossAccountId::from_eth(caller);496		let from = T::CrossAccountId::from_eth(from);497		let to = T::CrossAccountId::from_eth(to);498		let token = token_id.try_into()?;499		let budget = self500			.recorder501			.weight_calls_budget(<StructureWeight<T>>::find_parent());502503		let balance = balance(self, token, &from)?;504		ensure_single_owner(self, token, balance)?;505506		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)507			.map_err(dispatch_to_evm::<T>)?;508509		Ok(())510	}511512	/// @dev Not implemented513	fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {514		Err("not implemented".into())515	}516517	/// @notice Sets or unsets the approval of a given operator.518	///  The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.519	/// @param operator Operator520	/// @param approved Should operator status be granted or revoked?521	#[weight(<SelfWeightOf<T>>::set_allowance_for_all())]522	fn set_approval_for_all(523		&mut self,524		caller: Caller,525		operator: Address,526		approved: bool,527	) -> Result<()> {528		let caller = T::CrossAccountId::from_eth(caller);529		let operator = T::CrossAccountId::from_eth(operator);530531		<Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)532			.map_err(dispatch_to_evm::<T>)?;533		Ok(())534	}535536	/// @dev Not implemented537	fn get_approved(&self, _token_id: U256) -> Result<Address> {538		// TODO: Not implemetable539		Err("not implemented".into())540	}541542	/// @notice Tells whether the given `owner` approves the `operator`.543	#[weight(<SelfWeightOf<T>>::allowance_for_all())]544	fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {545		let owner = T::CrossAccountId::from_eth(owner);546		let operator = T::CrossAccountId::from_eth(operator);547548		Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))549	}550}551552/// Returns amount of pieces of `token` that `owner` have553pub fn balance<T: Config>(554	collection: &RefungibleHandle<T>,555	token: TokenId,556	owner: &T::CrossAccountId,557) -> Result<u128> {558	collection.consume_store_reads(1)?;559	let balance = <Balance<T>>::get((collection.id, token, &owner));560	Ok(balance)561}562563/// Throws if `owner_balance` is lower than total amount of `token` pieces564pub fn ensure_single_owner<T: Config>(565	collection: &RefungibleHandle<T>,566	token: TokenId,567	owner_balance: u128,568) -> Result<()> {569	collection.consume_store_reads(1)?;570	let total_supply = <TotalSupply<T>>::get((collection.id, token));571572	if owner_balance == 0 {573		return Err(dispatch_to_evm::<T>(574			<CommonError<T>>::MustBeTokenOwner.into(),575		));576	}577578	if total_supply != owner_balance {579		return Err("token has multiple owners".into());580	}581	Ok(())582}583584/// @title ERC721 Token that can be irreversibly burned (destroyed).585#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]586impl<T: Config> RefungibleHandle<T> {587	/// @notice Burns a specific ERC721 token.588	/// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized589	///  operator of the current owner.590	/// @param tokenId The RFT to approve591	#[weight(<SelfWeightOf<T>>::burn_item_fully())]592	fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {593		let caller = T::CrossAccountId::from_eth(caller);594		let token = token_id.try_into()?;595596		let balance = balance(self, token, &caller)?;597		ensure_single_owner(self, token, balance)?;598599		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;600		Ok(())601	}602}603604/// @title ERC721 minting logic.605#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]606impl<T: Config> RefungibleHandle<T> {607	/// @notice Function to mint a token.608	/// @param to The new owner609	/// @return uint256 The id of the newly minted token610	#[weight(<SelfWeightOf<T>>::create_item())]611	fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {612		let token_id: U256 = <TokensMinted<T>>::get(self.id)613			.checked_add(1)614			.ok_or("item id overflow")?615			.into();616		self.mint_check_id(caller, to, token_id)?;617		Ok(token_id)618	}619620	/// @notice Function to mint a token.621	/// @dev `tokenId` should be obtained with `nextTokenId` method,622	///  unlike standard, you can't specify it manually623	/// @param to The new owner624	/// @param tokenId ID of the minted RFT625	#[solidity(hide, rename_selector = "mint")]626	#[weight(<SelfWeightOf<T>>::create_item())]627	fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {628		let caller = T::CrossAccountId::from_eth(caller);629		let to = T::CrossAccountId::from_eth(to);630		let token_id: u32 = token_id.try_into()?;631		let budget = self632			.recorder633			.weight_calls_budget(<StructureWeight<T>>::find_parent());634635		if <TokensMinted<T>>::get(self.id)636			.checked_add(1)637			.ok_or("item id overflow")?638			!= token_id639		{640			return Err("item id should be next".into());641		}642643		let users = [(to, 1)]644			.into_iter()645			.collect::<BTreeMap<_, _>>()646			.try_into()647			.unwrap();648		<Pallet<T>>::create_item(649			self,650			&caller,651			CreateItemData::<T> {652				users,653				properties: CollectionPropertiesVec::default(),654			},655			&budget,656		)657		.map_err(dispatch_to_evm::<T>)?;658659		Ok(true)660	}661662	/// @notice Function to mint token with the given tokenUri.663	/// @param to The new owner664	/// @param tokenUri Token URI that would be stored in the NFT properties665	/// @return uint256 The id of the newly minted token666	#[solidity(rename_selector = "mintWithTokenURI")]667	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]668	fn mint_with_token_uri(669		&mut self,670		caller: Caller,671		to: Address,672		token_uri: String,673	) -> Result<U256> {674		let token_id: U256 = <TokensMinted<T>>::get(self.id)675			.checked_add(1)676			.ok_or("item id overflow")?677			.into();678		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;679		Ok(token_id)680	}681682	/// @notice Function to mint token with the given tokenUri.683	/// @dev `tokenId` should be obtained with `nextTokenId` method,684	///  unlike standard, you can't specify it manually685	/// @param to The new owner686	/// @param tokenId ID of the minted RFT687	/// @param tokenUri Token URI that would be stored in the RFT properties688	#[solidity(hide, rename_selector = "mintWithTokenURI")]689	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]690	fn mint_with_token_uri_check_id(691		&mut self,692		caller: Caller,693		to: Address,694		token_id: U256,695		token_uri: String,696	) -> Result<bool> {697		let key = key::url();698		let permission = get_token_permission::<T>(self.id, &key)?;699		if !permission.collection_admin {700			return Err("Operation is not allowed".into());701		}702703		let caller = T::CrossAccountId::from_eth(caller);704		let to = T::CrossAccountId::from_eth(to);705		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;706		let budget = self707			.recorder708			.weight_calls_budget(<StructureWeight<T>>::find_parent());709710		if <TokensMinted<T>>::get(self.id)711			.checked_add(1)712			.ok_or("item id overflow")?713			!= token_id714		{715			return Err("item id should be next".into());716		}717718		let mut properties = CollectionPropertiesVec::default();719		properties720			.try_push(Property {721				key,722				value: token_uri723					.into_bytes()724					.try_into()725					.map_err(|_| "token uri is too long")?,726			})727			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;728729		let users = [(to, 1)]730			.into_iter()731			.collect::<BTreeMap<_, _>>()732			.try_into()733			.unwrap();734		<Pallet<T>>::create_item(735			self,736			&caller,737			CreateItemData::<T> { users, properties },738			&budget,739		)740		.map_err(dispatch_to_evm::<T>)?;741		Ok(true)742	}743}744745fn get_token_property<T: Config>(746	collection: &CollectionHandle<T>,747	token_id: u32,748	key: &up_data_structs::PropertyKey,749) -> Result<String> {750	collection.consume_store_reads(1)?;751	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))752		.map_err(|_| Error::Revert("Token properties not found".into()))?;753	if let Some(property) = properties.get(key) {754		return Ok(String::from_utf8_lossy(property).into());755	}756757	Err("Property tokenURI not found".into())758}759760fn get_token_permission<T: Config>(761	collection_id: CollectionId,762	key: &PropertyKey,763) -> Result<PropertyPermission> {764	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)765		.map_err(|_| Error::Revert("No permissions for collection".into()))?;766	let a = token_property_permissions767		.get(key)768		.map(Clone::clone)769		.ok_or_else(|| {770			let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();771			Error::Revert(alloc::format!("No permission for key {key}"))772		})?;773	Ok(a)774}775776/// @title Unique extensions for ERC721.777#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]778impl<T: Config> RefungibleHandle<T>779where780	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,781{782	/// @notice A descriptive name for a collection of NFTs in this contract783	fn name(&self) -> Result<String> {784		Ok(decode_utf16(self.name.iter().copied())785			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))786			.collect::<String>())787	}788789	/// @notice An abbreviated name for NFTs in this contract790	fn symbol(&self) -> Result<String> {791		Ok(String::from_utf8_lossy(&self.token_prefix).into())792	}793794	/// @notice A description for the collection.795	fn description(&self) -> Result<String> {796		Ok(decode_utf16(self.description.iter().copied())797			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))798			.collect::<String>())799	}800801	/// Returns the owner (in cross format) of the token.802	///803	/// @param tokenId Id for the token.804	#[solidity(hide)]805	fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {806		Self::owner_of_cross(self, token_id)807	}808809	/// Returns the owner (in cross format) of the token.810	///811	/// @param tokenId Id for the token.812	fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {813		Self::token_owner(self, token_id.try_into()?)814			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))815			.or_else(|err| match err {816				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),817				TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(818					ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,819				)),820			})821	}822823	/// @notice Count all RFTs assigned to an owner824	/// @param owner An cross address for whom to query the balance825	/// @return The number of RFTs owned by `owner`, possibly zero826	fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {827		self.consume_store_reads(1)?;828		let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));829		Ok(balance.into())830	}831832	/// Returns the token properties.833	///834	/// @param tokenId Id for the token.835	/// @param keys Properties keys. Empty keys for all propertyes.836	/// @return Vector of properties key/value pairs.837	fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {838		let keys = keys839			.into_iter()840			.map(|key| {841				<Vec<u8>>::from(key)842					.try_into()843					.map_err(|_| Error::Revert("key too large".into()))844			})845			.collect::<Result<Vec<_>>>()?;846847		<Self as CommonCollectionOperations<T>>::token_properties(848			self,849			token_id.try_into()?,850			if keys.is_empty() { None } else { Some(keys) },851		)852		.into_iter()853		.map(eth::Property::try_from)854		.collect::<Result<Vec<_>>>()855	}856	/// @notice Transfer ownership of an RFT857	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`858	///  is the zero address. Throws if `tokenId` is not a valid RFT.859	///  Throws if RFT pieces have multiple owners.860	/// @param to The new owner861	/// @param tokenId The RFT to transfer862	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]863	fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {864		let caller = T::CrossAccountId::from_eth(caller);865		let to = T::CrossAccountId::from_eth(to);866		let token = token_id.try_into()?;867		let budget = self868			.recorder869			.weight_calls_budget(<StructureWeight<T>>::find_parent());870871		let balance = balance(self, token, &caller)?;872		ensure_single_owner(self, token, balance)?;873874		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)875			.map_err(dispatch_to_evm::<T>)?;876		Ok(())877	}878879	/// @notice Transfer ownership of an RFT880	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`881	///  is the zero address. Throws if `tokenId` is not a valid RFT.882	///  Throws if RFT pieces have multiple owners.883	/// @param to The new owner884	/// @param tokenId The RFT to transfer885	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]886	fn transfer_cross(887		&mut self,888		caller: Caller,889		to: eth::CrossAddress,890		token_id: U256,891	) -> Result<()> {892		let caller = T::CrossAccountId::from_eth(caller);893		let to = to.into_sub_cross_account::<T>()?;894		let token = token_id.try_into()?;895		let budget = self896			.recorder897			.weight_calls_budget(<StructureWeight<T>>::find_parent());898899		let balance = balance(self, token, &caller)?;900		ensure_single_owner(self, token, balance)?;901902		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)903			.map_err(dispatch_to_evm::<T>)?;904		Ok(())905	}906907	/// @notice Transfer ownership of an RFT908	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`909	///  is the zero address. Throws if `tokenId` is not a valid RFT.910	///  Throws if RFT pieces have multiple owners.911	/// @param to The new owner912	/// @param tokenId The RFT to transfer913	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]914	fn transfer_from_cross(915		&mut self,916		caller: Caller,917		from: eth::CrossAddress,918		to: eth::CrossAddress,919		token_id: U256,920	) -> Result<()> {921		let caller = T::CrossAccountId::from_eth(caller);922		let from = from.into_sub_cross_account::<T>()?;923		let to = to.into_sub_cross_account::<T>()?;924		let token_id = token_id.try_into()?;925		let budget = self926			.recorder927			.weight_calls_budget(<StructureWeight<T>>::find_parent());928929		let balance = balance(self, token_id, &from)?;930		ensure_single_owner(self, token_id, balance)?;931932		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)933			.map_err(dispatch_to_evm::<T>)?;934		Ok(())935	}936937	/// @notice Burns a specific ERC721 token.938	/// @dev Throws unless `msg.sender` is the current owner or an authorized939	///  operator for this RFT. Throws if `from` is not the current owner. Throws940	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.941	///  Throws if RFT pieces have multiple owners.942	/// @param from The current owner of the RFT943	/// @param tokenId The RFT to transfer944	#[solidity(hide)]945	#[weight(<SelfWeightOf<T>>::burn_from())]946	fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {947		let caller = T::CrossAccountId::from_eth(caller);948		let from = T::CrossAccountId::from_eth(from);949		let token = token_id.try_into()?;950		let budget = self951			.recorder952			.weight_calls_budget(<StructureWeight<T>>::find_parent());953954		let balance = balance(self, token, &from)?;955		ensure_single_owner(self, token, balance)?;956957		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)958			.map_err(dispatch_to_evm::<T>)?;959		Ok(())960	}961962	/// @notice Burns a specific ERC721 token.963	/// @dev Throws unless `msg.sender` is the current owner or an authorized964	///  operator for this RFT. Throws if `from` is not the current owner. Throws965	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.966	///  Throws if RFT pieces have multiple owners.967	/// @param from The current owner of the RFT968	/// @param tokenId The RFT to transfer969	#[weight(<SelfWeightOf<T>>::burn_from())]970	fn burn_from_cross(971		&mut self,972		caller: Caller,973		from: eth::CrossAddress,974		token_id: U256,975	) -> Result<()> {976		let caller = T::CrossAccountId::from_eth(caller);977		let from = from.into_sub_cross_account::<T>()?;978		let token = token_id.try_into()?;979		let budget = self980			.recorder981			.weight_calls_budget(<StructureWeight<T>>::find_parent());982983		let balance = balance(self, token, &from)?;984		ensure_single_owner(self, token, balance)?;985986		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)987			.map_err(dispatch_to_evm::<T>)?;988		Ok(())989	}990991	/// @notice Returns next free RFT ID.992	fn next_token_id(&self) -> Result<U256> {993		self.consume_store_reads(1)?;994		Ok(<Pallet<T>>::next_token_id(self)995			.map_err(dispatch_to_evm::<T>)?996			.into())997	}998999	/// @notice Function to mint multiple tokens.1000	/// @dev `tokenIds` should be an array of consecutive numbers and first number1001	///  should be obtained with `nextTokenId` method1002	/// @param to The new owner1003	/// @param tokenIds IDs of the minted RFTs1004	#[solidity(hide)]1005	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]1006	fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {1007		let caller = T::CrossAccountId::from_eth(caller);1008		let to = T::CrossAccountId::from_eth(to);1009		let mut expected_index = <TokensMinted<T>>::get(self.id)1010			.checked_add(1)1011			.ok_or("item id overflow")?;1012		let budget = self1013			.recorder1014			.weight_calls_budget(<StructureWeight<T>>::find_parent());10151016		let total_tokens = token_ids.len();1017		for id in token_ids.into_iter() {1018			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1019			if id != expected_index {1020				return Err("item id should be next".into());1021			}1022			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1023		}1024		let users = [(to, 1)]1025			.into_iter()1026			.collect::<BTreeMap<_, _>>()1027			.try_into()1028			.unwrap();1029		let create_item_data = CreateItemData::<T> {1030			users,1031			properties: CollectionPropertiesVec::default(),1032		};1033		let data = (0..total_tokens)1034			.map(|_| create_item_data.clone())1035			.collect();10361037		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1038			.map_err(dispatch_to_evm::<T>)?;1039		Ok(true)1040	}10411042	/// @notice Function to mint a token.1043	/// @param tokenProperties Properties of minted token1044	#[weight(if token_properties.len() == 1 {1045		<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(token_properties.iter().next().unwrap().owners.len() as u32)1046	} else {1047		<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(token_properties.len() as u32)1048	} + <SelfWeightOf<T>>::set_token_properties(token_properties.len() as u32))]1049	fn mint_bulk_cross(1050		&mut self,1051		caller: Caller,1052		token_properties: Vec<MintTokenData>,1053	) -> Result<bool> {1054		let caller = T::CrossAccountId::from_eth(caller);1055		let budget = self1056			.recorder1057			.weight_calls_budget(<StructureWeight<T>>::find_parent());1058		let has_multiple_tokens = token_properties.len() > 1;10591060		let mut create_rft_data = Vec::with_capacity(token_properties.len());1061		for MintTokenData { owners, properties } in token_properties {1062			let has_multiple_owners = owners.len() > 1;1063			if has_multiple_tokens & has_multiple_owners {1064				return Err(1065					"creation of multiple tokens supported only if they have single owner each"1066						.into(),1067				);1068			}1069			let users: BoundedBTreeMap<_, _, _> = owners1070				.into_iter()1071				.map(|data| Ok((data.owner.into_sub_cross_account::<T>()?, data.pieces)))1072				.collect::<Result<BTreeMap<_, _>>>()?1073				.try_into()1074				.map_err(|_| "too many users")?;1075			create_rft_data.push(CreateItemData::<T> {1076				properties: properties1077					.into_iter()1078					.map(|property| property.try_into())1079					.collect::<Result<Vec<_>>>()?1080					.try_into()1081					.map_err(|_| "too many properties")?,1082				users,1083			});1084		}10851086		<Pallet<T>>::create_multiple_items(self, &caller, create_rft_data, &budget)1087			.map_err(dispatch_to_evm::<T>)?;1088		Ok(true)1089	}10901091	/// @notice Function to mint multiple tokens with the given tokenUris.1092	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1093	///  numbers and first number should be obtained with `nextTokenId` method1094	/// @param to The new owner1095	/// @param tokens array of pairs of token ID and token URI for minted tokens1096	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1097	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1098	fn mint_bulk_with_token_uri(1099		&mut self,1100		caller: Caller,1101		to: Address,1102		tokens: Vec<TokenUri>,1103	) -> Result<bool> {1104		let key = key::url();1105		let caller = T::CrossAccountId::from_eth(caller);1106		let to = T::CrossAccountId::from_eth(to);1107		let mut expected_index = <TokensMinted<T>>::get(self.id)1108			.checked_add(1)1109			.ok_or("item id overflow")?;1110		let budget = self1111			.recorder1112			.weight_calls_budget(<StructureWeight<T>>::find_parent());11131114		let mut data = Vec::with_capacity(tokens.len());1115		let users: BoundedBTreeMap<_, _, _> = [(to, 1)]1116			.into_iter()1117			.collect::<BTreeMap<_, _>>()1118			.try_into()1119			.unwrap();1120		for TokenUri { id, uri } in tokens {1121			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1122			if id != expected_index {1123				return Err("item id should be next".into());1124			}1125			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;11261127			let mut properties = CollectionPropertiesVec::default();1128			properties1129				.try_push(Property {1130					key: key.clone(),1131					value: uri1132						.into_bytes()1133						.try_into()1134						.map_err(|_| "token uri is too long")?,1135				})1136				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;11371138			let create_item_data = CreateItemData::<T> {1139				users: users.clone(),1140				properties,1141			};1142			data.push(create_item_data);1143		}11441145		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1146			.map_err(dispatch_to_evm::<T>)?;1147		Ok(true)1148	}11491150	/// @notice Function to mint a token.1151	/// @param to The new owner crossAccountId1152	/// @param properties Properties of minted token1153	/// @return uint256 The id of the newly minted token1154	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1155	fn mint_cross(1156		&mut self,1157		caller: Caller,1158		to: eth::CrossAddress,1159		properties: Vec<eth::Property>,1160	) -> Result<U256> {1161		let token_id = <TokensMinted<T>>::get(self.id)1162			.checked_add(1)1163			.ok_or("item id overflow")?;11641165		let to = to.into_sub_cross_account::<T>()?;11661167		let properties = properties1168			.into_iter()1169			.map(eth::Property::try_into)1170			.collect::<Result<Vec<_>>>()?1171			.try_into()1172			.map_err(|_| Error::Revert("too many properties".to_string()))?;11731174		let caller = T::CrossAccountId::from_eth(caller);11751176		let budget = self1177			.recorder1178			.weight_calls_budget(<StructureWeight<T>>::find_parent());11791180		let users = [(to, 1)]1181			.into_iter()1182			.collect::<BTreeMap<_, _>>()1183			.try_into()1184			.unwrap();1185		<Pallet<T>>::create_item(1186			self,1187			&caller,1188			CreateItemData::<T> { users, properties },1189			&budget,1190		)1191		.map_err(dispatch_to_evm::<T>)?;11921193		Ok(token_id.into())1194	}11951196	/// Returns EVM address for refungible token1197	///1198	/// @param token ID of the token1199	fn token_contract_address(&self, token: U256) -> Result<Address> {1200		Ok(T::EvmTokenAddressMapping::token_to_address(1201			self.id,1202			token.try_into().map_err(|_| "token id overflow")?,1203		))1204	}12051206	/// @notice Returns collection helper contract address1207	fn collection_helper_address(&self) -> Result<Address> {1208		Ok(T::ContractAddress::get())1209	}1210}12111212#[solidity_interface(1213	name = UniqueRefungible,1214	is(1215		ERC721,1216		ERC721Enumerable,1217		ERC721UniqueExtensions,1218		ERC721UniqueMintable,1219		ERC721Burnable,1220		ERC721Metadata(if(this.flags.erc721metadata)),1221		Collection(via(common_mut returns CollectionHandle<T>)),1222		TokenProperties,1223	),1224	enum(derive(PreDispatch)),1225)]1226impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}12271228// Not a tests, but code generators1229generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1230generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);12311232impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1233where1234	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1235{1236	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1237	fn call(1238		self,1239		handle: &mut impl PrecompileHandle,1240	) -> Option<pallet_common::erc::PrecompileResult> {1241		call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1242	}1243}
after · pallets/refungible/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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26	char::{REPLACEMENT_CHARACTER, decode_utf16},27	convert::TryInto,28};29use evm_coder::{abi::AbiType, AbiCoder, ToLog, generate_stubgen, solidity_interface, types::*};30use frame_support::{BoundedBTreeMap, BoundedVec};31use pallet_common::{32	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,33	Error as CommonError,34	erc::{CommonEvmHandler, CollectionCall, static_property::key},35	eth::{self, TokenUri},36};37use pallet_evm::{account::CrossAccountId, PrecompileHandle};38use pallet_evm_coder_substrate::{39	call, dispatch_to_evm,40	execution::{PreDispatch, Result, Error},41	frontier_contract,42};43use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};44use sp_core::{H160, U256, Get};45use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};46use up_data_structs::{47	CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,48	PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,49};5051use crate::{52	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, TokenProperties,53	TokensMinted, TotalSupply, SelfWeightOf, weights::WeightInfo,54};5556frontier_contract! {57	macro_rules! RefungibleHandle_result {...}58	impl<T: Config> Contract for RefungibleHandle<T> {...}59}6061pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);6263/// Rft events.64#[derive(ToLog)]65pub enum ERC721TokenEvent {66	/// The token has been changed.67	TokenChanged {68		/// Token ID.69		#[indexed]70		token_id: U256,71	},72}7374/// Token minting parameters75#[derive(AbiCoder, Default, Debug)]76pub struct OwnerPieces {77	/// Minted token owner78	pub owner: eth::CrossAddress,79	/// Number of token pieces80	pub pieces: u128,81}8283/// Token minting parameters84#[derive(AbiCoder, Default, Debug)]85pub struct MintTokenData {86	/// Minted token owner and number of pieces87	pub owners: Vec<OwnerPieces>,88	/// Minted token properties89	pub properties: Vec<eth::Property>,90}9192/// @title A contract that allows to set and delete token properties and change token property permissions.93#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]94impl<T: Config> RefungibleHandle<T> {95	/// @notice Set permissions for token property.96	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.97	/// @param key Property key.98	/// @param isMutable Permission to mutate property.99	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.100	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.101	#[solidity(hide)]102	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]103	fn set_token_property_permission(104		&mut self,105		caller: Caller,106		key: String,107		is_mutable: bool,108		collection_admin: bool,109		token_owner: bool,110	) -> Result<()> {111		let caller = T::CrossAccountId::from_eth(caller);112		<Pallet<T>>::set_token_property_permissions(113			self,114			&caller,115			vec![PropertyKeyPermission {116				key: <Vec<u8>>::from(key)117					.try_into()118					.map_err(|_| "too long key")?,119				permission: PropertyPermission {120					mutable: is_mutable,121					collection_admin,122					token_owner,123				},124			}],125		)126		.map_err(dispatch_to_evm::<T>)127	}128129	/// @notice Set permissions for token property.130	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.131	/// @param permissions Permissions for keys.132	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]133	fn set_token_property_permissions(134		&mut self,135		caller: Caller,136		permissions: Vec<eth::TokenPropertyPermission>,137	) -> Result<()> {138		let caller = T::CrossAccountId::from_eth(caller);139		let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;140141		<Pallet<T>>::set_token_property_permissions(self, &caller, perms)142			.map_err(dispatch_to_evm::<T>)143	}144145	/// @notice Get permissions for token properties.146	fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {147		let perms = <Pallet<T>>::token_property_permission(self.id);148		Ok(perms149			.into_iter()150			.map(eth::TokenPropertyPermission::from)151			.collect())152	}153154	/// @notice Set token property value.155	/// @dev Throws error if `msg.sender` has no permission to edit the property.156	/// @param tokenId ID of the token.157	/// @param key Property key.158	/// @param value Property value.159	#[solidity(hide)]160	#[weight(<SelfWeightOf<T>>::set_token_properties(1))]161	fn set_property(162		&mut self,163		caller: Caller,164		token_id: U256,165		key: String,166		value: Bytes,167	) -> Result<()> {168		let caller = T::CrossAccountId::from_eth(caller);169		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;170		let key = <Vec<u8>>::from(key)171			.try_into()172			.map_err(|_| "key too long")?;173		let value = value.0.try_into().map_err(|_| "value too long")?;174175		let nesting_budget = self176			.recorder177			.weight_calls_budget(<StructureWeight<T>>::find_parent());178179		<Pallet<T>>::set_token_property(180			self,181			&caller,182			TokenId(token_id),183			Property { key, value },184			&nesting_budget,185		)186		.map_err(dispatch_to_evm::<T>)187	}188189	/// @notice Set token properties value.190	/// @dev Throws error if `msg.sender` has no permission to edit the property.191	/// @param tokenId ID of the token.192	/// @param properties settable properties193	#[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]194	fn set_properties(195		&mut self,196		caller: Caller,197		token_id: U256,198		properties: Vec<eth::Property>,199	) -> Result<()> {200		let caller = T::CrossAccountId::from_eth(caller);201		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;202203		let nesting_budget = self204			.recorder205			.weight_calls_budget(<StructureWeight<T>>::find_parent());206207		let properties = properties208			.into_iter()209			.map(eth::Property::try_into)210			.collect::<Result<Vec<_>>>()?;211212		<Pallet<T>>::set_token_properties(213			self,214			&caller,215			TokenId(token_id),216			properties.into_iter(),217			&nesting_budget,218		)219		.map_err(dispatch_to_evm::<T>)220	}221222	/// @notice Delete token property value.223	/// @dev Throws error if `msg.sender` has no permission to edit the property.224	/// @param tokenId ID of the token.225	/// @param key Property key.226	#[solidity(hide)]227	#[weight(<SelfWeightOf<T>>::delete_token_properties(1))]228	fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {229		let caller = T::CrossAccountId::from_eth(caller);230		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;231		let key = <Vec<u8>>::from(key)232			.try_into()233			.map_err(|_| "key too long")?;234235		let nesting_budget = self236			.recorder237			.weight_calls_budget(<StructureWeight<T>>::find_parent());238239		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)240			.map_err(dispatch_to_evm::<T>)241	}242243	/// @notice Delete token properties value.244	/// @dev Throws error if `msg.sender` has no permission to edit the property.245	/// @param tokenId ID of the token.246	/// @param keys Properties key.247	#[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]248	fn delete_properties(249		&mut self,250		token_id: U256,251		caller: Caller,252		keys: Vec<String>,253	) -> Result<()> {254		let caller = T::CrossAccountId::from_eth(caller);255		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;256		let keys = keys257			.into_iter()258			.map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))259			.collect::<Result<Vec<_>>>()?;260261		let nesting_budget = self262			.recorder263			.weight_calls_budget(<StructureWeight<T>>::find_parent());264265		<Pallet<T>>::delete_token_properties(266			self,267			&caller,268			TokenId(token_id),269			keys.into_iter(),270			&nesting_budget,271		)272		.map_err(dispatch_to_evm::<T>)273	}274275	/// @notice Get token property value.276	/// @dev Throws error if key not found277	/// @param tokenId ID of the token.278	/// @param key Property key.279	/// @return Property value bytes280	fn property(&self, token_id: U256, key: String) -> Result<Bytes> {281		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;282		let key = <Vec<u8>>::from(key)283			.try_into()284			.map_err(|_| "key too long")?;285286		let props =287			<TokenProperties<T>>::get((self.id, token_id)).ok_or("token properties not found")?;288		let prop = props.get(&key).ok_or("key not found")?;289290		Ok(prop.to_vec().into())291	}292}293294#[derive(ToLog)]295pub enum ERC721Events {296	/// @dev This event emits when NFTs are created (`from` == 0) and destroyed297	///  (`to` == 0). Exception: during contract creation, any number of RFTs298	///  may be created and assigned without emitting Transfer.299	Transfer {300		#[indexed]301		from: Address,302		#[indexed]303		to: Address,304		#[indexed]305		token_id: U256,306	},307	/// @dev Not supported308	Approval {309		#[indexed]310		owner: Address,311		#[indexed]312		approved: Address,313		#[indexed]314		token_id: U256,315	},316	/// @dev Not supported317	#[allow(dead_code)]318	ApprovalForAll {319		#[indexed]320		owner: Address,321		#[indexed]322		operator: Address,323		approved: bool,324	},325}326327/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension328/// @dev See https://eips.ethereum.org/EIPS/eip-721329#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]330impl<T: Config> RefungibleHandle<T>331where332	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,333{334	/// @notice A descriptive name for a collection of NFTs in this contract335	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`336	#[solidity(hide, rename_selector = "name")]337	fn name_proxy(&self) -> Result<String> {338		self.name()339	}340341	/// @notice An abbreviated name for NFTs in this contract342	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`343	#[solidity(hide, rename_selector = "symbol")]344	fn symbol_proxy(&self) -> Result<String> {345		self.symbol()346	}347348	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.349	///350	/// @dev If the token has a `url` property and it is not empty, it is returned.351	///  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`.352	///  If the collection property `baseURI` is empty or absent, return "" (empty string)353	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix354	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).355	///356	/// @return token's const_metadata357	#[solidity(rename_selector = "tokenURI")]358	fn token_uri(&self, token_id: U256) -> Result<String> {359		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;360361		match get_token_property(self, token_id_u32, &key::url()).as_deref() {362			Err(_) | Ok("") => (),363			Ok(url) => {364				return Ok(url.into());365			}366		};367368		let base_uri =369			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())370				.map(BoundedVec::into_inner)371				.map(String::from_utf8)372				.transpose()373				.map_err(|e| {374					Error::Revert(alloc::format!(375						"can not convert value \"baseURI\" to string with error \"{e}\""376					))377				})?;378379		let base_uri = match base_uri.as_deref() {380			None | Some("") => {381				return Ok("".into());382			}383			Some(base_uri) => base_uri.into(),384		};385386		Ok(387			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {388				Err(_) | Ok("") => base_uri,389				Ok(suffix) => base_uri + suffix,390			},391		)392	}393}394395/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension396/// @dev See https://eips.ethereum.org/EIPS/eip-721397#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]398impl<T: Config> RefungibleHandle<T> {399	/// @notice Enumerate valid RFTs400	/// @param index A counter less than `totalSupply()`401	/// @return The token identifier for the `index`th NFT,402	///  (sort order not specified)403	fn token_by_index(&self, index: U256) -> U256 {404		index405	}406407	/// Not implemented408	fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {409		// TODO: Not implemetable410		Err("not implemented".into())411	}412413	/// @notice Count RFTs tracked by this contract414	/// @return A count of valid RFTs tracked by this contract, where each one of415	///  them has an assigned and queryable owner not equal to the zero address416	fn total_supply(&self) -> Result<U256> {417		self.consume_store_reads(1)?;418		Ok(<Pallet<T>>::total_supply(self).into())419	}420}421422/// @title ERC-721 Non-Fungible Token Standard423/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md424#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]425impl<T: Config> RefungibleHandle<T> {426	/// @notice Count all RFTs assigned to an owner427	/// @dev RFTs assigned to the zero address are considered invalid, and this428	///  function throws for queries about the zero address.429	/// @param owner An address for whom to query the balance430	/// @return The number of RFTs owned by `owner`, possibly zero431	fn balance_of(&self, owner: Address) -> Result<U256> {432		self.consume_store_reads(1)?;433		let owner = T::CrossAccountId::from_eth(owner);434		let balance = <AccountBalance<T>>::get((self.id, owner));435		Ok(balance.into())436	}437438	/// @notice Find the owner of an RFT439	/// @dev RFTs assigned to zero address are considered invalid, and queries440	///  about them do throw.441	///  Returns special 0xffffffffffffffffffffffffffffffffffffffff address for442	///  the tokens that are partially owned.443	/// @param tokenId The identifier for an RFT444	/// @return The address of the owner of the RFT445	fn owner_of(&self, token_id: U256) -> Result<Address> {446		self.consume_store_reads(2)?;447		let token = token_id.try_into()?;448		let owner = <Pallet<T>>::token_owner(self.id, token);449		owner450			.map(|address| *address.as_eth())451			.or_else(|err| match err {452				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),453				TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),454			})455	}456457	/// @dev Not implemented458	#[solidity(rename_selector = "safeTransferFrom")]459	fn safe_transfer_from_with_data(460		&mut self,461		_from: Address,462		_to: Address,463		_token_id: U256,464		_data: Bytes,465	) -> Result<()> {466		// TODO: Not implemetable467		Err("not implemented".into())468	}469470	/// @dev Not implemented471	#[solidity(rename_selector = "safeTransferFrom")]472	fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {473		// TODO: Not implemetable474		Err("not implemented".into())475	}476477	/// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE478	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE479	///  THEY MAY BE PERMANENTLY LOST480	/// @dev Throws unless `msg.sender` is the current owner or an authorized481	///  operator for this RFT. Throws if `from` is not the current owner. Throws482	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.483	///  Throws if RFT pieces have multiple owners.484	/// @param from The current owner of the NFT485	/// @param to The new owner486	/// @param tokenId The NFT to transfer487	#[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]488	fn transfer_from(489		&mut self,490		caller: Caller,491		from: Address,492		to: Address,493		token_id: U256,494	) -> Result<()> {495		let caller = T::CrossAccountId::from_eth(caller);496		let from = T::CrossAccountId::from_eth(from);497		let to = T::CrossAccountId::from_eth(to);498		let token = token_id.try_into()?;499		let budget = self500			.recorder501			.weight_calls_budget(<StructureWeight<T>>::find_parent());502503		let balance = balance(self, token, &from)?;504		ensure_single_owner(self, token, balance)?;505506		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)507			.map_err(dispatch_to_evm::<T>)?;508509		Ok(())510	}511512	/// @dev Not implemented513	fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {514		Err("not implemented".into())515	}516517	/// @notice Sets or unsets the approval of a given operator.518	///  The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.519	/// @param operator Operator520	/// @param approved Should operator status be granted or revoked?521	#[weight(<SelfWeightOf<T>>::set_allowance_for_all())]522	fn set_approval_for_all(523		&mut self,524		caller: Caller,525		operator: Address,526		approved: bool,527	) -> Result<()> {528		let caller = T::CrossAccountId::from_eth(caller);529		let operator = T::CrossAccountId::from_eth(operator);530531		<Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)532			.map_err(dispatch_to_evm::<T>)?;533		Ok(())534	}535536	/// @dev Not implemented537	fn get_approved(&self, _token_id: U256) -> Result<Address> {538		// TODO: Not implemetable539		Err("not implemented".into())540	}541542	/// @notice Tells whether the given `owner` approves the `operator`.543	#[weight(<SelfWeightOf<T>>::allowance_for_all())]544	fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {545		let owner = T::CrossAccountId::from_eth(owner);546		let operator = T::CrossAccountId::from_eth(operator);547548		Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))549	}550}551552/// Returns amount of pieces of `token` that `owner` have553pub fn balance<T: Config>(554	collection: &RefungibleHandle<T>,555	token: TokenId,556	owner: &T::CrossAccountId,557) -> Result<u128> {558	collection.consume_store_reads(1)?;559	let balance = <Balance<T>>::get((collection.id, token, &owner));560	Ok(balance)561}562563/// Throws if `owner_balance` is lower than total amount of `token` pieces564pub fn ensure_single_owner<T: Config>(565	collection: &RefungibleHandle<T>,566	token: TokenId,567	owner_balance: u128,568) -> Result<()> {569	collection.consume_store_reads(1)?;570	let total_supply = <TotalSupply<T>>::get((collection.id, token));571572	if owner_balance == 0 {573		return Err(dispatch_to_evm::<T>(574			<CommonError<T>>::MustBeTokenOwner.into(),575		));576	}577578	if total_supply != owner_balance {579		return Err("token has multiple owners".into());580	}581	Ok(())582}583584/// @title ERC721 Token that can be irreversibly burned (destroyed).585#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]586impl<T: Config> RefungibleHandle<T> {587	/// @notice Burns a specific ERC721 token.588	/// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized589	///  operator of the current owner.590	/// @param tokenId The RFT to approve591	#[weight(<SelfWeightOf<T>>::burn_item_fully())]592	fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {593		let caller = T::CrossAccountId::from_eth(caller);594		let token = token_id.try_into()?;595596		let balance = balance(self, token, &caller)?;597		ensure_single_owner(self, token, balance)?;598599		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;600		Ok(())601	}602}603604/// @title ERC721 minting logic.605#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]606impl<T: Config> RefungibleHandle<T> {607	/// @notice Function to mint a token.608	/// @param to The new owner609	/// @return uint256 The id of the newly minted token610	#[weight(<SelfWeightOf<T>>::create_item())]611	fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {612		let token_id: U256 = <TokensMinted<T>>::get(self.id)613			.checked_add(1)614			.ok_or("item id overflow")?615			.into();616		self.mint_check_id(caller, to, token_id)?;617		Ok(token_id)618	}619620	/// @notice Function to mint a token.621	/// @dev `tokenId` should be obtained with `nextTokenId` method,622	///  unlike standard, you can't specify it manually623	/// @param to The new owner624	/// @param tokenId ID of the minted RFT625	#[solidity(hide, rename_selector = "mint")]626	#[weight(<SelfWeightOf<T>>::create_item())]627	fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {628		let caller = T::CrossAccountId::from_eth(caller);629		let to = T::CrossAccountId::from_eth(to);630		let token_id: u32 = token_id.try_into()?;631		let budget = self632			.recorder633			.weight_calls_budget(<StructureWeight<T>>::find_parent());634635		if <TokensMinted<T>>::get(self.id)636			.checked_add(1)637			.ok_or("item id overflow")?638			!= token_id639		{640			return Err("item id should be next".into());641		}642643		let users = [(to, 1)]644			.into_iter()645			.collect::<BTreeMap<_, _>>()646			.try_into()647			.unwrap();648		<Pallet<T>>::create_item(649			self,650			&caller,651			CreateItemData::<T> {652				users,653				properties: CollectionPropertiesVec::default(),654			},655			&budget,656		)657		.map_err(dispatch_to_evm::<T>)?;658659		Ok(true)660	}661662	/// @notice Function to mint token with the given tokenUri.663	/// @param to The new owner664	/// @param tokenUri Token URI that would be stored in the NFT properties665	/// @return uint256 The id of the newly minted token666	#[solidity(rename_selector = "mintWithTokenURI")]667	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]668	fn mint_with_token_uri(669		&mut self,670		caller: Caller,671		to: Address,672		token_uri: String,673	) -> Result<U256> {674		let token_id: U256 = <TokensMinted<T>>::get(self.id)675			.checked_add(1)676			.ok_or("item id overflow")?677			.into();678		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;679		Ok(token_id)680	}681682	/// @notice Function to mint token with the given tokenUri.683	/// @dev `tokenId` should be obtained with `nextTokenId` method,684	///  unlike standard, you can't specify it manually685	/// @param to The new owner686	/// @param tokenId ID of the minted RFT687	/// @param tokenUri Token URI that would be stored in the RFT properties688	#[solidity(hide, rename_selector = "mintWithTokenURI")]689	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]690	fn mint_with_token_uri_check_id(691		&mut self,692		caller: Caller,693		to: Address,694		token_id: U256,695		token_uri: String,696	) -> Result<bool> {697		let key = key::url();698		let permission = get_token_permission::<T>(self.id, &key)?;699		if !permission.collection_admin {700			return Err("operation is not allowed".into());701		}702703		let caller = T::CrossAccountId::from_eth(caller);704		let to = T::CrossAccountId::from_eth(to);705		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;706		let budget = self707			.recorder708			.weight_calls_budget(<StructureWeight<T>>::find_parent());709710		if <TokensMinted<T>>::get(self.id)711			.checked_add(1)712			.ok_or("item id overflow")?713			!= token_id714		{715			return Err("item id should be next".into());716		}717718		let mut properties = CollectionPropertiesVec::default();719		properties720			.try_push(Property {721				key,722				value: token_uri723					.into_bytes()724					.try_into()725					.map_err(|_| "token uri is too long")?,726			})727			.map_err(|e| Error::Revert(alloc::format!("can't add property: {e:?}")))?;728729		let users = [(to, 1)]730			.into_iter()731			.collect::<BTreeMap<_, _>>()732			.try_into()733			.unwrap();734		<Pallet<T>>::create_item(735			self,736			&caller,737			CreateItemData::<T> { users, properties },738			&budget,739		)740		.map_err(dispatch_to_evm::<T>)?;741		Ok(true)742	}743}744745fn get_token_property<T: Config>(746	collection: &CollectionHandle<T>,747	token_id: u32,748	key: &up_data_structs::PropertyKey,749) -> Result<String> {750	collection.consume_store_reads(1)?;751	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))752		.map_err(|_| Error::Revert("token properties not found".into()))?;753	if let Some(property) = properties.get(key) {754		return Ok(String::from_utf8_lossy(property).into());755	}756757	Err("property tokenURI not found".into())758}759760fn get_token_permission<T: Config>(761	collection_id: CollectionId,762	key: &PropertyKey,763) -> Result<PropertyPermission> {764	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)765		.map_err(|_| Error::Revert("no permissions for collection".into()))?;766	let a = token_property_permissions767		.get(key)768		.map(Clone::clone)769		.ok_or_else(|| {770			let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();771			Error::Revert(alloc::format!("no permission for key {key}"))772		})?;773	Ok(a)774}775776/// @title Unique extensions for ERC721.777#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]778impl<T: Config> RefungibleHandle<T>779where780	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,781{782	/// @notice A descriptive name for a collection of NFTs in this contract783	fn name(&self) -> Result<String> {784		Ok(decode_utf16(self.name.iter().copied())785			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))786			.collect::<String>())787	}788789	/// @notice An abbreviated name for NFTs in this contract790	fn symbol(&self) -> Result<String> {791		Ok(String::from_utf8_lossy(&self.token_prefix).into())792	}793794	/// @notice A description for the collection.795	fn description(&self) -> Result<String> {796		Ok(decode_utf16(self.description.iter().copied())797			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))798			.collect::<String>())799	}800801	/// Returns the owner (in cross format) of the token.802	///803	/// @param tokenId Id for the token.804	#[solidity(hide)]805	fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {806		Self::owner_of_cross(self, token_id)807	}808809	/// Returns the owner (in cross format) of the token.810	///811	/// @param tokenId Id for the token.812	fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {813		Self::token_owner(self, token_id.try_into()?)814			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))815			.or_else(|err| match err {816				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),817				TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(818					ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,819				)),820			})821	}822823	/// @notice Count all RFTs assigned to an owner824	/// @param owner An cross address for whom to query the balance825	/// @return The number of RFTs owned by `owner`, possibly zero826	fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {827		self.consume_store_reads(1)?;828		let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));829		Ok(balance.into())830	}831832	/// Returns the token properties.833	///834	/// @param tokenId Id for the token.835	/// @param keys Properties keys. Empty keys for all propertyes.836	/// @return Vector of properties key/value pairs.837	fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {838		let keys = keys839			.into_iter()840			.map(|key| {841				<Vec<u8>>::from(key)842					.try_into()843					.map_err(|_| Error::Revert("key too large".into()))844			})845			.collect::<Result<Vec<_>>>()?;846847		<Self as CommonCollectionOperations<T>>::token_properties(848			self,849			token_id.try_into()?,850			if keys.is_empty() { None } else { Some(keys) },851		)852		.into_iter()853		.map(eth::Property::try_from)854		.collect::<Result<Vec<_>>>()855	}856	/// @notice Transfer ownership of an RFT857	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`858	///  is the zero address. Throws if `tokenId` is not a valid RFT.859	///  Throws if RFT pieces have multiple owners.860	/// @param to The new owner861	/// @param tokenId The RFT to transfer862	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]863	fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {864		let caller = T::CrossAccountId::from_eth(caller);865		let to = T::CrossAccountId::from_eth(to);866		let token = token_id.try_into()?;867		let budget = self868			.recorder869			.weight_calls_budget(<StructureWeight<T>>::find_parent());870871		let balance = balance(self, token, &caller)?;872		ensure_single_owner(self, token, balance)?;873874		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)875			.map_err(dispatch_to_evm::<T>)?;876		Ok(())877	}878879	/// @notice Transfer ownership of an RFT880	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`881	///  is the zero address. Throws if `tokenId` is not a valid RFT.882	///  Throws if RFT pieces have multiple owners.883	/// @param to The new owner884	/// @param tokenId The RFT to transfer885	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]886	fn transfer_cross(887		&mut self,888		caller: Caller,889		to: eth::CrossAddress,890		token_id: U256,891	) -> Result<()> {892		let caller = T::CrossAccountId::from_eth(caller);893		let to = to.into_sub_cross_account::<T>()?;894		let token = token_id.try_into()?;895		let budget = self896			.recorder897			.weight_calls_budget(<StructureWeight<T>>::find_parent());898899		let balance = balance(self, token, &caller)?;900		ensure_single_owner(self, token, balance)?;901902		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)903			.map_err(dispatch_to_evm::<T>)?;904		Ok(())905	}906907	/// @notice Transfer ownership of an RFT908	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`909	///  is the zero address. Throws if `tokenId` is not a valid RFT.910	///  Throws if RFT pieces have multiple owners.911	/// @param to The new owner912	/// @param tokenId The RFT to transfer913	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]914	fn transfer_from_cross(915		&mut self,916		caller: Caller,917		from: eth::CrossAddress,918		to: eth::CrossAddress,919		token_id: U256,920	) -> Result<()> {921		let caller = T::CrossAccountId::from_eth(caller);922		let from = from.into_sub_cross_account::<T>()?;923		let to = to.into_sub_cross_account::<T>()?;924		let token_id = token_id.try_into()?;925		let budget = self926			.recorder927			.weight_calls_budget(<StructureWeight<T>>::find_parent());928929		let balance = balance(self, token_id, &from)?;930		ensure_single_owner(self, token_id, balance)?;931932		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)933			.map_err(dispatch_to_evm::<T>)?;934		Ok(())935	}936937	/// @notice Burns a specific ERC721 token.938	/// @dev Throws unless `msg.sender` is the current owner or an authorized939	///  operator for this RFT. Throws if `from` is not the current owner. Throws940	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.941	///  Throws if RFT pieces have multiple owners.942	/// @param from The current owner of the RFT943	/// @param tokenId The RFT to transfer944	#[solidity(hide)]945	#[weight(<SelfWeightOf<T>>::burn_from())]946	fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {947		let caller = T::CrossAccountId::from_eth(caller);948		let from = T::CrossAccountId::from_eth(from);949		let token = token_id.try_into()?;950		let budget = self951			.recorder952			.weight_calls_budget(<StructureWeight<T>>::find_parent());953954		let balance = balance(self, token, &from)?;955		ensure_single_owner(self, token, balance)?;956957		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)958			.map_err(dispatch_to_evm::<T>)?;959		Ok(())960	}961962	/// @notice Burns a specific ERC721 token.963	/// @dev Throws unless `msg.sender` is the current owner or an authorized964	///  operator for this RFT. Throws if `from` is not the current owner. Throws965	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.966	///  Throws if RFT pieces have multiple owners.967	/// @param from The current owner of the RFT968	/// @param tokenId The RFT to transfer969	#[weight(<SelfWeightOf<T>>::burn_from())]970	fn burn_from_cross(971		&mut self,972		caller: Caller,973		from: eth::CrossAddress,974		token_id: U256,975	) -> Result<()> {976		let caller = T::CrossAccountId::from_eth(caller);977		let from = from.into_sub_cross_account::<T>()?;978		let token = token_id.try_into()?;979		let budget = self980			.recorder981			.weight_calls_budget(<StructureWeight<T>>::find_parent());982983		let balance = balance(self, token, &from)?;984		ensure_single_owner(self, token, balance)?;985986		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)987			.map_err(dispatch_to_evm::<T>)?;988		Ok(())989	}990991	/// @notice Returns next free RFT ID.992	fn next_token_id(&self) -> Result<U256> {993		self.consume_store_reads(1)?;994		Ok(<Pallet<T>>::next_token_id(self)995			.map_err(dispatch_to_evm::<T>)?996			.into())997	}998999	/// @notice Function to mint multiple tokens.1000	/// @dev `tokenIds` should be an array of consecutive numbers and first number1001	///  should be obtained with `nextTokenId` method1002	/// @param to The new owner1003	/// @param tokenIds IDs of the minted RFTs1004	#[solidity(hide)]1005	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]1006	fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {1007		let caller = T::CrossAccountId::from_eth(caller);1008		let to = T::CrossAccountId::from_eth(to);1009		let mut expected_index = <TokensMinted<T>>::get(self.id)1010			.checked_add(1)1011			.ok_or("item id overflow")?;1012		let budget = self1013			.recorder1014			.weight_calls_budget(<StructureWeight<T>>::find_parent());10151016		let total_tokens = token_ids.len();1017		for id in token_ids.into_iter() {1018			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1019			if id != expected_index {1020				return Err("item id should be next".into());1021			}1022			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1023		}1024		let users = [(to, 1)]1025			.into_iter()1026			.collect::<BTreeMap<_, _>>()1027			.try_into()1028			.unwrap();1029		let create_item_data = CreateItemData::<T> {1030			users,1031			properties: CollectionPropertiesVec::default(),1032		};1033		let data = (0..total_tokens)1034			.map(|_| create_item_data.clone())1035			.collect();10361037		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1038			.map_err(dispatch_to_evm::<T>)?;1039		Ok(true)1040	}10411042	/// @notice Function to mint a token.1043	/// @param tokenProperties Properties of minted token1044	#[weight(if token_properties.len() == 1 {1045		<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(token_properties.iter().next().unwrap().owners.len() as u32)1046	} else {1047		<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(token_properties.len() as u32)1048	} + <SelfWeightOf<T>>::set_token_properties(token_properties.len() as u32))]1049	fn mint_bulk_cross(1050		&mut self,1051		caller: Caller,1052		token_properties: Vec<MintTokenData>,1053	) -> Result<bool> {1054		let caller = T::CrossAccountId::from_eth(caller);1055		let budget = self1056			.recorder1057			.weight_calls_budget(<StructureWeight<T>>::find_parent());1058		let has_multiple_tokens = token_properties.len() > 1;10591060		let mut create_rft_data = Vec::with_capacity(token_properties.len());1061		for MintTokenData { owners, properties } in token_properties {1062			let has_multiple_owners = owners.len() > 1;1063			if has_multiple_tokens & has_multiple_owners {1064				return Err(1065					"creation of multiple tokens supported only if they have single owner each"1066						.into(),1067				);1068			}1069			let users: BoundedBTreeMap<_, _, _> = owners1070				.into_iter()1071				.map(|data| Ok((data.owner.into_sub_cross_account::<T>()?, data.pieces)))1072				.collect::<Result<BTreeMap<_, _>>>()?1073				.try_into()1074				.map_err(|_| "too many users")?;1075			create_rft_data.push(CreateItemData::<T> {1076				properties: properties1077					.into_iter()1078					.map(|property| property.try_into())1079					.collect::<Result<Vec<_>>>()?1080					.try_into()1081					.map_err(|_| "too many properties")?,1082				users,1083			});1084		}10851086		<Pallet<T>>::create_multiple_items(self, &caller, create_rft_data, &budget)1087			.map_err(dispatch_to_evm::<T>)?;1088		Ok(true)1089	}10901091	/// @notice Function to mint multiple tokens with the given tokenUris.1092	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1093	///  numbers and first number should be obtained with `nextTokenId` method1094	/// @param to The new owner1095	/// @param tokens array of pairs of token ID and token URI for minted tokens1096	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1097	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1098	fn mint_bulk_with_token_uri(1099		&mut self,1100		caller: Caller,1101		to: Address,1102		tokens: Vec<TokenUri>,1103	) -> Result<bool> {1104		let key = key::url();1105		let caller = T::CrossAccountId::from_eth(caller);1106		let to = T::CrossAccountId::from_eth(to);1107		let mut expected_index = <TokensMinted<T>>::get(self.id)1108			.checked_add(1)1109			.ok_or("item id overflow")?;1110		let budget = self1111			.recorder1112			.weight_calls_budget(<StructureWeight<T>>::find_parent());11131114		let mut data = Vec::with_capacity(tokens.len());1115		let users: BoundedBTreeMap<_, _, _> = [(to, 1)]1116			.into_iter()1117			.collect::<BTreeMap<_, _>>()1118			.try_into()1119			.unwrap();1120		for TokenUri { id, uri } in tokens {1121			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1122			if id != expected_index {1123				return Err("item id should be next".into());1124			}1125			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;11261127			let mut properties = CollectionPropertiesVec::default();1128			properties1129				.try_push(Property {1130					key: key.clone(),1131					value: uri1132						.into_bytes()1133						.try_into()1134						.map_err(|_| "token uri is too long")?,1135				})1136				.map_err(|e| Error::Revert(alloc::format!("can't add property: {e:?}")))?;11371138			let create_item_data = CreateItemData::<T> {1139				users: users.clone(),1140				properties,1141			};1142			data.push(create_item_data);1143		}11441145		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1146			.map_err(dispatch_to_evm::<T>)?;1147		Ok(true)1148	}11491150	/// @notice Function to mint a token.1151	/// @param to The new owner crossAccountId1152	/// @param properties Properties of minted token1153	/// @return uint256 The id of the newly minted token1154	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1155	fn mint_cross(1156		&mut self,1157		caller: Caller,1158		to: eth::CrossAddress,1159		properties: Vec<eth::Property>,1160	) -> Result<U256> {1161		let token_id = <TokensMinted<T>>::get(self.id)1162			.checked_add(1)1163			.ok_or("item id overflow")?;11641165		let to = to.into_sub_cross_account::<T>()?;11661167		let properties = properties1168			.into_iter()1169			.map(eth::Property::try_into)1170			.collect::<Result<Vec<_>>>()?1171			.try_into()1172			.map_err(|_| Error::Revert("too many properties".to_string()))?;11731174		let caller = T::CrossAccountId::from_eth(caller);11751176		let budget = self1177			.recorder1178			.weight_calls_budget(<StructureWeight<T>>::find_parent());11791180		let users = [(to, 1)]1181			.into_iter()1182			.collect::<BTreeMap<_, _>>()1183			.try_into()1184			.unwrap();1185		<Pallet<T>>::create_item(1186			self,1187			&caller,1188			CreateItemData::<T> { users, properties },1189			&budget,1190		)1191		.map_err(dispatch_to_evm::<T>)?;11921193		Ok(token_id.into())1194	}11951196	/// Returns EVM address for refungible token1197	///1198	/// @param token ID of the token1199	fn token_contract_address(&self, token: U256) -> Result<Address> {1200		Ok(T::EvmTokenAddressMapping::token_to_address(1201			self.id,1202			token.try_into().map_err(|_| "token id overflow")?,1203		))1204	}12051206	/// @notice Returns collection helper contract address1207	fn collection_helper_address(&self) -> Result<Address> {1208		Ok(T::ContractAddress::get())1209	}1210}12111212#[solidity_interface(1213	name = UniqueRefungible,1214	is(1215		ERC721,1216		ERC721Enumerable,1217		ERC721UniqueExtensions,1218		ERC721UniqueMintable,1219		ERC721Burnable,1220		ERC721Metadata(if(this.flags.erc721metadata)),1221		Collection(via(common_mut returns CollectionHandle<T>)),1222		TokenProperties,1223	),1224	enum(derive(PreDispatch)),1225)]1226impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}12271228// Not a tests, but code generators1229generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1230generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);12311232impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1233where1234	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1235{1236	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1237	fn call(1238		self,1239		handle: &mut impl PrecompileHandle,1240	) -> Option<pallet_common::erc::PrecompileResult> {1241		call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1242	}1243}