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

difftreelog

source

pallets/refungible/src/erc.rs39.0 KiBsourcehistory
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::{decode_utf16, REPLACEMENT_CHARACTER},27	convert::TryInto,28};2930use evm_coder::{abi::AbiType, generate_stubgen, solidity_interface, types::*, AbiCoder, ToLog};31use frame_support::{BoundedBTreeMap, BoundedVec};32use pallet_common::{33	erc::{static_property::key, CollectionCall, CommonEvmHandler},34	eth::{self, TokenUri},35	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations, CommonWeightInfo,36	Error as CommonError,37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{40	call, dispatch_to_evm,41	execution::{Error, PreDispatch, Result},42	frontier_contract, SubstrateRecorder,43};44use pallet_structure::{weights::WeightInfo as _, SelfWeightOf as StructureWeight};45use sp_core::{Get, H160, U256};46use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};47use up_data_structs::{48	budget::Budget, mapping::TokenAddressMapping, CollectionId, CollectionPropertiesVec, Property,49	PropertyKey, PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,50};5152use crate::{53	common::{mint_with_props_weight, CommonWeights},54	weights::WeightInfo,55	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,56	TokenProperties, TokensMinted, TotalSupply,57};5859frontier_contract! {60	macro_rules! RefungibleHandle_result {...}61	impl<T: Config> Contract for RefungibleHandle<T> {...}62}6364pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);6566/// Rft events.67#[derive(ToLog)]68pub enum ERC721TokenEvent {69	/// The token has been changed.70	TokenChanged {71		/// Token ID.72		#[indexed]73		token_id: U256,74	},75}7677/// Token minting parameters78#[derive(AbiCoder, Default, Debug)]79pub struct OwnerPieces {80	/// Minted token owner81	pub owner: eth::CrossAddress,82	/// Number of token pieces83	pub pieces: u128,84}8586/// Token minting parameters87#[derive(AbiCoder, Default, Debug)]88pub struct MintTokenData {89	/// Minted token owner and number of pieces90	pub owners: Vec<OwnerPieces>,91	/// Minted token properties92	pub properties: Vec<eth::Property>,93}9495pub fn nesting_budget<T: Config>(recorder: &SubstrateRecorder<T>) -> impl Budget + '_ {96	recorder.weight_calls_budget(<StructureWeight<T>>::find_parent())97}9899/// @title A contract that allows to set and delete token properties and change token property permissions.100#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]101impl<T: Config> RefungibleHandle<T> {102	/// @notice Set permissions for token property.103	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.104	/// @param key Property key.105	/// @param isMutable Permission to mutate property.106	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.107	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.108	#[solidity(hide)]109	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]110	fn set_token_property_permission(111		&mut self,112		caller: Caller,113		key: String,114		is_mutable: bool,115		collection_admin: bool,116		token_owner: bool,117	) -> Result<()> {118		let caller = T::CrossAccountId::from_eth(caller);119		<Pallet<T>>::set_token_property_permissions(120			self,121			&caller,122			vec![PropertyKeyPermission {123				key: <Vec<u8>>::from(key)124					.try_into()125					.map_err(|_| "too long key")?,126				permission: PropertyPermission {127					mutable: is_mutable,128					collection_admin,129					token_owner,130				},131			}],132		)133		.map_err(dispatch_to_evm::<T>)134	}135136	/// @notice Set permissions for token property.137	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.138	/// @param permissions Permissions for keys.139	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]140	fn set_token_property_permissions(141		&mut self,142		caller: Caller,143		permissions: Vec<eth::TokenPropertyPermission>,144	) -> Result<()> {145		let caller = T::CrossAccountId::from_eth(caller);146		let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;147148		<Pallet<T>>::set_token_property_permissions(self, &caller, perms)149			.map_err(dispatch_to_evm::<T>)150	}151152	/// @notice Get permissions for token properties.153	fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {154		let perms = <Pallet<T>>::token_property_permission(self.id);155		Ok(perms156			.into_iter()157			.map(eth::TokenPropertyPermission::from)158			.collect())159	}160161	/// @notice Set token property value.162	/// @dev Throws error if `msg.sender` has no permission to edit the property.163	/// @param tokenId ID of the token.164	/// @param key Property key.165	/// @param value Property value.166	#[solidity(hide)]167	#[weight(<CommonWeights<T>>::set_token_properties(1))]168	fn set_property(169		&mut self,170		caller: Caller,171		token_id: U256,172		key: String,173		value: Bytes,174	) -> Result<()> {175		let caller = T::CrossAccountId::from_eth(caller);176		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;177		let key = <Vec<u8>>::from(key)178			.try_into()179			.map_err(|_| "key too long")?;180		let value = value.0.try_into().map_err(|_| "value too long")?;181182		<Pallet<T>>::set_token_property(183			self,184			&caller,185			TokenId(token_id),186			Property { key, value },187			&nesting_budget(&self.recorder),188		)189		.map_err(dispatch_to_evm::<T>)190	}191192	/// @notice Set token properties value.193	/// @dev Throws error if `msg.sender` has no permission to edit the property.194	/// @param tokenId ID of the token.195	/// @param properties settable properties196	#[weight(<CommonWeights<T>>::set_token_properties(properties.len() as u32))]197	fn set_properties(198		&mut self,199		caller: Caller,200		token_id: U256,201		properties: Vec<eth::Property>,202	) -> Result<()> {203		let caller = T::CrossAccountId::from_eth(caller);204		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;205206		let properties = properties207			.into_iter()208			.map(eth::Property::try_into)209			.collect::<Result<Vec<_>>>()?;210211		<Pallet<T>>::set_token_properties(212			self,213			&caller,214			TokenId(token_id),215			properties.into_iter(),216			&nesting_budget(&self.recorder),217		)218		.map_err(dispatch_to_evm::<T>)219	}220221	/// @notice Delete token property value.222	/// @dev Throws error if `msg.sender` has no permission to edit the property.223	/// @param tokenId ID of the token.224	/// @param key Property key.225	#[solidity(hide)]226	#[weight(<CommonWeights<T>>::delete_token_properties(1))]227	fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {228		let caller = T::CrossAccountId::from_eth(caller);229		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;230		let key = <Vec<u8>>::from(key)231			.try_into()232			.map_err(|_| "key too long")?;233234		<Pallet<T>>::delete_token_property(235			self,236			&caller,237			TokenId(token_id),238			key,239			&nesting_budget(&self.recorder),240		)241		.map_err(dispatch_to_evm::<T>)242	}243244	/// @notice Delete token properties value.245	/// @dev Throws error if `msg.sender` has no permission to edit the property.246	/// @param tokenId ID of the token.247	/// @param keys Properties key.248	#[weight(<CommonWeights<T>>::delete_token_properties(keys.len() as u32))]249	fn delete_properties(250		&mut self,251		token_id: U256,252		caller: Caller,253		keys: Vec<String>,254	) -> Result<()> {255		let caller = T::CrossAccountId::from_eth(caller);256		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;257		let keys = keys258			.into_iter()259			.map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))260			.collect::<Result<Vec<_>>>()?;261262		<Pallet<T>>::delete_token_properties(263			self,264			&caller,265			TokenId(token_id),266			keys.into_iter(),267			&nesting_budget(&self.recorder),268		)269		.map_err(dispatch_to_evm::<T>)270	}271272	/// @notice Get token property value.273	/// @dev Throws error if key not found274	/// @param tokenId ID of the token.275	/// @param key Property key.276	/// @return Property value bytes277	fn property(&self, token_id: U256, key: String) -> Result<Bytes> {278		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;279		let key = <Vec<u8>>::from(key)280			.try_into()281			.map_err(|_| "key too long")?;282283		let props =284			<TokenProperties<T>>::get((self.id, token_id)).ok_or("token properties not found")?;285		let prop = props.get(&key).ok_or("key not found")?;286287		Ok(prop.to_vec().into())288	}289}290291#[derive(ToLog)]292pub enum ERC721Events {293	/// @dev This event emits when NFTs are created (`from` == 0) and destroyed294	///  (`to` == 0). Exception: during contract creation, any number of RFTs295	///  may be created and assigned without emitting Transfer.296	Transfer {297		#[indexed]298		from: Address,299		#[indexed]300		to: Address,301		#[indexed]302		token_id: U256,303	},304	/// @dev Not supported305	Approval {306		#[indexed]307		owner: Address,308		#[indexed]309		approved: Address,310		#[indexed]311		token_id: U256,312	},313	/// @dev Not supported314	#[allow(dead_code)]315	ApprovalForAll {316		#[indexed]317		owner: Address,318		#[indexed]319		operator: Address,320		approved: bool,321	},322}323324/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension325/// @dev See https://eips.ethereum.org/EIPS/eip-721326#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]327impl<T: Config> RefungibleHandle<T>328where329	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,330{331	/// @notice A descriptive name for a collection of NFTs in this contract332	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`333	#[solidity(hide, rename_selector = "name")]334	fn name_proxy(&self) -> Result<String> {335		self.name()336	}337338	/// @notice An abbreviated name for NFTs in this contract339	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`340	#[solidity(hide, rename_selector = "symbol")]341	fn symbol_proxy(&self) -> Result<String> {342		self.symbol()343	}344345	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.346	///347	/// @dev If the token has a `url` property and it is not empty, it is returned.348	///  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`.349	///  If the collection property `baseURI` is empty or absent, return "" (empty string)350	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix351	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).352	///353	/// @return token's const_metadata354	#[solidity(rename_selector = "tokenURI")]355	fn token_uri(&self, token_id: U256) -> Result<String> {356		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;357358		match get_token_property(self, token_id_u32, &key::url()).as_deref() {359			Err(_) | Ok("") => (),360			Ok(url) => {361				return Ok(url.into());362			}363		};364365		let base_uri =366			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())367				.map(BoundedVec::into_inner)368				.map(String::from_utf8)369				.transpose()370				.map_err(|e| {371					Error::Revert(alloc::format!(372						"can not convert value \"baseURI\" to string with error \"{e}\""373					))374				})?;375376		let base_uri = match base_uri.as_deref() {377			None | Some("") => {378				return Ok("".into());379			}380			Some(base_uri) => base_uri.into(),381		};382383		Ok(384			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {385				Err(_) | Ok("") => base_uri,386				Ok(suffix) => base_uri + suffix,387			},388		)389	}390}391392/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension393/// @dev See https://eips.ethereum.org/EIPS/eip-721394#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]395impl<T: Config> RefungibleHandle<T> {396	/// @notice Enumerate valid RFTs397	/// @param index A counter less than `totalSupply()`398	/// @return The token identifier for the `index`th NFT,399	///  (sort order not specified)400	fn token_by_index(&self, index: U256) -> U256 {401		index402	}403404	/// Not implemented405	fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {406		// TODO: Not implemetable407		Err("not implemented".into())408	}409410	/// @notice Count RFTs tracked by this contract411	/// @return A count of valid RFTs tracked by this contract, where each one of412	///  them has an assigned and queryable owner not equal to the zero address413	fn total_supply(&self) -> Result<U256> {414		self.consume_store_reads(1)?;415		Ok(<Pallet<T>>::total_supply(self).into())416	}417}418419/// @title ERC-721 Non-Fungible Token Standard420/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md421#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]422impl<T: Config> RefungibleHandle<T> {423	/// @notice Count all RFTs assigned to an owner424	/// @dev RFTs assigned to the zero address are considered invalid, and this425	///  function throws for queries about the zero address.426	/// @param owner An address for whom to query the balance427	/// @return The number of RFTs owned by `owner`, possibly zero428	fn balance_of(&self, owner: Address) -> Result<U256> {429		self.consume_store_reads(1)?;430		let owner = T::CrossAccountId::from_eth(owner);431		let balance = <AccountBalance<T>>::get((self.id, owner));432		Ok(balance.into())433	}434435	/// @notice Find the owner of an RFT436	/// @dev RFTs assigned to zero address are considered invalid, and queries437	///  about them do throw.438	///  Returns special 0xffffffffffffffffffffffffffffffffffffffff address for439	///  the tokens that are partially owned.440	/// @param tokenId The identifier for an RFT441	/// @return The address of the owner of the RFT442	fn owner_of(&self, token_id: U256) -> Result<Address> {443		self.consume_store_reads(2)?;444		let token = token_id.try_into()?;445		let owner = <Pallet<T>>::token_owner(self.id, token);446		owner447			.map(|address| *address.as_eth())448			.or_else(|err| match err {449				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),450				TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),451			})452	}453454	/// @dev Not implemented455	#[solidity(rename_selector = "safeTransferFrom")]456	fn safe_transfer_from_with_data(457		&mut self,458		_from: Address,459		_to: Address,460		_token_id: U256,461		_data: Bytes,462	) -> Result<()> {463		// TODO: Not implemetable464		Err("not implemented".into())465	}466467	/// @dev Not implemented468	#[solidity(rename_selector = "safeTransferFrom")]469	fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {470		// TODO: Not implemetable471		Err("not implemented".into())472	}473474	/// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE475	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE476	///  THEY MAY BE PERMANENTLY LOST477	/// @dev Throws unless `msg.sender` is the current owner or an authorized478	///  operator for this RFT. Throws if `from` is not the current owner. Throws479	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.480	///  Throws if RFT pieces have multiple owners.481	/// @param from The current owner of the NFT482	/// @param to The new owner483	/// @param tokenId The NFT to transfer484	#[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]485	fn transfer_from(486		&mut self,487		caller: Caller,488		from: Address,489		to: Address,490		token_id: U256,491	) -> Result<()> {492		let caller = T::CrossAccountId::from_eth(caller);493		let from = T::CrossAccountId::from_eth(from);494		let to = T::CrossAccountId::from_eth(to);495		let token = token_id.try_into()?;496497		let balance = balance(self, token, &from)?;498		ensure_single_owner(self, token, balance)?;499500		<Pallet<T>>::transfer_from(501			self,502			&caller,503			&from,504			&to,505			token,506			balance,507			&nesting_budget(&self.recorder),508		)509		.map_err(dispatch_to_evm::<T>)?;510511		Ok(())512	}513514	/// @dev Not implemented515	fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {516		Err("not implemented".into())517	}518519	/// @notice Sets or unsets the approval of a given operator.520	///  The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.521	/// @param operator Operator522	/// @param approved Should operator status be granted or revoked?523	#[weight(<SelfWeightOf<T>>::set_allowance_for_all())]524	fn set_approval_for_all(525		&mut self,526		caller: Caller,527		operator: Address,528		approved: bool,529	) -> Result<()> {530		let caller = T::CrossAccountId::from_eth(caller);531		let operator = T::CrossAccountId::from_eth(operator);532533		<Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)534			.map_err(dispatch_to_evm::<T>)?;535		Ok(())536	}537538	/// @dev Not implemented539	fn get_approved(&self, _token_id: U256) -> Result<Address> {540		// TODO: Not implemetable541		Err("not implemented".into())542	}543544	/// @notice Tells whether the given `owner` approves the `operator`.545	#[weight(<SelfWeightOf<T>>::allowance_for_all())]546	fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {547		let owner = T::CrossAccountId::from_eth(owner);548		let operator = T::CrossAccountId::from_eth(operator);549550		Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))551	}552}553554/// Returns amount of pieces of `token` that `owner` have555pub fn balance<T: Config>(556	collection: &RefungibleHandle<T>,557	token: TokenId,558	owner: &T::CrossAccountId,559) -> Result<u128> {560	collection.consume_store_reads(1)?;561	let balance = <Balance<T>>::get((collection.id, token, &owner));562	Ok(balance)563}564565/// Throws if `owner_balance` is lower than total amount of `token` pieces566pub fn ensure_single_owner<T: Config>(567	collection: &RefungibleHandle<T>,568	token: TokenId,569	owner_balance: u128,570) -> Result<()> {571	collection.consume_store_reads(1)?;572	let total_supply = <TotalSupply<T>>::get((collection.id, token));573574	if owner_balance == 0 {575		return Err(dispatch_to_evm::<T>(576			<CommonError<T>>::MustBeTokenOwner.into(),577		));578	}579580	if total_supply != owner_balance {581		return Err("token has multiple owners".into());582	}583	Ok(())584}585586/// @title ERC721 Token that can be irreversibly burned (destroyed).587#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]588impl<T: Config> RefungibleHandle<T> {589	/// @notice Burns a specific ERC721 token.590	/// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized591	///  operator of the current owner.592	/// @param tokenId The RFT to approve593	#[weight(<SelfWeightOf<T>>::burn_item_fully())]594	fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {595		let caller = T::CrossAccountId::from_eth(caller);596		let token = token_id.try_into()?;597598		let balance = balance(self, token, &caller)?;599		ensure_single_owner(self, token, balance)?;600601		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;602		Ok(())603	}604}605606/// @title ERC721 minting logic.607#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]608impl<T: Config> RefungibleHandle<T> {609	/// @notice Function to mint a token.610	/// @param to The new owner611	/// @return uint256 The id of the newly minted token612	#[weight(<SelfWeightOf<T>>::create_item())]613	fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {614		let token_id: U256 = <TokensMinted<T>>::get(self.id)615			.checked_add(1)616			.ok_or("item id overflow")?617			.into();618		self.mint_check_id(caller, to, token_id)?;619		Ok(token_id)620	}621622	/// @notice Function to mint a token.623	/// @dev `tokenId` should be obtained with `nextTokenId` method,624	///  unlike standard, you can't specify it manually625	/// @param to The new owner626	/// @param tokenId ID of the minted RFT627	#[solidity(hide, rename_selector = "mint")]628	#[weight(<SelfWeightOf<T>>::create_item())]629	fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {630		let caller = T::CrossAccountId::from_eth(caller);631		let to = T::CrossAccountId::from_eth(to);632		let token_id: u32 = token_id.try_into()?;633634		if <TokensMinted<T>>::get(self.id)635			.checked_add(1)636			.ok_or("item id overflow")?637			!= token_id638		{639			return Err("item id should be next".into());640		}641642		let users = [(to, 1)]643			.into_iter()644			.collect::<BTreeMap<_, _>>()645			.try_into()646			.unwrap();647		<Pallet<T>>::create_item(648			self,649			&caller,650			CreateItemData::<T> {651				users,652				properties: CollectionPropertiesVec::default(),653			},654			&nesting_budget(&self.recorder),655		)656		.map_err(dispatch_to_evm::<T>)?;657658		Ok(true)659	}660661	/// @notice Function to mint token with the given tokenUri.662	/// @param to The new owner663	/// @param tokenUri Token URI that would be stored in the NFT properties664	/// @return uint256 The id of the newly minted token665	#[solidity(rename_selector = "mintWithTokenURI")]666	#[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [1].into_iter()))]667	fn mint_with_token_uri(668		&mut self,669		caller: Caller,670		to: Address,671		token_uri: String,672	) -> Result<U256> {673		let token_id: U256 = <TokensMinted<T>>::get(self.id)674			.checked_add(1)675			.ok_or("item id overflow")?676			.into();677		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;678		Ok(token_id)679	}680681	/// @notice Function to mint token with the given tokenUri.682	/// @dev `tokenId` should be obtained with `nextTokenId` method,683	///  unlike standard, you can't specify it manually684	/// @param to The new owner685	/// @param tokenId ID of the minted RFT686	/// @param tokenUri Token URI that would be stored in the RFT properties687	#[solidity(hide, rename_selector = "mintWithTokenURI")]688	#[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [1].into_iter()))]689	fn mint_with_token_uri_check_id(690		&mut self,691		caller: Caller,692		to: Address,693		token_id: U256,694		token_uri: String,695	) -> Result<bool> {696		let key = key::url();697		let permission = get_token_permission::<T>(self.id, &key)?;698		if !permission.collection_admin {699			return Err("operation is not allowed".into());700		}701702		let caller = T::CrossAccountId::from_eth(caller);703		let to = T::CrossAccountId::from_eth(to);704		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;705706		if <TokensMinted<T>>::get(self.id)707			.checked_add(1)708			.ok_or("item id overflow")?709			!= token_id710		{711			return Err("item id should be next".into());712		}713714		let mut properties = CollectionPropertiesVec::default();715		properties716			.try_push(Property {717				key,718				value: token_uri719					.into_bytes()720					.try_into()721					.map_err(|_| "token uri is too long")?,722			})723			.map_err(|e| Error::Revert(alloc::format!("can't add property: {e:?}")))?;724725		let users = [(to, 1)]726			.into_iter()727			.collect::<BTreeMap<_, _>>()728			.try_into()729			.unwrap();730		<Pallet<T>>::create_item(731			self,732			&caller,733			CreateItemData::<T> { users, properties },734			&nesting_budget(&self.recorder),735		)736		.map_err(dispatch_to_evm::<T>)?;737		Ok(true)738	}739}740741fn get_token_property<T: Config>(742	collection: &CollectionHandle<T>,743	token_id: u32,744	key: &up_data_structs::PropertyKey,745) -> Result<String> {746	collection.consume_store_reads(1)?;747	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))748		.map_err(|_| Error::Revert("token properties not found".into()))?;749	if let Some(property) = properties.get(key) {750		return Ok(String::from_utf8_lossy(property).into());751	}752753	Err("property tokenURI not found".into())754}755756fn get_token_permission<T: Config>(757	collection_id: CollectionId,758	key: &PropertyKey,759) -> Result<PropertyPermission> {760	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)761		.map_err(|_| Error::Revert("no permissions for collection".into()))?;762	let a = token_property_permissions763		.get(key)764		.map(Clone::clone)765		.ok_or_else(|| {766			let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();767			Error::Revert(alloc::format!("no permission for key {key}"))768		})?;769	Ok(a)770}771772/// @title Unique extensions for ERC721.773#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]774impl<T: Config> RefungibleHandle<T>775where776	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,777{778	/// @notice A descriptive name for a collection of NFTs in this contract779	fn name(&self) -> Result<String> {780		Ok(decode_utf16(self.name.iter().copied())781			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))782			.collect::<String>())783	}784785	/// @notice An abbreviated name for NFTs in this contract786	fn symbol(&self) -> Result<String> {787		Ok(String::from_utf8_lossy(&self.token_prefix).into())788	}789790	/// @notice A description for the collection.791	fn description(&self) -> Result<String> {792		Ok(decode_utf16(self.description.iter().copied())793			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))794			.collect::<String>())795	}796797	/// Returns the owner (in cross format) of the token.798	///799	/// @param tokenId Id for the token.800	#[solidity(hide)]801	fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {802		Self::owner_of_cross(self, token_id)803	}804805	/// Returns the owner (in cross format) of the token.806	///807	/// @param tokenId Id for the token.808	fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {809		Self::token_owner(self, token_id.try_into()?)810			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))811			.or_else(|err| match err {812				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),813				TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(814					ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,815				)),816			})817	}818819	/// @notice Count all RFTs assigned to an owner820	/// @param owner An cross address for whom to query the balance821	/// @return The number of RFTs owned by `owner`, possibly zero822	fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {823		self.consume_store_reads(1)?;824		let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));825		Ok(balance.into())826	}827828	/// Returns the token properties.829	///830	/// @param tokenId Id for the token.831	/// @param keys Properties keys. Empty keys for all propertyes.832	/// @return Vector of properties key/value pairs.833	fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {834		let keys = keys835			.into_iter()836			.map(|key| {837				<Vec<u8>>::from(key)838					.try_into()839					.map_err(|_| Error::Revert("key too large".into()))840			})841			.collect::<Result<Vec<_>>>()?;842843		<Self as CommonCollectionOperations<T>>::token_properties(844			self,845			token_id.try_into()?,846			if keys.is_empty() { None } else { Some(keys) },847		)848		.into_iter()849		.map(eth::Property::try_from)850		.collect::<Result<Vec<_>>>()851	}852	/// @notice Transfer ownership of an RFT853	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`854	///  is the zero address. Throws if `tokenId` is not a valid RFT.855	///  Throws if RFT pieces have multiple owners.856	/// @param to The new owner857	/// @param tokenId The RFT to transfer858	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]859	fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {860		let caller = T::CrossAccountId::from_eth(caller);861		let to = T::CrossAccountId::from_eth(to);862		let token = token_id.try_into()?;863864		let balance = balance(self, token, &caller)?;865		ensure_single_owner(self, token, balance)?;866867		<Pallet<T>>::transfer(868			self,869			&caller,870			&to,871			token,872			balance,873			&nesting_budget(&self.recorder),874		)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()?;895896		let balance = balance(self, token, &caller)?;897		ensure_single_owner(self, token, balance)?;898899		<Pallet<T>>::transfer(900			self,901			&caller,902			&to,903			token,904			balance,905			&nesting_budget(&self.recorder),906		)907		.map_err(dispatch_to_evm::<T>)?;908		Ok(())909	}910911	/// @notice Transfer ownership of an RFT912	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`913	///  is the zero address. Throws if `tokenId` is not a valid RFT.914	///  Throws if RFT pieces have multiple owners.915	/// @param to The new owner916	/// @param tokenId The RFT to transfer917	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]918	fn transfer_from_cross(919		&mut self,920		caller: Caller,921		from: eth::CrossAddress,922		to: eth::CrossAddress,923		token_id: U256,924	) -> Result<()> {925		let caller = T::CrossAccountId::from_eth(caller);926		let from = from.into_sub_cross_account::<T>()?;927		let to = to.into_sub_cross_account::<T>()?;928		let token_id = token_id.try_into()?;929930		let balance = balance(self, token_id, &from)?;931		ensure_single_owner(self, token_id, balance)?;932933		Pallet::<T>::transfer_from(934			self,935			&caller,936			&from,937			&to,938			token_id,939			balance,940			&nesting_budget(&self.recorder),941		)942		.map_err(dispatch_to_evm::<T>)?;943		Ok(())944	}945946	/// @notice Burns a specific ERC721 token.947	/// @dev Throws unless `msg.sender` is the current owner or an authorized948	///  operator for this RFT. Throws if `from` is not the current owner. Throws949	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.950	///  Throws if RFT pieces have multiple owners.951	/// @param from The current owner of the RFT952	/// @param tokenId The RFT to transfer953	#[solidity(hide)]954	#[weight(<SelfWeightOf<T>>::burn_from())]955	fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {956		let caller = T::CrossAccountId::from_eth(caller);957		let from = T::CrossAccountId::from_eth(from);958		let token = token_id.try_into()?;959960		let balance = balance(self, token, &from)?;961		ensure_single_owner(self, token, balance)?;962963		<Pallet<T>>::burn_from(964			self,965			&caller,966			&from,967			token,968			balance,969			&nesting_budget(&self.recorder),970		)971		.map_err(dispatch_to_evm::<T>)?;972		Ok(())973	}974975	/// @notice Burns a specific ERC721 token.976	/// @dev Throws unless `msg.sender` is the current owner or an authorized977	///  operator for this RFT. Throws if `from` is not the current owner. Throws978	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.979	///  Throws if RFT pieces have multiple owners.980	/// @param from The current owner of the RFT981	/// @param tokenId The RFT to transfer982	#[weight(<SelfWeightOf<T>>::burn_from())]983	fn burn_from_cross(984		&mut self,985		caller: Caller,986		from: eth::CrossAddress,987		token_id: U256,988	) -> Result<()> {989		let caller = T::CrossAccountId::from_eth(caller);990		let from = from.into_sub_cross_account::<T>()?;991		let token = token_id.try_into()?;992993		let balance = balance(self, token, &from)?;994		ensure_single_owner(self, token, balance)?;995996		<Pallet<T>>::burn_from(997			self,998			&caller,999			&from,1000			token,1001			balance,1002			&nesting_budget(&self.recorder),1003		)1004		.map_err(dispatch_to_evm::<T>)?;1005		Ok(())1006	}10071008	/// @notice Returns next free RFT ID.1009	fn next_token_id(&self) -> Result<U256> {1010		self.consume_store_reads(1)?;1011		Ok(<Pallet<T>>::next_token_id(self)1012			.map_err(dispatch_to_evm::<T>)?1013			.into())1014	}10151016	/// @notice Function to mint multiple tokens.1017	/// @dev `tokenIds` should be an array of consecutive numbers and first number1018	///  should be obtained with `nextTokenId` method1019	/// @param to The new owner1020	/// @param tokenIds IDs of the minted RFTs1021	#[solidity(hide)]1022	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]1023	fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {1024		let caller = T::CrossAccountId::from_eth(caller);1025		let to = T::CrossAccountId::from_eth(to);1026		let mut expected_index = <TokensMinted<T>>::get(self.id)1027			.checked_add(1)1028			.ok_or("item id overflow")?;10291030		let total_tokens = token_ids.len();1031		for id in token_ids.into_iter() {1032			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1033			if id != expected_index {1034				return Err("item id should be next".into());1035			}1036			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1037		}1038		let users = [(to, 1)]1039			.into_iter()1040			.collect::<BTreeMap<_, _>>()1041			.try_into()1042			.unwrap();1043		let create_item_data = CreateItemData::<T> {1044			users,1045			properties: CollectionPropertiesVec::default(),1046		};1047		let data = (0..total_tokens)1048			.map(|_| create_item_data.clone())1049			.collect();10501051		<Pallet<T>>::create_multiple_items(self, &caller, data, &nesting_budget(&self.recorder))1052			.map_err(dispatch_to_evm::<T>)?;1053		Ok(true)1054	}10551056	/// @notice Function to mint a token.1057	/// @param tokensData Data of minted token(s)1058	#[weight(if tokens_data.len() == 1 {1059		let token_data = tokens_data.first().unwrap();10601061		mint_with_props_weight::<T>(1062			<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(token_data.owners.len() as u32),1063			[token_data.properties.len() as u32].into_iter(),1064		)1065	} else {1066		mint_with_props_weight::<T>(1067			<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(tokens_data.len() as u32),1068			tokens_data.iter().map(|d| d.properties.len() as u32),1069		)1070	})]1071	fn mint_bulk_cross(&mut self, caller: Caller, tokens_data: Vec<MintTokenData>) -> Result<bool> {1072		let caller = T::CrossAccountId::from_eth(caller);1073		let has_multiple_tokens = tokens_data.len() > 1;10741075		let mut create_rft_data = Vec::with_capacity(tokens_data.len());1076		for MintTokenData { owners, properties } in tokens_data {1077			let has_multiple_owners = owners.len() > 1;1078			if has_multiple_tokens & has_multiple_owners {1079				return Err(1080					"creation of multiple tokens supported only if they have single owner each"1081						.into(),1082				);1083			}1084			let users: BoundedBTreeMap<_, _, _> = owners1085				.into_iter()1086				.map(|data| Ok((data.owner.into_sub_cross_account::<T>()?, data.pieces)))1087				.collect::<Result<BTreeMap<_, _>>>()?1088				.try_into()1089				.map_err(|_| "too many users")?;1090			create_rft_data.push(CreateItemData::<T> {1091				properties: properties1092					.into_iter()1093					.map(|property| property.try_into())1094					.collect::<Result<Vec<_>>>()?1095					.try_into()1096					.map_err(|_| "too many properties")?,1097				users,1098			});1099		}11001101		<Pallet<T>>::create_multiple_items(1102			self,1103			&caller,1104			create_rft_data,1105			&nesting_budget(&self.recorder),1106		)1107		.map_err(dispatch_to_evm::<T>)?;1108		Ok(true)1109	}11101111	/// @notice Function to mint multiple tokens with the given tokenUris.1112	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1113	///  numbers and first number should be obtained with `nextTokenId` method1114	/// @param to The new owner1115	/// @param tokens array of pairs of token ID and token URI for minted tokens1116	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1117	#[weight(1118		mint_with_props_weight::<T>(1119			<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32),1120			tokens.iter().map(|_| 1),1121		)1122	)]1123	fn mint_bulk_with_token_uri(1124		&mut self,1125		caller: Caller,1126		to: Address,1127		tokens: Vec<TokenUri>,1128	) -> Result<bool> {1129		let key = key::url();1130		let caller = T::CrossAccountId::from_eth(caller);1131		let to = T::CrossAccountId::from_eth(to);1132		let mut expected_index = <TokensMinted<T>>::get(self.id)1133			.checked_add(1)1134			.ok_or("item id overflow")?;11351136		let mut data = Vec::with_capacity(tokens.len());1137		let users: BoundedBTreeMap<_, _, _> = [(to, 1)]1138			.into_iter()1139			.collect::<BTreeMap<_, _>>()1140			.try_into()1141			.unwrap();1142		for TokenUri { id, uri } in tokens {1143			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1144			if id != expected_index {1145				return Err("item id should be next".into());1146			}1147			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;11481149			let mut properties = CollectionPropertiesVec::default();1150			properties1151				.try_push(Property {1152					key: key.clone(),1153					value: uri1154						.into_bytes()1155						.try_into()1156						.map_err(|_| "token uri is too long")?,1157				})1158				.map_err(|e| Error::Revert(alloc::format!("can't add property: {e:?}")))?;11591160			let create_item_data = CreateItemData::<T> {1161				users: users.clone(),1162				properties,1163			};1164			data.push(create_item_data);1165		}11661167		<Pallet<T>>::create_multiple_items(self, &caller, data, &nesting_budget(&self.recorder))1168			.map_err(dispatch_to_evm::<T>)?;1169		Ok(true)1170	}11711172	/// @notice Function to mint a token.1173	/// @param to The new owner crossAccountId1174	/// @param properties Properties of minted token1175	/// @return uint256 The id of the newly minted token1176	#[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [properties.len() as u32].into_iter()))]1177	fn mint_cross(1178		&mut self,1179		caller: Caller,1180		to: eth::CrossAddress,1181		properties: Vec<eth::Property>,1182	) -> Result<U256> {1183		let token_id = <TokensMinted<T>>::get(self.id)1184			.checked_add(1)1185			.ok_or("item id overflow")?;11861187		let to = to.into_sub_cross_account::<T>()?;11881189		let properties = properties1190			.into_iter()1191			.map(eth::Property::try_into)1192			.collect::<Result<Vec<_>>>()?1193			.try_into()1194			.map_err(|_| Error::Revert("too many properties".to_string()))?;11951196		let caller = T::CrossAccountId::from_eth(caller);11971198		let users = [(to, 1)]1199			.into_iter()1200			.collect::<BTreeMap<_, _>>()1201			.try_into()1202			.unwrap();1203		<Pallet<T>>::create_item(1204			self,1205			&caller,1206			CreateItemData::<T> { users, properties },1207			&nesting_budget(&self.recorder),1208		)1209		.map_err(dispatch_to_evm::<T>)?;12101211		Ok(token_id.into())1212	}12131214	/// Returns EVM address for refungible token1215	///1216	/// @param token ID of the token1217	fn token_contract_address(&self, token: U256) -> Result<Address> {1218		Ok(T::EvmTokenAddressMapping::token_to_address(1219			self.id,1220			token.try_into().map_err(|_| "token id overflow")?,1221		))1222	}12231224	/// @notice Returns collection helper contract address1225	fn collection_helper_address(&self) -> Result<Address> {1226		Ok(T::ContractAddress::get())1227	}1228}12291230#[solidity_interface(1231	name = UniqueRefungible,1232	is(1233		ERC721,1234		ERC721Enumerable,1235		ERC721UniqueExtensions,1236		ERC721UniqueMintable,1237		ERC721Burnable,1238		ERC721Metadata(if(this.flags.erc721metadata)),1239		Collection(via(common_mut returns CollectionHandle<T>)),1240		TokenProperties,1241	),1242	enum(derive(PreDispatch)),1243)]1244impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}12451246// Not a tests, but code generators1247generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1248generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);12491250impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1251where1252	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1253{1254	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1255	fn call(1256		self,1257		handle: &mut impl PrecompileHandle,1258	) -> Option<pallet_common::erc::PrecompileResult> {1259		call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1260	}1261}