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

difftreelog

source

pallets/refungible/src/erc.rs36.3 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 core::{25	char::{REPLACEMENT_CHARACTER, decode_utf16},26	convert::TryInto,27};28use evm_coder::{29	abi::AbiType, ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*,30	weight,31};32use frame_support::{BoundedBTreeMap, BoundedVec};33use pallet_common::{34	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,35	Error as CommonError,36	erc::{CommonEvmHandler, CollectionCall, static_property::key},37	eth::{self, TokenUri},38};39use pallet_evm::{account::CrossAccountId, PrecompileHandle};40use pallet_evm_coder_substrate::{call, dispatch_to_evm};41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};42use sp_core::{H160, U256, Get};43use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};44use up_data_structs::{45	CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,46	PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,47};4849use crate::{50	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,51	TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,52};5354pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);5556/// @title A contract that allows to set and delete token properties and change token property permissions.57#[solidity_interface(name = TokenProperties)]58impl<T: Config> RefungibleHandle<T> {59	/// @notice Set permissions for token property.60	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.61	/// @param key Property key.62	/// @param isMutable Permission to mutate property.63	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.64	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.65	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]66	#[solidity(hide)]67	fn set_token_property_permission(68		&mut self,69		caller: Caller,70		key: String,71		is_mutable: bool,72		collection_admin: bool,73		token_owner: bool,74	) -> Result<()> {75		let caller = T::CrossAccountId::from_eth(caller);76		<Pallet<T>>::set_token_property_permissions(77			self,78			&caller,79			vec![PropertyKeyPermission {80				key: <Vec<u8>>::from(key)81					.try_into()82					.map_err(|_| "too long key")?,83				permission: PropertyPermission {84					mutable: is_mutable,85					collection_admin,86					token_owner,87				},88			}],89		)90		.map_err(dispatch_to_evm::<T>)91	}9293	/// @notice Set permissions for token property.94	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.95	/// @param permissions Permissions for keys.96	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]97	fn set_token_property_permissions(98		&mut self,99		caller: Caller,100		permissions: Vec<eth::TokenPropertyPermission>,101	) -> Result<()> {102		let caller = T::CrossAccountId::from_eth(caller);103		let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;104105		<Pallet<T>>::set_token_property_permissions(self, &caller, perms)106			.map_err(dispatch_to_evm::<T>)107	}108109	/// @notice Get permissions for token properties.110	fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {111		let perms = <Pallet<T>>::token_property_permission(self.id);112		Ok(perms113			.into_iter()114			.map(eth::TokenPropertyPermission::from)115			.collect())116	}117118	/// @notice Set token property value.119	/// @dev Throws error if `msg.sender` has no permission to edit the property.120	/// @param tokenId ID of the token.121	/// @param key Property key.122	/// @param value Property value.123	#[solidity(hide)]124	#[weight(<SelfWeightOf<T>>::set_token_properties(1))]125	fn set_property(126		&mut self,127		caller: Caller,128		token_id: U256,129		key: String,130		value: Bytes,131	) -> Result<()> {132		let caller = T::CrossAccountId::from_eth(caller);133		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;134		let key = <Vec<u8>>::from(key)135			.try_into()136			.map_err(|_| "key too long")?;137		let value = value.0.try_into().map_err(|_| "value too long")?;138139		let nesting_budget = self140			.recorder141			.weight_calls_budget(<StructureWeight<T>>::find_parent());142143		<Pallet<T>>::set_token_property(144			self,145			&caller,146			TokenId(token_id),147			Property { key, value },148			&nesting_budget,149		)150		.map_err(dispatch_to_evm::<T>)151	}152153	/// @notice Set token properties value.154	/// @dev Throws error if `msg.sender` has no permission to edit the property.155	/// @param tokenId ID of the token.156	/// @param properties settable properties157	#[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]158	fn set_properties(159		&mut self,160		caller: Caller,161		token_id: U256,162		properties: Vec<eth::Property>,163	) -> Result<()> {164		let caller = T::CrossAccountId::from_eth(caller);165		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;166167		let nesting_budget = self168			.recorder169			.weight_calls_budget(<StructureWeight<T>>::find_parent());170171		let properties = properties172			.into_iter()173			.map(eth::Property::try_into)174			.collect::<Result<Vec<_>>>()?;175176		<Pallet<T>>::set_token_properties(177			self,178			&caller,179			TokenId(token_id),180			properties.into_iter(),181			false,182			&nesting_budget,183		)184		.map_err(dispatch_to_evm::<T>)185	}186187	/// @notice Delete token property value.188	/// @dev Throws error if `msg.sender` has no permission to edit the property.189	/// @param tokenId ID of the token.190	/// @param key Property key.191	#[solidity(hide)]192	#[weight(<SelfWeightOf<T>>::delete_token_properties(1))]193	fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {194		let caller = T::CrossAccountId::from_eth(caller);195		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;196		let key = <Vec<u8>>::from(key)197			.try_into()198			.map_err(|_| "key too long")?;199200		let nesting_budget = self201			.recorder202			.weight_calls_budget(<StructureWeight<T>>::find_parent());203204		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)205			.map_err(dispatch_to_evm::<T>)206	}207208	/// @notice Delete token properties value.209	/// @dev Throws error if `msg.sender` has no permission to edit the property.210	/// @param tokenId ID of the token.211	/// @param keys Properties key.212	#[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]213	fn delete_properties(214		&mut self,215		token_id: U256,216		caller: Caller,217		keys: Vec<String>,218	) -> Result<()> {219		let caller = T::CrossAccountId::from_eth(caller);220		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;221		let keys = keys222			.into_iter()223			.map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))224			.collect::<Result<Vec<_>>>()?;225226		let nesting_budget = self227			.recorder228			.weight_calls_budget(<StructureWeight<T>>::find_parent());229230		<Pallet<T>>::delete_token_properties(231			self,232			&caller,233			TokenId(token_id),234			keys.into_iter(),235			&nesting_budget,236		)237		.map_err(dispatch_to_evm::<T>)238	}239240	/// @notice Get token property value.241	/// @dev Throws error if key not found242	/// @param tokenId ID of the token.243	/// @param key Property key.244	/// @return Property value bytes245	fn property(&self, token_id: U256, key: String) -> Result<Bytes> {246		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;247		let key = <Vec<u8>>::from(key)248			.try_into()249			.map_err(|_| "key too long")?;250251		let props = <TokenProperties<T>>::get((self.id, token_id));252		let prop = props.get(&key).ok_or("key not found")?;253254		Ok(prop.to_vec().into())255	}256}257258#[derive(ToLog)]259pub enum ERC721Events {260	/// @dev This event emits when NFTs are created (`from` == 0) and destroyed261	///  (`to` == 0). Exception: during contract creation, any number of RFTs262	///  may be created and assigned without emitting Transfer.263	Transfer {264		#[indexed]265		from: Address,266		#[indexed]267		to: Address,268		#[indexed]269		token_id: U256,270	},271	/// @dev Not supported272	Approval {273		#[indexed]274		owner: Address,275		#[indexed]276		approved: Address,277		#[indexed]278		token_id: U256,279	},280	/// @dev Not supported281	#[allow(dead_code)]282	ApprovalForAll {283		#[indexed]284		owner: Address,285		#[indexed]286		operator: Address,287		approved: bool,288	},289}290291/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension292/// @dev See https://eips.ethereum.org/EIPS/eip-721293#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]294impl<T: Config> RefungibleHandle<T>295where296	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,297{298	/// @notice A descriptive name for a collection of NFTs in this contract299	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`300	#[solidity(hide, rename_selector = "name")]301	fn name_proxy(&self) -> Result<String> {302		self.name()303	}304305	/// @notice An abbreviated name for NFTs in this contract306	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`307	#[solidity(hide, rename_selector = "symbol")]308	fn symbol_proxy(&self) -> Result<String> {309		self.symbol()310	}311312	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.313	///314	/// @dev If the token has a `url` property and it is not empty, it is returned.315	///  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`.316	///  If the collection property `baseURI` is empty or absent, return "" (empty string)317	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix318	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).319	///320	/// @return token's const_metadata321	#[solidity(rename_selector = "tokenURI")]322	fn token_uri(&self, token_id: U256) -> Result<String> {323		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;324325		match get_token_property(self, token_id_u32, &key::url()).as_deref() {326			Err(_) | Ok("") => (),327			Ok(url) => {328				return Ok(url.into());329			}330		};331332		let base_uri =333			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())334				.map(BoundedVec::into_inner)335				.map(String::from_utf8)336				.transpose()337				.map_err(|e| {338					Error::Revert(alloc::format!(339						"Can not convert value \"baseURI\" to string with error \"{}\"",340						e341					))342				})?;343344		let base_uri = match base_uri.as_deref() {345			None | Some("") => {346				return Ok("".into());347			}348			Some(base_uri) => base_uri.into(),349		};350351		Ok(352			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {353				Err(_) | Ok("") => base_uri,354				Ok(suffix) => base_uri + suffix,355			},356		)357	}358}359360/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension361/// @dev See https://eips.ethereum.org/EIPS/eip-721362#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]363impl<T: Config> RefungibleHandle<T> {364	/// @notice Enumerate valid RFTs365	/// @param index A counter less than `totalSupply()`366	/// @return The token identifier for the `index`th NFT,367	///  (sort order not specified)368	fn token_by_index(&self, index: U256) -> Result<U256> {369		Ok(index)370	}371372	/// Not implemented373	fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {374		// TODO: Not implemetable375		Err("not implemented".into())376	}377378	/// @notice Count RFTs tracked by this contract379	/// @return A count of valid RFTs tracked by this contract, where each one of380	///  them has an assigned and queryable owner not equal to the zero address381	fn total_supply(&self) -> Result<U256> {382		self.consume_store_reads(1)?;383		Ok(<Pallet<T>>::total_supply(self).into())384	}385}386387/// @title ERC-721 Non-Fungible Token Standard388/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md389#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]390impl<T: Config> RefungibleHandle<T> {391	/// @notice Count all RFTs assigned to an owner392	/// @dev RFTs assigned to the zero address are considered invalid, and this393	///  function throws for queries about the zero address.394	/// @param owner An address for whom to query the balance395	/// @return The number of RFTs owned by `owner`, possibly zero396	fn balance_of(&self, owner: Address) -> Result<U256> {397		self.consume_store_reads(1)?;398		let owner = T::CrossAccountId::from_eth(owner);399		let balance = <AccountBalance<T>>::get((self.id, owner));400		Ok(balance.into())401	}402403	/// @notice Find the owner of an RFT404	/// @dev RFTs assigned to zero address are considered invalid, and queries405	///  about them do throw.406	///  Returns special 0xffffffffffffffffffffffffffffffffffffffff address for407	///  the tokens that are partially owned.408	/// @param tokenId The identifier for an RFT409	/// @return The address of the owner of the RFT410	fn owner_of(&self, token_id: U256) -> Result<Address> {411		self.consume_store_reads(2)?;412		let token = token_id.try_into()?;413		let owner = <Pallet<T>>::token_owner(self.id, token);414		owner415			.map(|address| *address.as_eth())416			.or_else(|err| match err {417				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),418				TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),419			})420	}421422	/// @dev Not implemented423	#[solidity(rename_selector = "safeTransferFrom")]424	fn safe_transfer_from_with_data(425		&mut self,426		_from: Address,427		_to: Address,428		_token_id: U256,429		_data: Bytes,430	) -> Result<()> {431		// TODO: Not implemetable432		Err("not implemented".into())433	}434435	/// @dev Not implemented436	#[solidity(rename_selector = "safeTransferFrom")]437	fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {438		// TODO: Not implemetable439		Err("not implemented".into())440	}441442	/// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE443	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE444	///  THEY MAY BE PERMANENTLY LOST445	/// @dev Throws unless `msg.sender` is the current owner or an authorized446	///  operator for this RFT. Throws if `from` is not the current owner. Throws447	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.448	///  Throws if RFT pieces have multiple owners.449	/// @param from The current owner of the NFT450	/// @param to The new owner451	/// @param tokenId The NFT to transfer452	#[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]453	fn transfer_from(454		&mut self,455		caller: Caller,456		from: Address,457		to: Address,458		token_id: U256,459	) -> Result<()> {460		let caller = T::CrossAccountId::from_eth(caller);461		let from = T::CrossAccountId::from_eth(from);462		let to = T::CrossAccountId::from_eth(to);463		let token = token_id.try_into()?;464		let budget = self465			.recorder466			.weight_calls_budget(<StructureWeight<T>>::find_parent());467468		let balance = balance(&self, token, &from)?;469		ensure_single_owner(&self, token, balance)?;470471		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)472			.map_err(dispatch_to_evm::<T>)?;473474		Ok(())475	}476477	/// @dev Not implemented478	fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {479		Err("not implemented".into())480	}481482	/// @notice Sets or unsets the approval of a given operator.483	///  The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.484	/// @param operator Operator485	/// @param approved Should operator status be granted or revoked?486	#[weight(<SelfWeightOf<T>>::set_allowance_for_all())]487	fn set_approval_for_all(488		&mut self,489		caller: Caller,490		operator: Address,491		approved: bool,492	) -> Result<()> {493		let caller = T::CrossAccountId::from_eth(caller);494		let operator = T::CrossAccountId::from_eth(operator);495496		<Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)497			.map_err(dispatch_to_evm::<T>)?;498		Ok(())499	}500501	/// @dev Not implemented502	fn get_approved(&self, _token_id: U256) -> Result<Address> {503		// TODO: Not implemetable504		Err("not implemented".into())505	}506507	/// @notice Tells whether the given `owner` approves the `operator`.508	#[weight(<SelfWeightOf<T>>::allowance_for_all())]509	fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {510		let owner = T::CrossAccountId::from_eth(owner);511		let operator = T::CrossAccountId::from_eth(operator);512513		Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))514	}515}516517/// Returns amount of pieces of `token` that `owner` have518pub fn balance<T: Config>(519	collection: &RefungibleHandle<T>,520	token: TokenId,521	owner: &T::CrossAccountId,522) -> Result<u128> {523	collection.consume_store_reads(1)?;524	let balance = <Balance<T>>::get((collection.id, token, &owner));525	Ok(balance)526}527528/// Throws if `owner_balance` is lower than total amount of `token` pieces529pub fn ensure_single_owner<T: Config>(530	collection: &RefungibleHandle<T>,531	token: TokenId,532	owner_balance: u128,533) -> Result<()> {534	collection.consume_store_reads(1)?;535	let total_supply = <TotalSupply<T>>::get((collection.id, token));536537	if owner_balance == 0 {538		return Err(dispatch_to_evm::<T>(539			<CommonError<T>>::MustBeTokenOwner.into(),540		));541	}542543	if total_supply != owner_balance {544		return Err("token has multiple owners".into());545	}546	Ok(())547}548549/// @title ERC721 Token that can be irreversibly burned (destroyed).550#[solidity_interface(name = ERC721Burnable)]551impl<T: Config> RefungibleHandle<T> {552	/// @notice Burns a specific ERC721 token.553	/// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized554	///  operator of the current owner.555	/// @param tokenId The RFT to approve556	#[weight(<SelfWeightOf<T>>::burn_item_fully())]557	fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {558		let caller = T::CrossAccountId::from_eth(caller);559		let token = token_id.try_into()?;560561		let balance = balance(&self, token, &caller)?;562		ensure_single_owner(&self, token, balance)?;563564		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;565		Ok(())566	}567}568569/// @title ERC721 minting logic.570#[solidity_interface(name = ERC721UniqueMintable)]571impl<T: Config> RefungibleHandle<T> {572	/// @notice Function to mint a token.573	/// @param to The new owner574	/// @return uint256 The id of the newly minted token575	#[weight(<SelfWeightOf<T>>::create_item())]576	fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {577		let token_id: U256 = <TokensMinted<T>>::get(self.id)578			.checked_add(1)579			.ok_or("item id overflow")?580			.into();581		self.mint_check_id(caller, to, token_id)?;582		Ok(token_id)583	}584585	/// @notice Function to mint a token.586	/// @dev `tokenId` should be obtained with `nextTokenId` method,587	///  unlike standard, you can't specify it manually588	/// @param to The new owner589	/// @param tokenId ID of the minted RFT590	#[solidity(hide, rename_selector = "mint")]591	#[weight(<SelfWeightOf<T>>::create_item())]592	fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {593		let caller = T::CrossAccountId::from_eth(caller);594		let to = T::CrossAccountId::from_eth(to);595		let token_id: u32 = token_id.try_into()?;596		let budget = self597			.recorder598			.weight_calls_budget(<StructureWeight<T>>::find_parent());599600		if <TokensMinted<T>>::get(self.id)601			.checked_add(1)602			.ok_or("item id overflow")?603			!= token_id604		{605			return Err("item id should be next".into());606		}607608		let users = [(to.clone(), 1)]609			.into_iter()610			.collect::<BTreeMap<_, _>>()611			.try_into()612			.unwrap();613		<Pallet<T>>::create_item(614			self,615			&caller,616			CreateItemData::<T> {617				users,618				properties: CollectionPropertiesVec::default(),619			},620			&budget,621		)622		.map_err(dispatch_to_evm::<T>)?;623624		Ok(true)625	}626627	/// @notice Function to mint token with the given tokenUri.628	/// @param to The new owner629	/// @param tokenUri Token URI that would be stored in the NFT properties630	/// @return uint256 The id of the newly minted token631	#[solidity(rename_selector = "mintWithTokenURI")]632	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]633	fn mint_with_token_uri(634		&mut self,635		caller: Caller,636		to: Address,637		token_uri: String,638	) -> Result<U256> {639		let token_id: U256 = <TokensMinted<T>>::get(self.id)640			.checked_add(1)641			.ok_or("item id overflow")?642			.into();643		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;644		Ok(token_id)645	}646647	/// @notice Function to mint token with the given tokenUri.648	/// @dev `tokenId` should be obtained with `nextTokenId` method,649	///  unlike standard, you can't specify it manually650	/// @param to The new owner651	/// @param tokenId ID of the minted RFT652	/// @param tokenUri Token URI that would be stored in the RFT properties653	#[solidity(hide, rename_selector = "mintWithTokenURI")]654	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]655	fn mint_with_token_uri_check_id(656		&mut self,657		caller: Caller,658		to: Address,659		token_id: U256,660		token_uri: String,661	) -> Result<bool> {662		let key = key::url();663		let permission = get_token_permission::<T>(self.id, &key)?;664		if !permission.collection_admin {665			return Err("Operation is not allowed".into());666		}667668		let caller = T::CrossAccountId::from_eth(caller);669		let to = T::CrossAccountId::from_eth(to);670		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;671		let budget = self672			.recorder673			.weight_calls_budget(<StructureWeight<T>>::find_parent());674675		if <TokensMinted<T>>::get(self.id)676			.checked_add(1)677			.ok_or("item id overflow")?678			!= token_id679		{680			return Err("item id should be next".into());681		}682683		let mut properties = CollectionPropertiesVec::default();684		properties685			.try_push(Property {686				key,687				value: token_uri688					.into_bytes()689					.try_into()690					.map_err(|_| "token uri is too long")?,691			})692			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;693694		let users = [(to.clone(), 1)]695			.into_iter()696			.collect::<BTreeMap<_, _>>()697			.try_into()698			.unwrap();699		<Pallet<T>>::create_item(700			self,701			&caller,702			CreateItemData::<T> { users, properties },703			&budget,704		)705		.map_err(dispatch_to_evm::<T>)?;706		Ok(true)707	}708}709710fn get_token_property<T: Config>(711	collection: &CollectionHandle<T>,712	token_id: u32,713	key: &up_data_structs::PropertyKey,714) -> Result<String> {715	collection.consume_store_reads(1)?;716	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))717		.map_err(|_| Error::Revert("Token properties not found".into()))?;718	if let Some(property) = properties.get(key) {719		return Ok(String::from_utf8_lossy(property).into());720	}721722	Err("Property tokenURI not found".into())723}724725fn get_token_permission<T: Config>(726	collection_id: CollectionId,727	key: &PropertyKey,728) -> Result<PropertyPermission> {729	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)730		.map_err(|_| Error::Revert("No permissions for collection".into()))?;731	let a = token_property_permissions732		.get(key)733		.map(Clone::clone)734		.ok_or_else(|| {735			let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();736			Error::Revert(alloc::format!("No permission for key {}", key))737		})?;738	Ok(a)739}740741/// @title Unique extensions for ERC721.742#[solidity_interface(name = ERC721UniqueExtensions)]743impl<T: Config> RefungibleHandle<T>744where745	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,746{747	/// @notice A descriptive name for a collection of NFTs in this contract748	fn name(&self) -> Result<String> {749		Ok(decode_utf16(self.name.iter().copied())750			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))751			.collect::<String>())752	}753754	/// @notice An abbreviated name for NFTs in this contract755	fn symbol(&self) -> Result<String> {756		Ok(String::from_utf8_lossy(&self.token_prefix).into())757	}758759	/// @notice A description for the collection.760	fn description(&self) -> Result<String> {761		Ok(decode_utf16(self.description.iter().copied())762			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))763			.collect::<String>())764	}765766	/// Returns the owner (in cross format) of the token.767	///768	/// @param tokenId Id for the token.769	fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {770		Self::token_owner(&self, token_id.try_into()?)771			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))772			.or_else(|err| match err {773				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),774				TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(775					ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,776				)),777			})778	}779780	/// Returns the token properties.781	///782	/// @param tokenId Id for the token.783	/// @param keys Properties keys. Empty keys for all propertyes.784	/// @return Vector of properties key/value pairs.785	fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {786		let keys = keys787			.into_iter()788			.map(|key| {789				<Vec<u8>>::from(key)790					.try_into()791					.map_err(|_| Error::Revert("key too large".into()))792			})793			.collect::<Result<Vec<_>>>()?;794795		<Self as CommonCollectionOperations<T>>::token_properties(796			&self,797			token_id.try_into()?,798			if keys.is_empty() { None } else { Some(keys) },799		)800		.into_iter()801		.map(eth::Property::try_from)802		.collect::<Result<Vec<_>>>()803	}804	/// @notice Transfer ownership of an RFT805	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`806	///  is the zero address. Throws if `tokenId` is not a valid RFT.807	///  Throws if RFT pieces have multiple owners.808	/// @param to The new owner809	/// @param tokenId The RFT to transfer810	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]811	fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {812		let caller = T::CrossAccountId::from_eth(caller);813		let to = T::CrossAccountId::from_eth(to);814		let token = token_id.try_into()?;815		let budget = self816			.recorder817			.weight_calls_budget(<StructureWeight<T>>::find_parent());818819		let balance = balance(self, token, &caller)?;820		ensure_single_owner(self, token, balance)?;821822		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)823			.map_err(dispatch_to_evm::<T>)?;824		Ok(())825	}826827	/// @notice Transfer ownership of an RFT828	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`829	///  is the zero address. Throws if `tokenId` is not a valid RFT.830	///  Throws if RFT pieces have multiple owners.831	/// @param to The new owner832	/// @param tokenId The RFT to transfer833	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]834	fn transfer_cross(835		&mut self,836		caller: Caller,837		to: eth::CrossAddress,838		token_id: U256,839	) -> Result<()> {840		let caller = T::CrossAccountId::from_eth(caller);841		let to = to.into_sub_cross_account::<T>()?;842		let token = token_id.try_into()?;843		let budget = self844			.recorder845			.weight_calls_budget(<StructureWeight<T>>::find_parent());846847		let balance = balance(self, token, &caller)?;848		ensure_single_owner(self, token, balance)?;849850		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)851			.map_err(dispatch_to_evm::<T>)?;852		Ok(())853	}854855	/// @notice Transfer ownership of an RFT856	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`857	///  is the zero address. Throws if `tokenId` is not a valid RFT.858	///  Throws if RFT pieces have multiple owners.859	/// @param to The new owner860	/// @param tokenId The RFT to transfer861	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]862	fn transfer_from_cross(863		&mut self,864		caller: Caller,865		from: eth::CrossAddress,866		to: eth::CrossAddress,867		token_id: U256,868	) -> Result<()> {869		let caller = T::CrossAccountId::from_eth(caller);870		let from = from.into_sub_cross_account::<T>()?;871		let to = to.into_sub_cross_account::<T>()?;872		let token_id = token_id.try_into()?;873		let budget = self874			.recorder875			.weight_calls_budget(<StructureWeight<T>>::find_parent());876877		let balance = balance(self, token_id, &from)?;878		ensure_single_owner(self, token_id, balance)?;879880		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)881			.map_err(dispatch_to_evm::<T>)?;882		Ok(())883	}884885	/// @notice Burns a specific ERC721 token.886	/// @dev Throws unless `msg.sender` is the current owner or an authorized887	///  operator for this RFT. Throws if `from` is not the current owner. Throws888	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.889	///  Throws if RFT pieces have multiple owners.890	/// @param from The current owner of the RFT891	/// @param tokenId The RFT to transfer892	#[solidity(hide)]893	#[weight(<SelfWeightOf<T>>::burn_from())]894	fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {895		let caller = T::CrossAccountId::from_eth(caller);896		let from = T::CrossAccountId::from_eth(from);897		let token = token_id.try_into()?;898		let budget = self899			.recorder900			.weight_calls_budget(<StructureWeight<T>>::find_parent());901902		let balance = balance(self, token, &from)?;903		ensure_single_owner(self, token, balance)?;904905		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)906			.map_err(dispatch_to_evm::<T>)?;907		Ok(())908	}909910	/// @notice Burns a specific ERC721 token.911	/// @dev Throws unless `msg.sender` is the current owner or an authorized912	///  operator for this RFT. Throws if `from` is not the current owner. Throws913	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.914	///  Throws if RFT pieces have multiple owners.915	/// @param from The current owner of the RFT916	/// @param tokenId The RFT to transfer917	#[weight(<SelfWeightOf<T>>::burn_from())]918	fn burn_from_cross(919		&mut self,920		caller: Caller,921		from: eth::CrossAddress,922		token_id: U256,923	) -> Result<()> {924		let caller = T::CrossAccountId::from_eth(caller);925		let from = from.into_sub_cross_account::<T>()?;926		let token = token_id.try_into()?;927		let budget = self928			.recorder929			.weight_calls_budget(<StructureWeight<T>>::find_parent());930931		let balance = balance(self, token, &from)?;932		ensure_single_owner(self, token, balance)?;933934		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)935			.map_err(dispatch_to_evm::<T>)?;936		Ok(())937	}938939	/// @notice Returns next free RFT ID.940	fn next_token_id(&self) -> Result<U256> {941		self.consume_store_reads(1)?;942		Ok(<TokensMinted<T>>::get(self.id)943			.checked_add(1)944			.ok_or("item id overflow")?945			.into())946	}947948	/// @notice Function to mint multiple tokens.949	/// @dev `tokenIds` should be an array of consecutive numbers and first number950	///  should be obtained with `nextTokenId` method951	/// @param to The new owner952	/// @param tokenIds IDs of the minted RFTs953	#[solidity(hide)]954	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]955	fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {956		let caller = T::CrossAccountId::from_eth(caller);957		let to = T::CrossAccountId::from_eth(to);958		let mut expected_index = <TokensMinted<T>>::get(self.id)959			.checked_add(1)960			.ok_or("item id overflow")?;961		let budget = self962			.recorder963			.weight_calls_budget(<StructureWeight<T>>::find_parent());964965		let total_tokens = token_ids.len();966		for id in token_ids.into_iter() {967			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;968			if id != expected_index {969				return Err("item id should be next".into());970			}971			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;972		}973		let users = [(to.clone(), 1)]974			.into_iter()975			.collect::<BTreeMap<_, _>>()976			.try_into()977			.unwrap();978		let create_item_data = CreateItemData::<T> {979			users,980			properties: CollectionPropertiesVec::default(),981		};982		let data = (0..total_tokens)983			.map(|_| create_item_data.clone())984			.collect();985986		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)987			.map_err(dispatch_to_evm::<T>)?;988		Ok(true)989	}990991	/// @notice Function to mint multiple tokens with the given tokenUris.992	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive993	///  numbers and first number should be obtained with `nextTokenId` method994	/// @param to The new owner995	/// @param tokens array of pairs of token ID and token URI for minted tokens996	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]997	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]998	fn mint_bulk_with_token_uri(999		&mut self,1000		caller: Caller,1001		to: Address,1002		tokens: Vec<TokenUri>,1003	) -> Result<bool> {1004		let key = key::url();1005		let caller = T::CrossAccountId::from_eth(caller);1006		let to = T::CrossAccountId::from_eth(to);1007		let mut expected_index = <TokensMinted<T>>::get(self.id)1008			.checked_add(1)1009			.ok_or("item id overflow")?;1010		let budget = self1011			.recorder1012			.weight_calls_budget(<StructureWeight<T>>::find_parent());10131014		let mut data = Vec::with_capacity(tokens.len());1015		let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]1016			.into_iter()1017			.collect::<BTreeMap<_, _>>()1018			.try_into()1019			.unwrap();1020		for TokenUri { id, uri } in tokens {1021			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1022			if id != expected_index {1023				return Err("item id should be next".into());1024			}1025			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10261027			let mut properties = CollectionPropertiesVec::default();1028			properties1029				.try_push(Property {1030					key: key.clone(),1031					value: uri1032						.into_bytes()1033						.try_into()1034						.map_err(|_| "token uri is too long")?,1035				})1036				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;10371038			let create_item_data = CreateItemData::<T> {1039				users: users.clone(),1040				properties,1041			};1042			data.push(create_item_data);1043		}10441045		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1046			.map_err(dispatch_to_evm::<T>)?;1047		Ok(true)1048	}10491050	/// @notice Function to mint a token.1051	/// @param to The new owner crossAccountId1052	/// @param properties Properties of minted token1053	/// @return uint256 The id of the newly minted token1054	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1055	fn mint_cross(1056		&mut self,1057		caller: Caller,1058		to: eth::CrossAddress,1059		properties: Vec<eth::Property>,1060	) -> Result<U256> {1061		let token_id = <TokensMinted<T>>::get(self.id)1062			.checked_add(1)1063			.ok_or("item id overflow")?;10641065		let to = to.into_sub_cross_account::<T>()?;10661067		let properties = properties1068			.into_iter()1069			.map(eth::Property::try_into)1070			.collect::<Result<Vec<_>>>()?1071			.try_into()1072			.map_err(|_| Error::Revert(alloc::format!("too many properties")))?;10731074		let caller = T::CrossAccountId::from_eth(caller);10751076		let budget = self1077			.recorder1078			.weight_calls_budget(<StructureWeight<T>>::find_parent());10791080		let users = [(to, 1)]1081			.into_iter()1082			.collect::<BTreeMap<_, _>>()1083			.try_into()1084			.unwrap();1085		<Pallet<T>>::create_item(1086			self,1087			&caller,1088			CreateItemData::<T> { users, properties },1089			&budget,1090		)1091		.map_err(dispatch_to_evm::<T>)?;10921093		Ok(token_id.into())1094	}10951096	/// Returns EVM address for refungible token1097	///1098	/// @param token ID of the token1099	fn token_contract_address(&self, token: U256) -> Result<Address> {1100		Ok(T::EvmTokenAddressMapping::token_to_address(1101			self.id,1102			token.try_into().map_err(|_| "token id overflow")?,1103		))1104	}11051106	/// @notice Returns collection helper contract address1107	fn collection_helper_address(&self) -> Result<Address> {1108		Ok(T::ContractAddress::get())1109	}1110}11111112#[solidity_interface(1113	name = UniqueRefungible,1114	is(1115		ERC721,1116		ERC721Enumerable,1117		ERC721UniqueExtensions,1118		ERC721UniqueMintable,1119		ERC721Burnable,1120		ERC721Metadata(if(this.flags.erc721metadata)),1121		Collection(via(common_mut returns CollectionHandle<T>)),1122		TokenProperties,1123	)1124)]1125impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11261127// Not a tests, but code generators1128generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1129generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);11301131impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1132where1133	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1134{1135	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1136	fn call(1137		self,1138		handle: &mut impl PrecompileHandle,1139	) -> Option<pallet_common::erc::PrecompileResult> {1140		call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1141	}1142}