git.delta.rocks / unique-network / refs/commits / 4f4018846dc9

difftreelog

source

pallets/refungible/src/erc.rs35.9 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,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, 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,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: uint256,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: uint256,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: uint256, 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: uint256,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: uint256, 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: uint256,270	},271	/// @dev Not supported272	Approval {273		#[indexed]274		owner: address,275		#[indexed]276		approved: address,277		#[indexed]278		token_id: uint256,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: uint256) -> 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: uint256) -> Result<uint256> {369		Ok(index)370	}371372	/// Not implemented373	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {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<uint256> {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<uint256> {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: uint256) -> 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		Ok(owner415			.map(|address| *address.as_eth())416			.unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))417	}418419	/// @dev Not implemented420	#[solidity(rename_selector = "safeTransferFrom")]421	fn safe_transfer_from_with_data(422		&mut self,423		_from: address,424		_to: address,425		_token_id: uint256,426		_data: bytes,427	) -> Result<void> {428		// TODO: Not implemetable429		Err("not implemented".into())430	}431432	/// @dev Not implemented433	#[solidity(rename_selector = "safeTransferFrom")]434	fn safe_transfer_from(435		&mut self,436		_from: address,437		_to: address,438		_token_id: uint256,439	) -> Result<void> {440		// TODO: Not implemetable441		Err("not implemented".into())442	}443444	/// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE445	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE446	///  THEY MAY BE PERMANENTLY LOST447	/// @dev Throws unless `msg.sender` is the current owner or an authorized448	///  operator for this RFT. Throws if `from` is not the current owner. Throws449	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.450	///  Throws if RFT pieces have multiple owners.451	/// @param from The current owner of the NFT452	/// @param to The new owner453	/// @param tokenId The NFT to transfer454	#[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]455	fn transfer_from(456		&mut self,457		caller: caller,458		from: address,459		to: address,460		token_id: uint256,461	) -> Result<void> {462		let caller = T::CrossAccountId::from_eth(caller);463		let from = T::CrossAccountId::from_eth(from);464		let to = T::CrossAccountId::from_eth(to);465		let token = token_id.try_into()?;466		let budget = self467			.recorder468			.weight_calls_budget(<StructureWeight<T>>::find_parent());469470		let balance = balance(&self, token, &from)?;471		ensure_single_owner(&self, token, balance)?;472473		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)474			.map_err(dispatch_to_evm::<T>)?;475476		Ok(())477	}478479	/// @dev Not implemented480	fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {481		Err("not implemented".into())482	}483484	/// @notice Sets or unsets the approval of a given operator.485	///  The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.486	/// @param operator Operator487	/// @param approved Should operator status be granted or revoked?488	#[weight(<SelfWeightOf<T>>::set_allowance_for_all())]489	fn set_approval_for_all(490		&mut self,491		caller: caller,492		operator: address,493		approved: bool,494	) -> Result<void> {495		let caller = T::CrossAccountId::from_eth(caller);496		let operator = T::CrossAccountId::from_eth(operator);497498		<Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)499			.map_err(dispatch_to_evm::<T>)?;500		Ok(())501	}502503	/// @dev Not implemented504	fn get_approved(&self, _token_id: uint256) -> Result<address> {505		// TODO: Not implemetable506		Err("not implemented".into())507	}508509	/// @notice Tells whether the given `owner` approves the `operator`.510	#[weight(<SelfWeightOf<T>>::allowance_for_all())]511	fn is_approved_for_all(&self, owner: address, operator: address) -> Result<bool> {512		let owner = T::CrossAccountId::from_eth(owner);513		let operator = T::CrossAccountId::from_eth(operator);514515		Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))516	}517}518519/// Returns amount of pieces of `token` that `owner` have520pub fn balance<T: Config>(521	collection: &RefungibleHandle<T>,522	token: TokenId,523	owner: &T::CrossAccountId,524) -> Result<u128> {525	collection.consume_store_reads(1)?;526	let balance = <Balance<T>>::get((collection.id, token, &owner));527	Ok(balance)528}529530/// Throws if `owner_balance` is lower than total amount of `token` pieces531pub fn ensure_single_owner<T: Config>(532	collection: &RefungibleHandle<T>,533	token: TokenId,534	owner_balance: u128,535) -> Result<()> {536	collection.consume_store_reads(1)?;537	let total_supply = <TotalSupply<T>>::get((collection.id, token));538539	if owner_balance == 0 {540		return Err(dispatch_to_evm::<T>(541			<CommonError<T>>::MustBeTokenOwner.into(),542		));543	}544545	if total_supply != owner_balance {546		return Err("token has multiple owners".into());547	}548	Ok(())549}550551/// @title ERC721 Token that can be irreversibly burned (destroyed).552#[solidity_interface(name = ERC721Burnable)]553impl<T: Config> RefungibleHandle<T> {554	/// @notice Burns a specific ERC721 token.555	/// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized556	///  operator of the current owner.557	/// @param tokenId The RFT to approve558	#[weight(<SelfWeightOf<T>>::burn_item_fully())]559	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {560		let caller = T::CrossAccountId::from_eth(caller);561		let token = token_id.try_into()?;562563		let balance = balance(&self, token, &caller)?;564		ensure_single_owner(&self, token, balance)?;565566		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;567		Ok(())568	}569}570571/// @title ERC721 minting logic.572#[solidity_interface(name = ERC721UniqueMintable)]573impl<T: Config> RefungibleHandle<T> {574	/// @notice Function to mint a token.575	/// @param to The new owner576	/// @return uint256 The id of the newly minted token577	#[weight(<SelfWeightOf<T>>::create_item())]578	fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {579		let token_id: uint256 = <TokensMinted<T>>::get(self.id)580			.checked_add(1)581			.ok_or("item id overflow")?582			.into();583		self.mint_check_id(caller, to, token_id)?;584		Ok(token_id)585	}586587	/// @notice Function to mint a token.588	/// @dev `tokenId` should be obtained with `nextTokenId` method,589	///  unlike standard, you can't specify it manually590	/// @param to The new owner591	/// @param tokenId ID of the minted RFT592	#[solidity(hide, rename_selector = "mint")]593	#[weight(<SelfWeightOf<T>>::create_item())]594	fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {595		let caller = T::CrossAccountId::from_eth(caller);596		let to = T::CrossAccountId::from_eth(to);597		let token_id: u32 = token_id.try_into()?;598		let budget = self599			.recorder600			.weight_calls_budget(<StructureWeight<T>>::find_parent());601602		if <TokensMinted<T>>::get(self.id)603			.checked_add(1)604			.ok_or("item id overflow")?605			!= token_id606		{607			return Err("item id should be next".into());608		}609610		let users = [(to.clone(), 1)]611			.into_iter()612			.collect::<BTreeMap<_, _>>()613			.try_into()614			.unwrap();615		<Pallet<T>>::create_item(616			self,617			&caller,618			CreateItemData::<T> {619				users,620				properties: CollectionPropertiesVec::default(),621			},622			&budget,623		)624		.map_err(dispatch_to_evm::<T>)?;625626		Ok(true)627	}628629	/// @notice Function to mint token with the given tokenUri.630	/// @param to The new owner631	/// @param tokenUri Token URI that would be stored in the NFT properties632	/// @return uint256 The id of the newly minted token633	#[solidity(rename_selector = "mintWithTokenURI")]634	#[weight(<SelfWeightOf<T>>::create_item())]635	fn mint_with_token_uri(636		&mut self,637		caller: caller,638		to: address,639		token_uri: string,640	) -> Result<uint256> {641		let token_id: uint256 = <TokensMinted<T>>::get(self.id)642			.checked_add(1)643			.ok_or("item id overflow")?644			.into();645		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;646		Ok(token_id)647	}648649	/// @notice Function to mint token with the given tokenUri.650	/// @dev `tokenId` should be obtained with `nextTokenId` method,651	///  unlike standard, you can't specify it manually652	/// @param to The new owner653	/// @param tokenId ID of the minted RFT654	/// @param tokenUri Token URI that would be stored in the RFT properties655	#[solidity(hide, rename_selector = "mintWithTokenURI")]656	#[weight(<SelfWeightOf<T>>::create_item())]657	fn mint_with_token_uri_check_id(658		&mut self,659		caller: caller,660		to: address,661		token_id: uint256,662		token_uri: string,663	) -> Result<bool> {664		let key = key::url();665		let permission = get_token_permission::<T>(self.id, &key)?;666		if !permission.collection_admin {667			return Err("Operation is not allowed".into());668		}669670		let caller = T::CrossAccountId::from_eth(caller);671		let to = T::CrossAccountId::from_eth(to);672		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;673		let budget = self674			.recorder675			.weight_calls_budget(<StructureWeight<T>>::find_parent());676677		if <TokensMinted<T>>::get(self.id)678			.checked_add(1)679			.ok_or("item id overflow")?680			!= token_id681		{682			return Err("item id should be next".into());683		}684685		let mut properties = CollectionPropertiesVec::default();686		properties687			.try_push(Property {688				key,689				value: token_uri690					.into_bytes()691					.try_into()692					.map_err(|_| "token uri is too long")?,693			})694			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;695696		let users = [(to.clone(), 1)]697			.into_iter()698			.collect::<BTreeMap<_, _>>()699			.try_into()700			.unwrap();701		<Pallet<T>>::create_item(702			self,703			&caller,704			CreateItemData::<T> { users, properties },705			&budget,706		)707		.map_err(dispatch_to_evm::<T>)?;708		Ok(true)709	}710}711712fn get_token_property<T: Config>(713	collection: &CollectionHandle<T>,714	token_id: u32,715	key: &up_data_structs::PropertyKey,716) -> Result<string> {717	collection.consume_store_reads(1)?;718	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))719		.map_err(|_| Error::Revert("Token properties not found".into()))?;720	if let Some(property) = properties.get(key) {721		return Ok(string::from_utf8_lossy(property).into());722	}723724	Err("Property tokenURI not found".into())725}726727fn get_token_permission<T: Config>(728	collection_id: CollectionId,729	key: &PropertyKey,730) -> Result<PropertyPermission> {731	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)732		.map_err(|_| Error::Revert("No permissions for collection".into()))?;733	let a = token_property_permissions734		.get(key)735		.map(Clone::clone)736		.ok_or_else(|| {737			let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();738			Error::Revert(alloc::format!("No permission for key {}", key))739		})?;740	Ok(a)741}742743/// @title Unique extensions for ERC721.744#[solidity_interface(name = ERC721UniqueExtensions)]745impl<T: Config> RefungibleHandle<T>746where747	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,748{749	/// @notice A descriptive name for a collection of NFTs in this contract750	fn name(&self) -> Result<string> {751		Ok(decode_utf16(self.name.iter().copied())752			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))753			.collect::<string>())754	}755756	/// @notice An abbreviated name for NFTs in this contract757	fn symbol(&self) -> Result<string> {758		Ok(string::from_utf8_lossy(&self.token_prefix).into())759	}760761	/// @notice A description for the collection.762	fn description(&self) -> Result<string> {763		Ok(decode_utf16(self.description.iter().copied())764			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))765			.collect::<string>())766	}767768	/// Returns the owner (in cross format) of the token.769	///770	/// @param tokenId Id for the token.771	fn cross_owner_of(&self, token_id: uint256) -> Result<eth::CrossAddress> {772		Self::token_owner(&self, token_id.try_into()?)773			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))774			.ok_or(Error::Revert("key too large".into()))775	}776777	/// Returns the token properties.778	///779	/// @param tokenId Id for the token.780	/// @param keys Properties keys. Empty keys for all propertyes.781	/// @return Vector of properties key/value pairs.782	fn properties(&self, token_id: uint256, keys: Vec<string>) -> Result<Vec<eth::Property>> {783		let keys = keys784			.into_iter()785			.map(|key| {786				<Vec<u8>>::from(key)787					.try_into()788					.map_err(|_| Error::Revert("key too large".into()))789			})790			.collect::<Result<Vec<_>>>()?;791792		<Self as CommonCollectionOperations<T>>::token_properties(793			&self,794			token_id.try_into()?,795			if keys.is_empty() { None } else { Some(keys) },796		)797		.into_iter()798		.map(eth::Property::try_from)799		.collect::<Result<Vec<_>>>()800	}801	/// @notice Transfer ownership of an RFT802	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`803	///  is the zero address. Throws if `tokenId` is not a valid RFT.804	///  Throws if RFT pieces have multiple owners.805	/// @param to The new owner806	/// @param tokenId The RFT to transfer807	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]808	fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {809		let caller = T::CrossAccountId::from_eth(caller);810		let to = T::CrossAccountId::from_eth(to);811		let token = token_id.try_into()?;812		let budget = self813			.recorder814			.weight_calls_budget(<StructureWeight<T>>::find_parent());815816		let balance = balance(self, token, &caller)?;817		ensure_single_owner(self, token, balance)?;818819		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)820			.map_err(dispatch_to_evm::<T>)?;821		Ok(())822	}823824	/// @notice Transfer ownership of an RFT825	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`826	///  is the zero address. Throws if `tokenId` is not a valid RFT.827	///  Throws if RFT pieces have multiple owners.828	/// @param to The new owner829	/// @param tokenId The RFT to transfer830	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]831	fn transfer_cross(832		&mut self,833		caller: caller,834		to: eth::CrossAddress,835		token_id: uint256,836	) -> Result<void> {837		let caller = T::CrossAccountId::from_eth(caller);838		let to = to.into_sub_cross_account::<T>()?;839		let token = token_id.try_into()?;840		let budget = self841			.recorder842			.weight_calls_budget(<StructureWeight<T>>::find_parent());843844		let balance = balance(self, token, &caller)?;845		ensure_single_owner(self, token, balance)?;846847		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)848			.map_err(dispatch_to_evm::<T>)?;849		Ok(())850	}851852	/// @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_from_cross(860		&mut self,861		caller: caller,862		from: eth::CrossAddress,863		to: eth::CrossAddress,864		token_id: uint256,865	) -> Result<void> {866		let caller = T::CrossAccountId::from_eth(caller);867		let from = from.into_sub_cross_account::<T>()?;868		let to = to.into_sub_cross_account::<T>()?;869		let token_id = token_id.try_into()?;870		let budget = self871			.recorder872			.weight_calls_budget(<StructureWeight<T>>::find_parent());873874		let balance = balance(self, token_id, &from)?;875		ensure_single_owner(self, token_id, balance)?;876877		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)878			.map_err(dispatch_to_evm::<T>)?;879		Ok(())880	}881882	/// @notice Burns a specific ERC721 token.883	/// @dev Throws unless `msg.sender` is the current owner or an authorized884	///  operator for this RFT. Throws if `from` is not the current owner. Throws885	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.886	///  Throws if RFT pieces have multiple owners.887	/// @param from The current owner of the RFT888	/// @param tokenId The RFT to transfer889	#[solidity(hide)]890	#[weight(<SelfWeightOf<T>>::burn_from())]891	fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {892		let caller = T::CrossAccountId::from_eth(caller);893		let from = T::CrossAccountId::from_eth(from);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, &from)?;900		ensure_single_owner(self, token, balance)?;901902		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)903			.map_err(dispatch_to_evm::<T>)?;904		Ok(())905	}906907	/// @notice Burns a specific ERC721 token.908	/// @dev Throws unless `msg.sender` is the current owner or an authorized909	///  operator for this RFT. Throws if `from` is not the current owner. Throws910	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.911	///  Throws if RFT pieces have multiple owners.912	/// @param from The current owner of the RFT913	/// @param tokenId The RFT to transfer914	#[weight(<SelfWeightOf<T>>::burn_from())]915	fn burn_from_cross(916		&mut self,917		caller: caller,918		from: eth::CrossAddress,919		token_id: uint256,920	) -> Result<void> {921		let caller = T::CrossAccountId::from_eth(caller);922		let from = from.into_sub_cross_account::<T>()?;923		let token = token_id.try_into()?;924		let budget = self925			.recorder926			.weight_calls_budget(<StructureWeight<T>>::find_parent());927928		let balance = balance(self, token, &from)?;929		ensure_single_owner(self, token, balance)?;930931		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)932			.map_err(dispatch_to_evm::<T>)?;933		Ok(())934	}935936	/// @notice Returns next free RFT ID.937	fn next_token_id(&self) -> Result<uint256> {938		self.consume_store_reads(1)?;939		Ok(<TokensMinted<T>>::get(self.id)940			.checked_add(1)941			.ok_or("item id overflow")?942			.into())943	}944945	/// @notice Function to mint multiple tokens.946	/// @dev `tokenIds` should be an array of consecutive numbers and first number947	///  should be obtained with `nextTokenId` method948	/// @param to The new owner949	/// @param tokenIds IDs of the minted RFTs950	#[solidity(hide)]951	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]952	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {953		let caller = T::CrossAccountId::from_eth(caller);954		let to = T::CrossAccountId::from_eth(to);955		let mut expected_index = <TokensMinted<T>>::get(self.id)956			.checked_add(1)957			.ok_or("item id overflow")?;958		let budget = self959			.recorder960			.weight_calls_budget(<StructureWeight<T>>::find_parent());961962		let total_tokens = token_ids.len();963		for id in token_ids.into_iter() {964			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;965			if id != expected_index {966				return Err("item id should be next".into());967			}968			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;969		}970		let users = [(to.clone(), 1)]971			.into_iter()972			.collect::<BTreeMap<_, _>>()973			.try_into()974			.unwrap();975		let create_item_data = CreateItemData::<T> {976			users,977			properties: CollectionPropertiesVec::default(),978		};979		let data = (0..total_tokens)980			.map(|_| create_item_data.clone())981			.collect();982983		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)984			.map_err(dispatch_to_evm::<T>)?;985		Ok(true)986	}987988	/// @notice Function to mint multiple tokens with the given tokenUris.989	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive990	///  numbers and first number should be obtained with `nextTokenId` method991	/// @param to The new owner992	/// @param tokens array of pairs of token ID and token URI for minted tokens993	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]994	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]995	fn mint_bulk_with_token_uri(996		&mut self,997		caller: caller,998		to: address,999		tokens: Vec<(uint256, string)>,1000	) -> Result<bool> {1001		let key = key::url();1002		let caller = T::CrossAccountId::from_eth(caller);1003		let to = T::CrossAccountId::from_eth(to);1004		let mut expected_index = <TokensMinted<T>>::get(self.id)1005			.checked_add(1)1006			.ok_or("item id overflow")?;1007		let budget = self1008			.recorder1009			.weight_calls_budget(<StructureWeight<T>>::find_parent());10101011		let mut data = Vec::with_capacity(tokens.len());1012		let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]1013			.into_iter()1014			.collect::<BTreeMap<_, _>>()1015			.try_into()1016			.unwrap();1017		for (id, token_uri) in tokens {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")?;10231024			let mut properties = CollectionPropertiesVec::default();1025			properties1026				.try_push(Property {1027					key: key.clone(),1028					value: token_uri1029						.into_bytes()1030						.try_into()1031						.map_err(|_| "token uri is too long")?,1032				})1033				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;10341035			let create_item_data = CreateItemData::<T> {1036				users: users.clone(),1037				properties,1038			};1039			data.push(create_item_data);1040		}10411042		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1043			.map_err(dispatch_to_evm::<T>)?;1044		Ok(true)1045	}10461047	/// @notice Function to mint a token.1048	/// @param to The new owner crossAccountId1049	/// @param properties Properties of minted token1050	/// @return uint256 The id of the newly minted token1051	#[weight(<SelfWeightOf<T>>::create_item())]1052	fn mint_cross(1053		&mut self,1054		caller: caller,1055		to: eth::CrossAddress,1056		properties: Vec<eth::Property>,1057	) -> Result<uint256> {1058		let token_id = <TokensMinted<T>>::get(self.id)1059			.checked_add(1)1060			.ok_or("item id overflow")?;10611062		let to = to.into_sub_cross_account::<T>()?;10631064		let properties = properties1065			.into_iter()1066			.map(eth::Property::try_into)1067			.collect::<Result<Vec<_>>>()?1068			.try_into()1069			.map_err(|_| Error::Revert(alloc::format!("too many properties")))?;10701071		let caller = T::CrossAccountId::from_eth(caller);10721073		let budget = self1074			.recorder1075			.weight_calls_budget(<StructureWeight<T>>::find_parent());10761077		let users = [(to, 1)]1078			.into_iter()1079			.collect::<BTreeMap<_, _>>()1080			.try_into()1081			.unwrap();1082		<Pallet<T>>::create_item(1083			self,1084			&caller,1085			CreateItemData::<T> { users, properties },1086			&budget,1087		)1088		.map_err(dispatch_to_evm::<T>)?;10891090		Ok(token_id.into())1091	}10921093	/// Returns EVM address for refungible token1094	///1095	/// @param token ID of the token1096	fn token_contract_address(&self, token: uint256) -> Result<address> {1097		Ok(T::EvmTokenAddressMapping::token_to_address(1098			self.id,1099			token.try_into().map_err(|_| "token id overflow")?,1100		))1101	}11021103	/// @notice Returns collection helper contract address1104	fn collection_helper_address(&self) -> Result<address> {1105		Ok(T::ContractAddress::get())1106	}1107}11081109#[solidity_interface(1110	name = UniqueRefungible,1111	is(1112		ERC721,1113		ERC721Enumerable,1114		ERC721UniqueExtensions,1115		ERC721UniqueMintable,1116		ERC721Burnable,1117		ERC721Metadata(if(this.flags.erc721metadata)),1118		Collection(via(common_mut returns CollectionHandle<T>)),1119		TokenProperties,1120	)1121)]1122impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11231124// Not a tests, but code generators1125generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1126generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);11271128impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1129where1130	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1131{1132	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1133	fn call(1134		self,1135		handle: &mut impl PrecompileHandle,1136	) -> Option<pallet_common::erc::PrecompileResult> {1137		call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1138	}1139}